OSDN Git Service

2010-06-23 Javier Miranda <miranda@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 -gnata
4064 @cindex @option{-gnata} (@command{gcc})
4065 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4066 activated. Note that these pragmas can also be controlled using the
4067 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4068 It also activates pragmas @code{Check}, @code{Precondition}, and
4069 @code{Postcondition}. Note that these pragmas can also be controlled
4070 using the configuration pragma @code{Check_Policy}.
4071
4072 @item -gnatA
4073 @cindex @option{-gnatA} (@command{gcc})
4074 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4075 it will be ignored.
4076
4077 @item -gnatb
4078 @cindex @option{-gnatb} (@command{gcc})
4079 Generate brief messages to @file{stderr} even if verbose mode set.
4080
4081 @item -gnatB
4082 @cindex @option{-gnatB} (@command{gcc})
4083 Assume no invalid (bad) values except for 'Valid attribute use
4084 (@pxref{Validity Checking}).
4085
4086 @item -gnatc
4087 @cindex @option{-gnatc} (@command{gcc})
4088 Check syntax and semantics only (no code generation attempted).
4089
4090 @item -gnatC
4091 @cindex @option{-gnatC} (@command{gcc})
4092 Generate CodePeer information (no code generation attempted).
4093 This switch will generate an intermediate representation suitable for
4094 use by CodePeer (@file{.scil} files). This switch is not compatible with
4095 code generation (it will, among other things, disable some switches such
4096 as -gnatn, and enable others such as -gnata).
4097
4098 @item -gnatd
4099 @cindex @option{-gnatd} (@command{gcc})
4100 Specify debug options for the compiler. The string of characters after
4101 the @option{-gnatd} specify the specific debug options. The possible
4102 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4103 compiler source file @file{debug.adb} for details of the implemented
4104 debug options. Certain debug options are relevant to applications
4105 programmers, and these are documented at appropriate points in this
4106 users guide.
4107
4108 @ifclear vms
4109 @item -gnatD
4110 @cindex @option{-gnatD[nn]} (@command{gcc})
4111 @end ifclear
4112 @ifset vms
4113 @item /XDEBUG /LXDEBUG=nnn
4114 @end ifset
4115 Create expanded source files for source level debugging. This switch
4116 also suppress generation of cross-reference information
4117 (see @option{-gnatx}).
4118
4119 @item -gnatec=@var{path}
4120 @cindex @option{-gnatec} (@command{gcc})
4121 Specify a configuration pragma file
4122 @ifclear vms
4123 (the equal sign is optional)
4124 @end ifclear
4125 (@pxref{The Configuration Pragmas Files}).
4126
4127 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4128 @cindex @option{-gnateD} (@command{gcc})
4129 Defines a symbol, associated with @var{value}, for preprocessing.
4130 (@pxref{Integrated Preprocessing}).
4131
4132 @item -gnatef
4133 @cindex @option{-gnatef} (@command{gcc})
4134 Display full source path name in brief error messages.
4135
4136 @item -gnateG
4137 @cindex @option{-gnateG} (@command{gcc})
4138 Save result of preprocessing in a text file.
4139
4140 @item -gnatem=@var{path}
4141 @cindex @option{-gnatem} (@command{gcc})
4142 Specify a mapping file
4143 @ifclear vms
4144 (the equal sign is optional)
4145 @end ifclear
4146 (@pxref{Units to Sources Mapping Files}).
4147
4148 @item -gnatep=@var{file}
4149 @cindex @option{-gnatep} (@command{gcc})
4150 Specify a preprocessing data file
4151 @ifclear vms
4152 (the equal sign is optional)
4153 @end ifclear
4154 (@pxref{Integrated Preprocessing}).
4155
4156 @item -gnateS
4157 @cindex @option{-gnateS} (@command{gcc})
4158 Generate SCO (Source Coverage Obligation) information in the ALI
4159 file. This information is used by advanced coverage tools. See
4160 unit @file{SCOs} in the compiler sources for details in files
4161 @file{scos.ads} and @file{scos.adb}.
4162
4163 @item -gnatE
4164 @cindex @option{-gnatE} (@command{gcc})
4165 Full dynamic elaboration checks.
4166
4167 @item -gnatf
4168 @cindex @option{-gnatf} (@command{gcc})
4169 Full errors. Multiple errors per line, all undefined references, do not
4170 attempt to suppress cascaded errors.
4171
4172 @item -gnatF
4173 @cindex @option{-gnatF} (@command{gcc})
4174 Externals names are folded to all uppercase.
4175
4176 @item ^-gnatg^/GNAT_INTERNAL^
4177 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4178 Internal GNAT implementation mode. This should not be used for
4179 applications programs, it is intended only for use by the compiler
4180 and its run-time library. For documentation, see the GNAT sources.
4181 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4182 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4183 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4184 so that all standard warnings and all standard style options are turned on.
4185 All warnings and style messages are treated as errors.
4186
4187 @ifclear vms
4188 @item -gnatG=nn
4189 @cindex @option{-gnatG[nn]} (@command{gcc})
4190 @end ifclear
4191 @ifset vms
4192 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4193 @end ifset
4194 List generated expanded code in source form.
4195
4196 @item ^-gnath^/HELP^
4197 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4198 Output usage information. The output is written to @file{stdout}.
4199
4200 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4201 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4202 Identifier character set
4203 @ifclear vms
4204 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4205 @end ifclear
4206 For details of the possible selections for @var{c},
4207 see @ref{Character Set Control}.
4208
4209 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4210 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4211 Ignore representation clauses. When this switch is used,
4212 representation clauses are treated as comments. This is useful
4213 when initially porting code where you want to ignore rep clause
4214 problems, and also for compiling foreign code (particularly
4215 for use with ASIS). The representation clauses that are ignored
4216 are: enumeration_representation_clause, record_representation_clause,
4217 and attribute_definition_clause for the following attributes:
4218 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4219 Object_Size, Size, Small, Stream_Size, and Value_Size.
4220 Note that this option should be used only for compiling -- the
4221 code is likely to malfunction at run time.
4222
4223 @item -gnatjnn
4224 @cindex @option{-gnatjnn} (@command{gcc})
4225 Reformat error messages to fit on nn character lines
4226
4227 @item -gnatk=@var{n}
4228 @cindex @option{-gnatk} (@command{gcc})
4229 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4230
4231 @item -gnatl
4232 @cindex @option{-gnatl} (@command{gcc})
4233 Output full source listing with embedded error messages.
4234
4235 @item -gnatL
4236 @cindex @option{-gnatL} (@command{gcc})
4237 Used in conjunction with -gnatG or -gnatD to intersperse original
4238 source lines (as comment lines with line numbers) in the expanded
4239 source output.
4240
4241 @item -gnatm=@var{n}
4242 @cindex @option{-gnatm} (@command{gcc})
4243 Limit number of detected error or warning messages to @var{n}
4244 where @var{n} is in the range 1..999999. The default setting if
4245 no switch is given is 9999. If the number of warnings reaches this
4246 limit, then a message is output and further warnings are suppressed,
4247 but the compilation is continued. If the number of error messages
4248 reaches this limit, then a message is output and the compilation
4249 is abandoned. The equal sign here is optional. A value of zero
4250 means that no limit applies.
4251
4252 @item -gnatn
4253 @cindex @option{-gnatn} (@command{gcc})
4254 Activate inlining for subprograms for which
4255 pragma @code{inline} is specified. This inlining is performed
4256 by the GCC back-end.
4257
4258 @item -gnatN
4259 @cindex @option{-gnatN} (@command{gcc})
4260 Activate front end inlining for subprograms for which
4261 pragma @code{Inline} is specified. This inlining is performed
4262 by the front end and will be visible in the
4263 @option{-gnatG} output.
4264
4265 When using a gcc-based back end (in practice this means using any version
4266 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4267 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4268 Historically front end inlining was more extensive than the gcc back end
4269 inlining, but that is no longer the case.
4270
4271 @item -gnato
4272 @cindex @option{-gnato} (@command{gcc})
4273 Enable numeric overflow checking (which is not normally enabled by
4274 default). Note that division by zero is a separate check that is not
4275 controlled by this switch (division by zero checking is on by default).
4276
4277 @item -gnatp
4278 @cindex @option{-gnatp} (@command{gcc})
4279 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4280 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4281
4282 @item -gnat-p
4283 @cindex @option{-gnat-p} (@command{gcc})
4284 Cancel effect of previous @option{-gnatp} switch.
4285
4286 @item -gnatP
4287 @cindex @option{-gnatP} (@command{gcc})
4288 Enable polling. This is required on some systems (notably Windows NT) to
4289 obtain asynchronous abort and asynchronous transfer of control capability.
4290 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4291 details.
4292
4293 @item -gnatq
4294 @cindex @option{-gnatq} (@command{gcc})
4295 Don't quit. Try semantics, even if parse errors.
4296
4297 @item -gnatQ
4298 @cindex @option{-gnatQ} (@command{gcc})
4299 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4300
4301 @item -gnatr
4302 @cindex @option{-gnatr} (@command{gcc})
4303 Treat pragma Restrictions as Restriction_Warnings.
4304
4305 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4306 @cindex @option{-gnatR} (@command{gcc})
4307 Output representation information for declared types and objects.
4308
4309 @item -gnats
4310 @cindex @option{-gnats} (@command{gcc})
4311 Syntax check only.
4312
4313 @item -gnatS
4314 @cindex @option{-gnatS} (@command{gcc})
4315 Print package Standard.
4316
4317 @item -gnatt
4318 @cindex @option{-gnatt} (@command{gcc})
4319 Generate tree output file.
4320
4321 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4322 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4323 All compiler tables start at @var{nnn} times usual starting size.
4324
4325 @item -gnatu
4326 @cindex @option{-gnatu} (@command{gcc})
4327 List units for this compilation.
4328
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 Tag all error messages with the unique string ``error:''
4332
4333 @item -gnatv
4334 @cindex @option{-gnatv} (@command{gcc})
4335 Verbose mode. Full error output with source lines to @file{stdout}.
4336
4337 @item -gnatV
4338 @cindex @option{-gnatV} (@command{gcc})
4339 Control level of validity checking (@pxref{Validity Checking}).
4340
4341 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4342 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4343 Warning mode where
4344 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4345 the exact warnings that
4346 are enabled or disabled (@pxref{Warning Message Control}).
4347
4348 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4349 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4350 Wide character encoding method
4351 @ifclear vms
4352 (@var{e}=n/h/u/s/e/8).
4353 @end ifclear
4354 @ifset vms
4355 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4356 @end ifset
4357
4358 @item -gnatx
4359 @cindex @option{-gnatx} (@command{gcc})
4360 Suppress generation of cross-reference information.
4361
4362 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4363 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4364 Enable built-in style checks (@pxref{Style Checking}).
4365
4366 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4367 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4368 Distribution stub generation and compilation
4369 @ifclear vms
4370 (@var{m}=r/c for receiver/caller stubs).
4371 @end ifclear
4372 @ifset vms
4373 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4374 to be generated and compiled).
4375 @end ifset
4376
4377 @item ^-I^/SEARCH=^@var{dir}
4378 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4379 @cindex RTL
4380 Direct GNAT to search the @var{dir} directory for source files needed by
4381 the current compilation
4382 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4383
4384 @item ^-I-^/NOCURRENT_DIRECTORY^
4385 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4386 @cindex RTL
4387 Except for the source file named in the command line, do not look for source
4388 files in the directory containing the source file named in the command line
4389 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4390
4391 @ifclear vms
4392 @item -mbig-switch
4393 @cindex @option{-mbig-switch} (@command{gcc})
4394 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4395 This standard gcc switch causes the compiler to use larger offsets in its
4396 jump table representation for @code{case} statements.
4397 This may result in less efficient code, but is sometimes necessary
4398 (for example on HP-UX targets)
4399 @cindex HP-UX and @option{-mbig-switch} option
4400 in order to compile large and/or nested @code{case} statements.
4401
4402 @item -o @var{file}
4403 @cindex @option{-o} (@command{gcc})
4404 This switch is used in @command{gcc} to redirect the generated object file
4405 and its associated ALI file. Beware of this switch with GNAT, because it may
4406 cause the object file and ALI file to have different names which in turn
4407 may confuse the binder and the linker.
4408 @end ifclear
4409
4410 @item -nostdinc
4411 @cindex @option{-nostdinc} (@command{gcc})
4412 Inhibit the search of the default location for the GNAT Run Time
4413 Library (RTL) source files.
4414
4415 @item -nostdlib
4416 @cindex @option{-nostdlib} (@command{gcc})
4417 Inhibit the search of the default location for the GNAT Run Time
4418 Library (RTL) ALI files.
4419
4420 @ifclear vms
4421 @c @item -O@ovar{n}
4422 @c Expanding @ovar macro inline (explanation in macro def comments)
4423 @item -O@r{[}@var{n}@r{]}
4424 @cindex @option{-O} (@command{gcc})
4425 @var{n} controls the optimization level.
4426
4427 @table @asis
4428 @item n = 0
4429 No optimization, the default setting if no @option{-O} appears
4430
4431 @item n = 1
4432 Normal optimization, the default if you specify @option{-O} without
4433 an operand. A good compromise between code quality and compilation
4434 time.
4435
4436 @item n = 2
4437 Extensive optimization, may improve execution time, possibly at the cost of
4438 substantially increased compilation time.
4439
4440 @item n = 3
4441 Same as @option{-O2}, and also includes inline expansion for small subprograms
4442 in the same unit.
4443
4444 @item n = s
4445 Optimize space usage
4446 @end table
4447
4448 @noindent
4449 See also @ref{Optimization Levels}.
4450 @end ifclear
4451
4452 @ifset vms
4453 @item  /NOOPTIMIZE
4454 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4455 Equivalent to @option{/OPTIMIZE=NONE}.
4456 This is the default behavior in the absence of an @option{/OPTIMIZE}
4457 qualifier.
4458
4459 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4460 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4461 Selects the level of optimization for your program. The supported
4462 keywords are as follows:
4463 @table @code
4464 @item   ALL
4465 Perform most optimizations, including those that
4466 are expensive.
4467 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4468 without keyword options.
4469
4470 @item   NONE
4471 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4472
4473 @item SOME
4474 Perform some optimizations, but omit ones that are costly.
4475
4476 @item   DEVELOPMENT
4477 Same as @code{SOME}.
4478
4479 @item INLINING
4480 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4481 automatic inlining of small subprograms within a unit
4482
4483 @item   UNROLL_LOOPS
4484 Try to unroll loops. This keyword may be specified together with
4485 any keyword above other than @code{NONE}. Loop unrolling
4486 usually, but not always, improves the performance of programs.
4487
4488 @item SPACE
4489 Optimize space usage
4490 @end table
4491
4492 @noindent
4493 See also @ref{Optimization Levels}.
4494 @end ifset
4495
4496 @ifclear vms
4497 @item -pass-exit-codes
4498 @cindex @option{-pass-exit-codes} (@command{gcc})
4499 Catch exit codes from the compiler and use the most meaningful as
4500 exit status.
4501 @end ifclear
4502
4503 @item --RTS=@var{rts-path}
4504 @cindex @option{--RTS} (@command{gcc})
4505 Specifies the default location of the runtime library. Same meaning as the
4506 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4507
4508 @item ^-S^/ASM^
4509 @cindex @option{^-S^/ASM^} (@command{gcc})
4510 ^Used in place of @option{-c} to^Used to^
4511 cause the assembler source file to be
4512 generated, using @file{^.s^.S^} as the extension,
4513 instead of the object file.
4514 This may be useful if you need to examine the generated assembly code.
4515
4516 @item ^-fverbose-asm^/VERBOSE_ASM^
4517 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4518 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4519 to cause the generated assembly code file to be annotated with variable
4520 names, making it significantly easier to follow.
4521
4522 @item ^-v^/VERBOSE^
4523 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4524 Show commands generated by the @command{gcc} driver. Normally used only for
4525 debugging purposes or if you need to be sure what version of the
4526 compiler you are executing.
4527
4528 @ifclear vms
4529 @item -V @var{ver}
4530 @cindex @option{-V} (@command{gcc})
4531 Execute @var{ver} version of the compiler. This is the @command{gcc}
4532 version, not the GNAT version.
4533 @end ifclear
4534
4535 @item ^-w^/NO_BACK_END_WARNINGS^
4536 @cindex @option{-w} (@command{gcc})
4537 Turn off warnings generated by the back end of the compiler. Use of
4538 this switch also causes the default for front end warnings to be set
4539 to suppress (as though @option{-gnatws} had appeared at the start of
4540 the options).
4541
4542 @end table
4543
4544 @ifclear vms
4545 @c Combining qualifiers does not work on VMS
4546 You may combine a sequence of GNAT switches into a single switch. For
4547 example, the combined switch
4548
4549 @cindex Combining GNAT switches
4550 @smallexample
4551 -gnatofi3
4552 @end smallexample
4553
4554 @noindent
4555 is equivalent to specifying the following sequence of switches:
4556
4557 @smallexample
4558 -gnato -gnatf -gnati3
4559 @end smallexample
4560 @end ifclear
4561
4562 @noindent
4563 The following restrictions apply to the combination of switches
4564 in this manner:
4565
4566 @itemize @bullet
4567 @item
4568 The switch @option{-gnatc} if combined with other switches must come
4569 first in the string.
4570
4571 @item
4572 The switch @option{-gnats} if combined with other switches must come
4573 first in the string.
4574
4575 @item
4576 The switches
4577 ^^@option{/DISTRIBUTION_STUBS=},^
4578 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4579 switches, and only one of them may appear in the command line.
4580
4581 @item
4582 The switch @option{-gnat-p} may not be combined with any other switch.
4583
4584 @ifclear vms
4585 @item
4586 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4587 switch), then all further characters in the switch are interpreted
4588 as style modifiers (see description of @option{-gnaty}).
4589
4590 @item
4591 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4592 switch), then all further characters in the switch are interpreted
4593 as debug flags (see description of @option{-gnatd}).
4594
4595 @item
4596 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4597 switch), then all further characters in the switch are interpreted
4598 as warning mode modifiers (see description of @option{-gnatw}).
4599
4600 @item
4601 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4602 switch), then all further characters in the switch are interpreted
4603 as validity checking options (@pxref{Validity Checking}).
4604
4605 @item
4606 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4607 a combined list of options.
4608 @end ifclear
4609 @end itemize
4610
4611 @node Output and Error Message Control
4612 @subsection Output and Error Message Control
4613 @findex stderr
4614
4615 @noindent
4616 The standard default format for error messages is called ``brief format''.
4617 Brief format messages are written to @file{stderr} (the standard error
4618 file) and have the following form:
4619
4620 @smallexample
4621 e.adb:3:04: Incorrect spelling of keyword "function"
4622 e.adb:4:20: ";" should be "is"
4623 @end smallexample
4624
4625 @noindent
4626 The first integer after the file name is the line number in the file,
4627 and the second integer is the column number within the line.
4628 @ifclear vms
4629 @code{GPS} can parse the error messages
4630 and point to the referenced character.
4631 @end ifclear
4632 The following switches provide control over the error message
4633 format:
4634
4635 @table @option
4636 @c !sort!
4637 @item -gnatv
4638 @cindex @option{-gnatv} (@command{gcc})
4639 @findex stdout
4640 @ifclear vms
4641 The v stands for verbose.
4642 @end ifclear
4643 The effect of this setting is to write long-format error
4644 messages to @file{stdout} (the standard output file.
4645 The same program compiled with the
4646 @option{-gnatv} switch would generate:
4647
4648 @smallexample
4649 @cartouche
4650 3. funcion X (Q : Integer)
4651    |
4652 >>> Incorrect spelling of keyword "function"
4653 4. return Integer;
4654                  |
4655 >>> ";" should be "is"
4656 @end cartouche
4657 @end smallexample
4658
4659 @noindent
4660 The vertical bar indicates the location of the error, and the @samp{>>>}
4661 prefix can be used to search for error messages. When this switch is
4662 used the only source lines output are those with errors.
4663
4664 @item -gnatl
4665 @cindex @option{-gnatl} (@command{gcc})
4666 @ifclear vms
4667 The @code{l} stands for list.
4668 @end ifclear
4669 This switch causes a full listing of
4670 the file to be generated. In the case where a body is
4671 compiled, the corresponding spec is also listed, along
4672 with any subunits. Typical output from compiling a package
4673 body @file{p.adb} might look like:
4674
4675 @smallexample @c ada
4676 @cartouche
4677  Compiling: p.adb
4678
4679      1. package body p is
4680      2.    procedure a;
4681      3.    procedure a is separate;
4682      4. begin
4683      5.    null
4684                |
4685         >>> missing ";"
4686
4687      6. end;
4688
4689 Compiling: p.ads
4690
4691      1. package p is
4692      2.    pragma Elaborate_Body
4693                                 |
4694         >>> missing ";"
4695
4696      3. end p;
4697
4698 Compiling: p-a.adb
4699
4700      1. separate p
4701                 |
4702         >>> missing "("
4703
4704      2. procedure a is
4705      3. begin
4706      4.    null
4707                |
4708         >>> missing ";"
4709
4710      5. end;
4711 @end cartouche
4712 @end smallexample
4713
4714 @noindent
4715 @findex stderr
4716 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4717 standard output is redirected, a brief summary is written to
4718 @file{stderr} (standard error) giving the number of error messages and
4719 warning messages generated.
4720
4721 @item -^gnatl^OUTPUT_FILE^=file
4722 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4723 This has the same effect as @option{-gnatl} except that the output is
4724 written to a file instead of to standard output. If the given name
4725 @file{fname} does not start with a period, then it is the full name
4726 of the file to be written. If @file{fname} is an extension, it is
4727 appended to the name of the file being compiled. For example, if
4728 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4729 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4730
4731 @item -gnatU
4732 @cindex @option{-gnatU} (@command{gcc})
4733 This switch forces all error messages to be preceded by the unique
4734 string ``error:''. This means that error messages take a few more
4735 characters in space, but allows easy searching for and identification
4736 of error messages.
4737
4738 @item -gnatb
4739 @cindex @option{-gnatb} (@command{gcc})
4740 @ifclear vms
4741 The @code{b} stands for brief.
4742 @end ifclear
4743 This switch causes GNAT to generate the
4744 brief format error messages to @file{stderr} (the standard error
4745 file) as well as the verbose
4746 format message or full listing (which as usual is written to
4747 @file{stdout} (the standard output file).
4748
4749 @item -gnatm=@var{n}
4750 @cindex @option{-gnatm} (@command{gcc})
4751 @ifclear vms
4752 The @code{m} stands for maximum.
4753 @end ifclear
4754 @var{n} is a decimal integer in the
4755 range of 1 to 999999 and limits the number of error or warning
4756 messages to be generated. For example, using
4757 @option{-gnatm2} might yield
4758
4759 @smallexample
4760 e.adb:3:04: Incorrect spelling of keyword "function"
4761 e.adb:5:35: missing ".."
4762 fatal error: maximum number of errors detected
4763 compilation abandoned
4764 @end smallexample
4765
4766 @noindent
4767 The default setting if
4768 no switch is given is 9999. If the number of warnings reaches this
4769 limit, then a message is output and further warnings are suppressed,
4770 but the compilation is continued. If the number of error messages
4771 reaches this limit, then a message is output and the compilation
4772 is abandoned. A value of zero means that no limit applies.
4773
4774 @noindent
4775 Note that the equal sign is optional, so the switches
4776 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4777
4778 @item -gnatf
4779 @cindex @option{-gnatf} (@command{gcc})
4780 @cindex Error messages, suppressing
4781 @ifclear vms
4782 The @code{f} stands for full.
4783 @end ifclear
4784 Normally, the compiler suppresses error messages that are likely to be
4785 redundant. This switch causes all error
4786 messages to be generated. In particular, in the case of
4787 references to undefined variables. If a given variable is referenced
4788 several times, the normal format of messages is
4789 @smallexample
4790 e.adb:7:07: "V" is undefined (more references follow)
4791 @end smallexample
4792
4793 @noindent
4794 where the parenthetical comment warns that there are additional
4795 references to the variable @code{V}. Compiling the same program with the
4796 @option{-gnatf} switch yields
4797
4798 @smallexample
4799 e.adb:7:07: "V" is undefined
4800 e.adb:8:07: "V" is undefined
4801 e.adb:8:12: "V" is undefined
4802 e.adb:8:16: "V" is undefined
4803 e.adb:9:07: "V" is undefined
4804 e.adb:9:12: "V" is undefined
4805 @end smallexample
4806
4807 @noindent
4808 The @option{-gnatf} switch also generates additional information for
4809 some error messages.  Some examples are:
4810
4811 @itemize @bullet
4812 @item
4813 Details on possibly non-portable unchecked conversion
4814 @item
4815 List possible interpretations for ambiguous calls
4816 @item
4817 Additional details on incorrect parameters
4818 @end itemize
4819
4820 @item -gnatjnn
4821 @cindex @option{-gnatjnn} (@command{gcc})
4822 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4823 with continuation lines are treated as though the continuation lines were
4824 separate messages (and so a warning with two continuation lines counts as
4825 three warnings, and is listed as three separate messages).
4826
4827 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4828 messages are output in a different manner. A message and all its continuation
4829 lines are treated as a unit, and count as only one warning or message in the
4830 statistics totals. Furthermore, the message is reformatted so that no line
4831 is longer than nn characters.
4832
4833 @item -gnatq
4834 @cindex @option{-gnatq} (@command{gcc})
4835 @ifclear vms
4836 The @code{q} stands for quit (really ``don't quit'').
4837 @end ifclear
4838 In normal operation mode, the compiler first parses the program and
4839 determines if there are any syntax errors. If there are, appropriate
4840 error messages are generated and compilation is immediately terminated.
4841 This switch tells
4842 GNAT to continue with semantic analysis even if syntax errors have been
4843 found. This may enable the detection of more errors in a single run. On
4844 the other hand, the semantic analyzer is more likely to encounter some
4845 internal fatal error when given a syntactically invalid tree.
4846
4847 @item -gnatQ
4848 @cindex @option{-gnatQ} (@command{gcc})
4849 In normal operation mode, the @file{ALI} file is not generated if any
4850 illegalities are detected in the program. The use of @option{-gnatQ} forces
4851 generation of the @file{ALI} file. This file is marked as being in
4852 error, so it cannot be used for binding purposes, but it does contain
4853 reasonably complete cross-reference information, and thus may be useful
4854 for use by tools (e.g., semantic browsing tools or integrated development
4855 environments) that are driven from the @file{ALI} file. This switch
4856 implies @option{-gnatq}, since the semantic phase must be run to get a
4857 meaningful ALI file.
4858
4859 In addition, if @option{-gnatt} is also specified, then the tree file is
4860 generated even if there are illegalities. It may be useful in this case
4861 to also specify @option{-gnatq} to ensure that full semantic processing
4862 occurs. The resulting tree file can be processed by ASIS, for the purpose
4863 of providing partial information about illegal units, but if the error
4864 causes the tree to be badly malformed, then ASIS may crash during the
4865 analysis.
4866
4867 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4868 being in error, @command{gnatmake} will attempt to recompile the source when it
4869 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4870
4871 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4872 since ALI files are never generated if @option{-gnats} is set.
4873
4874 @end table
4875
4876 @node Warning Message Control
4877 @subsection Warning Message Control
4878 @cindex Warning messages
4879 @noindent
4880 In addition to error messages, which correspond to illegalities as defined
4881 in the Ada Reference Manual, the compiler detects two kinds of warning
4882 situations.
4883
4884 First, the compiler considers some constructs suspicious and generates a
4885 warning message to alert you to a possible error. Second, if the
4886 compiler detects a situation that is sure to raise an exception at
4887 run time, it generates a warning message. The following shows an example
4888 of warning messages:
4889 @smallexample
4890 e.adb:4:24: warning: creation of object may raise Storage_Error
4891 e.adb:10:17: warning: static value out of range
4892 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4893 @end smallexample
4894
4895 @noindent
4896 GNAT considers a large number of situations as appropriate
4897 for the generation of warning messages. As always, warnings are not
4898 definite indications of errors. For example, if you do an out-of-range
4899 assignment with the deliberate intention of raising a
4900 @code{Constraint_Error} exception, then the warning that may be
4901 issued does not indicate an error. Some of the situations for which GNAT
4902 issues warnings (at least some of the time) are given in the following
4903 list. This list is not complete, and new warnings are often added to
4904 subsequent versions of GNAT. The list is intended to give a general idea
4905 of the kinds of warnings that are generated.
4906
4907 @itemize @bullet
4908 @item
4909 Possible infinitely recursive calls
4910
4911 @item
4912 Out-of-range values being assigned
4913
4914 @item
4915 Possible order of elaboration problems
4916
4917 @item
4918 Assertions (pragma Assert) that are sure to fail
4919
4920 @item
4921 Unreachable code
4922
4923 @item
4924 Address clauses with possibly unaligned values, or where an attempt is
4925 made to overlay a smaller variable with a larger one.
4926
4927 @item
4928 Fixed-point type declarations with a null range
4929
4930 @item
4931 Direct_IO or Sequential_IO instantiated with a type that has access values
4932
4933 @item
4934 Variables that are never assigned a value
4935
4936 @item
4937 Variables that are referenced before being initialized
4938
4939 @item
4940 Task entries with no corresponding @code{accept} statement
4941
4942 @item
4943 Duplicate accepts for the same task entry in a @code{select}
4944
4945 @item
4946 Objects that take too much storage
4947
4948 @item
4949 Unchecked conversion between types of differing sizes
4950
4951 @item
4952 Missing @code{return} statement along some execution path in a function
4953
4954 @item
4955 Incorrect (unrecognized) pragmas
4956
4957 @item
4958 Incorrect external names
4959
4960 @item
4961 Allocation from empty storage pool
4962
4963 @item
4964 Potentially blocking operation in protected type
4965
4966 @item
4967 Suspicious parenthesization of expressions
4968
4969 @item
4970 Mismatching bounds in an aggregate
4971
4972 @item
4973 Attempt to return local value by reference
4974
4975 @item
4976 Premature instantiation of a generic body
4977
4978 @item
4979 Attempt to pack aliased components
4980
4981 @item
4982 Out of bounds array subscripts
4983
4984 @item
4985 Wrong length on string assignment
4986
4987 @item
4988 Violations of style rules if style checking is enabled
4989
4990 @item
4991 Unused @code{with} clauses
4992
4993 @item
4994 @code{Bit_Order} usage that does not have any effect
4995
4996 @item
4997 @code{Standard.Duration} used to resolve universal fixed expression
4998
4999 @item
5000 Dereference of possibly null value
5001
5002 @item
5003 Declaration that is likely to cause storage error
5004
5005 @item
5006 Internal GNAT unit @code{with}'ed by application unit
5007
5008 @item
5009 Values known to be out of range at compile time
5010
5011 @item
5012 Unreferenced labels and variables
5013
5014 @item
5015 Address overlays that could clobber memory
5016
5017 @item
5018 Unexpected initialization when address clause present
5019
5020 @item
5021 Bad alignment for address clause
5022
5023 @item
5024 Useless type conversions
5025
5026 @item
5027 Redundant assignment statements and other redundant constructs
5028
5029 @item
5030 Useless exception handlers
5031
5032 @item
5033 Accidental hiding of name by child unit
5034
5035 @item
5036 Access before elaboration detected at compile time
5037
5038 @item
5039 A range in a @code{for} loop that is known to be null or might be null
5040
5041 @end itemize
5042
5043 @noindent
5044 The following section lists compiler switches that are available
5045 to control the handling of warning messages. It is also possible
5046 to exercise much finer control over what warnings are issued and
5047 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5048 gnat_rm, GNAT Reference manual}.
5049
5050 @table @option
5051 @c !sort!
5052 @item -gnatwa
5053 @emph{Activate all optional errors.}
5054 @cindex @option{-gnatwa} (@command{gcc})
5055 This switch activates most optional warning messages, see remaining list
5056 in this section for details on optional warning messages that can be
5057 individually controlled.  The warnings that are not turned on by this
5058 switch are
5059 @option{-gnatwd} (implicit dereferencing),
5060 @option{-gnatwh} (hiding),
5061 @option{-gnatwl} (elaboration warnings),
5062 @option{-gnatw.o} (warn on values set by out parameters ignored)
5063 and @option{-gnatwt} (tracking of deleted conditional code).
5064 All other optional warnings are turned on.
5065
5066 @item -gnatwA
5067 @emph{Suppress all optional errors.}
5068 @cindex @option{-gnatwA} (@command{gcc})
5069 This switch suppresses all optional warning messages, see remaining list
5070 in this section for details on optional warning messages that can be
5071 individually controlled.
5072
5073 @item -gnatw.a
5074 @emph{Activate warnings on failing assertions.}
5075 @cindex @option{-gnatw.a} (@command{gcc})
5076 @cindex Assert failures
5077 This switch activates warnings for assertions where the compiler can tell at
5078 compile time that the assertion will fail. Note that this warning is given
5079 even if assertions are disabled. The default is that such warnings are
5080 generated.
5081
5082 @item -gnatw.A
5083 @emph{Suppress warnings on failing assertions.}
5084 @cindex @option{-gnatw.A} (@command{gcc})
5085 @cindex Assert failures
5086 This switch suppresses warnings for assertions where the compiler can tell at
5087 compile time that the assertion will fail.
5088
5089 @item -gnatwb
5090 @emph{Activate warnings on bad fixed values.}
5091 @cindex @option{-gnatwb} (@command{gcc})
5092 @cindex Bad fixed values
5093 @cindex Fixed-point Small value
5094 @cindex Small value
5095 This switch activates warnings for static fixed-point expressions whose
5096 value is not an exact multiple of Small. Such values are implementation
5097 dependent, since an implementation is free to choose either of the multiples
5098 that surround the value. GNAT always chooses the closer one, but this is not
5099 required behavior, and it is better to specify a value that is an exact
5100 multiple, ensuring predictable execution. The default is that such warnings
5101 are not generated.
5102
5103 @item -gnatwB
5104 @emph{Suppress warnings on bad fixed values.}
5105 @cindex @option{-gnatwB} (@command{gcc})
5106 This switch suppresses warnings for static fixed-point expressions whose
5107 value is not an exact multiple of Small.
5108
5109 @item -gnatw.b
5110 @emph{Activate warnings on biased representation.}
5111 @cindex @option{-gnatw.b} (@command{gcc})
5112 @cindex Biased representation
5113 This switch activates warnings when a size clause, value size clause, component
5114 clause, or component size clause forces the use of biased representation for an
5115 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5116 to represent 10/11). The default is that such warnings are generated.
5117
5118 @item -gnatw.B
5119 @emph{Suppress warnings on biased representation.}
5120 @cindex @option{-gnatwB} (@command{gcc})
5121 This switch suppresses warnings for representation clauses that force the use
5122 of biased representation.
5123
5124 @item -gnatwc
5125 @emph{Activate warnings on conditionals.}
5126 @cindex @option{-gnatwc} (@command{gcc})
5127 @cindex Conditionals, constant
5128 This switch activates warnings for conditional expressions used in
5129 tests that are known to be True or False at compile time. The default
5130 is that such warnings are not generated.
5131 Note that this warning does
5132 not get issued for the use of boolean variables or constants whose
5133 values are known at compile time, since this is a standard technique
5134 for conditional compilation in Ada, and this would generate too many
5135 false positive warnings.
5136
5137 This warning option also activates a special test for comparisons using
5138 the operators ``>='' and`` <=''.
5139 If the compiler can tell that only the equality condition is possible,
5140 then it will warn that the ``>'' or ``<'' part of the test
5141 is useless and that the operator could be replaced by ``=''.
5142 An example would be comparing a @code{Natural} variable <= 0.
5143
5144 This warning option also generates warnings if
5145 one or both tests is optimized away in a membership test for integer
5146 values if the result can be determined at compile time. Range tests on
5147 enumeration types are not included, since it is common for such tests
5148 to include an end point.
5149
5150 This warning can also be turned on using @option{-gnatwa}.
5151
5152 @item -gnatwC
5153 @emph{Suppress warnings on conditionals.}
5154 @cindex @option{-gnatwC} (@command{gcc})
5155 This switch suppresses warnings for conditional expressions used in
5156 tests that are known to be True or False at compile time.
5157
5158 @item -gnatw.c
5159 @emph{Activate warnings on missing component clauses.}
5160 @cindex @option{-gnatw.c} (@command{gcc})
5161 @cindex Component clause, missing
5162 This switch activates warnings for record components where a record
5163 representation clause is present and has component clauses for the
5164 majority, but not all, of the components. A warning is given for each
5165 component for which no component clause is present.
5166
5167 This warning can also be turned on using @option{-gnatwa}.
5168
5169 @item -gnatw.C
5170 @emph{Suppress warnings on missing component clauses.}
5171 @cindex @option{-gnatwC} (@command{gcc})
5172 This switch suppresses warnings for record components that are
5173 missing a component clause in the situation described above.
5174
5175 @item -gnatwd
5176 @emph{Activate warnings on implicit dereferencing.}
5177 @cindex @option{-gnatwd} (@command{gcc})
5178 If this switch is set, then the use of a prefix of an access type
5179 in an indexed component, slice, or selected component without an
5180 explicit @code{.all} will generate a warning. With this warning
5181 enabled, access checks occur only at points where an explicit
5182 @code{.all} appears in the source code (assuming no warnings are
5183 generated as a result of this switch). The default is that such
5184 warnings are not generated.
5185 Note that @option{-gnatwa} does not affect the setting of
5186 this warning option.
5187
5188 @item -gnatwD
5189 @emph{Suppress warnings on implicit dereferencing.}
5190 @cindex @option{-gnatwD} (@command{gcc})
5191 @cindex Implicit dereferencing
5192 @cindex Dereferencing, implicit
5193 This switch suppresses warnings for implicit dereferences in
5194 indexed components, slices, and selected components.
5195
5196 @item -gnatwe
5197 @emph{Treat warnings and style checks as errors.}
5198 @cindex @option{-gnatwe} (@command{gcc})
5199 @cindex Warnings, treat as error
5200 This switch causes warning messages and style check messages to be
5201 treated as errors.
5202 The warning string still appears, but the warning messages are counted
5203 as errors, and prevent the generation of an object file. Note that this
5204 is the only -gnatw switch that affects the handling of style check messages.
5205
5206 @item -gnatw.e
5207 @emph{Activate every optional warning}
5208 @cindex @option{-gnatw.e} (@command{gcc})
5209 @cindex Warnings, activate every optional warning
5210 This switch activates all optional warnings, including those which
5211 are not activated by @code{-gnatwa}.
5212
5213 @item -gnatwf
5214 @emph{Activate warnings on unreferenced formals.}
5215 @cindex @option{-gnatwf} (@command{gcc})
5216 @cindex Formals, unreferenced
5217 This switch causes a warning to be generated if a formal parameter
5218 is not referenced in the body of the subprogram. This warning can
5219 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5220 default is that these warnings are not generated.
5221
5222 @item -gnatwF
5223 @emph{Suppress warnings on unreferenced formals.}
5224 @cindex @option{-gnatwF} (@command{gcc})
5225 This switch suppresses warnings for unreferenced formal
5226 parameters. Note that the
5227 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5228 effect of warning on unreferenced entities other than subprogram
5229 formals.
5230
5231 @item -gnatwg
5232 @emph{Activate warnings on unrecognized pragmas.}
5233 @cindex @option{-gnatwg} (@command{gcc})
5234 @cindex Pragmas, unrecognized
5235 This switch causes a warning to be generated if an unrecognized
5236 pragma is encountered. Apart from issuing this warning, the
5237 pragma is ignored and has no effect. This warning can
5238 also be turned on using @option{-gnatwa}. The default
5239 is that such warnings are issued (satisfying the Ada Reference
5240 Manual requirement that such warnings appear).
5241
5242 @item -gnatwG
5243 @emph{Suppress warnings on unrecognized pragmas.}
5244 @cindex @option{-gnatwG} (@command{gcc})
5245 This switch suppresses warnings for unrecognized pragmas.
5246
5247 @item -gnatwh
5248 @emph{Activate warnings on hiding.}
5249 @cindex @option{-gnatwh} (@command{gcc})
5250 @cindex Hiding of Declarations
5251 This switch activates warnings on hiding declarations.
5252 A declaration is considered hiding
5253 if it is for a non-overloadable entity, and it declares an entity with the
5254 same name as some other entity that is directly or use-visible. The default
5255 is that such warnings are not generated.
5256 Note that @option{-gnatwa} does not affect the setting of this warning option.
5257
5258 @item -gnatwH
5259 @emph{Suppress warnings on hiding.}
5260 @cindex @option{-gnatwH} (@command{gcc})
5261 This switch suppresses warnings on hiding declarations.
5262
5263 @item -gnatwi
5264 @emph{Activate warnings on implementation units.}
5265 @cindex @option{-gnatwi} (@command{gcc})
5266 This switch activates warnings for a @code{with} of an internal GNAT
5267 implementation unit, defined as any unit from the @code{Ada},
5268 @code{Interfaces}, @code{GNAT},
5269 ^^@code{DEC},^ or @code{System}
5270 hierarchies that is not
5271 documented in either the Ada Reference Manual or the GNAT
5272 Programmer's Reference Manual. Such units are intended only
5273 for internal implementation purposes and should not be @code{with}'ed
5274 by user programs. The default is that such warnings are generated
5275 This warning can also be turned on using @option{-gnatwa}.
5276
5277 @item -gnatwI
5278 @emph{Disable warnings on implementation units.}
5279 @cindex @option{-gnatwI} (@command{gcc})
5280 This switch disables warnings for a @code{with} of an internal GNAT
5281 implementation unit.
5282
5283 @item -gnatw.i
5284 @emph{Activate warnings on overlapping actuals.}
5285 @cindex @option{-gnatw.i} (@command{gcc})
5286 This switch enables a warning on statically detectable overlapping actuals in
5287 a subprogram call, when one of the actuals is an in-out parameter, and the
5288 types of the actuals are not by-copy types. The warning is off by default,
5289 and is not included under -gnatwa.
5290
5291 @item -gnatw.I
5292 @emph{Disable warnings on overlapping actuals.}
5293 @cindex @option{-gnatw.I} (@command{gcc})
5294 This switch disables warnings on overlapping actuals in a call..
5295
5296 @item -gnatwj
5297 @emph{Activate warnings on obsolescent features (Annex J).}
5298 @cindex @option{-gnatwj} (@command{gcc})
5299 @cindex Features, obsolescent
5300 @cindex Obsolescent features
5301 If this warning option is activated, then warnings are generated for
5302 calls to subprograms marked with @code{pragma Obsolescent} and
5303 for use of features in Annex J of the Ada Reference Manual. In the
5304 case of Annex J, not all features are flagged. In particular use
5305 of the renamed packages (like @code{Text_IO}) and use of package
5306 @code{ASCII} are not flagged, since these are very common and
5307 would generate many annoying positive warnings. The default is that
5308 such warnings are not generated. This warning is also turned on by
5309 the use of @option{-gnatwa}.
5310
5311 In addition to the above cases, warnings are also generated for
5312 GNAT features that have been provided in past versions but which
5313 have been superseded (typically by features in the new Ada standard).
5314 For example, @code{pragma Ravenscar} will be flagged since its
5315 function is replaced by @code{pragma Profile(Ravenscar)}.
5316
5317 Note that this warning option functions differently from the
5318 restriction @code{No_Obsolescent_Features} in two respects.
5319 First, the restriction applies only to annex J features.
5320 Second, the restriction does flag uses of package @code{ASCII}.
5321
5322 @item -gnatwJ
5323 @emph{Suppress warnings on obsolescent features (Annex J).}
5324 @cindex @option{-gnatwJ} (@command{gcc})
5325 This switch disables warnings on use of obsolescent features.
5326
5327 @item -gnatwk
5328 @emph{Activate warnings on variables that could be constants.}
5329 @cindex @option{-gnatwk} (@command{gcc})
5330 This switch activates warnings for variables that are initialized but
5331 never modified, and then could be declared constants. The default is that
5332 such warnings are not given.
5333 This warning can also be turned on using @option{-gnatwa}.
5334
5335 @item -gnatwK
5336 @emph{Suppress warnings on variables that could be constants.}
5337 @cindex @option{-gnatwK} (@command{gcc})
5338 This switch disables warnings on variables that could be declared constants.
5339
5340 @item -gnatwl
5341 @emph{Activate warnings for elaboration pragmas.}
5342 @cindex @option{-gnatwl} (@command{gcc})
5343 @cindex Elaboration, warnings
5344 This switch activates warnings on missing
5345 @code{Elaborate_All} and @code{Elaborate} pragmas.
5346 See the section in this guide on elaboration checking for details on
5347 when such pragmas should be used. In dynamic elaboration mode, this switch
5348 generations warnings about the need to add elaboration pragmas. Note however,
5349 that if you blindly follow these warnings, and add @code{Elaborate_All}
5350 warnings wherever they are recommended, you basically end up with the
5351 equivalent of the static elaboration model, which may not be what you want for
5352 legacy code for which the static model does not work.
5353
5354 For the static model, the messages generated are labeled "info:" (for
5355 information messages). They are not warnings to add elaboration pragmas,
5356 merely informational messages showing what implicit elaboration pragmas
5357 have been added, for use in analyzing elaboration circularity problems.
5358
5359 Warnings are also generated if you
5360 are using the static mode of elaboration, and a @code{pragma Elaborate}
5361 is encountered. The default is that such warnings
5362 are not generated.
5363 This warning is not automatically turned on by the use of @option{-gnatwa}.
5364
5365 @item -gnatwL
5366 @emph{Suppress warnings for elaboration pragmas.}
5367 @cindex @option{-gnatwL} (@command{gcc})
5368 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5369 See the section in this guide on elaboration checking for details on
5370 when such pragmas should be used.
5371
5372 @item -gnatwm
5373 @emph{Activate warnings on modified but unreferenced variables.}
5374 @cindex @option{-gnatwm} (@command{gcc})
5375 This switch activates warnings for variables that are assigned (using
5376 an initialization value or with one or more assignment statements) but
5377 whose value is never read. The warning is suppressed for volatile
5378 variables and also for variables that are renamings of other variables
5379 or for which an address clause is given.
5380 This warning can also be turned on using @option{-gnatwa}.
5381 The default is that these warnings are not given.
5382
5383 @item -gnatwM
5384 @emph{Disable warnings on modified but unreferenced variables.}
5385 @cindex @option{-gnatwM} (@command{gcc})
5386 This switch disables warnings for variables that are assigned or
5387 initialized, but never read.
5388
5389 @item -gnatw.m
5390 @emph{Activate warnings on suspicious modulus values.}
5391 @cindex @option{-gnatw.m} (@command{gcc})
5392 This switch activates warnings for modulus values that seem suspicious.
5393 The cases caught are where the size is the same as the modulus (e.g.
5394 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5395 with no size clause. The guess in both cases is that 2**x was intended
5396 rather than x. The default is that these warnings are given.
5397
5398 @item -gnatw.M
5399 @emph{Disable warnings on suspicious modulus values.}
5400 @cindex @option{-gnatw.M} (@command{gcc})
5401 This switch disables warnings for suspicious modulus values.
5402
5403 @item -gnatwn
5404 @emph{Set normal warnings mode.}
5405 @cindex @option{-gnatwn} (@command{gcc})
5406 This switch sets normal warning mode, in which enabled warnings are
5407 issued and treated as warnings rather than errors. This is the default
5408 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5409 an explicit @option{-gnatws} or
5410 @option{-gnatwe}. It also cancels the effect of the
5411 implicit @option{-gnatwe} that is activated by the
5412 use of @option{-gnatg}.
5413
5414 @item -gnatwo
5415 @emph{Activate warnings on address clause overlays.}
5416 @cindex @option{-gnatwo} (@command{gcc})
5417 @cindex Address Clauses, warnings
5418 This switch activates warnings for possibly unintended initialization
5419 effects of defining address clauses that cause one variable to overlap
5420 another. The default is that such warnings are generated.
5421 This warning can also be turned on using @option{-gnatwa}.
5422
5423 @item -gnatwO
5424 @emph{Suppress warnings on address clause overlays.}
5425 @cindex @option{-gnatwO} (@command{gcc})
5426 This switch suppresses warnings on possibly unintended initialization
5427 effects of defining address clauses that cause one variable to overlap
5428 another.
5429
5430 @item -gnatw.o
5431 @emph{Activate warnings on modified but unreferenced out parameters.}
5432 @cindex @option{-gnatw.o} (@command{gcc})
5433 This switch activates warnings for variables that are modified by using
5434 them as actuals for a call to a procedure with an out mode formal, where
5435 the resulting assigned value is never read. It is applicable in the case
5436 where there is more than one out mode formal. If there is only one out
5437 mode formal, the warning is issued by default (controlled by -gnatwu).
5438 The warning is suppressed for volatile
5439 variables and also for variables that are renamings of other variables
5440 or for which an address clause is given.
5441 The default is that these warnings are not given. Note that this warning
5442 is not included in -gnatwa, it must be activated explicitly.
5443
5444 @item -gnatw.O
5445 @emph{Disable warnings on modified but unreferenced out parameters.}
5446 @cindex @option{-gnatw.O} (@command{gcc})
5447 This switch suppresses warnings for variables that are modified by using
5448 them as actuals for a call to a procedure with an out mode formal, where
5449 the resulting assigned value is never read.
5450
5451 @item -gnatwp
5452 @emph{Activate warnings on ineffective pragma Inlines.}
5453 @cindex @option{-gnatwp} (@command{gcc})
5454 @cindex Inlining, warnings
5455 This switch activates warnings for failure of front end inlining
5456 (activated by @option{-gnatN}) to inline a particular call. There are
5457 many reasons for not being able to inline a call, including most
5458 commonly that the call is too complex to inline. The default is
5459 that such warnings are not given.
5460 This warning can also be turned on using @option{-gnatwa}.
5461 Warnings on ineffective inlining by the gcc back-end can be activated
5462 separately, using the gcc switch -Winline.
5463
5464 @item -gnatwP
5465 @emph{Suppress warnings on ineffective pragma Inlines.}
5466 @cindex @option{-gnatwP} (@command{gcc})
5467 This switch suppresses warnings on ineffective pragma Inlines. If the
5468 inlining mechanism cannot inline a call, it will simply ignore the
5469 request silently.
5470
5471 @item -gnatw.p
5472 @emph{Activate warnings on parameter ordering.}
5473 @cindex @option{-gnatw.p} (@command{gcc})
5474 @cindex Parameter order, warnings
5475 This switch activates warnings for cases of suspicious parameter
5476 ordering when the list of arguments are all simple identifiers that
5477 match the names of the formals, but are in a different order. The
5478 warning is suppressed if any use of named parameter notation is used,
5479 so this is the appropriate way to suppress a false positive (and
5480 serves to emphasize that the "misordering" is deliberate). The
5481 default is
5482 that such warnings are not given.
5483 This warning can also be turned on using @option{-gnatwa}.
5484
5485 @item -gnatw.P
5486 @emph{Suppress warnings on parameter ordering.}
5487 @cindex @option{-gnatw.P} (@command{gcc})
5488 This switch suppresses warnings on cases of suspicious parameter
5489 ordering.
5490
5491 @item -gnatwq
5492 @emph{Activate warnings on questionable missing parentheses.}
5493 @cindex @option{-gnatwq} (@command{gcc})
5494 @cindex Parentheses, warnings
5495 This switch activates warnings for cases where parentheses are not used and
5496 the result is potential ambiguity from a readers point of view. For example
5497 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5498 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5499 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5500 follow the rule of always parenthesizing to make the association clear, and
5501 this warning switch warns if such parentheses are not present. The default
5502 is that these warnings are given.
5503 This warning can also be turned on using @option{-gnatwa}.
5504
5505 @item -gnatwQ
5506 @emph{Suppress warnings on questionable missing parentheses.}
5507 @cindex @option{-gnatwQ} (@command{gcc})
5508 This switch suppresses warnings for cases where the association is not
5509 clear and the use of parentheses is preferred.
5510
5511 @item -gnatwr
5512 @emph{Activate warnings on redundant constructs.}
5513 @cindex @option{-gnatwr} (@command{gcc})
5514 This switch activates warnings for redundant constructs. The following
5515 is the current list of constructs regarded as redundant:
5516
5517 @itemize @bullet
5518 @item
5519 Assignment of an item to itself.
5520 @item
5521 Type conversion that converts an expression to its own type.
5522 @item
5523 Use of the attribute @code{Base} where @code{typ'Base} is the same
5524 as @code{typ}.
5525 @item
5526 Use of pragma @code{Pack} when all components are placed by a record
5527 representation clause.
5528 @item
5529 Exception handler containing only a reraise statement (raise with no
5530 operand) which has no effect.
5531 @item
5532 Use of the operator abs on an operand that is known at compile time
5533 to be non-negative
5534 @item
5535 Comparison of boolean expressions to an explicit True value.
5536 @end itemize
5537
5538 This warning can also be turned on using @option{-gnatwa}.
5539 The default is that warnings for redundant constructs are not given.
5540
5541 @item -gnatwR
5542 @emph{Suppress warnings on redundant constructs.}
5543 @cindex @option{-gnatwR} (@command{gcc})
5544 This switch suppresses warnings for redundant constructs.
5545
5546 @item -gnatw.r
5547 @emph{Activate warnings for object renaming function.}
5548 @cindex @option{-gnatw.r} (@command{gcc})
5549 This switch activates warnings for an object renaming that renames a
5550 function call, which is equivalent to a constant declaration (as
5551 opposed to renaming the function itself).  The default is that these
5552 warnings are given.  This warning can also be turned on using
5553 @option{-gnatwa}.
5554
5555 @item -gnatw.R
5556 @emph{Suppress warnings for object renaming function.}
5557 @cindex @option{-gnatwT} (@command{gcc})
5558 This switch suppresses warnings for object renaming function.
5559
5560 @item -gnatws
5561 @emph{Suppress all warnings.}
5562 @cindex @option{-gnatws} (@command{gcc})
5563 This switch completely suppresses the
5564 output of all warning messages from the GNAT front end.
5565 Note that it does not suppress warnings from the @command{gcc} back end.
5566 To suppress these back end warnings as well, use the switch @option{-w}
5567 in addition to @option{-gnatws}. Also this switch has no effect on the
5568 handling of style check messages.
5569
5570 @item -gnatwt
5571 @emph{Activate warnings for tracking of deleted conditional code.}
5572 @cindex @option{-gnatwt} (@command{gcc})
5573 @cindex Deactivated code, warnings
5574 @cindex Deleted code, warnings
5575 This switch activates warnings for tracking of code in conditionals (IF and
5576 CASE statements) that is detected to be dead code which cannot be executed, and
5577 which is removed by the front end. This warning is off by default, and is not
5578 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5579 useful for detecting deactivated code in certified applications.
5580
5581 @item -gnatwT
5582 @emph{Suppress warnings for tracking of deleted conditional code.}
5583 @cindex @option{-gnatwT} (@command{gcc})
5584 This switch suppresses warnings for tracking of deleted conditional code.
5585
5586 @item -gnatwu
5587 @emph{Activate warnings on unused entities.}
5588 @cindex @option{-gnatwu} (@command{gcc})
5589 This switch activates warnings to be generated for entities that
5590 are declared but not referenced, and for units that are @code{with}'ed
5591 and not
5592 referenced. In the case of packages, a warning is also generated if
5593 no entities in the package are referenced. This means that if the package
5594 is referenced but the only references are in @code{use}
5595 clauses or @code{renames}
5596 declarations, a warning is still generated. A warning is also generated
5597 for a generic package that is @code{with}'ed but never instantiated.
5598 In the case where a package or subprogram body is compiled, and there
5599 is a @code{with} on the corresponding spec
5600 that is only referenced in the body,
5601 a warning is also generated, noting that the
5602 @code{with} can be moved to the body. The default is that
5603 such warnings are not generated.
5604 This switch also activates warnings on unreferenced formals
5605 (it includes the effect of @option{-gnatwf}).
5606 This warning can also be turned on using @option{-gnatwa}.
5607
5608 @item -gnatwU
5609 @emph{Suppress warnings on unused entities.}
5610 @cindex @option{-gnatwU} (@command{gcc})
5611 This switch suppresses warnings for unused entities and packages.
5612 It also turns off warnings on unreferenced formals (and thus includes
5613 the effect of @option{-gnatwF}).
5614
5615 @item -gnatwv
5616 @emph{Activate warnings on unassigned variables.}
5617 @cindex @option{-gnatwv} (@command{gcc})
5618 @cindex Unassigned variable warnings
5619 This switch activates warnings for access to variables which
5620 may not be properly initialized. The default is that
5621 such warnings are generated.
5622 This warning can also be turned on using @option{-gnatwa}.
5623
5624 @item -gnatwV
5625 @emph{Suppress warnings on unassigned variables.}
5626 @cindex @option{-gnatwV} (@command{gcc})
5627 This switch suppresses warnings for access to variables which
5628 may not be properly initialized.
5629 For variables of a composite type, the warning can also be suppressed in
5630 Ada 2005 by using a default initialization with a box. For example, if
5631 Table is an array of records whose components are only partially uninitialized,
5632 then the following code:
5633
5634 @smallexample @c ada
5635    Tab : Table := (others => <>);
5636 @end smallexample
5637
5638 will suppress warnings on subsequent statements that access components
5639 of variable Tab.
5640
5641 @item -gnatww
5642 @emph{Activate warnings on wrong low bound assumption.}
5643 @cindex @option{-gnatww} (@command{gcc})
5644 @cindex String indexing warnings
5645 This switch activates warnings for indexing an unconstrained string parameter
5646 with a literal or S'Length. This is a case where the code is assuming that the
5647 low bound is one, which is in general not true (for example when a slice is
5648 passed). The default is that such warnings are generated.
5649 This warning can also be turned on using @option{-gnatwa}.
5650
5651 @item -gnatwW
5652 @emph{Suppress warnings on wrong low bound assumption.}
5653 @cindex @option{-gnatwW} (@command{gcc})
5654 This switch suppresses warnings for indexing an unconstrained string parameter
5655 with a literal or S'Length. Note that this warning can also be suppressed
5656 in a particular case by adding an
5657 assertion that the lower bound is 1,
5658 as shown in the following example.
5659
5660 @smallexample @c ada
5661    procedure K (S : String) is
5662       pragma Assert (S'First = 1);
5663       @dots{}
5664 @end smallexample
5665
5666 @item -gnatw.w
5667 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5668 @cindex @option{-gnatw.w} (@command{gcc})
5669 @cindex Warnings Off control
5670 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5671 where either the pragma is entirely useless (because it suppresses no
5672 warnings), or it could be replaced by @code{pragma Unreferenced} or
5673 @code{pragma Unmodified}.The default is that these warnings are not given.
5674 Note that this warning is not included in -gnatwa, it must be
5675 activated explicitly.
5676
5677 @item -gnatw.W
5678 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5679 @cindex @option{-gnatw.W} (@command{gcc})
5680 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5681
5682 @item -gnatwx
5683 @emph{Activate warnings on Export/Import pragmas.}
5684 @cindex @option{-gnatwx} (@command{gcc})
5685 @cindex Export/Import pragma warnings
5686 This switch activates warnings on Export/Import pragmas when
5687 the compiler detects a possible conflict between the Ada and
5688 foreign language calling sequences. For example, the use of
5689 default parameters in a convention C procedure is dubious
5690 because the C compiler cannot supply the proper default, so
5691 a warning is issued. The default is that such warnings are
5692 generated.
5693 This warning can also be turned on using @option{-gnatwa}.
5694
5695 @item -gnatwX
5696 @emph{Suppress warnings on Export/Import pragmas.}
5697 @cindex @option{-gnatwX} (@command{gcc})
5698 This switch suppresses warnings on Export/Import pragmas.
5699 The sense of this is that you are telling the compiler that
5700 you know what you are doing in writing the pragma, and it
5701 should not complain at you.
5702
5703 @item -gnatw.x
5704 @emph{Activate warnings for No_Exception_Propagation mode.}
5705 @cindex @option{-gnatwm} (@command{gcc})
5706 This switch activates warnings for exception usage when pragma Restrictions
5707 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5708 explicit exception raises which are not covered by a local handler, and for
5709 exception handlers which do not cover a local raise. The default is that these
5710 warnings are not given.
5711
5712 @item -gnatw.X
5713 @emph{Disable warnings for No_Exception_Propagation mode.}
5714 This switch disables warnings for exception usage when pragma Restrictions
5715 (No_Exception_Propagation) is in effect.
5716
5717 @item -gnatwy
5718 @emph{Activate warnings for Ada 2005 compatibility issues.}
5719 @cindex @option{-gnatwy} (@command{gcc})
5720 @cindex Ada 2005 compatibility issues warnings
5721 For the most part Ada 2005 is upwards compatible with Ada 95,
5722 but there are some exceptions (for example the fact that
5723 @code{interface} is now a reserved word in Ada 2005). This
5724 switch activates several warnings to help in identifying
5725 and correcting such incompatibilities. The default is that
5726 these warnings are generated. Note that at one point Ada 2005
5727 was called Ada 0Y, hence the choice of character.
5728 This warning can also be turned on using @option{-gnatwa}.
5729
5730 @item -gnatwY
5731 @emph{Disable warnings for Ada 2005 compatibility issues.}
5732 @cindex @option{-gnatwY} (@command{gcc})
5733 @cindex Ada 2005 compatibility issues warnings
5734 This switch suppresses several warnings intended to help in identifying
5735 incompatibilities between Ada 95 and Ada 2005.
5736
5737 @item -gnatwz
5738 @emph{Activate warnings on unchecked conversions.}
5739 @cindex @option{-gnatwz} (@command{gcc})
5740 @cindex Unchecked_Conversion warnings
5741 This switch activates warnings for unchecked conversions
5742 where the types are known at compile time to have different
5743 sizes. The default
5744 is that such warnings are generated. Warnings are also
5745 generated for subprogram pointers with different conventions,
5746 and, on VMS only, for data pointers with different conventions.
5747 This warning can also be turned on using @option{-gnatwa}.
5748
5749 @item -gnatwZ
5750 @emph{Suppress warnings on unchecked conversions.}
5751 @cindex @option{-gnatwZ} (@command{gcc})
5752 This switch suppresses warnings for unchecked conversions
5753 where the types are known at compile time to have different
5754 sizes or conventions.
5755
5756 @item ^-Wunused^WARNINGS=UNUSED^
5757 @cindex @option{-Wunused}
5758 The warnings controlled by the @option{-gnatw} switch are generated by
5759 the front end of the compiler. The @option{GCC} back end can provide
5760 additional warnings and they are controlled by the @option{-W} switch.
5761 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5762 warnings for entities that are declared but not referenced.
5763
5764 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5765 @cindex @option{-Wuninitialized}
5766 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5767 the back end warning for uninitialized variables. This switch must be
5768 used in conjunction with an optimization level greater than zero.
5769
5770 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5771 @cindex @option{-Wall}
5772 This switch enables all the above warnings from the @option{GCC} back end.
5773 The code generator detects a number of warning situations that are missed
5774 by the @option{GNAT} front end, and this switch can be used to activate them.
5775 The use of this switch also sets the default front end warning mode to
5776 @option{-gnatwa}, that is, most front end warnings activated as well.
5777
5778 @item ^-w^/NO_BACK_END_WARNINGS^
5779 @cindex @option{-w}
5780 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5781 The use of this switch also sets the default front end warning mode to
5782 @option{-gnatws}, that is, front end warnings suppressed as well.
5783
5784 @end table
5785
5786 @noindent
5787 @ifclear vms
5788 A string of warning parameters can be used in the same parameter. For example:
5789
5790 @smallexample
5791 -gnatwaLe
5792 @end smallexample
5793
5794 @noindent
5795 will turn on all optional warnings except for elaboration pragma warnings,
5796 and also specify that warnings should be treated as errors.
5797 @end ifclear
5798 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5799
5800 @table @option
5801 @c !sort!
5802 @item -gnatwC
5803 @item -gnatwD
5804 @item -gnatwF
5805 @item -gnatwg
5806 @item -gnatwH
5807 @item -gnatwi
5808 @item -gnatwJ
5809 @item -gnatwK
5810 @item -gnatwL
5811 @item -gnatwM
5812 @item -gnatwn
5813 @item -gnatwo
5814 @item -gnatwP
5815 @item -gnatwR
5816 @item -gnatwU
5817 @item -gnatwv
5818 @item -gnatwz
5819 @item -gnatwx
5820
5821 @end table
5822
5823 @node Debugging and Assertion Control
5824 @subsection Debugging and Assertion Control
5825
5826 @table @option
5827 @item -gnata
5828 @cindex @option{-gnata} (@command{gcc})
5829 @findex Assert
5830 @findex Debug
5831 @cindex Assertions
5832
5833 @noindent
5834 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5835 are ignored. This switch, where @samp{a} stands for assert, causes
5836 @code{Assert} and @code{Debug} pragmas to be activated.
5837
5838 The pragmas have the form:
5839
5840 @smallexample
5841 @cartouche
5842    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5843                       @var{static-string-expression}@r{]})
5844    @b{pragma} Debug (@var{procedure call})
5845 @end cartouche
5846 @end smallexample
5847
5848 @noindent
5849 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5850 If the result is @code{True}, the pragma has no effect (other than
5851 possible side effects from evaluating the expression). If the result is
5852 @code{False}, the exception @code{Assert_Failure} declared in the package
5853 @code{System.Assertions} is
5854 raised (passing @var{static-string-expression}, if present, as the
5855 message associated with the exception). If no string expression is
5856 given the default is a string giving the file name and line number
5857 of the pragma.
5858
5859 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5860 @code{pragma Debug} may appear within a declaration sequence, allowing
5861 debugging procedures to be called between declarations.
5862
5863 @ifset vms
5864 @item /DEBUG@r{[}=debug-level@r{]}
5865 @itemx  /NODEBUG
5866 Specifies how much debugging information is to be included in
5867 the resulting object file where 'debug-level' is one of the following:
5868 @table @code
5869 @item   TRACEBACK
5870 Include both debugger symbol records and traceback
5871 the object file.
5872 This is the default setting.
5873 @item   ALL
5874 Include both debugger symbol records and traceback in
5875 object file.
5876 @item   NONE
5877 Excludes both debugger symbol records and traceback
5878 the object file. Same as /NODEBUG.
5879 @item   SYMBOLS
5880 Includes only debugger symbol records in the object
5881 file. Note that this doesn't include traceback information.
5882 @end table
5883 @end ifset
5884 @end table
5885
5886 @node Validity Checking
5887 @subsection Validity Checking
5888 @findex Validity Checking
5889
5890 @noindent
5891 The Ada Reference Manual defines the concept of invalid values (see
5892 RM 13.9.1). The primary source of invalid values is uninitialized
5893 variables. A scalar variable that is left uninitialized may contain
5894 an invalid value; the concept of invalid does not apply to access or
5895 composite types.
5896
5897 It is an error to read an invalid value, but the RM does not require
5898 run-time checks to detect such errors, except for some minimal
5899 checking to prevent erroneous execution (i.e. unpredictable
5900 behavior). This corresponds to the @option{-gnatVd} switch below,
5901 which is the default. For example, by default, if the expression of a
5902 case statement is invalid, it will raise Constraint_Error rather than
5903 causing a wild jump, and if an array index on the left-hand side of an
5904 assignment is invalid, it will raise Constraint_Error rather than
5905 overwriting an arbitrary memory location.
5906
5907 The @option{-gnatVa} may be used to enable additional validity checks,
5908 which are not required by the RM. These checks are often very
5909 expensive (which is why the RM does not require them). These checks
5910 are useful in tracking down uninitialized variables, but they are
5911 not usually recommended for production builds.
5912
5913 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5914 control; you can enable whichever validity checks you desire. However,
5915 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5916 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5917 sufficient for non-debugging use.
5918
5919 The @option{-gnatB} switch tells the compiler to assume that all
5920 values are valid (that is, within their declared subtype range)
5921 except in the context of a use of the Valid attribute. This means
5922 the compiler can generate more efficient code, since the range
5923 of values is better known at compile time. However, an uninitialized
5924 variable can cause wild jumps and memory corruption in this mode.
5925
5926 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5927 checking mode as described below.
5928 @ifclear vms
5929 The @code{x} argument is a string of letters that
5930 indicate validity checks that are performed or not performed in addition
5931 to the default checks required by Ada as described above.
5932 @end ifclear
5933 @ifset vms
5934 The options allowed for this qualifier
5935 indicate validity checks that are performed or not performed in addition
5936 to the default checks required by Ada as described above.
5937 @end ifset
5938
5939 @table @option
5940 @c !sort!
5941 @item -gnatVa
5942 @emph{All validity checks.}
5943 @cindex @option{-gnatVa} (@command{gcc})
5944 All validity checks are turned on.
5945 @ifclear vms
5946 That is, @option{-gnatVa} is
5947 equivalent to @option{gnatVcdfimorst}.
5948 @end ifclear
5949
5950 @item -gnatVc
5951 @emph{Validity checks for copies.}
5952 @cindex @option{-gnatVc} (@command{gcc})
5953 The right hand side of assignments, and the initializing values of
5954 object declarations are validity checked.
5955
5956 @item -gnatVd
5957 @emph{Default (RM) validity checks.}
5958 @cindex @option{-gnatVd} (@command{gcc})
5959 Some validity checks are done by default following normal Ada semantics
5960 (RM 13.9.1 (9-11)).
5961 A check is done in case statements that the expression is within the range
5962 of the subtype. If it is not, Constraint_Error is raised.
5963 For assignments to array components, a check is done that the expression used
5964 as index is within the range. If it is not, Constraint_Error is raised.
5965 Both these validity checks may be turned off using switch @option{-gnatVD}.
5966 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5967 switch @option{-gnatVd} will leave the checks turned on.
5968 Switch @option{-gnatVD} should be used only if you are sure that all such
5969 expressions have valid values. If you use this switch and invalid values
5970 are present, then the program is erroneous, and wild jumps or memory
5971 overwriting may occur.
5972
5973 @item -gnatVe
5974 @emph{Validity checks for elementary components.}
5975 @cindex @option{-gnatVe} (@command{gcc})
5976 In the absence of this switch, assignments to record or array components are
5977 not validity checked, even if validity checks for assignments generally
5978 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5979 require valid data, but assignment of individual components does. So for
5980 example, there is a difference between copying the elements of an array with a
5981 slice assignment, compared to assigning element by element in a loop. This
5982 switch allows you to turn off validity checking for components, even when they
5983 are assigned component by component.
5984
5985 @item -gnatVf
5986 @emph{Validity checks for floating-point values.}
5987 @cindex @option{-gnatVf} (@command{gcc})
5988 In the absence of this switch, validity checking occurs only for discrete
5989 values. If @option{-gnatVf} is specified, then validity checking also applies
5990 for floating-point values, and NaNs and infinities are considered invalid,
5991 as well as out of range values for constrained types. Note that this means
5992 that standard IEEE infinity mode is not allowed. The exact contexts
5993 in which floating-point values are checked depends on the setting of other
5994 options. For example,
5995 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5996 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5997 (the order does not matter) specifies that floating-point parameters of mode
5998 @code{in} should be validity checked.
5999
6000 @item -gnatVi
6001 @emph{Validity checks for @code{in} mode parameters}
6002 @cindex @option{-gnatVi} (@command{gcc})
6003 Arguments for parameters of mode @code{in} are validity checked in function
6004 and procedure calls at the point of call.
6005
6006 @item -gnatVm
6007 @emph{Validity checks for @code{in out} mode parameters.}
6008 @cindex @option{-gnatVm} (@command{gcc})
6009 Arguments for parameters of mode @code{in out} are validity checked in
6010 procedure calls at the point of call. The @code{'m'} here stands for
6011 modify, since this concerns parameters that can be modified by the call.
6012 Note that there is no specific option to test @code{out} parameters,
6013 but any reference within the subprogram will be tested in the usual
6014 manner, and if an invalid value is copied back, any reference to it
6015 will be subject to validity checking.
6016
6017 @item -gnatVn
6018 @emph{No validity checks.}
6019 @cindex @option{-gnatVn} (@command{gcc})
6020 This switch turns off all validity checking, including the default checking
6021 for case statements and left hand side subscripts. Note that the use of
6022 the switch @option{-gnatp} suppresses all run-time checks, including
6023 validity checks, and thus implies @option{-gnatVn}. When this switch
6024 is used, it cancels any other @option{-gnatV} previously issued.
6025
6026 @item -gnatVo
6027 @emph{Validity checks for operator and attribute operands.}
6028 @cindex @option{-gnatVo} (@command{gcc})
6029 Arguments for predefined operators and attributes are validity checked.
6030 This includes all operators in package @code{Standard},
6031 the shift operators defined as intrinsic in package @code{Interfaces}
6032 and operands for attributes such as @code{Pos}. Checks are also made
6033 on individual component values for composite comparisons, and on the
6034 expressions in type conversions and qualified expressions. Checks are
6035 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6036
6037 @item -gnatVp
6038 @emph{Validity checks for parameters.}
6039 @cindex @option{-gnatVp} (@command{gcc})
6040 This controls the treatment of parameters within a subprogram (as opposed
6041 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6042 of parameters on a call. If either of these call options is used, then
6043 normally an assumption is made within a subprogram that the input arguments
6044 have been validity checking at the point of call, and do not need checking
6045 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6046 is not made, and parameters are not assumed to be valid, so their validity
6047 will be checked (or rechecked) within the subprogram.
6048
6049 @item -gnatVr
6050 @emph{Validity checks for function returns.}
6051 @cindex @option{-gnatVr} (@command{gcc})
6052 The expression in @code{return} statements in functions is validity
6053 checked.
6054
6055 @item -gnatVs
6056 @emph{Validity checks for subscripts.}
6057 @cindex @option{-gnatVs} (@command{gcc})
6058 All subscripts expressions are checked for validity, whether they appear
6059 on the right side or left side (in default mode only left side subscripts
6060 are validity checked).
6061
6062 @item -gnatVt
6063 @emph{Validity checks for tests.}
6064 @cindex @option{-gnatVt} (@command{gcc})
6065 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6066 statements are checked, as well as guard expressions in entry calls.
6067
6068 @end table
6069
6070 @noindent
6071 The @option{-gnatV} switch may be followed by
6072 ^a string of letters^a list of options^
6073 to turn on a series of validity checking options.
6074 For example,
6075 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6076 specifies that in addition to the default validity checking, copies and
6077 function return expressions are to be validity checked.
6078 In order to make it easier
6079 to specify the desired combination of effects,
6080 @ifclear vms
6081 the upper case letters @code{CDFIMORST} may
6082 be used to turn off the corresponding lower case option.
6083 @end ifclear
6084 @ifset vms
6085 the prefix @code{NO} on an option turns off the corresponding validity
6086 checking:
6087 @itemize @bullet
6088 @item @code{NOCOPIES}
6089 @item @code{NODEFAULT}
6090 @item @code{NOFLOATS}
6091 @item @code{NOIN_PARAMS}
6092 @item @code{NOMOD_PARAMS}
6093 @item @code{NOOPERANDS}
6094 @item @code{NORETURNS}
6095 @item @code{NOSUBSCRIPTS}
6096 @item @code{NOTESTS}
6097 @end itemize
6098 @end ifset
6099 Thus
6100 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6101 turns on all validity checking options except for
6102 checking of @code{@b{in out}} procedure arguments.
6103
6104 The specification of additional validity checking generates extra code (and
6105 in the case of @option{-gnatVa} the code expansion can be substantial).
6106 However, these additional checks can be very useful in detecting
6107 uninitialized variables, incorrect use of unchecked conversion, and other
6108 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6109 is useful in conjunction with the extra validity checking, since this
6110 ensures that wherever possible uninitialized variables have invalid values.
6111
6112 See also the pragma @code{Validity_Checks} which allows modification of
6113 the validity checking mode at the program source level, and also allows for
6114 temporary disabling of validity checks.
6115
6116 @node Style Checking
6117 @subsection Style Checking
6118 @findex Style checking
6119
6120 @noindent
6121 The @option{-gnaty^x^(option,option,@dots{})^} switch
6122 @cindex @option{-gnaty} (@command{gcc})
6123 causes the compiler to
6124 enforce specified style rules. A limited set of style rules has been used
6125 in writing the GNAT sources themselves. This switch allows user programs
6126 to activate all or some of these checks. If the source program fails a
6127 specified style check, an appropriate message is given, preceded by
6128 the character sequence ``(style)''. This message does not prevent
6129 successful compilation (unless the @option{-gnatwe} switch is used).
6130
6131 @ifset vms
6132 @code{(option,option,@dots{})} is a sequence of keywords
6133 @end ifset
6134 @ifclear vms
6135 The string @var{x} is a sequence of letters or digits
6136 @end ifclear
6137 indicating the particular style
6138 checks to be performed. The following checks are defined:
6139
6140 @table @option
6141 @c !sort!
6142 @item 0-9
6143 @emph{Specify indentation level.}
6144 If a digit from 1-9 appears
6145 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6146 then proper indentation is checked, with the digit indicating the
6147 indentation level required. A value of zero turns off this style check.
6148 The general style of required indentation is as specified by
6149 the examples in the Ada Reference Manual. Full line comments must be
6150 aligned with the @code{--} starting on a column that is a multiple of
6151 the alignment level, or they may be aligned the same way as the following
6152 non-blank line (this is useful when full line comments appear in the middle
6153 of a statement.
6154
6155 @item ^a^ATTRIBUTE^
6156 @emph{Check attribute casing.}
6157 Attribute names, including the case of keywords such as @code{digits}
6158 used as attributes names, must be written in mixed case, that is, the
6159 initial letter and any letter following an underscore must be uppercase.
6160 All other letters must be lowercase.
6161
6162 @item ^A^ARRAY_INDEXES^
6163 @emph{Use of array index numbers in array attributes.}
6164 When using the array attributes First, Last, Range,
6165 or Length, the index number must be omitted for one-dimensional arrays
6166 and is required for multi-dimensional arrays.
6167
6168 @item ^b^BLANKS^
6169 @emph{Blanks not allowed at statement end.}
6170 Trailing blanks are not allowed at the end of statements. The purpose of this
6171 rule, together with h (no horizontal tabs), is to enforce a canonical format
6172 for the use of blanks to separate source tokens.
6173
6174 @item ^B^BOOLEAN_OPERATORS^
6175 @emph{Check Boolean operators.}
6176 The use of AND/OR operators is not permitted except in the cases of modular
6177 operands, array operands, and simple stand-alone boolean variables or
6178 boolean constants. In all other cases AND THEN/OR ELSE are required.
6179
6180 @item ^c^COMMENTS^
6181 @emph{Check comments.}
6182 Comments must meet the following set of rules:
6183
6184 @itemize @bullet
6185
6186 @item
6187 The ``@code{--}'' that starts the column must either start in column one,
6188 or else at least one blank must precede this sequence.
6189
6190 @item
6191 Comments that follow other tokens on a line must have at least one blank
6192 following the ``@code{--}'' at the start of the comment.
6193
6194 @item
6195 Full line comments must have two blanks following the ``@code{--}'' that
6196 starts the comment, with the following exceptions.
6197
6198 @item
6199 A line consisting only of the ``@code{--}'' characters, possibly preceded
6200 by blanks is permitted.
6201
6202 @item
6203 A comment starting with ``@code{--x}'' where @code{x} is a special character
6204 is permitted.
6205 This allows proper processing of the output generated by specialized tools
6206 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6207 annotation
6208 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6209 special character is defined as being in one of the ASCII ranges
6210 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6211 Note that this usage is not permitted
6212 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6213
6214 @item
6215 A line consisting entirely of minus signs, possibly preceded by blanks, is
6216 permitted. This allows the construction of box comments where lines of minus
6217 signs are used to form the top and bottom of the box.
6218
6219 @item
6220 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6221 least one blank follows the initial ``@code{--}''. Together with the preceding
6222 rule, this allows the construction of box comments, as shown in the following
6223 example:
6224 @smallexample
6225 ---------------------------
6226 -- This is a box comment --
6227 -- with two text lines.  --
6228 ---------------------------
6229 @end smallexample
6230 @end itemize
6231
6232 @item ^d^DOS_LINE_ENDINGS^
6233 @emph{Check no DOS line terminators present.}
6234 All lines must be terminated by a single ASCII.LF
6235 character (in particular the DOS line terminator sequence CR/LF is not
6236 allowed).
6237
6238 @item ^e^END^
6239 @emph{Check end/exit labels.}
6240 Optional labels on @code{end} statements ending subprograms and on
6241 @code{exit} statements exiting named loops, are required to be present.
6242
6243 @item ^f^VTABS^
6244 @emph{No form feeds or vertical tabs.}
6245 Neither form feeds nor vertical tab characters are permitted
6246 in the source text.
6247
6248 @item ^g^GNAT^
6249 @emph{GNAT style mode}
6250 The set of style check switches is set to match that used by the GNAT sources.
6251 This may be useful when developing code that is eventually intended to be
6252 incorporated into GNAT. For further details, see GNAT sources.
6253
6254 @item ^h^HTABS^
6255 @emph{No horizontal tabs.}
6256 Horizontal tab characters are not permitted in the source text.
6257 Together with the b (no blanks at end of line) check, this
6258 enforces a canonical form for the use of blanks to separate
6259 source tokens.
6260
6261 @item ^i^IF_THEN^
6262 @emph{Check if-then layout.}
6263 The keyword @code{then} must appear either on the same
6264 line as corresponding @code{if}, or on a line on its own, lined
6265 up under the @code{if} with at least one non-blank line in between
6266 containing all or part of the condition to be tested.
6267
6268 @item ^I^IN_MODE^
6269 @emph{check mode IN keywords}
6270 Mode @code{in} (the default mode) is not
6271 allowed to be given explicitly. @code{in out} is fine,
6272 but not @code{in} on its own.
6273
6274 @item ^k^KEYWORD^
6275 @emph{Check keyword casing.}
6276 All keywords must be in lower case (with the exception of keywords
6277 such as @code{digits} used as attribute names to which this check
6278 does not apply).
6279
6280 @item ^l^LAYOUT^
6281 @emph{Check layout.}
6282 Layout of statement and declaration constructs must follow the
6283 recommendations in the Ada Reference Manual, as indicated by the
6284 form of the syntax rules. For example an @code{else} keyword must
6285 be lined up with the corresponding @code{if} keyword.
6286
6287 There are two respects in which the style rule enforced by this check
6288 option are more liberal than those in the Ada Reference Manual. First
6289 in the case of record declarations, it is permissible to put the
6290 @code{record} keyword on the same line as the @code{type} keyword, and
6291 then the @code{end} in @code{end record} must line up under @code{type}.
6292 This is also permitted when the type declaration is split on two lines.
6293 For example, any of the following three layouts is acceptable:
6294
6295 @smallexample @c ada
6296 @cartouche
6297 type q is record
6298    a : integer;
6299    b : integer;
6300 end record;
6301
6302 type q is
6303    record
6304       a : integer;
6305       b : integer;
6306    end record;
6307
6308 type q is
6309    record
6310       a : integer;
6311       b : integer;
6312 end record;
6313
6314 @end cartouche
6315 @end smallexample
6316
6317 @noindent
6318 Second, in the case of a block statement, a permitted alternative
6319 is to put the block label on the same line as the @code{declare} or
6320 @code{begin} keyword, and then line the @code{end} keyword up under
6321 the block label. For example both the following are permitted:
6322
6323 @smallexample @c ada
6324 @cartouche
6325 Block : declare
6326    A : Integer := 3;
6327 begin
6328    Proc (A, A);
6329 end Block;
6330
6331 Block :
6332    declare
6333       A : Integer := 3;
6334    begin
6335       Proc (A, A);
6336    end Block;
6337 @end cartouche
6338 @end smallexample
6339
6340 @noindent
6341 The same alternative format is allowed for loops. For example, both of
6342 the following are permitted:
6343
6344 @smallexample @c ada
6345 @cartouche
6346 Clear : while J < 10 loop
6347    A (J) := 0;
6348 end loop Clear;
6349
6350 Clear :
6351    while J < 10 loop
6352       A (J) := 0;
6353    end loop Clear;
6354 @end cartouche
6355 @end smallexample
6356
6357 @item ^Lnnn^MAX_NESTING=nnn^
6358 @emph{Set maximum nesting level}
6359 The maximum level of nesting of constructs (including subprograms, loops,
6360 blocks, packages, and conditionals) may not exceed the given value
6361 @option{nnn}. A value of zero disconnects this style check.
6362
6363 @item ^m^LINE_LENGTH^
6364 @emph{Check maximum line length.}
6365 The length of source lines must not exceed 79 characters, including
6366 any trailing blanks. The value of 79 allows convenient display on an
6367 80 character wide device or window, allowing for possible special
6368 treatment of 80 character lines. Note that this count is of
6369 characters in the source text. This means that a tab character counts
6370 as one character in this count but a wide character sequence counts as
6371 a single character (however many bytes are needed in the encoding).
6372
6373 @item ^Mnnn^MAX_LENGTH=nnn^
6374 @emph{Set maximum line length.}
6375 The length of lines must not exceed the
6376 given value @option{nnn}. The maximum value that can be specified is 32767.
6377
6378 @item ^n^STANDARD_CASING^
6379 @emph{Check casing of entities in Standard.}
6380 Any identifier from Standard must be cased
6381 to match the presentation in the Ada Reference Manual (for example,
6382 @code{Integer} and @code{ASCII.NUL}).
6383
6384 @item ^N^NONE^
6385 @emph{Turn off all style checks}
6386 All style check options are turned off.
6387
6388 @item ^o^ORDERED_SUBPROGRAMS^
6389 @emph{Check order of subprogram bodies.}
6390 All subprogram bodies in a given scope
6391 (e.g.@: a package body) must be in alphabetical order. The ordering
6392 rule uses normal Ada rules for comparing strings, ignoring casing
6393 of letters, except that if there is a trailing numeric suffix, then
6394 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6395 before Junk10).
6396
6397 @item ^O^OVERRIDING_INDICATORS^
6398 @emph{Check that overriding subprograms are explicitly marked as such.}
6399 The declaration of a primitive operation of a type extension that overrides
6400 an inherited operation must carry an overriding indicator.
6401
6402 @item ^p^PRAGMA^
6403 @emph{Check pragma casing.}
6404 Pragma names must be written in mixed case, that is, the
6405 initial letter and any letter following an underscore must be uppercase.
6406 All other letters must be lowercase.
6407
6408 @item ^r^REFERENCES^
6409 @emph{Check references.}
6410 All identifier references must be cased in the same way as the
6411 corresponding declaration. No specific casing style is imposed on
6412 identifiers. The only requirement is for consistency of references
6413 with declarations.
6414
6415 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6416 @emph{Check no statements after THEN/ELSE.}
6417 No statements are allowed
6418 on the same line as a THEN or ELSE keyword following the
6419 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6420 and a special exception allows a pragma to appear after ELSE.
6421
6422 @item ^s^SPECS^
6423 @emph{Check separate specs.}
6424 Separate declarations (``specs'') are required for subprograms (a
6425 body is not allowed to serve as its own declaration). The only
6426 exception is that parameterless library level procedures are
6427 not required to have a separate declaration. This exception covers
6428 the most frequent form of main program procedures.
6429
6430 @item ^t^TOKEN^
6431 @emph{Check token spacing.}
6432 The following token spacing rules are enforced:
6433
6434 @itemize @bullet
6435
6436 @item
6437 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6438
6439 @item
6440 The token @code{=>} must be surrounded by spaces.
6441
6442 @item
6443 The token @code{<>} must be preceded by a space or a left parenthesis.
6444
6445 @item
6446 Binary operators other than @code{**} must be surrounded by spaces.
6447 There is no restriction on the layout of the @code{**} binary operator.
6448
6449 @item
6450 Colon must be surrounded by spaces.
6451
6452 @item
6453 Colon-equal (assignment, initialization) must be surrounded by spaces.
6454
6455 @item
6456 Comma must be the first non-blank character on the line, or be
6457 immediately preceded by a non-blank character, and must be followed
6458 by a space.
6459
6460 @item
6461 If the token preceding a left parenthesis ends with a letter or digit, then
6462 a space must separate the two tokens.
6463
6464 @item
6465 if the token following a right parenthesis starts with a letter or digit, then
6466 a space must separate the two tokens.
6467
6468 @item
6469 A right parenthesis must either be the first non-blank character on
6470 a line, or it must be preceded by a non-blank character.
6471
6472 @item
6473 A semicolon must not be preceded by a space, and must not be followed by
6474 a non-blank character.
6475
6476 @item
6477 A unary plus or minus may not be followed by a space.
6478
6479 @item
6480 A vertical bar must be surrounded by spaces.
6481 @end itemize
6482
6483 @item ^u^UNNECESSARY_BLANK_LINES^
6484 @emph{Check unnecessary blank lines.}
6485 Unnecessary blank lines are not allowed. A blank line is considered
6486 unnecessary if it appears at the end of the file, or if more than
6487 one blank line occurs in sequence.
6488
6489 @item ^x^XTRA_PARENS^
6490 @emph{Check extra parentheses.}
6491 Unnecessary extra level of parentheses (C-style) are not allowed
6492 around conditions in @code{if} statements, @code{while} statements and
6493 @code{exit} statements.
6494
6495 @item ^y^ALL_BUILTIN^
6496 @emph{Set all standard style check options}
6497 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6498 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6499 @option{-gnatyS}, @option{-gnatyLnnn},
6500 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6501
6502 @ifclear vms
6503 @item -
6504 @emph{Remove style check options}
6505 This causes any subsequent options in the string to act as canceling the
6506 corresponding style check option. To cancel maximum nesting level control,
6507 use @option{L} parameter witout any integer value after that, because any
6508 digit following @option{-} in the parameter string of the @option{-gnaty}
6509 option will be threated as canceling indentation check. The same is true
6510 for @option{M} parameter. @option{y} and @option{N} parameters are not
6511 allowed after @option{-}.
6512
6513 @item +
6514 This causes any subsequent options in the string to enable the corresponding
6515 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6516 if any.
6517 @end ifclear
6518
6519 @ifset vms
6520 @item NOxxx
6521 @emph{Removing style check options}
6522 If the name of a style check is preceded by @option{NO} then the corresponding
6523 style check is turned off. For example @option{NOCOMMENTS} turns off style
6524 checking for comments.
6525 @end ifset
6526 @end table
6527
6528 @noindent
6529 In the above rules, appearing in column one is always permitted, that is,
6530 counts as meeting either a requirement for a required preceding space,
6531 or as meeting a requirement for no preceding space.
6532
6533 Appearing at the end of a line is also always permitted, that is, counts
6534 as meeting either a requirement for a following space, or as meeting
6535 a requirement for no following space.
6536
6537 @noindent
6538 If any of these style rules is violated, a message is generated giving
6539 details on the violation. The initial characters of such messages are
6540 always ``@code{(style)}''. Note that these messages are treated as warning
6541 messages, so they normally do not prevent the generation of an object
6542 file. The @option{-gnatwe} switch can be used to treat warning messages,
6543 including style messages, as fatal errors.
6544
6545 The switch
6546 @ifclear vms
6547 @option{-gnaty} on its own (that is not
6548 followed by any letters or digits), then the effect is equivalent
6549 to the use of @option{-gnatyy}, as described above, that is all
6550 built-in standard style check options are enabled.
6551
6552 @end ifclear
6553 @ifset vms
6554 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6555 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6556 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6557 @end ifset
6558
6559 The switch
6560 @ifclear vms
6561 @option{-gnatyN}
6562 @end ifclear
6563 @ifset vms
6564 /STYLE_CHECKS=NONE
6565 @end ifset
6566 clears any previously set style checks.
6567
6568 @node Run-Time Checks
6569 @subsection Run-Time Checks
6570 @cindex Division by zero
6571 @cindex Access before elaboration
6572 @cindex Checks, division by zero
6573 @cindex Checks, access before elaboration
6574 @cindex Checks, stack overflow checking
6575
6576 @noindent
6577 By default, the following checks are suppressed: integer overflow
6578 checks, stack overflow checks, and checks for access before
6579 elaboration on subprogram calls. All other checks, including range
6580 checks and array bounds checks, are turned on by default. The
6581 following @command{gcc} switches refine this default behavior.
6582
6583 @table @option
6584 @c !sort!
6585 @item -gnatp
6586 @cindex @option{-gnatp} (@command{gcc})
6587 @cindex Suppressing checks
6588 @cindex Checks, suppressing
6589 @findex Suppress
6590 This switch causes the unit to be compiled
6591 as though @code{pragma Suppress (All_checks)}
6592 had been present in the source. Validity checks are also eliminated (in
6593 other words @option{-gnatp} also implies @option{-gnatVn}.
6594 Use this switch to improve the performance
6595 of the code at the expense of safety in the presence of invalid data or
6596 program bugs.
6597
6598 Note that when checks are suppressed, the compiler is allowed, but not
6599 required, to omit the checking code. If the run-time cost of the
6600 checking code is zero or near-zero, the compiler will generate it even
6601 if checks are suppressed. In particular, if the compiler can prove
6602 that a certain check will necessarily fail, it will generate code to
6603 do an unconditional ``raise'', even if checks are suppressed. The
6604 compiler warns in this case. Another case in which checks may not be
6605 eliminated is when they are embedded in certain run time routines such
6606 as math library routines.
6607
6608 Of course, run-time checks are omitted whenever the compiler can prove
6609 that they will not fail, whether or not checks are suppressed.
6610
6611 Note that if you suppress a check that would have failed, program
6612 execution is erroneous, which means the behavior is totally
6613 unpredictable. The program might crash, or print wrong answers, or
6614 do anything else. It might even do exactly what you wanted it to do
6615 (and then it might start failing mysteriously next week or next
6616 year). The compiler will generate code based on the assumption that
6617 the condition being checked is true, which can result in disaster if
6618 that assumption is wrong.
6619
6620 The @option{-gnatp} switch has no effect if a subsequent
6621 @option{-gnat-p} switch appears.
6622
6623 @item -gnat-p
6624 @cindex @option{-gnat-p} (@command{gcc})
6625 @cindex Suppressing checks
6626 @cindex Checks, suppressing
6627 @findex Suppress
6628 This switch cancels the effect of a previous @option{gnatp} switch.
6629
6630 @item -gnato
6631 @cindex @option{-gnato} (@command{gcc})
6632 @cindex Overflow checks
6633 @cindex Check, overflow
6634 Enables overflow checking for integer operations.
6635 This causes GNAT to generate slower and larger executable
6636 programs by adding code to check for overflow (resulting in raising
6637 @code{Constraint_Error} as required by standard Ada
6638 semantics). These overflow checks correspond to situations in which
6639 the true value of the result of an operation may be outside the base
6640 range of the result type. The following example shows the distinction:
6641
6642 @smallexample @c ada
6643 X1 : Integer := "Integer'Last";
6644 X2 : Integer range 1 .. 5 := "5";
6645 X3 : Integer := "Integer'Last";
6646 X4 : Integer range 1 .. 5 := "5";
6647 F  : Float := "2.0E+20";
6648 @dots{}
6649 X1 := X1 + 1;
6650 X2 := X2 + 1;
6651 X3 := Integer (F);
6652 X4 := Integer (F);
6653 @end smallexample
6654
6655 @noindent
6656 Note that if explicit values are assigned at compile time, the
6657 compiler may be able to detect overflow at compile time, in which case
6658 no actual run-time checking code is required, and Constraint_Error
6659 will be raised unconditionally, with or without
6660 @option{-gnato}. That's why the assigned values in the above fragment
6661 are in quotes, the meaning is "assign a value not known to the
6662 compiler that happens to be equal to ...". The remaining discussion
6663 assumes that the compiler cannot detect the values at compile time.
6664
6665 Here the first addition results in a value that is outside the base range
6666 of Integer, and hence requires an overflow check for detection of the
6667 constraint error. Thus the first assignment to @code{X1} raises a
6668 @code{Constraint_Error} exception only if @option{-gnato} is set.
6669
6670 The second increment operation results in a violation of the explicit
6671 range constraint; such range checks are performed by default, and are
6672 unaffected by @option{-gnato}.
6673
6674 The two conversions of @code{F} both result in values that are outside
6675 the base range of type @code{Integer} and thus will raise
6676 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6677 The fact that the result of the second conversion is assigned to
6678 variable @code{X4} with a restricted range is irrelevant, since the problem
6679 is in the conversion, not the assignment.
6680
6681 Basically the rule is that in the default mode (@option{-gnato} not
6682 used), the generated code assures that all integer variables stay
6683 within their declared ranges, or within the base range if there is
6684 no declared range. This prevents any serious problems like indexes
6685 out of range for array operations.
6686
6687 What is not checked in default mode is an overflow that results in
6688 an in-range, but incorrect value. In the above example, the assignments
6689 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6690 range of the target variable, but the result is wrong in the sense that
6691 it is too large to be represented correctly. Typically the assignment
6692 to @code{X1} will result in wrap around to the largest negative number.
6693 The conversions of @code{F} will result in some @code{Integer} value
6694 and if that integer value is out of the @code{X4} range then the
6695 subsequent assignment would generate an exception.
6696
6697 @findex Machine_Overflows
6698 Note that the @option{-gnato} switch does not affect the code generated
6699 for any floating-point operations; it applies only to integer
6700 semantics).
6701 For floating-point, GNAT has the @code{Machine_Overflows}
6702 attribute set to @code{False} and the normal mode of operation is to
6703 generate IEEE NaN and infinite values on overflow or invalid operations
6704 (such as dividing 0.0 by 0.0).
6705
6706 The reason that we distinguish overflow checking from other kinds of
6707 range constraint checking is that a failure of an overflow check, unlike
6708 for example the failure of a range check, can result in an incorrect
6709 value, but cannot cause random memory destruction (like an out of range
6710 subscript), or a wild jump (from an out of range case value). Overflow
6711 checking is also quite expensive in time and space, since in general it
6712 requires the use of double length arithmetic.
6713
6714 Note again that @option{-gnato} is off by default, so overflow checking is
6715 not performed in default mode. This means that out of the box, with the
6716 default settings, GNAT does not do all the checks expected from the
6717 language description in the Ada Reference Manual. If you want all constraint
6718 checks to be performed, as described in this Manual, then you must
6719 explicitly use the -gnato switch either on the @command{gnatmake} or
6720 @command{gcc} command.
6721
6722 @item -gnatE
6723 @cindex @option{-gnatE} (@command{gcc})
6724 @cindex Elaboration checks
6725 @cindex Check, elaboration
6726 Enables dynamic checks for access-before-elaboration
6727 on subprogram calls and generic instantiations.
6728 Note that @option{-gnatE} is not necessary for safety, because in the
6729 default mode, GNAT ensures statically that the checks would not fail.
6730 For full details of the effect and use of this switch,
6731 @xref{Compiling Using gcc}.
6732
6733 @item -fstack-check
6734 @cindex @option{-fstack-check} (@command{gcc})
6735 @cindex Stack Overflow Checking
6736 @cindex Checks, stack overflow checking
6737 Activates stack overflow checking. For full details of the effect and use of
6738 this switch see @ref{Stack Overflow Checking}.
6739 @end table
6740
6741 @findex Unsuppress
6742 @noindent
6743 The setting of these switches only controls the default setting of the
6744 checks. You may modify them using either @code{Suppress} (to remove
6745 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6746 the program source.
6747
6748 @node Using gcc for Syntax Checking
6749 @subsection Using @command{gcc} for Syntax Checking
6750 @table @option
6751 @item -gnats
6752 @cindex @option{-gnats} (@command{gcc})
6753 @ifclear vms
6754
6755 @noindent
6756 The @code{s} stands for ``syntax''.
6757 @end ifclear
6758
6759 Run GNAT in syntax checking only mode. For
6760 example, the command
6761
6762 @smallexample
6763 $ gcc -c -gnats x.adb
6764 @end smallexample
6765
6766 @noindent
6767 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6768 series of files in a single command
6769 @ifclear vms
6770 , and can use wild cards to specify such a group of files.
6771 Note that you must specify the @option{-c} (compile
6772 only) flag in addition to the @option{-gnats} flag.
6773 @end ifclear
6774 .
6775 You may use other switches in conjunction with @option{-gnats}. In
6776 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6777 format of any generated error messages.
6778
6779 When the source file is empty or contains only empty lines and/or comments,
6780 the output is a warning:
6781
6782 @smallexample
6783 $ gcc -c -gnats -x ada toto.txt
6784 toto.txt:1:01: warning: empty file, contains no compilation units
6785 $
6786 @end smallexample
6787
6788 Otherwise, the output is simply the error messages, if any. No object file or
6789 ALI file is generated by a syntax-only compilation. Also, no units other
6790 than the one specified are accessed. For example, if a unit @code{X}
6791 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6792 check only mode does not access the source file containing unit
6793 @code{Y}.
6794
6795 @cindex Multiple units, syntax checking
6796 Normally, GNAT allows only a single unit in a source file. However, this
6797 restriction does not apply in syntax-check-only mode, and it is possible
6798 to check a file containing multiple compilation units concatenated
6799 together. This is primarily used by the @code{gnatchop} utility
6800 (@pxref{Renaming Files Using gnatchop}).
6801 @end table
6802
6803 @node Using gcc for Semantic Checking
6804 @subsection Using @command{gcc} for Semantic Checking
6805 @table @option
6806 @item -gnatc
6807 @cindex @option{-gnatc} (@command{gcc})
6808
6809 @ifclear vms
6810 @noindent
6811 The @code{c} stands for ``check''.
6812 @end ifclear
6813 Causes the compiler to operate in semantic check mode,
6814 with full checking for all illegalities specified in the
6815 Ada Reference Manual, but without generation of any object code
6816 (no object file is generated).
6817
6818 Because dependent files must be accessed, you must follow the GNAT
6819 semantic restrictions on file structuring to operate in this mode:
6820
6821 @itemize @bullet
6822 @item
6823 The needed source files must be accessible
6824 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6825
6826 @item
6827 Each file must contain only one compilation unit.
6828
6829 @item
6830 The file name and unit name must match (@pxref{File Naming Rules}).
6831 @end itemize
6832
6833 The output consists of error messages as appropriate. No object file is
6834 generated. An @file{ALI} file is generated for use in the context of
6835 cross-reference tools, but this file is marked as not being suitable
6836 for binding (since no object file is generated).
6837 The checking corresponds exactly to the notion of
6838 legality in the Ada Reference Manual.
6839
6840 Any unit can be compiled in semantics-checking-only mode, including
6841 units that would not normally be compiled (subunits,
6842 and specifications where a separate body is present).
6843 @end table
6844
6845 @node Compiling Different Versions of Ada
6846 @subsection Compiling Different Versions of Ada
6847
6848 @noindent
6849 The switches described in this section allow you to explicitly specify
6850 the version of the Ada language that your programs are written in.
6851 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6852 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6853 indicate Ada 83 compatibility mode.
6854
6855 @table @option
6856 @cindex Compatibility with Ada 83
6857
6858 @item -gnat83 (Ada 83 Compatibility Mode)
6859 @cindex @option{-gnat83} (@command{gcc})
6860 @cindex ACVC, Ada 83 tests
6861 @cindex Ada 83 mode
6862
6863 @noindent
6864 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6865 specifies that the program is to be compiled in Ada 83 mode. With
6866 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6867 semantics where this can be done easily.
6868 It is not possible to guarantee this switch does a perfect
6869 job; some subtle tests, such as are
6870 found in earlier ACVC tests (and that have been removed from the ACATS suite
6871 for Ada 95), might not compile correctly.
6872 Nevertheless, this switch may be useful in some circumstances, for example
6873 where, due to contractual reasons, existing code needs to be maintained
6874 using only Ada 83 features.
6875
6876 With few exceptions (most notably the need to use @code{<>} on
6877 @cindex Generic formal parameters
6878 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6879 reserved words, and the use of packages
6880 with optional bodies), it is not necessary to specify the
6881 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6882 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6883 a correct Ada 83 program is usually also a correct program
6884 in these later versions of the language standard.
6885 For further information, please refer to @ref{Compatibility and Porting Guide}.
6886
6887 @item -gnat95 (Ada 95 mode)
6888 @cindex @option{-gnat95} (@command{gcc})
6889 @cindex Ada 95 mode
6890
6891 @noindent
6892 This switch directs the compiler to implement the Ada 95 version of the
6893 language.
6894 Since Ada 95 is almost completely upwards
6895 compatible with Ada 83, Ada 83 programs may generally be compiled using
6896 this switch (see the description of the @option{-gnat83} switch for further
6897 information about Ada 83 mode).
6898 If an Ada 2005 program is compiled in Ada 95 mode,
6899 uses of the new Ada 2005 features will cause error
6900 messages or warnings.
6901
6902 This switch also can be used to cancel the effect of a previous
6903 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6904
6905 @item -gnat05 (Ada 2005 mode)
6906 @cindex @option{-gnat05} (@command{gcc})
6907 @cindex Ada 2005 mode
6908
6909 @noindent
6910 This switch directs the compiler to implement the Ada 2005 version of the
6911 language.
6912 Since Ada 2005 is almost completely upwards
6913 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6914 may generally be compiled using this switch (see the description of the
6915 @option{-gnat83} and @option{-gnat95} switches for further
6916 information).
6917
6918 For information about the approved ``Ada Issues'' that have been incorporated
6919 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6920 Included with GNAT releases is a file @file{features-ada0y} that describes
6921 the set of implemented Ada 2005 features.
6922 @end table
6923
6924
6925 @node Character Set Control
6926 @subsection Character Set Control
6927 @table @option
6928 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6929 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6930
6931 @noindent
6932 Normally GNAT recognizes the Latin-1 character set in source program
6933 identifiers, as described in the Ada Reference Manual.
6934 This switch causes
6935 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6936 single character ^^or word^ indicating the character set, as follows:
6937
6938 @table @code
6939 @item 1
6940 ISO 8859-1 (Latin-1) identifiers
6941
6942 @item 2
6943 ISO 8859-2 (Latin-2) letters allowed in identifiers
6944
6945 @item 3
6946 ISO 8859-3 (Latin-3) letters allowed in identifiers
6947
6948 @item 4
6949 ISO 8859-4 (Latin-4) letters allowed in identifiers
6950
6951 @item 5
6952 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6953
6954 @item 9
6955 ISO 8859-15 (Latin-9) letters allowed in identifiers
6956
6957 @item ^p^PC^
6958 IBM PC letters (code page 437) allowed in identifiers
6959
6960 @item ^8^PC850^
6961 IBM PC letters (code page 850) allowed in identifiers
6962
6963 @item ^f^FULL_UPPER^
6964 Full upper-half codes allowed in identifiers
6965
6966 @item ^n^NO_UPPER^
6967 No upper-half codes allowed in identifiers
6968
6969 @item ^w^WIDE^
6970 Wide-character codes (that is, codes greater than 255)
6971 allowed in identifiers
6972 @end table
6973
6974 @xref{Foreign Language Representation}, for full details on the
6975 implementation of these character sets.
6976
6977 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6978 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6979 Specify the method of encoding for wide characters.
6980 @var{e} is one of the following:
6981
6982 @table @code
6983
6984 @item ^h^HEX^
6985 Hex encoding (brackets coding also recognized)
6986
6987 @item ^u^UPPER^
6988 Upper half encoding (brackets encoding also recognized)
6989
6990 @item ^s^SHIFT_JIS^
6991 Shift/JIS encoding (brackets encoding also recognized)
6992
6993 @item ^e^EUC^
6994 EUC encoding (brackets encoding also recognized)
6995
6996 @item ^8^UTF8^
6997 UTF-8 encoding (brackets encoding also recognized)
6998
6999 @item ^b^BRACKETS^
7000 Brackets encoding only (default value)
7001 @end table
7002 For full details on these encoding
7003 methods see @ref{Wide Character Encodings}.
7004 Note that brackets coding is always accepted, even if one of the other
7005 options is specified, so for example @option{-gnatW8} specifies that both
7006 brackets and UTF-8 encodings will be recognized. The units that are
7007 with'ed directly or indirectly will be scanned using the specified
7008 representation scheme, and so if one of the non-brackets scheme is
7009 used, it must be used consistently throughout the program. However,
7010 since brackets encoding is always recognized, it may be conveniently
7011 used in standard libraries, allowing these libraries to be used with
7012 any of the available coding schemes.
7013 scheme.
7014
7015 If no @option{-gnatW?} parameter is present, then the default
7016 representation is normally Brackets encoding only. However, if the
7017 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7018 byte order mark or BOM for UTF-8), then these three characters are
7019 skipped and the default representation for the file is set to UTF-8.
7020
7021 Note that the wide character representation that is specified (explicitly
7022 or by default) for the main program also acts as the default encoding used
7023 for Wide_Text_IO files if not specifically overridden by a WCEM form
7024 parameter.
7025
7026 @end table
7027 @node File Naming Control
7028 @subsection File Naming Control
7029
7030 @table @option
7031 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7032 @cindex @option{-gnatk} (@command{gcc})
7033 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7034 1-999, indicates the maximum allowable length of a file name (not
7035 including the @file{.ads} or @file{.adb} extension). The default is not
7036 to enable file name krunching.
7037
7038 For the source file naming rules, @xref{File Naming Rules}.
7039 @end table
7040
7041 @node Subprogram Inlining Control
7042 @subsection Subprogram Inlining Control
7043
7044 @table @option
7045 @c !sort!
7046 @item -gnatn
7047 @cindex @option{-gnatn} (@command{gcc})
7048 @ifclear vms
7049 The @code{n} here is intended to suggest the first syllable of the
7050 word ``inline''.
7051 @end ifclear
7052 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7053 inlining to actually occur, optimization must be enabled. To enable
7054 inlining of subprograms specified by pragma @code{Inline},
7055 you must also specify this switch.
7056 In the absence of this switch, GNAT does not attempt
7057 inlining and does not need to access the bodies of
7058 subprograms for which @code{pragma Inline} is specified if they are not
7059 in the current unit.
7060
7061 If you specify this switch the compiler will access these bodies,
7062 creating an extra source dependency for the resulting object file, and
7063 where possible, the call will be inlined.
7064 For further details on when inlining is possible
7065 see @ref{Inlining of Subprograms}.
7066
7067 @item -gnatN
7068 @cindex @option{-gnatN} (@command{gcc})
7069 This switch activates front-end inlining which also
7070 generates additional dependencies.
7071
7072 When using a gcc-based back end (in practice this means using any version
7073 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7074 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7075 Historically front end inlining was more extensive than the gcc back end
7076 inlining, but that is no longer the case.
7077 @end table
7078
7079 @node Auxiliary Output Control
7080 @subsection Auxiliary Output Control
7081
7082 @table @option
7083 @item -gnatt
7084 @cindex @option{-gnatt} (@command{gcc})
7085 @cindex Writing internal trees
7086 @cindex Internal trees, writing to file
7087 Causes GNAT to write the internal tree for a unit to a file (with the
7088 extension @file{.adt}.
7089 This not normally required, but is used by separate analysis tools.
7090 Typically
7091 these tools do the necessary compilations automatically, so you should
7092 not have to specify this switch in normal operation.
7093 Note that the combination of switches @option{-gnatct}
7094 generates a tree in the form required by ASIS applications.
7095
7096 @item -gnatu
7097 @cindex @option{-gnatu} (@command{gcc})
7098 Print a list of units required by this compilation on @file{stdout}.
7099 The listing includes all units on which the unit being compiled depends
7100 either directly or indirectly.
7101
7102 @ifclear vms
7103 @item -pass-exit-codes
7104 @cindex @option{-pass-exit-codes} (@command{gcc})
7105 If this switch is not used, the exit code returned by @command{gcc} when
7106 compiling multiple files indicates whether all source files have
7107 been successfully used to generate object files or not.
7108
7109 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7110 exit status and allows an integrated development environment to better
7111 react to a compilation failure. Those exit status are:
7112
7113 @table @asis
7114 @item 5
7115 There was an error in at least one source file.
7116 @item 3
7117 At least one source file did not generate an object file.
7118 @item 2
7119 The compiler died unexpectedly (internal error for example).
7120 @item 0
7121 An object file has been generated for every source file.
7122 @end table
7123 @end ifclear
7124 @end table
7125
7126 @node Debugging Control
7127 @subsection Debugging Control
7128
7129 @table @option
7130 @c !sort!
7131 @cindex Debugging options
7132 @ifclear vms
7133 @item -gnatd@var{x}
7134 @cindex @option{-gnatd} (@command{gcc})
7135 Activate internal debugging switches. @var{x} is a letter or digit, or
7136 string of letters or digits, which specifies the type of debugging
7137 outputs desired. Normally these are used only for internal development
7138 or system debugging purposes. You can find full documentation for these
7139 switches in the body of the @code{Debug} unit in the compiler source
7140 file @file{debug.adb}.
7141 @end ifclear
7142
7143 @item -gnatG[=nn]
7144 @cindex @option{-gnatG} (@command{gcc})
7145 This switch causes the compiler to generate auxiliary output containing
7146 a pseudo-source listing of the generated expanded code. Like most Ada
7147 compilers, GNAT works by first transforming the high level Ada code into
7148 lower level constructs. For example, tasking operations are transformed
7149 into calls to the tasking run-time routines. A unique capability of GNAT
7150 is to list this expanded code in a form very close to normal Ada source.
7151 This is very useful in understanding the implications of various Ada
7152 usage on the efficiency of the generated code. There are many cases in
7153 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7154 generate a lot of run-time code. By using @option{-gnatG} you can identify
7155 these cases, and consider whether it may be desirable to modify the coding
7156 approach to improve efficiency.
7157
7158 The optional parameter @code{nn} if present after -gnatG specifies an
7159 alternative maximum line length that overrides the normal default of 72.
7160 This value is in the range 40-999999, values less than 40 being silently
7161 reset to 40. The equal sign is optional.
7162
7163 The format of the output is very similar to standard Ada source, and is
7164 easily understood by an Ada programmer. The following special syntactic
7165 additions correspond to low level features used in the generated code that
7166 do not have any exact analogies in pure Ada source form. The following
7167 is a partial list of these special constructions. See the spec
7168 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7169
7170 If the switch @option{-gnatL} is used in conjunction with
7171 @cindex @option{-gnatL} (@command{gcc})
7172 @option{-gnatG}, then the original source lines are interspersed
7173 in the expanded source (as comment lines with the original line number).
7174
7175 @table @code
7176 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7177 Shows the storage pool being used for an allocator.
7178
7179 @item at end @var{procedure-name};
7180 Shows the finalization (cleanup) procedure for a scope.
7181
7182 @item (if @var{expr} then @var{expr} else @var{expr})
7183 Conditional expression equivalent to the @code{x?y:z} construction in C.
7184
7185 @item @var{target}^^^(@var{source})
7186 A conversion with floating-point truncation instead of rounding.
7187
7188 @item @var{target}?(@var{source})
7189 A conversion that bypasses normal Ada semantic checking. In particular
7190 enumeration types and fixed-point types are treated simply as integers.
7191
7192 @item @var{target}?^^^(@var{source})
7193 Combines the above two cases.
7194
7195 @item @var{x} #/ @var{y}
7196 @itemx @var{x} #mod @var{y}
7197 @itemx @var{x} #* @var{y}
7198 @itemx @var{x} #rem @var{y}
7199 A division or multiplication of fixed-point values which are treated as
7200 integers without any kind of scaling.
7201
7202 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7203 Shows the storage pool associated with a @code{free} statement.
7204
7205 @item [subtype or type declaration]
7206 Used to list an equivalent declaration for an internally generated
7207 type that is referenced elsewhere in the listing.
7208
7209 @c @item freeze @var{type-name} @ovar{actions}
7210 @c Expanding @ovar macro inline (explanation in macro def comments)
7211 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7212 Shows the point at which @var{type-name} is frozen, with possible
7213 associated actions to be performed at the freeze point.
7214
7215 @item reference @var{itype}
7216 Reference (and hence definition) to internal type @var{itype}.
7217
7218 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7219 Intrinsic function call.
7220
7221 @item @var{label-name} : label
7222 Declaration of label @var{labelname}.
7223
7224 @item #$ @var{subprogram-name}
7225 An implicit call to a run-time support routine
7226 (to meet the requirement of H.3.1(9) in a
7227 convenient manner).
7228
7229 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7230 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7231 @var{expr}, but handled more efficiently).
7232
7233 @item [constraint_error]
7234 Raise the @code{Constraint_Error} exception.
7235
7236 @item @var{expression}'reference
7237 A pointer to the result of evaluating @var{expression}.
7238
7239 @item @var{target-type}!(@var{source-expression})
7240 An unchecked conversion of @var{source-expression} to @var{target-type}.
7241
7242 @item [@var{numerator}/@var{denominator}]
7243 Used to represent internal real literals (that) have no exact
7244 representation in base 2-16 (for example, the result of compile time
7245 evaluation of the expression 1.0/27.0).
7246 @end table
7247
7248 @item -gnatD[=nn]
7249 @cindex @option{-gnatD} (@command{gcc})
7250 When used in conjunction with @option{-gnatG}, this switch causes
7251 the expanded source, as described above for
7252 @option{-gnatG} to be written to files with names
7253 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7254 instead of to the standard output file. For
7255 example, if the source file name is @file{hello.adb}, then a file
7256 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7257 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7258 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7259 you to do source level debugging using the generated code which is
7260 sometimes useful for complex code, for example to find out exactly
7261 which part of a complex construction raised an exception. This switch
7262 also suppress generation of cross-reference information (see
7263 @option{-gnatx}) since otherwise the cross-reference information
7264 would refer to the @file{^.dg^.DG^} file, which would cause
7265 confusion since this is not the original source file.
7266
7267 Note that @option{-gnatD} actually implies @option{-gnatG}
7268 automatically, so it is not necessary to give both options.
7269 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7270
7271 If the switch @option{-gnatL} is used in conjunction with
7272 @cindex @option{-gnatL} (@command{gcc})
7273 @option{-gnatDG}, then the original source lines are interspersed
7274 in the expanded source (as comment lines with the original line number).
7275
7276 The optional parameter @code{nn} if present after -gnatD specifies an
7277 alternative maximum line length that overrides the normal default of 72.
7278 This value is in the range 40-999999, values less than 40 being silently
7279 reset to 40. The equal sign is optional.
7280
7281 @item -gnatr
7282 @cindex @option{-gnatr} (@command{gcc})
7283 @cindex pragma Restrictions
7284 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7285 so that violation of restrictions causes warnings rather than illegalities.
7286 This is useful during the development process when new restrictions are added
7287 or investigated. The switch also causes pragma Profile to be treated as
7288 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7289 restriction warnings rather than restrictions.
7290
7291 @ifclear vms
7292 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7293 @cindex @option{-gnatR} (@command{gcc})
7294 This switch controls output from the compiler of a listing showing
7295 representation information for declared types and objects. For
7296 @option{-gnatR0}, no information is output (equivalent to omitting
7297 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7298 so @option{-gnatR} with no parameter has the same effect), size and alignment
7299 information is listed for declared array and record types. For
7300 @option{-gnatR2}, size and alignment information is listed for all
7301 declared types and objects. Finally @option{-gnatR3} includes symbolic
7302 expressions for values that are computed at run time for
7303 variant records. These symbolic expressions have a mostly obvious
7304 format with #n being used to represent the value of the n'th
7305 discriminant. See source files @file{repinfo.ads/adb} in the
7306 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7307 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7308 the output is to a file with the name @file{^file.rep^file_REP^} where
7309 file is the name of the corresponding source file.
7310 @end ifclear
7311 @ifset vms
7312 @item /REPRESENTATION_INFO
7313 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7314 This qualifier controls output from the compiler of a listing showing
7315 representation information for declared types and objects. For
7316 @option{/REPRESENTATION_INFO=NONE}, no information is output
7317 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7318 @option{/REPRESENTATION_INFO} without option is equivalent to
7319 @option{/REPRESENTATION_INFO=ARRAYS}.
7320 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7321 information is listed for declared array and record types. For
7322 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7323 is listed for all expression information for values that are computed
7324 at run time for variant records. These symbolic expressions have a mostly
7325 obvious format with #n being used to represent the value of the n'th
7326 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7327 @code{GNAT} sources for full details on the format of
7328 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7329 If _FILE is added at the end of an option
7330 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7331 then the output is to a file with the name @file{file_REP} where
7332 file is the name of the corresponding source file.
7333 @end ifset
7334 Note that it is possible for record components to have zero size. In
7335 this case, the component clause uses an obvious extension of permitted
7336 Ada syntax, for example @code{at 0 range 0 .. -1}.
7337
7338 Representation information requires that code be generated (since it is the
7339 code generator that lays out complex data structures). If an attempt is made
7340 to output representation information when no code is generated, for example
7341 when a subunit is compiled on its own, then no information can be generated
7342 and the compiler outputs a message to this effect.
7343
7344 @item -gnatS
7345 @cindex @option{-gnatS} (@command{gcc})
7346 The use of the switch @option{-gnatS} for an
7347 Ada compilation will cause the compiler to output a
7348 representation of package Standard in a form very
7349 close to standard Ada. It is not quite possible to
7350 do this entirely in standard Ada (since new
7351 numeric base types cannot be created in standard
7352 Ada), but the output is easily
7353 readable to any Ada programmer, and is useful to
7354 determine the characteristics of target dependent
7355 types in package Standard.
7356
7357 @item -gnatx
7358 @cindex @option{-gnatx} (@command{gcc})
7359 Normally the compiler generates full cross-referencing information in
7360 the @file{ALI} file. This information is used by a number of tools,
7361 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7362 suppresses this information. This saves some space and may slightly
7363 speed up compilation, but means that these tools cannot be used.
7364 @end table
7365
7366 @node Exception Handling Control
7367 @subsection Exception Handling Control
7368
7369 @noindent
7370 GNAT uses two methods for handling exceptions at run-time. The
7371 @code{setjmp/longjmp} method saves the context when entering
7372 a frame with an exception handler. Then when an exception is
7373 raised, the context can be restored immediately, without the
7374 need for tracing stack frames. This method provides very fast
7375 exception propagation, but introduces significant overhead for
7376 the use of exception handlers, even if no exception is raised.
7377
7378 The other approach is called ``zero cost'' exception handling.
7379 With this method, the compiler builds static tables to describe
7380 the exception ranges. No dynamic code is required when entering
7381 a frame containing an exception handler. When an exception is
7382 raised, the tables are used to control a back trace of the
7383 subprogram invocation stack to locate the required exception
7384 handler. This method has considerably poorer performance for
7385 the propagation of exceptions, but there is no overhead for
7386 exception handlers if no exception is raised. Note that in this
7387 mode and in the context of mixed Ada and C/C++ programming,
7388 to propagate an exception through a C/C++ code, the C/C++ code
7389 must be compiled with the @option{-funwind-tables} GCC's
7390 option.
7391
7392 The following switches may be used to control which of the
7393 two exception handling methods is used.
7394
7395 @table @option
7396 @c !sort!
7397
7398 @item --RTS=sjlj
7399 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7400 This switch causes the setjmp/longjmp run-time (when available) to be used
7401 for exception handling. If the default
7402 mechanism for the target is zero cost exceptions, then
7403 this switch can be used to modify this default, and must be
7404 used for all units in the partition.
7405 This option is rarely used. One case in which it may be
7406 advantageous is if you have an application where exception
7407 raising is common and the overall performance of the
7408 application is improved by favoring exception propagation.
7409
7410 @item --RTS=zcx
7411 @cindex @option{--RTS=zcx} (@command{gnatmake})
7412 @cindex Zero Cost Exceptions
7413 This switch causes the zero cost approach to be used
7414 for exception handling. If this is the default mechanism for the
7415 target (see below), then this switch is unneeded. If the default
7416 mechanism for the target is setjmp/longjmp exceptions, then
7417 this switch can be used to modify this default, and must be
7418 used for all units in the partition.
7419 This option can only be used if the zero cost approach
7420 is available for the target in use, otherwise it will generate an error.
7421 @end table
7422
7423 @noindent
7424 The same option @option{--RTS} must be used both for @command{gcc}
7425 and @command{gnatbind}. Passing this option to @command{gnatmake}
7426 (@pxref{Switches for gnatmake}) will ensure the required consistency
7427 through the compilation and binding steps.
7428
7429 @node Units to Sources Mapping Files
7430 @subsection Units to Sources Mapping Files
7431
7432 @table @option
7433
7434 @item -gnatem=@var{path}
7435 @cindex @option{-gnatem} (@command{gcc})
7436 A mapping file is a way to communicate to the compiler two mappings:
7437 from unit names to file names (without any directory information) and from
7438 file names to path names (with full directory information). These mappings
7439 are used by the compiler to short-circuit the path search.
7440
7441 The use of mapping files is not required for correct operation of the
7442 compiler, but mapping files can improve efficiency, particularly when
7443 sources are read over a slow network connection. In normal operation,
7444 you need not be concerned with the format or use of mapping files,
7445 and the @option{-gnatem} switch is not a switch that you would use
7446 explicitly. It is intended primarily for use by automatic tools such as
7447 @command{gnatmake} running under the project file facility. The
7448 description here of the format of mapping files is provided
7449 for completeness and for possible use by other tools.
7450
7451 A mapping file is a sequence of sets of three lines. In each set, the
7452 first line is the unit name, in lower case, with @code{%s} appended
7453 for specs and @code{%b} appended for bodies; the second line is the
7454 file name; and the third line is the path name.
7455
7456 Example:
7457 @smallexample
7458    main%b
7459    main.2.ada
7460    /gnat/project1/sources/main.2.ada
7461 @end smallexample
7462
7463 When the switch @option{-gnatem} is specified, the compiler will
7464 create in memory the two mappings from the specified file. If there is
7465 any problem (nonexistent file, truncated file or duplicate entries),
7466 no mapping will be created.
7467
7468 Several @option{-gnatem} switches may be specified; however, only the
7469 last one on the command line will be taken into account.
7470
7471 When using a project file, @command{gnatmake} creates a temporary
7472 mapping file and communicates it to the compiler using this switch.
7473
7474 @end table
7475
7476 @node Integrated Preprocessing
7477 @subsection Integrated Preprocessing
7478
7479 @noindent
7480 GNAT sources may be preprocessed immediately before compilation.
7481 In this case, the actual
7482 text of the source is not the text of the source file, but is derived from it
7483 through a process called preprocessing. Integrated preprocessing is specified
7484 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7485 indicates, through a text file, the preprocessing data to be used.
7486 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7487
7488 @noindent
7489 Note that when integrated preprocessing is used, the output from the
7490 preprocessor is not written to any external file. Instead it is passed
7491 internally to the compiler. If you need to preserve the result of
7492 preprocessing in a file, then you should use @command{gnatprep}
7493 to perform the desired preprocessing in stand-alone mode.
7494
7495 @noindent
7496 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7497 used when Integrated Preprocessing is used. The reason is that preprocessing
7498 with another Preprocessing Data file without changing the sources will
7499 not trigger recompilation without this switch.
7500
7501 @noindent
7502 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7503 always trigger recompilation for sources that are preprocessed,
7504 because @command{gnatmake} cannot compute the checksum of the source after
7505 preprocessing.
7506
7507 @noindent
7508 The actual preprocessing function is described in details in section
7509 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7510 preprocessing is triggered and parameterized.
7511
7512 @table @code
7513
7514 @item -gnatep=@var{file}
7515 @cindex @option{-gnatep} (@command{gcc})
7516 This switch indicates to the compiler the file name (without directory
7517 information) of the preprocessor data file to use. The preprocessor data file
7518 should be found in the source directories.
7519
7520 @noindent
7521 A preprocessing data file is a text file with significant lines indicating
7522 how should be preprocessed either a specific source or all sources not
7523 mentioned in other lines. A significant line is a nonempty, non-comment line.
7524 Comments are similar to Ada comments.
7525
7526 @noindent
7527 Each significant line starts with either a literal string or the character '*'.
7528 A literal string is the file name (without directory information) of the source
7529 to preprocess. A character '*' indicates the preprocessing for all the sources
7530 that are not specified explicitly on other lines (order of the lines is not
7531 significant). It is an error to have two lines with the same file name or two
7532 lines starting with the character '*'.
7533
7534 @noindent
7535 After the file name or the character '*', another optional literal string
7536 indicating the file name of the definition file to be used for preprocessing
7537 (@pxref{Form of Definitions File}). The definition files are found by the
7538 compiler in one of the source directories. In some cases, when compiling
7539 a source in a directory other than the current directory, if the definition
7540 file is in the current directory, it may be necessary to add the current
7541 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7542 the compiler would not find the definition file.
7543
7544 @noindent
7545 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7546 be found. Those ^switches^switches^ are:
7547
7548 @table @code
7549
7550 @item -b
7551 Causes both preprocessor lines and the lines deleted by
7552 preprocessing to be replaced by blank lines, preserving the line number.
7553 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7554 it cancels the effect of @option{-c}.
7555
7556 @item -c
7557 Causes both preprocessor lines and the lines deleted
7558 by preprocessing to be retained as comments marked
7559 with the special string ``@code{--! }''.
7560
7561 @item -Dsymbol=value
7562 Define or redefine a symbol, associated with value. A symbol is an Ada
7563 identifier, or an Ada reserved word, with the exception of @code{if},
7564 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7565 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7566 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7567 same name defined in a definition file.
7568
7569 @item -s
7570 Causes a sorted list of symbol names and values to be
7571 listed on the standard output file.
7572
7573 @item -u
7574 Causes undefined symbols to be treated as having the value @code{FALSE}
7575 in the context
7576 of a preprocessor test. In the absence of this option, an undefined symbol in
7577 a @code{#if} or @code{#elsif} test will be treated as an error.
7578
7579 @end table
7580
7581 @noindent
7582 Examples of valid lines in a preprocessor data file:
7583
7584 @smallexample
7585   "toto.adb"  "prep.def" -u
7586   --  preprocess "toto.adb", using definition file "prep.def",
7587   --  undefined symbol are False.
7588
7589   * -c -DVERSION=V101
7590   --  preprocess all other sources without a definition file;
7591   --  suppressed lined are commented; symbol VERSION has the value V101.
7592
7593   "titi.adb" "prep2.def" -s
7594   --  preprocess "titi.adb", using definition file "prep2.def";
7595   --  list all symbols with their values.
7596 @end smallexample
7597
7598 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7599 @cindex @option{-gnateD} (@command{gcc})
7600 Define or redefine a preprocessing symbol, associated with value. If no value
7601 is given on the command line, then the value of the symbol is @code{True}.
7602 A symbol is an identifier, following normal Ada (case-insensitive)
7603 rules for its syntax, and value is any sequence (including an empty sequence)
7604 of characters from the set (letters, digits, period, underline).
7605 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7606 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7607
7608 @noindent
7609 A symbol declared with this ^switch^switch^ on the command line replaces a
7610 symbol with the same name either in a definition file or specified with a
7611 ^switch^switch^ -D in the preprocessor data file.
7612
7613 @noindent
7614 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7615
7616 @item -gnateG
7617 When integrated preprocessing is performed and the preprocessor modifies
7618 the source text, write the result of this preprocessing into a file
7619 <source>^.prep^_prep^.
7620
7621 @end table
7622
7623 @node Code Generation Control
7624 @subsection Code Generation Control
7625
7626 @noindent
7627
7628 The GCC technology provides a wide range of target dependent
7629 @option{-m} switches for controlling
7630 details of code generation with respect to different versions of
7631 architectures. This includes variations in instruction sets (e.g.@:
7632 different members of the power pc family), and different requirements
7633 for optimal arrangement of instructions (e.g.@: different members of
7634 the x86 family). The list of available @option{-m} switches may be
7635 found in the GCC documentation.
7636
7637 Use of these @option{-m} switches may in some cases result in improved
7638 code performance.
7639
7640 The GNAT Pro technology is tested and qualified without any
7641 @option{-m} switches,
7642 so generally the most reliable approach is to avoid the use of these
7643 switches. However, we generally expect most of these switches to work
7644 successfully with GNAT Pro, and many customers have reported successful
7645 use of these options.
7646
7647 Our general advice is to avoid the use of @option{-m} switches unless
7648 special needs lead to requirements in this area. In particular,
7649 there is no point in using @option{-m} switches to improve performance
7650 unless you actually see a performance improvement.
7651
7652 @ifset vms
7653 @node Return Codes
7654 @subsection Return Codes
7655 @cindex Return Codes
7656 @cindex @option{/RETURN_CODES=VMS}
7657
7658 @noindent
7659 On VMS, GNAT compiled programs return POSIX-style codes by default,
7660 e.g.@: @option{/RETURN_CODES=POSIX}.
7661
7662 To enable VMS style return codes, use GNAT BIND and LINK with the option
7663 @option{/RETURN_CODES=VMS}. For example:
7664
7665 @smallexample
7666 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7667 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7668 @end smallexample
7669
7670 @noindent
7671 Programs built with /RETURN_CODES=VMS are suitable to be called in
7672 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7673 are suitable for spawning with appropriate GNAT RTL routines.
7674
7675 @end ifset
7676
7677 @node Search Paths and the Run-Time Library (RTL)
7678 @section Search Paths and the Run-Time Library (RTL)
7679
7680 @noindent
7681 With the GNAT source-based library system, the compiler must be able to
7682 find source files for units that are needed by the unit being compiled.
7683 Search paths are used to guide this process.
7684
7685 The compiler compiles one source file whose name must be given
7686 explicitly on the command line. In other words, no searching is done
7687 for this file. To find all other source files that are needed (the most
7688 common being the specs of units), the compiler examines the following
7689 directories, in the following order:
7690
7691 @enumerate
7692 @item
7693 The directory containing the source file of the main unit being compiled
7694 (the file name on the command line).
7695
7696 @item
7697 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7698 @command{gcc} command line, in the order given.
7699
7700 @item
7701 @findex ADA_PRJ_INCLUDE_FILE
7702 Each of the directories listed in the text file whose name is given
7703 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7704
7705 @noindent
7706 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7707 driver when project files are used. It should not normally be set
7708 by other means.
7709
7710 @item
7711 @findex ADA_INCLUDE_PATH
7712 Each of the directories listed in the value of the
7713 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7714 @ifclear vms
7715 Construct this value
7716 exactly as the @env{PATH} environment variable: a list of directory
7717 names separated by colons (semicolons when working with the NT version).
7718 @end ifclear
7719 @ifset vms
7720 Normally, define this value as a logical name containing a comma separated
7721 list of directory names.
7722
7723 This variable can also be defined by means of an environment string
7724 (an argument to the HP C exec* set of functions).
7725
7726 Logical Name:
7727 @smallexample
7728 DEFINE ANOTHER_PATH FOO:[BAG]
7729 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7730 @end smallexample
7731
7732 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7733 first, followed by the standard Ada
7734 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7735 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7736 (Text_IO, Sequential_IO, etc)
7737 instead of the standard Ada packages. Thus, in order to get the standard Ada
7738 packages by default, ADA_INCLUDE_PATH must be redefined.
7739 @end ifset
7740
7741 @item
7742 The content of the @file{ada_source_path} file which is part of the GNAT
7743 installation tree and is used to store standard libraries such as the
7744 GNAT Run Time Library (RTL) source files.
7745 @ifclear vms
7746 @ref{Installing a library}
7747 @end ifclear
7748 @end enumerate
7749
7750 @noindent
7751 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7752 inhibits the use of the directory
7753 containing the source file named in the command line. You can still
7754 have this directory on your search path, but in this case it must be
7755 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7756
7757 Specifying the switch @option{-nostdinc}
7758 inhibits the search of the default location for the GNAT Run Time
7759 Library (RTL) source files.
7760
7761 The compiler outputs its object files and ALI files in the current
7762 working directory.
7763 @ifclear vms
7764 Caution: The object file can be redirected with the @option{-o} switch;
7765 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7766 so the @file{ALI} file will not go to the right place. Therefore, you should
7767 avoid using the @option{-o} switch.
7768 @end ifclear
7769
7770 @findex System.IO
7771 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7772 children make up the GNAT RTL, together with the simple @code{System.IO}
7773 package used in the @code{"Hello World"} example. The sources for these units
7774 are needed by the compiler and are kept together in one directory. Not
7775 all of the bodies are needed, but all of the sources are kept together
7776 anyway. In a normal installation, you need not specify these directory
7777 names when compiling or binding. Either the environment variables or
7778 the built-in defaults cause these files to be found.
7779
7780 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7781 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7782 consisting of child units of @code{GNAT}. This is a collection of generally
7783 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7784 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7785
7786 Besides simplifying access to the RTL, a major use of search paths is
7787 in compiling sources from multiple directories. This can make
7788 development environments much more flexible.
7789
7790 @node Order of Compilation Issues
7791 @section Order of Compilation Issues
7792
7793 @noindent
7794 If, in our earlier example, there was a spec for the @code{hello}
7795 procedure, it would be contained in the file @file{hello.ads}; yet this
7796 file would not have to be explicitly compiled. This is the result of the
7797 model we chose to implement library management. Some of the consequences
7798 of this model are as follows:
7799
7800 @itemize @bullet
7801 @item
7802 There is no point in compiling specs (except for package
7803 specs with no bodies) because these are compiled as needed by clients. If
7804 you attempt a useless compilation, you will receive an error message.
7805 It is also useless to compile subunits because they are compiled as needed
7806 by the parent.
7807
7808 @item
7809 There are no order of compilation requirements: performing a
7810 compilation never obsoletes anything. The only way you can obsolete
7811 something and require recompilations is to modify one of the
7812 source files on which it depends.
7813
7814 @item
7815 There is no library as such, apart from the ALI files
7816 (@pxref{The Ada Library Information Files}, for information on the format
7817 of these files). For now we find it convenient to create separate ALI files,
7818 but eventually the information therein may be incorporated into the object
7819 file directly.
7820
7821 @item
7822 When you compile a unit, the source files for the specs of all units
7823 that it @code{with}'s, all its subunits, and the bodies of any generics it
7824 instantiates must be available (reachable by the search-paths mechanism
7825 described above), or you will receive a fatal error message.
7826 @end itemize
7827
7828 @node Examples
7829 @section Examples
7830
7831 @noindent
7832 The following are some typical Ada compilation command line examples:
7833
7834 @table @code
7835 @item $ gcc -c xyz.adb
7836 Compile body in file @file{xyz.adb} with all default options.
7837
7838 @ifclear vms
7839 @item $ gcc -c -O2 -gnata xyz-def.adb
7840 @end ifclear
7841 @ifset vms
7842 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7843 @end ifset
7844
7845 Compile the child unit package in file @file{xyz-def.adb} with extensive
7846 optimizations, and pragma @code{Assert}/@code{Debug} statements
7847 enabled.
7848
7849 @item $ gcc -c -gnatc abc-def.adb
7850 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7851 mode.
7852 @end table
7853
7854 @node Binding Using gnatbind
7855 @chapter Binding Using @code{gnatbind}
7856 @findex gnatbind
7857
7858 @menu
7859 * Running gnatbind::
7860 * Switches for gnatbind::
7861 * Command-Line Access::
7862 * Search Paths for gnatbind::
7863 * Examples of gnatbind Usage::
7864 @end menu
7865
7866 @noindent
7867 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7868 to bind compiled GNAT objects.
7869
7870 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7871 driver (see @ref{The GNAT Driver and Project Files}).
7872
7873 The @code{gnatbind} program performs four separate functions:
7874
7875 @enumerate
7876 @item
7877 Checks that a program is consistent, in accordance with the rules in
7878 Chapter 10 of the Ada Reference Manual. In particular, error
7879 messages are generated if a program uses inconsistent versions of a
7880 given unit.
7881
7882 @item
7883 Checks that an acceptable order of elaboration exists for the program
7884 and issues an error message if it cannot find an order of elaboration
7885 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7886
7887 @item
7888 Generates a main program incorporating the given elaboration order.
7889 This program is a small Ada package (body and spec) that
7890 must be subsequently compiled
7891 using the GNAT compiler. The necessary compilation step is usually
7892 performed automatically by @command{gnatlink}. The two most important
7893 functions of this program
7894 are to call the elaboration routines of units in an appropriate order
7895 and to call the main program.
7896
7897 @item
7898 Determines the set of object files required by the given main program.
7899 This information is output in the forms of comments in the generated program,
7900 to be read by the @command{gnatlink} utility used to link the Ada application.
7901 @end enumerate
7902
7903 @node Running gnatbind
7904 @section Running @code{gnatbind}
7905
7906 @noindent
7907 The form of the @code{gnatbind} command is
7908
7909 @smallexample
7910 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7911 @c Expanding @ovar macro inline (explanation in macro def comments)
7912 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7913 @end smallexample
7914
7915 @noindent
7916 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7917 unit body. @code{gnatbind} constructs an Ada
7918 package in two files whose names are
7919 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7920 For example, if given the
7921 parameter @file{hello.ali}, for a main program contained in file
7922 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7923 and @file{b~hello.adb}.
7924
7925 When doing consistency checking, the binder takes into consideration
7926 any source files it can locate. For example, if the binder determines
7927 that the given main program requires the package @code{Pack}, whose
7928 @file{.ALI}
7929 file is @file{pack.ali} and whose corresponding source spec file is
7930 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7931 (using the same search path conventions as previously described for the
7932 @command{gcc} command). If it can locate this source file, it checks that
7933 the time stamps
7934 or source checksums of the source and its references to in @file{ALI} files
7935 match. In other words, any @file{ALI} files that mentions this spec must have
7936 resulted from compiling this version of the source file (or in the case
7937 where the source checksums match, a version close enough that the
7938 difference does not matter).
7939
7940 @cindex Source files, use by binder
7941 The effect of this consistency checking, which includes source files, is
7942 that the binder ensures that the program is consistent with the latest
7943 version of the source files that can be located at bind time. Editing a
7944 source file without compiling files that depend on the source file cause
7945 error messages to be generated by the binder.
7946
7947 For example, suppose you have a main program @file{hello.adb} and a
7948 package @code{P}, from file @file{p.ads} and you perform the following
7949 steps:
7950
7951 @enumerate
7952 @item
7953 Enter @code{gcc -c hello.adb} to compile the main program.
7954
7955 @item
7956 Enter @code{gcc -c p.ads} to compile package @code{P}.
7957
7958 @item
7959 Edit file @file{p.ads}.
7960
7961 @item
7962 Enter @code{gnatbind hello}.
7963 @end enumerate
7964
7965 @noindent
7966 At this point, the file @file{p.ali} contains an out-of-date time stamp
7967 because the file @file{p.ads} has been edited. The attempt at binding
7968 fails, and the binder generates the following error messages:
7969
7970 @smallexample
7971 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7972 error: "p.ads" has been modified and must be recompiled
7973 @end smallexample
7974
7975 @noindent
7976 Now both files must be recompiled as indicated, and then the bind can
7977 succeed, generating a main program. You need not normally be concerned
7978 with the contents of this file, but for reference purposes a sample
7979 binder output file is given in @ref{Example of Binder Output File}.
7980
7981 In most normal usage, the default mode of @command{gnatbind} which is to
7982 generate the main package in Ada, as described in the previous section.
7983 In particular, this means that any Ada programmer can read and understand
7984 the generated main program. It can also be debugged just like any other
7985 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7986 @command{gnatbind} and @command{gnatlink}.
7987
7988 @node Switches for gnatbind
7989 @section Switches for @command{gnatbind}
7990
7991 @noindent
7992 The following switches are available with @code{gnatbind}; details will
7993 be presented in subsequent sections.
7994
7995 @menu
7996 * Consistency-Checking Modes::
7997 * Binder Error Message Control::
7998 * Elaboration Control::
7999 * Output Control::
8000 * Binding with Non-Ada Main Programs::
8001 * Binding Programs with No Main Subprogram::
8002 @end menu
8003
8004 @table @option
8005 @c !sort!
8006
8007 @item --version
8008 @cindex @option{--version} @command{gnatbind}
8009 Display Copyright and version, then exit disregarding all other options.
8010
8011 @item --help
8012 @cindex @option{--help} @command{gnatbind}
8013 If @option{--version} was not used, display usage, then exit disregarding
8014 all other options.
8015
8016 @item -a
8017 @cindex @option{-a} @command{gnatbind}
8018 Indicates that, if supported by the platform, the adainit procedure should
8019 be treated as an initialisation routine by the linker (a constructor). This
8020 is intended to be used by the Project Manager to automatically initialize
8021 shared Stand-Alone Libraries.
8022
8023 @item ^-aO^/OBJECT_SEARCH^
8024 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8025 Specify directory to be searched for ALI files.
8026
8027 @item ^-aI^/SOURCE_SEARCH^
8028 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8029 Specify directory to be searched for source file.
8030
8031 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8032 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8033 Output ALI list (to standard output or to the named file).
8034
8035 @item ^-b^/REPORT_ERRORS=BRIEF^
8036 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8037 Generate brief messages to @file{stderr} even if verbose mode set.
8038
8039 @item ^-c^/NOOUTPUT^
8040 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8041 Check only, no generation of binder output file.
8042
8043 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8044 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8045 This switch can be used to change the default task stack size value
8046 to a specified size @var{nn}, which is expressed in bytes by default, or
8047 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8048 with @var{m}.
8049 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8050 in effect, to completing all task specs with
8051 @smallexample @c ada
8052    pragma Storage_Size (nn);
8053 @end smallexample
8054 When they do not already have such a pragma.
8055
8056 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8057 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8058 This switch can be used to change the default secondary stack size value
8059 to a specified size @var{nn}, which is expressed in bytes by default, or
8060 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8061 with @var{m}.
8062
8063 The secondary stack is used to deal with functions that return a variable
8064 sized result, for example a function returning an unconstrained
8065 String. There are two ways in which this secondary stack is allocated.
8066
8067 For most targets, the secondary stack is growing on demand and is allocated
8068 as a chain of blocks in the heap. The -D option is not very
8069 relevant. It only give some control over the size of the allocated
8070 blocks (whose size is the minimum of the default secondary stack size value,
8071 and the actual size needed for the current allocation request).
8072
8073 For certain targets, notably VxWorks 653,
8074 the secondary stack is allocated by carving off a fixed ratio chunk of the
8075 primary task stack. The -D option is used to define the
8076 size of the environment task's secondary stack.
8077
8078 @item ^-e^/ELABORATION_DEPENDENCIES^
8079 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8080 Output complete list of elaboration-order dependencies.
8081
8082 @item ^-E^/STORE_TRACEBACKS^
8083 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8084 Store tracebacks in exception occurrences when the target supports it.
8085 This is the default with the zero cost exception mechanism.
8086 @ignore
8087 @c The following may get moved to an appendix
8088 This option is currently supported on the following targets:
8089 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8090 @end ignore
8091 See also the packages @code{GNAT.Traceback} and
8092 @code{GNAT.Traceback.Symbolic} for more information.
8093 @ifclear vms
8094 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8095 @command{gcc} option.
8096 @end ifclear
8097
8098 @item ^-F^/FORCE_ELABS_FLAGS^
8099 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8100 Force the checks of elaboration flags. @command{gnatbind} does not normally
8101 generate checks of elaboration flags for the main executable, except when
8102 a Stand-Alone Library is used. However, there are cases when this cannot be
8103 detected by gnatbind. An example is importing an interface of a Stand-Alone
8104 Library through a pragma Import and only specifying through a linker switch
8105 this Stand-Alone Library. This switch is used to guarantee that elaboration
8106 flag checks are generated.
8107
8108 @item ^-h^/HELP^
8109 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8110 Output usage (help) information
8111
8112 @item ^-I^/SEARCH^
8113 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8114 Specify directory to be searched for source and ALI files.
8115
8116 @item ^-I-^/NOCURRENT_DIRECTORY^
8117 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8118 Do not look for sources in the current directory where @code{gnatbind} was
8119 invoked, and do not look for ALI files in the directory containing the
8120 ALI file named in the @code{gnatbind} command line.
8121
8122 @item ^-l^/ORDER_OF_ELABORATION^
8123 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8124 Output chosen elaboration order.
8125
8126 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8127 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8128 Bind the units for library building. In this case the adainit and
8129 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8130 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8131 ^@var{xxx}final^@var{XXX}FINAL^.
8132 Implies ^-n^/NOCOMPILE^.
8133 @ifclear vms
8134 (@xref{GNAT and Libraries}, for more details.)
8135 @end ifclear
8136 @ifset vms
8137 On OpenVMS, these init and final procedures are exported in uppercase
8138 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8139 the init procedure will be "TOTOINIT" and the exported name of the final
8140 procedure will be "TOTOFINAL".
8141 @end ifset
8142
8143 @item ^-Mxyz^/RENAME_MAIN=xyz^
8144 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8145 Rename generated main program from main to xyz. This option is
8146 supported on cross environments only.
8147
8148 @item ^-m^/ERROR_LIMIT=^@var{n}
8149 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8150 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8151 in the range 1..999999. The default value if no switch is
8152 given is 9999. If the number of warnings reaches this limit, then a
8153 message is output and further warnings are suppressed, the bind
8154 continues in this case. If the number of errors reaches this
8155 limit, then a message is output and the bind is abandoned.
8156 A value of zero means that no limit is enforced. The equal
8157 sign is optional.
8158
8159 @ifset unw
8160 Furthermore, under Windows, the sources pointed to by the libraries path
8161 set in the registry are not searched for.
8162 @end ifset
8163
8164 @item ^-n^/NOMAIN^
8165 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8166 No main program.
8167
8168 @item -nostdinc
8169 @cindex @option{-nostdinc} (@command{gnatbind})
8170 Do not look for sources in the system default directory.
8171
8172 @item -nostdlib
8173 @cindex @option{-nostdlib} (@command{gnatbind})
8174 Do not look for library files in the system default directory.
8175
8176 @item --RTS=@var{rts-path}
8177 @cindex @option{--RTS} (@code{gnatbind})
8178 Specifies the default location of the runtime library. Same meaning as the
8179 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8180
8181 @item ^-o ^/OUTPUT=^@var{file}
8182 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8183 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8184 Note that if this option is used, then linking must be done manually,
8185 gnatlink cannot be used.
8186
8187 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8188 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8189 Output object list (to standard output or to the named file).
8190
8191 @item ^-p^/PESSIMISTIC_ELABORATION^
8192 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8193 Pessimistic (worst-case) elaboration order
8194
8195 @item ^-R^-R^
8196 @cindex @option{^-R^-R^} (@command{gnatbind})
8197 Output closure source list.
8198
8199 @item ^-s^/READ_SOURCES=ALL^
8200 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8201 Require all source files to be present.
8202
8203 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8204 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8205 Specifies the value to be used when detecting uninitialized scalar
8206 objects with pragma Initialize_Scalars.
8207 The @var{xxx} ^string specified with the switch^option^ may be either
8208 @itemize @bullet
8209 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8210 @item ``@option{^lo^LOW^}'' for the lowest possible value
8211 @item ``@option{^hi^HIGH^}'' for the highest possible value
8212 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8213 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8214 @end itemize
8215
8216 In addition, you can specify @option{-Sev} to indicate that the value is
8217 to be set at run time. In this case, the program will look for an environment
8218 @cindex GNAT_INIT_SCALARS
8219 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8220 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8221 If no environment variable is found, or if it does not have a valid value,
8222 then the default is @option{in} (invalid values).
8223
8224 @ifclear vms
8225 @item -static
8226 @cindex @option{-static} (@code{gnatbind})
8227 Link against a static GNAT run time.
8228
8229 @item -shared
8230 @cindex @option{-shared} (@code{gnatbind})
8231 Link against a shared GNAT run time when available.
8232 @end ifclear
8233
8234 @item ^-t^/NOTIME_STAMP_CHECK^
8235 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8236 Tolerate time stamp and other consistency errors
8237
8238 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8239 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8240 Set the time slice value to @var{n} milliseconds. If the system supports
8241 the specification of a specific time slice value, then the indicated value
8242 is used. If the system does not support specific time slice values, but
8243 does support some general notion of round-robin scheduling, then any
8244 nonzero value will activate round-robin scheduling.
8245
8246 A value of zero is treated specially. It turns off time
8247 slicing, and in addition, indicates to the tasking run time that the
8248 semantics should match as closely as possible the Annex D
8249 requirements of the Ada RM, and in particular sets the default
8250 scheduling policy to @code{FIFO_Within_Priorities}.
8251
8252 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8253 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8254 Enable dynamic stack usage, with @var{n} results stored and displayed
8255 at program termination. A result is generated when a task
8256 terminates. Results that can't be stored are displayed on the fly, at
8257 task termination. This option is currently not supported on Itanium
8258 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8259
8260 @item ^-v^/REPORT_ERRORS=VERBOSE^
8261 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8262 Verbose mode. Write error messages, header, summary output to
8263 @file{stdout}.
8264
8265 @ifclear vms
8266 @item -w@var{x}
8267 @cindex @option{-w} (@code{gnatbind})
8268 Warning mode (@var{x}=s/e for suppress/treat as error)
8269 @end ifclear
8270
8271 @ifset vms
8272 @item /WARNINGS=NORMAL
8273 @cindex @option{/WARNINGS} (@code{gnatbind})
8274 Normal warnings mode. Warnings are issued but ignored
8275
8276 @item /WARNINGS=SUPPRESS
8277 @cindex @option{/WARNINGS} (@code{gnatbind})
8278 All warning messages are suppressed
8279
8280 @item /WARNINGS=ERROR
8281 @cindex @option{/WARNINGS} (@code{gnatbind})
8282 Warning messages are treated as fatal errors
8283 @end ifset
8284
8285 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8286 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8287 Override default wide character encoding for standard Text_IO files.
8288
8289 @item ^-x^/READ_SOURCES=NONE^
8290 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8291 Exclude source files (check object consistency only).
8292
8293 @ifset vms
8294 @item /READ_SOURCES=AVAILABLE
8295 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8296 Default mode, in which sources are checked for consistency only if
8297 they are available.
8298 @end ifset
8299
8300 @item ^-y^/ENABLE_LEAP_SECONDS^
8301 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8302 Enable leap seconds support in @code{Ada.Calendar} and its children.
8303
8304 @item ^-z^/ZERO_MAIN^
8305 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8306 No main subprogram.
8307 @end table
8308
8309 @ifclear vms
8310 @noindent
8311 You may obtain this listing of switches by running @code{gnatbind} with
8312 no arguments.
8313 @end ifclear
8314
8315 @node Consistency-Checking Modes
8316 @subsection Consistency-Checking Modes
8317
8318 @noindent
8319 As described earlier, by default @code{gnatbind} checks
8320 that object files are consistent with one another and are consistent
8321 with any source files it can locate. The following switches control binder
8322 access to sources.
8323
8324 @table @option
8325 @c !sort!
8326 @item ^-s^/READ_SOURCES=ALL^
8327 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8328 Require source files to be present. In this mode, the binder must be
8329 able to locate all source files that are referenced, in order to check
8330 their consistency. In normal mode, if a source file cannot be located it
8331 is simply ignored. If you specify this switch, a missing source
8332 file is an error.
8333
8334 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8335 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8336 Override default wide character encoding for standard Text_IO files.
8337 Normally the default wide character encoding method used for standard
8338 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8339 the main source input (see description of switch
8340 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8341 use of this switch for the binder (which has the same set of
8342 possible arguments) overrides this default as specified.
8343
8344 @item ^-x^/READ_SOURCES=NONE^
8345 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8346 Exclude source files. In this mode, the binder only checks that ALI
8347 files are consistent with one another. Source files are not accessed.
8348 The binder runs faster in this mode, and there is still a guarantee that
8349 the resulting program is self-consistent.
8350 If a source file has been edited since it was last compiled, and you
8351 specify this switch, the binder will not detect that the object
8352 file is out of date with respect to the source file. Note that this is the
8353 mode that is automatically used by @command{gnatmake} because in this
8354 case the checking against sources has already been performed by
8355 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8356
8357 @ifset vms
8358 @item /READ_SOURCES=AVAILABLE
8359 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8360 This is the default mode in which source files are checked if they are
8361 available, and ignored if they are not available.
8362 @end ifset
8363 @end table
8364
8365 @node Binder Error Message Control
8366 @subsection Binder Error Message Control
8367
8368 @noindent
8369 The following switches provide control over the generation of error
8370 messages from the binder:
8371
8372 @table @option
8373 @c !sort!
8374 @item ^-v^/REPORT_ERRORS=VERBOSE^
8375 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8376 Verbose mode. In the normal mode, brief error messages are generated to
8377 @file{stderr}. If this switch is present, a header is written
8378 to @file{stdout} and any error messages are directed to @file{stdout}.
8379 All that is written to @file{stderr} is a brief summary message.
8380
8381 @item ^-b^/REPORT_ERRORS=BRIEF^
8382 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8383 Generate brief error messages to @file{stderr} even if verbose mode is
8384 specified. This is relevant only when used with the
8385 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8386
8387 @ifclear vms
8388 @item -m@var{n}
8389 @cindex @option{-m} (@code{gnatbind})
8390 Limits the number of error messages to @var{n}, a decimal integer in the
8391 range 1-999. The binder terminates immediately if this limit is reached.
8392
8393 @item -M@var{xxx}
8394 @cindex @option{-M} (@code{gnatbind})
8395 Renames the generated main program from @code{main} to @code{xxx}.
8396 This is useful in the case of some cross-building environments, where
8397 the actual main program is separate from the one generated
8398 by @code{gnatbind}.
8399 @end ifclear
8400
8401 @item ^-ws^/WARNINGS=SUPPRESS^
8402 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8403 @cindex Warnings
8404 Suppress all warning messages.
8405
8406 @item ^-we^/WARNINGS=ERROR^
8407 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8408 Treat any warning messages as fatal errors.
8409
8410 @ifset vms
8411 @item /WARNINGS=NORMAL
8412 Standard mode with warnings generated, but warnings do not get treated
8413 as errors.
8414 @end ifset
8415
8416 @item ^-t^/NOTIME_STAMP_CHECK^
8417 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8418 @cindex Time stamp checks, in binder
8419 @cindex Binder consistency checks
8420 @cindex Consistency checks, in binder
8421 The binder performs a number of consistency checks including:
8422
8423 @itemize @bullet
8424 @item
8425 Check that time stamps of a given source unit are consistent
8426 @item
8427 Check that checksums of a given source unit are consistent
8428 @item
8429 Check that consistent versions of @code{GNAT} were used for compilation
8430 @item
8431 Check consistency of configuration pragmas as required
8432 @end itemize
8433
8434 @noindent
8435 Normally failure of such checks, in accordance with the consistency
8436 requirements of the Ada Reference Manual, causes error messages to be
8437 generated which abort the binder and prevent the output of a binder
8438 file and subsequent link to obtain an executable.
8439
8440 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8441 into warnings, so that
8442 binding and linking can continue to completion even in the presence of such
8443 errors. The result may be a failed link (due to missing symbols), or a
8444 non-functional executable which has undefined semantics.
8445 @emph{This means that
8446 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8447 with extreme care.}
8448 @end table
8449
8450 @node Elaboration Control
8451 @subsection Elaboration Control
8452
8453 @noindent
8454 The following switches provide additional control over the elaboration
8455 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8456
8457 @table @option
8458 @item ^-p^/PESSIMISTIC_ELABORATION^
8459 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8460 Normally the binder attempts to choose an elaboration order that is
8461 likely to minimize the likelihood of an elaboration order error resulting
8462 in raising a @code{Program_Error} exception. This switch reverses the
8463 action of the binder, and requests that it deliberately choose an order
8464 that is likely to maximize the likelihood of an elaboration error.
8465 This is useful in ensuring portability and avoiding dependence on
8466 accidental fortuitous elaboration ordering.
8467
8468 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8469 switch if dynamic
8470 elaboration checking is used (@option{-gnatE} switch used for compilation).
8471 This is because in the default static elaboration mode, all necessary
8472 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8473 These implicit pragmas are still respected by the binder in
8474 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8475 safe elaboration order is assured.
8476 @end table
8477
8478 @node Output Control
8479 @subsection Output Control
8480
8481 @noindent
8482 The following switches allow additional control over the output
8483 generated by the binder.
8484
8485 @table @option
8486 @c !sort!
8487
8488 @item ^-c^/NOOUTPUT^
8489 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8490 Check only. Do not generate the binder output file. In this mode the
8491 binder performs all error checks but does not generate an output file.
8492
8493 @item ^-e^/ELABORATION_DEPENDENCIES^
8494 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8495 Output complete list of elaboration-order dependencies, showing the
8496 reason for each dependency. This output can be rather extensive but may
8497 be useful in diagnosing problems with elaboration order. The output is
8498 written to @file{stdout}.
8499
8500 @item ^-h^/HELP^
8501 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8502 Output usage information. The output is written to @file{stdout}.
8503
8504 @item ^-K^/LINKER_OPTION_LIST^
8505 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8506 Output linker options to @file{stdout}. Includes library search paths,
8507 contents of pragmas Ident and Linker_Options, and libraries added
8508 by @code{gnatbind}.
8509
8510 @item ^-l^/ORDER_OF_ELABORATION^
8511 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8512 Output chosen elaboration order. The output is written to @file{stdout}.
8513
8514 @item ^-O^/OBJECT_LIST^
8515 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8516 Output full names of all the object files that must be linked to provide
8517 the Ada component of the program. The output is written to @file{stdout}.
8518 This list includes the files explicitly supplied and referenced by the user
8519 as well as implicitly referenced run-time unit files. The latter are
8520 omitted if the corresponding units reside in shared libraries. The
8521 directory names for the run-time units depend on the system configuration.
8522
8523 @item ^-o ^/OUTPUT=^@var{file}
8524 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8525 Set name of output file to @var{file} instead of the normal
8526 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8527 binder generated body filename.
8528 Note that if this option is used, then linking must be done manually.
8529 It is not possible to use gnatlink in this case, since it cannot locate
8530 the binder file.
8531
8532 @item ^-r^/RESTRICTION_LIST^
8533 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8534 Generate list of @code{pragma Restrictions} that could be applied to
8535 the current unit. This is useful for code audit purposes, and also may
8536 be used to improve code generation in some cases.
8537
8538 @end table
8539
8540 @node Binding with Non-Ada Main Programs
8541 @subsection Binding with Non-Ada Main Programs
8542
8543 @noindent
8544 In our description so far we have assumed that the main
8545 program is in Ada, and that the task of the binder is to generate a
8546 corresponding function @code{main} that invokes this Ada main
8547 program. GNAT also supports the building of executable programs where
8548 the main program is not in Ada, but some of the called routines are
8549 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8550 The following switch is used in this situation:
8551
8552 @table @option
8553 @item ^-n^/NOMAIN^
8554 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8555 No main program. The main program is not in Ada.
8556 @end table
8557
8558 @noindent
8559 In this case, most of the functions of the binder are still required,
8560 but instead of generating a main program, the binder generates a file
8561 containing the following callable routines:
8562
8563 @table @code
8564 @item adainit
8565 @findex adainit
8566 You must call this routine to initialize the Ada part of the program by
8567 calling the necessary elaboration routines. A call to @code{adainit} is
8568 required before the first call to an Ada subprogram.
8569
8570 Note that it is assumed that the basic execution environment must be setup
8571 to be appropriate for Ada execution at the point where the first Ada
8572 subprogram is called. In particular, if the Ada code will do any
8573 floating-point operations, then the FPU must be setup in an appropriate
8574 manner. For the case of the x86, for example, full precision mode is
8575 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8576 that the FPU is in the right state.
8577
8578 @item adafinal
8579 @findex adafinal
8580 You must call this routine to perform any library-level finalization
8581 required by the Ada subprograms. A call to @code{adafinal} is required
8582 after the last call to an Ada subprogram, and before the program
8583 terminates.
8584 @end table
8585
8586 @noindent
8587 If the @option{^-n^/NOMAIN^} switch
8588 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8589 @cindex Binder, multiple input files
8590 is given, more than one ALI file may appear on
8591 the command line for @code{gnatbind}. The normal @dfn{closure}
8592 calculation is performed for each of the specified units. Calculating
8593 the closure means finding out the set of units involved by tracing
8594 @code{with} references. The reason it is necessary to be able to
8595 specify more than one ALI file is that a given program may invoke two or
8596 more quite separate groups of Ada units.
8597
8598 The binder takes the name of its output file from the last specified ALI
8599 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8600 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8601 The output is an Ada unit in source form that can be compiled with GNAT.
8602 This compilation occurs automatically as part of the @command{gnatlink}
8603 processing.
8604
8605 Currently the GNAT run time requires a FPU using 80 bits mode
8606 precision. Under targets where this is not the default it is required to
8607 call GNAT.Float_Control.Reset before using floating point numbers (this
8608 include float computation, float input and output) in the Ada code. A
8609 side effect is that this could be the wrong mode for the foreign code
8610 where floating point computation could be broken after this call.
8611
8612 @node Binding Programs with No Main Subprogram
8613 @subsection Binding Programs with No Main Subprogram
8614
8615 @noindent
8616 It is possible to have an Ada program which does not have a main
8617 subprogram. This program will call the elaboration routines of all the
8618 packages, then the finalization routines.
8619
8620 The following switch is used to bind programs organized in this manner:
8621
8622 @table @option
8623 @item ^-z^/ZERO_MAIN^
8624 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8625 Normally the binder checks that the unit name given on the command line
8626 corresponds to a suitable main subprogram. When this switch is used,
8627 a list of ALI files can be given, and the execution of the program
8628 consists of elaboration of these units in an appropriate order. Note
8629 that the default wide character encoding method for standard Text_IO
8630 files is always set to Brackets if this switch is set (you can use
8631 the binder switch
8632 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8633 @end table
8634
8635 @node Command-Line Access
8636 @section Command-Line Access
8637
8638 @noindent
8639 The package @code{Ada.Command_Line} provides access to the command-line
8640 arguments and program name. In order for this interface to operate
8641 correctly, the two variables
8642
8643 @smallexample
8644 @group
8645 int gnat_argc;
8646 char **gnat_argv;
8647 @end group
8648 @end smallexample
8649
8650 @noindent
8651 @findex gnat_argv
8652 @findex gnat_argc
8653 are declared in one of the GNAT library routines. These variables must
8654 be set from the actual @code{argc} and @code{argv} values passed to the
8655 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8656 generates the C main program to automatically set these variables.
8657 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8658 set these variables. If they are not set, the procedures in
8659 @code{Ada.Command_Line} will not be available, and any attempt to use
8660 them will raise @code{Constraint_Error}. If command line access is
8661 required, your main program must set @code{gnat_argc} and
8662 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8663 it.
8664
8665 @node Search Paths for gnatbind
8666 @section Search Paths for @code{gnatbind}
8667
8668 @noindent
8669 The binder takes the name of an ALI file as its argument and needs to
8670 locate source files as well as other ALI files to verify object consistency.
8671
8672 For source files, it follows exactly the same search rules as @command{gcc}
8673 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8674 directories searched are:
8675
8676 @enumerate
8677 @item
8678 The directory containing the ALI file named in the command line, unless
8679 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8680
8681 @item
8682 All directories specified by @option{^-I^/SEARCH^}
8683 switches on the @code{gnatbind}
8684 command line, in the order given.
8685
8686 @item
8687 @findex ADA_PRJ_OBJECTS_FILE
8688 Each of the directories listed in the text file whose name is given
8689 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8690
8691 @noindent
8692 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8693 driver when project files are used. It should not normally be set
8694 by other means.
8695
8696 @item
8697 @findex ADA_OBJECTS_PATH
8698 Each of the directories listed in the value of the
8699 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8700 @ifset unw
8701 Construct this value
8702 exactly as the @env{PATH} environment variable: a list of directory
8703 names separated by colons (semicolons when working with the NT version
8704 of GNAT).
8705 @end ifset
8706 @ifset vms
8707 Normally, define this value as a logical name containing a comma separated
8708 list of directory names.
8709
8710 This variable can also be defined by means of an environment string
8711 (an argument to the HP C exec* set of functions).
8712
8713 Logical Name:
8714 @smallexample
8715 DEFINE ANOTHER_PATH FOO:[BAG]
8716 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8717 @end smallexample
8718
8719 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8720 first, followed by the standard Ada
8721 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8722 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8723 (Text_IO, Sequential_IO, etc)
8724 instead of the standard Ada packages. Thus, in order to get the standard Ada
8725 packages by default, ADA_OBJECTS_PATH must be redefined.
8726 @end ifset
8727
8728 @item
8729 The content of the @file{ada_object_path} file which is part of the GNAT
8730 installation tree and is used to store standard libraries such as the
8731 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8732 specified.
8733 @ifclear vms
8734 @ref{Installing a library}
8735 @end ifclear
8736 @end enumerate
8737
8738 @noindent
8739 In the binder the switch @option{^-I^/SEARCH^}
8740 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8741 is used to specify both source and
8742 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8743 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8744 instead if you want to specify
8745 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8746 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8747 if you want to specify library paths
8748 only. This means that for the binder
8749 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8750 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8751 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8752 The binder generates the bind file (a C language source file) in the
8753 current working directory.
8754
8755 @findex Ada
8756 @findex System
8757 @findex Interfaces
8758 @findex GNAT
8759 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8760 children make up the GNAT Run-Time Library, together with the package
8761 GNAT and its children, which contain a set of useful additional
8762 library functions provided by GNAT. The sources for these units are
8763 needed by the compiler and are kept together in one directory. The ALI
8764 files and object files generated by compiling the RTL are needed by the
8765 binder and the linker and are kept together in one directory, typically
8766 different from the directory containing the sources. In a normal
8767 installation, you need not specify these directory names when compiling
8768 or binding. Either the environment variables or the built-in defaults
8769 cause these files to be found.
8770
8771 Besides simplifying access to the RTL, a major use of search paths is
8772 in compiling sources from multiple directories. This can make
8773 development environments much more flexible.
8774
8775 @node Examples of gnatbind Usage
8776 @section Examples of @code{gnatbind} Usage
8777
8778 @noindent
8779 This section contains a number of examples of using the GNAT binding
8780 utility @code{gnatbind}.
8781
8782 @table @code
8783 @item gnatbind hello
8784 The main program @code{Hello} (source program in @file{hello.adb}) is
8785 bound using the standard switch settings. The generated main program is
8786 @file{b~hello.adb}. This is the normal, default use of the binder.
8787
8788 @ifclear vms
8789 @item gnatbind hello -o mainprog.adb
8790 @end ifclear
8791 @ifset vms
8792 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8793 @end ifset
8794 The main program @code{Hello} (source program in @file{hello.adb}) is
8795 bound using the standard switch settings. The generated main program is
8796 @file{mainprog.adb} with the associated spec in
8797 @file{mainprog.ads}. Note that you must specify the body here not the
8798 spec. Note that if this option is used, then linking must be done manually,
8799 since gnatlink will not be able to find the generated file.
8800 @end table
8801
8802 @c ------------------------------------
8803 @node Linking Using gnatlink
8804 @chapter Linking Using @command{gnatlink}
8805 @c ------------------------------------
8806 @findex gnatlink
8807
8808 @noindent
8809 This chapter discusses @command{gnatlink}, a tool that links
8810 an Ada program and builds an executable file. This utility
8811 invokes the system linker ^(via the @command{gcc} command)^^
8812 with a correct list of object files and library references.
8813 @command{gnatlink} automatically determines the list of files and
8814 references for the Ada part of a program. It uses the binder file
8815 generated by the @command{gnatbind} to determine this list.
8816
8817 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8818 driver (see @ref{The GNAT Driver and Project Files}).
8819
8820 @menu
8821 * Running gnatlink::
8822 * Switches for gnatlink::
8823 @end menu
8824
8825 @node Running gnatlink
8826 @section Running @command{gnatlink}
8827
8828 @noindent
8829 The form of the @command{gnatlink} command is
8830
8831 @smallexample
8832 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8833 @c            @ovar{non-Ada objects} @ovar{linker options}
8834 @c Expanding @ovar macro inline (explanation in macro def comments)
8835 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8836            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8837
8838 @end smallexample
8839
8840 @noindent
8841 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8842 non-Ada objects
8843 or linker options) may be in any order, provided that no non-Ada object may
8844 be mistaken for a main @file{ALI} file.
8845 Any file name @file{F} without the @file{.ali}
8846 extension will be taken as the main @file{ALI} file if a file exists
8847 whose name is the concatenation of @file{F} and @file{.ali}.
8848
8849 @noindent
8850 @file{@var{mainprog}.ali} references the ALI file of the main program.
8851 The @file{.ali} extension of this file can be omitted. From this
8852 reference, @command{gnatlink} locates the corresponding binder file
8853 @file{b~@var{mainprog}.adb} and, using the information in this file along
8854 with the list of non-Ada objects and linker options, constructs a
8855 linker command file to create the executable.
8856
8857 The arguments other than the @command{gnatlink} switches and the main
8858 @file{ALI} file are passed to the linker uninterpreted.
8859 They typically include the names of
8860 object files for units written in other languages than Ada and any library
8861 references required to resolve references in any of these foreign language
8862 units, or in @code{Import} pragmas in any Ada units.
8863
8864 @var{linker options} is an optional list of linker specific
8865 switches.
8866 The default linker called by gnatlink is @command{gcc} which in
8867 turn calls the appropriate system linker.
8868 Standard options for the linker such as @option{-lmy_lib} or
8869 @option{-Ldir} can be added as is.
8870 For options that are not recognized by
8871 @command{gcc} as linker options, use the @command{gcc} switches
8872 @option{-Xlinker} or @option{-Wl,}.
8873 Refer to the GCC documentation for
8874 details. Here is an example showing how to generate a linker map:
8875
8876 @smallexample
8877 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8878 @end smallexample
8879
8880 Using @var{linker options} it is possible to set the program stack and
8881 heap size.
8882 @ifset unw
8883 See @ref{Setting Stack Size from gnatlink} and
8884 @ref{Setting Heap Size from gnatlink}.
8885 @end ifset
8886
8887 @command{gnatlink} determines the list of objects required by the Ada
8888 program and prepends them to the list of objects passed to the linker.
8889 @command{gnatlink} also gathers any arguments set by the use of
8890 @code{pragma Linker_Options} and adds them to the list of arguments
8891 presented to the linker.
8892
8893 @ifset vms
8894 @command{gnatlink} accepts the following types of extra files on the command
8895 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8896 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8897 handled according to their extension.
8898 @end ifset
8899
8900 @node Switches for gnatlink
8901 @section Switches for @command{gnatlink}
8902
8903 @noindent
8904 The following switches are available with the @command{gnatlink} utility:
8905
8906 @table @option
8907 @c !sort!
8908
8909 @item --version
8910 @cindex @option{--version} @command{gnatlink}
8911 Display Copyright and version, then exit disregarding all other options.
8912
8913 @item --help
8914 @cindex @option{--help} @command{gnatlink}
8915 If @option{--version} was not used, display usage, then exit disregarding
8916 all other options.
8917
8918 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8919 @cindex Command line length
8920 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8921 On some targets, the command line length is limited, and @command{gnatlink}
8922 will generate a separate file for the linker if the list of object files
8923 is too long.
8924 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8925 to be generated even if
8926 the limit is not exceeded. This is useful in some cases to deal with
8927 special situations where the command line length is exceeded.
8928
8929 @item ^-g^/DEBUG^
8930 @cindex Debugging information, including
8931 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8932 The option to include debugging information causes the Ada bind file (in
8933 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8934 @option{^-g^/DEBUG^}.
8935 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8936 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8937 Without @option{^-g^/DEBUG^}, the binder removes these files by
8938 default. The same procedure apply if a C bind file was generated using
8939 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8940 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8941
8942 @item ^-n^/NOCOMPILE^
8943 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8944 Do not compile the file generated by the binder. This may be used when
8945 a link is rerun with different options, but there is no need to recompile
8946 the binder file.
8947
8948 @item ^-v^/VERBOSE^
8949 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8950 Causes additional information to be output, including a full list of the
8951 included object files. This switch option is most useful when you want
8952 to see what set of object files are being used in the link step.
8953
8954 @item ^-v -v^/VERBOSE/VERBOSE^
8955 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8956 Very verbose mode. Requests that the compiler operate in verbose mode when
8957 it compiles the binder file, and that the system linker run in verbose mode.
8958
8959 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8960 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8961 @var{exec-name} specifies an alternate name for the generated
8962 executable program. If this switch is omitted, the executable has the same
8963 name as the main unit. For example, @code{gnatlink try.ali} creates
8964 an executable called @file{^try^TRY.EXE^}.
8965
8966 @ifclear vms
8967 @item -b @var{target}
8968 @cindex @option{-b} (@command{gnatlink})
8969 Compile your program to run on @var{target}, which is the name of a
8970 system configuration. You must have a GNAT cross-compiler built if
8971 @var{target} is not the same as your host system.
8972
8973 @item -B@var{dir}
8974 @cindex @option{-B} (@command{gnatlink})
8975 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8976 from @var{dir} instead of the default location. Only use this switch
8977 when multiple versions of the GNAT compiler are available.
8978 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8979 for further details. You would normally use the @option{-b} or
8980 @option{-V} switch instead.
8981
8982 @item --GCC=@var{compiler_name}
8983 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8984 Program used for compiling the binder file. The default is
8985 @command{gcc}. You need to use quotes around @var{compiler_name} if
8986 @code{compiler_name} contains spaces or other separator characters.
8987 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8988 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8989 inserted after your command name. Thus in the above example the compiler
8990 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8991 A limitation of this syntax is that the name and path name of the executable
8992 itself must not include any embedded spaces. If the compiler executable is
8993 different from the default one (gcc or <prefix>-gcc), then the back-end
8994 switches in the ALI file are not used to compile the binder generated source.
8995 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8996 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8997 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8998 is taken into account. However, all the additional switches are also taken
8999 into account. Thus,
9000 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9001 @option{--GCC="bar -x -y -z -t"}.
9002
9003 @item --LINK=@var{name}
9004 @cindex @option{--LINK=} (@command{gnatlink})
9005 @var{name} is the name of the linker to be invoked. This is especially
9006 useful in mixed language programs since languages such as C++ require
9007 their own linker to be used. When this switch is omitted, the default
9008 name for the linker is @command{gcc}. When this switch is used, the
9009 specified linker is called instead of @command{gcc} with exactly the same
9010 parameters that would have been passed to @command{gcc} so if the desired
9011 linker requires different parameters it is necessary to use a wrapper
9012 script that massages the parameters before invoking the real linker. It
9013 may be useful to control the exact invocation by using the verbose
9014 switch.
9015
9016 @end ifclear
9017
9018 @ifset vms
9019 @item /DEBUG=TRACEBACK
9020 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9021 This qualifier causes sufficient information to be included in the
9022 executable file to allow a traceback, but does not include the full
9023 symbol information needed by the debugger.
9024
9025 @item /IDENTIFICATION="<string>"
9026 @code{"<string>"} specifies the string to be stored in the image file
9027 identification field in the image header.
9028 It overrides any pragma @code{Ident} specified string.
9029
9030 @item /NOINHIBIT-EXEC
9031 Generate the executable file even if there are linker warnings.
9032
9033 @item /NOSTART_FILES
9034 Don't link in the object file containing the ``main'' transfer address.
9035 Used when linking with a foreign language main program compiled with an
9036 HP compiler.
9037
9038 @item /STATIC
9039 Prefer linking with object libraries over sharable images, even without
9040 /DEBUG.
9041 @end ifset
9042
9043 @end table
9044
9045 @node The GNAT Make Program gnatmake
9046 @chapter The GNAT Make Program @command{gnatmake}
9047 @findex gnatmake
9048
9049 @menu
9050 * Running gnatmake::
9051 * Switches for gnatmake::
9052 * Mode Switches for gnatmake::
9053 * Notes on the Command Line::
9054 * How gnatmake Works::
9055 * Examples of gnatmake Usage::
9056 @end menu
9057 @noindent
9058 A typical development cycle when working on an Ada program consists of
9059 the following steps:
9060
9061 @enumerate
9062 @item
9063 Edit some sources to fix bugs.
9064
9065 @item
9066 Add enhancements.
9067
9068 @item
9069 Compile all sources affected.
9070
9071 @item
9072 Rebind and relink.
9073
9074 @item
9075 Test.
9076 @end enumerate
9077
9078 @noindent
9079 The third step can be tricky, because not only do the modified files
9080 @cindex Dependency rules
9081 have to be compiled, but any files depending on these files must also be
9082 recompiled. The dependency rules in Ada can be quite complex, especially
9083 in the presence of overloading, @code{use} clauses, generics and inlined
9084 subprograms.
9085
9086 @command{gnatmake} automatically takes care of the third and fourth steps
9087 of this process. It determines which sources need to be compiled,
9088 compiles them, and binds and links the resulting object files.
9089
9090 Unlike some other Ada make programs, the dependencies are always
9091 accurately recomputed from the new sources. The source based approach of
9092 the GNAT compilation model makes this possible. This means that if
9093 changes to the source program cause corresponding changes in
9094 dependencies, they will always be tracked exactly correctly by
9095 @command{gnatmake}.
9096
9097 @node Running gnatmake
9098 @section Running @command{gnatmake}
9099
9100 @noindent
9101 The usual form of the @command{gnatmake} command is
9102
9103 @smallexample
9104 @c $ gnatmake @ovar{switches} @var{file_name}
9105 @c       @ovar{file_names} @ovar{mode_switches}
9106 @c Expanding @ovar macro inline (explanation in macro def comments)
9107 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9108       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9109 @end smallexample
9110
9111 @noindent
9112 The only required argument is one @var{file_name}, which specifies
9113 a compilation unit that is a main program. Several @var{file_names} can be
9114 specified: this will result in several executables being built.
9115 If @code{switches} are present, they can be placed before the first
9116 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9117 If @var{mode_switches} are present, they must always be placed after
9118 the last @var{file_name} and all @code{switches}.
9119
9120 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9121 extension may be omitted from the @var{file_name} arguments. However, if
9122 you are using non-standard extensions, then it is required that the
9123 extension be given. A relative or absolute directory path can be
9124 specified in a @var{file_name}, in which case, the input source file will
9125 be searched for in the specified directory only. Otherwise, the input
9126 source file will first be searched in the directory where
9127 @command{gnatmake} was invoked and if it is not found, it will be search on
9128 the source path of the compiler as described in
9129 @ref{Search Paths and the Run-Time Library (RTL)}.
9130
9131 All @command{gnatmake} output (except when you specify
9132 @option{^-M^/DEPENDENCIES_LIST^}) is to
9133 @file{stderr}. The output produced by the
9134 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9135 @file{stdout}.
9136
9137 @node Switches for gnatmake
9138 @section Switches for @command{gnatmake}
9139
9140 @noindent
9141 You may specify any of the following switches to @command{gnatmake}:
9142
9143 @table @option
9144 @c !sort!
9145
9146 @item --version
9147 @cindex @option{--version} @command{gnatmake}
9148 Display Copyright and version, then exit disregarding all other options.
9149
9150 @item --help
9151 @cindex @option{--help} @command{gnatmake}
9152 If @option{--version} was not used, display usage, then exit disregarding
9153 all other options.
9154
9155 @ifclear vms
9156 @item --GCC=@var{compiler_name}
9157 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9158 Program used for compiling. The default is `@command{gcc}'. You need to use
9159 quotes around @var{compiler_name} if @code{compiler_name} contains
9160 spaces or other separator characters. As an example @option{--GCC="foo -x
9161 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9162 compiler. A limitation of this syntax is that the name and path name of
9163 the executable itself must not include any embedded spaces. Note that
9164 switch @option{-c} is always inserted after your command name. Thus in the
9165 above example the compiler command that will be used by @command{gnatmake}
9166 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9167 used, only the last @var{compiler_name} is taken into account. However,
9168 all the additional switches are also taken into account. Thus,
9169 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9170 @option{--GCC="bar -x -y -z -t"}.
9171
9172 @item --GNATBIND=@var{binder_name}
9173 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9174 Program used for binding. The default is `@code{gnatbind}'. You need to
9175 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9176 or other separator characters. As an example @option{--GNATBIND="bar -x
9177 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9178 binder. Binder switches that are normally appended by @command{gnatmake}
9179 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9180 A limitation of this syntax is that the name and path name of the executable
9181 itself must not include any embedded spaces.
9182
9183 @item --GNATLINK=@var{linker_name}
9184 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9185 Program used for linking. The default is `@command{gnatlink}'. You need to
9186 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9187 or other separator characters. As an example @option{--GNATLINK="lan -x
9188 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9189 linker. Linker switches that are normally appended by @command{gnatmake} to
9190 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9191 A limitation of this syntax is that the name and path name of the executable
9192 itself must not include any embedded spaces.
9193
9194 @end ifclear
9195
9196 @item ^--subdirs^/SUBDIRS^=subdir
9197 Actual object directory of each project file is the subdirectory subdir of the
9198 object directory specified or defauted in the project file.
9199
9200 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9201 By default, shared library projects are not allowed to import static library
9202 projects. When this switch is used on the command line, this restriction is
9203 relaxed.
9204
9205 @item ^-a^/ALL_FILES^
9206 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9207 Consider all files in the make process, even the GNAT internal system
9208 files (for example, the predefined Ada library files), as well as any
9209 locked files. Locked files are files whose ALI file is write-protected.
9210 By default,
9211 @command{gnatmake} does not check these files,
9212 because the assumption is that the GNAT internal files are properly up
9213 to date, and also that any write protected ALI files have been properly
9214 installed. Note that if there is an installation problem, such that one
9215 of these files is not up to date, it will be properly caught by the
9216 binder.
9217 You may have to specify this switch if you are working on GNAT
9218 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9219 in conjunction with @option{^-f^/FORCE_COMPILE^}
9220 if you need to recompile an entire application,
9221 including run-time files, using special configuration pragmas,
9222 such as a @code{Normalize_Scalars} pragma.
9223
9224 By default
9225 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9226 internal files with
9227 @ifclear vms
9228 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9229 @end ifclear
9230 @ifset vms
9231 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9232 @end ifset
9233
9234 @item ^-b^/ACTIONS=BIND^
9235 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9236 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9237 compilation and binding, but no link.
9238 Can be combined with @option{^-l^/ACTIONS=LINK^}
9239 to do binding and linking. When not combined with
9240 @option{^-c^/ACTIONS=COMPILE^}
9241 all the units in the closure of the main program must have been previously
9242 compiled and must be up to date. The root unit specified by @var{file_name}
9243 may be given without extension, with the source extension or, if no GNAT
9244 Project File is specified, with the ALI file extension.
9245
9246 @item ^-c^/ACTIONS=COMPILE^
9247 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9248 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9249 is also specified. Do not perform linking, except if both
9250 @option{^-b^/ACTIONS=BIND^} and
9251 @option{^-l^/ACTIONS=LINK^} are also specified.
9252 If the root unit specified by @var{file_name} is not a main unit, this is the
9253 default. Otherwise @command{gnatmake} will attempt binding and linking
9254 unless all objects are up to date and the executable is more recent than
9255 the objects.
9256
9257 @item ^-C^/MAPPING^
9258 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9259 Use a temporary mapping file. A mapping file is a way to communicate
9260 to the compiler two mappings: from unit names to file names (without
9261 any directory information) and from file names to path names (with
9262 full directory information). A mapping file can make the compiler's
9263 file searches faster, especially if there are many source directories,
9264 or the sources are read over a slow network connection. If
9265 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9266 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9267 is initially populated based on the project file. If
9268 @option{^-C^/MAPPING^} is used without
9269 @option{^-P^/PROJECT_FILE^},
9270 the mapping file is initially empty. Each invocation of the compiler
9271 will add any newly accessed sources to the mapping file.
9272
9273 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9274 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9275 Use a specific mapping file. The file, specified as a path name (absolute or
9276 relative) by this switch, should already exist, otherwise the switch is
9277 ineffective. The specified mapping file will be communicated to the compiler.
9278 This switch is not compatible with a project file
9279 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9280 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9281
9282 @item ^-d^/DISPLAY_PROGRESS^
9283 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9284 Display progress for each source, up to date or not, as a single line
9285
9286 @smallexample
9287 completed x out of y (zz%)
9288 @end smallexample
9289
9290 If the file needs to be compiled this is displayed after the invocation of
9291 the compiler. These lines are displayed even in quiet output mode.
9292
9293 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9294 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9295 Put all object files and ALI file in directory @var{dir}.
9296 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9297 and ALI files go in the current working directory.
9298
9299 This switch cannot be used when using a project file.
9300
9301 @ifclear vms
9302 @item -eL
9303 @cindex @option{-eL} (@command{gnatmake})
9304 @cindex symbolic links
9305 Follow all symbolic links when processing project files.
9306 This should be used if your project uses symbolic links for files or
9307 directories, but is not needed in other cases.
9308
9309 @cindex naming scheme
9310 This also assumes that no directory matches the naming scheme for files (for
9311 instance that you do not have a directory called "sources.ads" when using the
9312 default GNAT naming scheme).
9313
9314 When you do not have to use this switch (ie by default), gnatmake is able to
9315 save a lot of system calls (several per source file and object file), which
9316 can result in a significant speed up to load and manipulate a project file,
9317 especially when using source files from a remote system.
9318
9319 @end ifclear
9320
9321 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9322 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9323 Output the commands for the compiler, the binder and the linker
9324 on ^standard output^SYS$OUTPUT^,
9325 instead of ^standard error^SYS$ERROR^.
9326
9327 @item ^-f^/FORCE_COMPILE^
9328 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9329 Force recompilations. Recompile all sources, even though some object
9330 files may be up to date, but don't recompile predefined or GNAT internal
9331 files or locked files (files with a write-protected ALI file),
9332 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9333
9334 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9335 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9336 When using project files, if some errors or warnings are detected during
9337 parsing and verbose mode is not in effect (no use of switch
9338 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9339 file, rather than its simple file name.
9340
9341 @item ^-g^/DEBUG^
9342 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9343 Enable debugging. This switch is simply passed to the compiler and to the
9344 linker.
9345
9346 @item ^-i^/IN_PLACE^
9347 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9348 In normal mode, @command{gnatmake} compiles all object files and ALI files
9349 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9350 then instead object files and ALI files that already exist are overwritten
9351 in place. This means that once a large project is organized into separate
9352 directories in the desired manner, then @command{gnatmake} will automatically
9353 maintain and update this organization. If no ALI files are found on the
9354 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9355 the new object and ALI files are created in the
9356 directory containing the source being compiled. If another organization
9357 is desired, where objects and sources are kept in different directories,
9358 a useful technique is to create dummy ALI files in the desired directories.
9359 When detecting such a dummy file, @command{gnatmake} will be forced to
9360 recompile the corresponding source file, and it will be put the resulting
9361 object and ALI files in the directory where it found the dummy file.
9362
9363 @item ^-j^/PROCESSES=^@var{n}
9364 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9365 @cindex Parallel make
9366 Use @var{n} processes to carry out the (re)compilations. On a
9367 multiprocessor machine compilations will occur in parallel. In the
9368 event of compilation errors, messages from various compilations might
9369 get interspersed (but @command{gnatmake} will give you the full ordered
9370 list of failing compiles at the end). If this is problematic, rerun
9371 the make process with n set to 1 to get a clean list of messages.
9372
9373 @item ^-k^/CONTINUE_ON_ERROR^
9374 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9375 Keep going. Continue as much as possible after a compilation error. To
9376 ease the programmer's task in case of compilation errors, the list of
9377 sources for which the compile fails is given when @command{gnatmake}
9378 terminates.
9379
9380 If @command{gnatmake} is invoked with several @file{file_names} and with this
9381 switch, if there are compilation errors when building an executable,
9382 @command{gnatmake} will not attempt to build the following executables.
9383
9384 @item ^-l^/ACTIONS=LINK^
9385 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9386 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9387 and linking. Linking will not be performed if combined with
9388 @option{^-c^/ACTIONS=COMPILE^}
9389 but not with @option{^-b^/ACTIONS=BIND^}.
9390 When not combined with @option{^-b^/ACTIONS=BIND^}
9391 all the units in the closure of the main program must have been previously
9392 compiled and must be up to date, and the main program needs to have been bound.
9393 The root unit specified by @var{file_name}
9394 may be given without extension, with the source extension or, if no GNAT
9395 Project File is specified, with the ALI file extension.
9396
9397 @item ^-m^/MINIMAL_RECOMPILATION^
9398 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9399 Specify that the minimum necessary amount of recompilations
9400 be performed. In this mode @command{gnatmake} ignores time
9401 stamp differences when the only
9402 modifications to a source file consist in adding/removing comments,
9403 empty lines, spaces or tabs. This means that if you have changed the
9404 comments in a source file or have simply reformatted it, using this
9405 switch will tell @command{gnatmake} not to recompile files that depend on it
9406 (provided other sources on which these files depend have undergone no
9407 semantic modifications). Note that the debugging information may be
9408 out of date with respect to the sources if the @option{-m} switch causes
9409 a compilation to be switched, so the use of this switch represents a
9410 trade-off between compilation time and accurate debugging information.
9411
9412 @item ^-M^/DEPENDENCIES_LIST^
9413 @cindex Dependencies, producing list
9414 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9415 Check if all objects are up to date. If they are, output the object
9416 dependences to @file{stdout} in a form that can be directly exploited in
9417 a @file{Makefile}. By default, each source file is prefixed with its
9418 (relative or absolute) directory name. This name is whatever you
9419 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9420 and @option{^-I^/SEARCH^} switches. If you use
9421 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9422 @option{^-q^/QUIET^}
9423 (see below), only the source file names,
9424 without relative paths, are output. If you just specify the
9425 @option{^-M^/DEPENDENCIES_LIST^}
9426 switch, dependencies of the GNAT internal system files are omitted. This
9427 is typically what you want. If you also specify
9428 the @option{^-a^/ALL_FILES^} switch,
9429 dependencies of the GNAT internal files are also listed. Note that
9430 dependencies of the objects in external Ada libraries (see switch
9431 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9432 are never reported.
9433
9434 @item ^-n^/DO_OBJECT_CHECK^
9435 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9436 Don't compile, bind, or link. Checks if all objects are up to date.
9437 If they are not, the full name of the first file that needs to be
9438 recompiled is printed.
9439 Repeated use of this option, followed by compiling the indicated source
9440 file, will eventually result in recompiling all required units.
9441
9442 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9443 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9444 Output executable name. The name of the final executable program will be
9445 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9446 name for the executable will be the name of the input file in appropriate form
9447 for an executable file on the host system.
9448
9449 This switch cannot be used when invoking @command{gnatmake} with several
9450 @file{file_names}.
9451
9452 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9453 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9454 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9455 automatically missing object directories, library directories and exec
9456 directories.
9457
9458 @item ^-P^/PROJECT_FILE=^@var{project}
9459 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9460 Use project file @var{project}. Only one such switch can be used.
9461 @xref{gnatmake and Project Files}.
9462
9463 @item ^-q^/QUIET^
9464 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9465 Quiet. When this flag is not set, the commands carried out by
9466 @command{gnatmake} are displayed.
9467
9468 @item ^-s^/SWITCH_CHECK/^
9469 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9470 Recompile if compiler switches have changed since last compilation.
9471 All compiler switches but -I and -o are taken into account in the
9472 following way:
9473 orders between different ``first letter'' switches are ignored, but
9474 orders between same switches are taken into account. For example,
9475 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9476 is equivalent to @option{-O -g}.
9477
9478 This switch is recommended when Integrated Preprocessing is used.
9479
9480 @item ^-u^/UNIQUE^
9481 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9482 Unique. Recompile at most the main files. It implies -c. Combined with
9483 -f, it is equivalent to calling the compiler directly. Note that using
9484 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9485 (@pxref{Project Files and Main Subprograms}).
9486
9487 @item ^-U^/ALL_PROJECTS^
9488 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9489 When used without a project file or with one or several mains on the command
9490 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9491 on the command line, all sources of all project files are checked and compiled
9492 if not up to date, and libraries are rebuilt, if necessary.
9493
9494 @item ^-v^/REASONS^
9495 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9496 Verbose. Display the reason for all recompilations @command{gnatmake}
9497 decides are necessary, with the highest verbosity level.
9498
9499 @item ^-vl^/LOW_VERBOSITY^
9500 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9501 Verbosity level Low. Display fewer lines than in verbosity Medium.
9502
9503 @item ^-vm^/MEDIUM_VERBOSITY^
9504 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9505 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9506
9507 @item ^-vh^/HIGH_VERBOSITY^
9508 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9509 Verbosity level High. Equivalent to ^-v^/REASONS^.
9510
9511 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9512 Indicate the verbosity of the parsing of GNAT project files.
9513 @xref{Switches Related to Project Files}.
9514
9515 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9516 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9517 Indicate that sources that are not part of any Project File may be compiled.
9518 Normally, when using Project Files, only sources that are part of a Project
9519 File may be compile. When this switch is used, a source outside of all Project
9520 Files may be compiled. The ALI file and the object file will be put in the
9521 object directory of the main Project. The compilation switches used will only
9522 be those specified on the command line. Even when
9523 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9524 command line need to be sources of a project file.
9525
9526 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9527 Indicate that external variable @var{name} has the value @var{value}.
9528 The Project Manager will use this value for occurrences of
9529 @code{external(name)} when parsing the project file.
9530 @xref{Switches Related to Project Files}.
9531
9532 @item ^-z^/NOMAIN^
9533 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9534 No main subprogram. Bind and link the program even if the unit name
9535 given on the command line is a package name. The resulting executable
9536 will execute the elaboration routines of the package and its closure,
9537 then the finalization routines.
9538
9539 @end table
9540
9541 @table @asis
9542 @item @command{gcc} @asis{switches}
9543 @ifclear vms
9544 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9545 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9546 @end ifclear
9547 @ifset vms
9548 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9549 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9550 automatically treated as a compiler switch, and passed on to all
9551 compilations that are carried out.
9552 @end ifset
9553 @end table
9554
9555 @noindent
9556 Source and library search path switches:
9557
9558 @table @option
9559 @c !sort!
9560 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9561 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9562 When looking for source files also look in directory @var{dir}.
9563 The order in which source files search is undertaken is
9564 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9565
9566 @item ^-aL^/SKIP_MISSING=^@var{dir}
9567 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9568 Consider @var{dir} as being an externally provided Ada library.
9569 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9570 files have been located in directory @var{dir}. This allows you to have
9571 missing bodies for the units in @var{dir} and to ignore out of date bodies
9572 for the same units. You still need to specify
9573 the location of the specs for these units by using the switches
9574 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9575 or @option{^-I^/SEARCH=^@var{dir}}.
9576 Note: this switch is provided for compatibility with previous versions
9577 of @command{gnatmake}. The easier method of causing standard libraries
9578 to be excluded from consideration is to write-protect the corresponding
9579 ALI files.
9580
9581 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9582 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9583 When searching for library and object files, look in directory
9584 @var{dir}. The order in which library files are searched is described in
9585 @ref{Search Paths for gnatbind}.
9586
9587 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9588 @cindex Search paths, for @command{gnatmake}
9589 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9590 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9591 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9592
9593 @item ^-I^/SEARCH=^@var{dir}
9594 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9595 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9596 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9597
9598 @item ^-I-^/NOCURRENT_DIRECTORY^
9599 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9600 @cindex Source files, suppressing search
9601 Do not look for source files in the directory containing the source
9602 file named in the command line.
9603 Do not look for ALI or object files in the directory
9604 where @command{gnatmake} was invoked.
9605
9606 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9607 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9608 @cindex Linker libraries
9609 Add directory @var{dir} to the list of directories in which the linker
9610 will search for libraries. This is equivalent to
9611 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9612 @ifclear vms
9613 Furthermore, under Windows, the sources pointed to by the libraries path
9614 set in the registry are not searched for.
9615 @end ifclear
9616
9617 @item -nostdinc
9618 @cindex @option{-nostdinc} (@command{gnatmake})
9619 Do not look for source files in the system default directory.
9620
9621 @item -nostdlib
9622 @cindex @option{-nostdlib} (@command{gnatmake})
9623 Do not look for library files in the system default directory.
9624
9625 @item --RTS=@var{rts-path}
9626 @cindex @option{--RTS} (@command{gnatmake})
9627 Specifies the default location of the runtime library. GNAT looks for the
9628 runtime
9629 in the following directories, and stops as soon as a valid runtime is found
9630 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9631 @file{ada_object_path} present):
9632
9633 @itemize @bullet
9634 @item <current directory>/$rts_path
9635
9636 @item <default-search-dir>/$rts_path
9637
9638 @item <default-search-dir>/rts-$rts_path
9639 @end itemize
9640
9641 @noindent
9642 The selected path is handled like a normal RTS path.
9643
9644 @end table
9645
9646 @node Mode Switches for gnatmake
9647 @section Mode Switches for @command{gnatmake}
9648
9649 @noindent
9650 The mode switches (referred to as @code{mode_switches}) allow the
9651 inclusion of switches that are to be passed to the compiler itself, the
9652 binder or the linker. The effect of a mode switch is to cause all
9653 subsequent switches up to the end of the switch list, or up to the next
9654 mode switch, to be interpreted as switches to be passed on to the
9655 designated component of GNAT.
9656
9657 @table @option
9658 @c !sort!
9659 @item -cargs @var{switches}
9660 @cindex @option{-cargs} (@command{gnatmake})
9661 Compiler switches. Here @var{switches} is a list of switches
9662 that are valid switches for @command{gcc}. They will be passed on to
9663 all compile steps performed by @command{gnatmake}.
9664
9665 @item -bargs @var{switches}
9666 @cindex @option{-bargs} (@command{gnatmake})
9667 Binder switches. Here @var{switches} is a list of switches
9668 that are valid switches for @code{gnatbind}. They will be passed on to
9669 all bind steps performed by @command{gnatmake}.
9670
9671 @item -largs @var{switches}
9672 @cindex @option{-largs} (@command{gnatmake})
9673 Linker switches. Here @var{switches} is a list of switches
9674 that are valid switches for @command{gnatlink}. They will be passed on to
9675 all link steps performed by @command{gnatmake}.
9676
9677 @item -margs @var{switches}
9678 @cindex @option{-margs} (@command{gnatmake})
9679 Make switches. The switches are directly interpreted by @command{gnatmake},
9680 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9681 or @option{-largs}.
9682 @end table
9683
9684 @node Notes on the Command Line
9685 @section Notes on the Command Line
9686
9687 @noindent
9688 This section contains some additional useful notes on the operation
9689 of the @command{gnatmake} command.
9690
9691 @itemize @bullet
9692 @item
9693 @cindex Recompilation, by @command{gnatmake}
9694 If @command{gnatmake} finds no ALI files, it recompiles the main program
9695 and all other units required by the main program.
9696 This means that @command{gnatmake}
9697 can be used for the initial compile, as well as during subsequent steps of
9698 the development cycle.
9699
9700 @item
9701 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9702 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9703 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9704 warning.
9705
9706 @item
9707 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9708 is used to specify both source and
9709 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9710 instead if you just want to specify
9711 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9712 if you want to specify library paths
9713 only.
9714
9715 @item
9716 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9717 This may conveniently be used to exclude standard libraries from
9718 consideration and in particular it means that the use of the
9719 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9720 unless @option{^-a^/ALL_FILES^} is also specified.
9721
9722 @item
9723 @command{gnatmake} has been designed to make the use of Ada libraries
9724 particularly convenient. Assume you have an Ada library organized
9725 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9726 of your Ada compilation units,
9727 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9728 specs of these units, but no bodies. Then to compile a unit
9729 stored in @code{main.adb}, which uses this Ada library you would just type
9730
9731 @smallexample
9732 @ifclear vms
9733 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9734 @end ifclear
9735 @ifset vms
9736 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9737            /SKIP_MISSING=@i{[OBJ_DIR]} main
9738 @end ifset
9739 @end smallexample
9740
9741 @item
9742 Using @command{gnatmake} along with the
9743 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9744 switch provides a mechanism for avoiding unnecessary recompilations. Using
9745 this switch,
9746 you can update the comments/format of your
9747 source files without having to recompile everything. Note, however, that
9748 adding or deleting lines in a source files may render its debugging
9749 info obsolete. If the file in question is a spec, the impact is rather
9750 limited, as that debugging info will only be useful during the
9751 elaboration phase of your program. For bodies the impact can be more
9752 significant. In all events, your debugger will warn you if a source file
9753 is more recent than the corresponding object, and alert you to the fact
9754 that the debugging information may be out of date.
9755 @end itemize
9756
9757 @node How gnatmake Works
9758 @section How @command{gnatmake} Works
9759
9760 @noindent
9761 Generally @command{gnatmake} automatically performs all necessary
9762 recompilations and you don't need to worry about how it works. However,
9763 it may be useful to have some basic understanding of the @command{gnatmake}
9764 approach and in particular to understand how it uses the results of
9765 previous compilations without incorrectly depending on them.
9766
9767 First a definition: an object file is considered @dfn{up to date} if the
9768 corresponding ALI file exists and if all the source files listed in the
9769 dependency section of this ALI file have time stamps matching those in
9770 the ALI file. This means that neither the source file itself nor any
9771 files that it depends on have been modified, and hence there is no need
9772 to recompile this file.
9773
9774 @command{gnatmake} works by first checking if the specified main unit is up
9775 to date. If so, no compilations are required for the main unit. If not,
9776 @command{gnatmake} compiles the main program to build a new ALI file that
9777 reflects the latest sources. Then the ALI file of the main unit is
9778 examined to find all the source files on which the main program depends,
9779 and @command{gnatmake} recursively applies the above procedure on all these
9780 files.
9781
9782 This process ensures that @command{gnatmake} only trusts the dependencies
9783 in an existing ALI file if they are known to be correct. Otherwise it
9784 always recompiles to determine a new, guaranteed accurate set of
9785 dependencies. As a result the program is compiled ``upside down'' from what may
9786 be more familiar as the required order of compilation in some other Ada
9787 systems. In particular, clients are compiled before the units on which
9788 they depend. The ability of GNAT to compile in any order is critical in
9789 allowing an order of compilation to be chosen that guarantees that
9790 @command{gnatmake} will recompute a correct set of new dependencies if
9791 necessary.
9792
9793 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9794 imported by several of the executables, it will be recompiled at most once.
9795
9796 Note: when using non-standard naming conventions
9797 (@pxref{Using Other File Names}), changing through a configuration pragmas
9798 file the version of a source and invoking @command{gnatmake} to recompile may
9799 have no effect, if the previous version of the source is still accessible
9800 by @command{gnatmake}. It may be necessary to use the switch
9801 ^-f^/FORCE_COMPILE^.
9802
9803 @node Examples of gnatmake Usage
9804 @section Examples of @command{gnatmake} Usage
9805
9806 @table @code
9807 @item gnatmake hello.adb
9808 Compile all files necessary to bind and link the main program
9809 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9810 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9811
9812 @item gnatmake main1 main2 main3
9813 Compile all files necessary to bind and link the main programs
9814 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9815 (containing unit @code{Main2}) and @file{main3.adb}
9816 (containing unit @code{Main3}) and bind and link the resulting object files
9817 to generate three executable files @file{^main1^MAIN1.EXE^},
9818 @file{^main2^MAIN2.EXE^}
9819 and @file{^main3^MAIN3.EXE^}.
9820
9821 @ifclear vms
9822 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9823 @end ifclear
9824
9825 @ifset vms
9826 @item gnatmake Main_Unit /QUIET
9827 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9828 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9829 @end ifset
9830 Compile all files necessary to bind and link the main program unit
9831 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9832 be done with optimization level 2 and the order of elaboration will be
9833 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9834 displaying commands it is executing.
9835 @end table
9836
9837 @c *************************
9838 @node Improving Performance
9839 @chapter Improving Performance
9840 @cindex Improving performance
9841
9842 @noindent
9843 This chapter presents several topics related to program performance.
9844 It first describes some of the tradeoffs that need to be considered
9845 and some of the techniques for making your program run faster.
9846 It then documents the @command{gnatelim} tool and unused subprogram/data
9847 elimination feature, which can reduce the size of program executables.
9848
9849 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9850 driver (see @ref{The GNAT Driver and Project Files}).
9851
9852 @ifnottex
9853 @menu
9854 * Performance Considerations::
9855 * Text_IO Suggestions::
9856 * Reducing Size of Ada Executables with gnatelim::
9857 * Reducing Size of Executables with unused subprogram/data elimination::
9858 @end menu
9859 @end ifnottex
9860
9861 @c *****************************
9862 @node Performance Considerations
9863 @section Performance Considerations
9864
9865 @noindent
9866 The GNAT system provides a number of options that allow a trade-off
9867 between
9868
9869 @itemize @bullet
9870 @item
9871 performance of the generated code
9872
9873 @item
9874 speed of compilation
9875
9876 @item
9877 minimization of dependences and recompilation
9878
9879 @item
9880 the degree of run-time checking.
9881 @end itemize
9882
9883 @noindent
9884 The defaults (if no options are selected) aim at improving the speed
9885 of compilation and minimizing dependences, at the expense of performance
9886 of the generated code:
9887
9888 @itemize @bullet
9889 @item
9890 no optimization
9891
9892 @item
9893 no inlining of subprogram calls
9894
9895 @item
9896 all run-time checks enabled except overflow and elaboration checks
9897 @end itemize
9898
9899 @noindent
9900 These options are suitable for most program development purposes. This
9901 chapter describes how you can modify these choices, and also provides
9902 some guidelines on debugging optimized code.
9903
9904 @menu
9905 * Controlling Run-Time Checks::
9906 * Use of Restrictions::
9907 * Optimization Levels::
9908 * Debugging Optimized Code::
9909 * Inlining of Subprograms::
9910 * Other Optimization Switches::
9911 * Optimization and Strict Aliasing::
9912
9913 @ifset vms
9914 * Coverage Analysis::
9915 @end ifset
9916 @end menu
9917
9918 @node Controlling Run-Time Checks
9919 @subsection Controlling Run-Time Checks
9920
9921 @noindent
9922 By default, GNAT generates all run-time checks, except integer overflow
9923 checks, stack overflow checks, and checks for access before elaboration on
9924 subprogram calls. The latter are not required in default mode, because all
9925 necessary checking is done at compile time.
9926 @cindex @option{-gnatp} (@command{gcc})
9927 @cindex @option{-gnato} (@command{gcc})
9928 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9929 be modified. @xref{Run-Time Checks}.
9930
9931 Our experience is that the default is suitable for most development
9932 purposes.
9933
9934 We treat integer overflow specially because these
9935 are quite expensive and in our experience are not as important as other
9936 run-time checks in the development process. Note that division by zero
9937 is not considered an overflow check, and divide by zero checks are
9938 generated where required by default.
9939
9940 Elaboration checks are off by default, and also not needed by default, since
9941 GNAT uses a static elaboration analysis approach that avoids the need for
9942 run-time checking. This manual contains a full chapter discussing the issue
9943 of elaboration checks, and if the default is not satisfactory for your use,
9944 you should read this chapter.
9945
9946 For validity checks, the minimal checks required by the Ada Reference
9947 Manual (for case statements and assignments to array elements) are on
9948 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9949 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9950 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9951 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9952 are also suppressed entirely if @option{-gnatp} is used.
9953
9954 @cindex Overflow checks
9955 @cindex Checks, overflow
9956 @findex Suppress
9957 @findex Unsuppress
9958 @cindex pragma Suppress
9959 @cindex pragma Unsuppress
9960 Note that the setting of the switches controls the default setting of
9961 the checks. They may be modified using either @code{pragma Suppress} (to
9962 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9963 checks) in the program source.
9964
9965 @node Use of Restrictions
9966 @subsection Use of Restrictions
9967
9968 @noindent
9969 The use of pragma Restrictions allows you to control which features are
9970 permitted in your program. Apart from the obvious point that if you avoid
9971 relatively expensive features like finalization (enforceable by the use
9972 of pragma Restrictions (No_Finalization), the use of this pragma does not
9973 affect the generated code in most cases.
9974
9975 One notable exception to this rule is that the possibility of task abort
9976 results in some distributed overhead, particularly if finalization or
9977 exception handlers are used. The reason is that certain sections of code
9978 have to be marked as non-abortable.
9979
9980 If you use neither the @code{abort} statement, nor asynchronous transfer
9981 of control (@code{select @dots{} then abort}), then this distributed overhead
9982 is removed, which may have a general positive effect in improving
9983 overall performance.  Especially code involving frequent use of tasking
9984 constructs and controlled types will show much improved performance.
9985 The relevant restrictions pragmas are
9986
9987 @smallexample @c ada
9988    pragma Restrictions (No_Abort_Statements);
9989    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9990 @end smallexample
9991
9992 @noindent
9993 It is recommended that these restriction pragmas be used if possible. Note
9994 that this also means that you can write code without worrying about the
9995 possibility of an immediate abort at any point.
9996
9997 @node Optimization Levels
9998 @subsection Optimization Levels
9999 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10000
10001 @noindent
10002 Without any optimization ^option,^qualifier,^
10003 the compiler's goal is to reduce the cost of
10004 compilation and to make debugging produce the expected results.
10005 Statements are independent: if you stop the program with a breakpoint between
10006 statements, you can then assign a new value to any variable or change
10007 the program counter to any other statement in the subprogram and get exactly
10008 the results you would expect from the source code.
10009
10010 Turning on optimization makes the compiler attempt to improve the
10011 performance and/or code size at the expense of compilation time and
10012 possibly the ability to debug the program.
10013
10014 If you use multiple
10015 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10016 the last such option is the one that is effective.
10017
10018 @noindent
10019 The default is optimization off. This results in the fastest compile
10020 times, but GNAT makes absolutely no attempt to optimize, and the
10021 generated programs are considerably larger and slower than when
10022 optimization is enabled. You can use the
10023 @ifclear vms
10024 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10025 @option{-O2}, @option{-O3}, and @option{-Os})
10026 @end ifclear
10027 @ifset vms
10028 @code{OPTIMIZE} qualifier
10029 @end ifset
10030 to @command{gcc} to control the optimization level:
10031
10032 @table @option
10033 @item ^-O0^/OPTIMIZE=NONE^
10034 No optimization (the default);
10035 generates unoptimized code but has
10036 the fastest compilation time.
10037
10038 Note that many other compilers do fairly extensive optimization
10039 even if ``no optimization'' is specified. With gcc, it is
10040 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10041 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10042 really does mean no optimization at all. This difference between
10043 gcc and other compilers should be kept in mind when doing
10044 performance comparisons.
10045
10046 @item ^-O1^/OPTIMIZE=SOME^
10047 Moderate optimization;
10048 optimizes reasonably well but does not
10049 degrade compilation time significantly.
10050
10051 @item ^-O2^/OPTIMIZE=ALL^
10052 @ifset vms
10053 @itemx /OPTIMIZE=DEVELOPMENT
10054 @end ifset
10055 Full optimization;
10056 generates highly optimized code and has
10057 the slowest compilation time.
10058
10059 @item ^-O3^/OPTIMIZE=INLINING^
10060 Full optimization as in @option{-O2},
10061 and also attempts automatic inlining of small
10062 subprograms within a unit (@pxref{Inlining of Subprograms}).
10063
10064 @item ^-Os^/OPTIMIZE=SPACE^
10065 Optimize space usage of resulting program.
10066 @end table
10067
10068 @noindent
10069 Higher optimization levels perform more global transformations on the
10070 program and apply more expensive analysis algorithms in order to generate
10071 faster and more compact code. The price in compilation time, and the
10072 resulting improvement in execution time,
10073 both depend on the particular application and the hardware environment.
10074 You should experiment to find the best level for your application.
10075
10076 Since the precise set of optimizations done at each level will vary from
10077 release to release (and sometime from target to target), it is best to think
10078 of the optimization settings in general terms.
10079 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10080 the GNU Compiler Collection (GCC)}, for details about
10081 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10082 individually enable or disable specific optimizations.
10083
10084 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10085 been tested extensively at all optimization levels. There are some bugs
10086 which appear only with optimization turned on, but there have also been
10087 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10088 level of optimization does not improve the reliability of the code
10089 generator, which in practice is highly reliable at all optimization
10090 levels.
10091
10092 Note regarding the use of @option{-O3}: The use of this optimization level
10093 is generally discouraged with GNAT, since it often results in larger
10094 executables which run more slowly. See further discussion of this point
10095 in @ref{Inlining of Subprograms}.
10096
10097 @node Debugging Optimized Code
10098 @subsection Debugging Optimized Code
10099 @cindex Debugging optimized code
10100 @cindex Optimization and debugging
10101
10102 @noindent
10103 Although it is possible to do a reasonable amount of debugging at
10104 @ifclear vms
10105 nonzero optimization levels,
10106 the higher the level the more likely that
10107 @end ifclear
10108 @ifset vms
10109 @option{/OPTIMIZE} settings other than @code{NONE},
10110 such settings will make it more likely that
10111 @end ifset
10112 source-level constructs will have been eliminated by optimization.
10113 For example, if a loop is strength-reduced, the loop
10114 control variable may be completely eliminated and thus cannot be
10115 displayed in the debugger.
10116 This can only happen at @option{-O2} or @option{-O3}.
10117 Explicit temporary variables that you code might be eliminated at
10118 ^level^setting^ @option{-O1} or higher.
10119
10120 The use of the @option{^-g^/DEBUG^} switch,
10121 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10122 which is needed for source-level debugging,
10123 affects the size of the program executable on disk,
10124 and indeed the debugging information can be quite large.
10125 However, it has no effect on the generated code (and thus does not
10126 degrade performance)
10127
10128 Since the compiler generates debugging tables for a compilation unit before
10129 it performs optimizations, the optimizing transformations may invalidate some
10130 of the debugging data.  You therefore need to anticipate certain
10131 anomalous situations that may arise while debugging optimized code.
10132 These are the most common cases:
10133
10134 @enumerate
10135 @item
10136 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10137 commands show
10138 the PC bouncing back and forth in the code.  This may result from any of
10139 the following optimizations:
10140
10141 @itemize @bullet
10142 @item
10143 @i{Common subexpression elimination:} using a single instance of code for a
10144 quantity that the source computes several times.  As a result you
10145 may not be able to stop on what looks like a statement.
10146
10147 @item
10148 @i{Invariant code motion:} moving an expression that does not change within a
10149 loop, to the beginning of the loop.
10150
10151 @item
10152 @i{Instruction scheduling:} moving instructions so as to
10153 overlap loads and stores (typically) with other code, or in
10154 general to move computations of values closer to their uses. Often
10155 this causes you to pass an assignment statement without the assignment
10156 happening and then later bounce back to the statement when the
10157 value is actually needed.  Placing a breakpoint on a line of code
10158 and then stepping over it may, therefore, not always cause all the
10159 expected side-effects.
10160 @end itemize
10161
10162 @item
10163 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10164 two identical pieces of code are merged and the program counter suddenly
10165 jumps to a statement that is not supposed to be executed, simply because
10166 it (and the code following) translates to the same thing as the code
10167 that @emph{was} supposed to be executed.  This effect is typically seen in
10168 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10169 a @code{break} in a C @code{^switch^switch^} statement.
10170
10171 @item
10172 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10173 There are various reasons for this effect:
10174
10175 @itemize @bullet
10176 @item
10177 In a subprogram prologue, a parameter may not yet have been moved to its
10178 ``home''.
10179
10180 @item
10181 A variable may be dead, and its register re-used.  This is
10182 probably the most common cause.
10183
10184 @item
10185 As mentioned above, the assignment of a value to a variable may
10186 have been moved.
10187
10188 @item
10189 A variable may be eliminated entirely by value propagation or
10190 other means.  In this case, GCC may incorrectly generate debugging
10191 information for the variable
10192 @end itemize
10193
10194 @noindent
10195 In general, when an unexpected value appears for a local variable or parameter
10196 you should first ascertain if that value was actually computed by
10197 your program, as opposed to being incorrectly reported by the debugger.
10198 Record fields or
10199 array elements in an object designated by an access value
10200 are generally less of a problem, once you have ascertained that the access
10201 value is sensible.
10202 Typically, this means checking variables in the preceding code and in the
10203 calling subprogram to verify that the value observed is explainable from other
10204 values (one must apply the procedure recursively to those
10205 other values); or re-running the code and stopping a little earlier
10206 (perhaps before the call) and stepping to better see how the variable obtained
10207 the value in question; or continuing to step @emph{from} the point of the
10208 strange value to see if code motion had simply moved the variable's
10209 assignments later.
10210 @end enumerate
10211
10212 @noindent
10213 In light of such anomalies, a recommended technique is to use @option{-O0}
10214 early in the software development cycle, when extensive debugging capabilities
10215 are most needed, and then move to @option{-O1} and later @option{-O2} as
10216 the debugger becomes less critical.
10217 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10218 a release management issue.
10219 @ifclear vms
10220 Note that if you use @option{-g} you can then use the @command{strip} program
10221 on the resulting executable,
10222 which removes both debugging information and global symbols.
10223 @end ifclear
10224
10225 @node Inlining of Subprograms
10226 @subsection Inlining of Subprograms
10227
10228 @noindent
10229 A call to a subprogram in the current unit is inlined if all the
10230 following conditions are met:
10231
10232 @itemize @bullet
10233 @item
10234 The optimization level is at least @option{-O1}.
10235
10236 @item
10237 The called subprogram is suitable for inlining: It must be small enough
10238 and not contain something that @command{gcc} cannot support in inlined
10239 subprograms.
10240
10241 @item
10242 @cindex pragma Inline
10243 @findex Inline
10244 Either @code{pragma Inline} applies to the subprogram, or it is local
10245 to the unit and called once from within it, or it is small and automatic
10246 inlining (optimization level @option{-O3}) is specified.
10247 @end itemize
10248
10249 @noindent
10250 Calls to subprograms in @code{with}'ed units are normally not inlined.
10251 To achieve actual inlining (that is, replacement of the call by the code
10252 in the body of the subprogram), the following conditions must all be true.
10253
10254 @itemize @bullet
10255 @item
10256 The optimization level is at least @option{-O1}.
10257
10258 @item
10259 The called subprogram is suitable for inlining: It must be small enough
10260 and not contain something that @command{gcc} cannot support in inlined
10261 subprograms.
10262
10263 @item
10264 The call appears in a body (not in a package spec).
10265
10266 @item
10267 There is a @code{pragma Inline} for the subprogram.
10268
10269 @item
10270 @cindex @option{-gnatn} (@command{gcc})
10271 The @option{^-gnatn^/INLINE^} switch
10272 is used in the @command{gcc} command line
10273 @end itemize
10274
10275 Even if all these conditions are met, it may not be possible for
10276 the compiler to inline the call, due to the length of the body,
10277 or features in the body that make it impossible for the compiler
10278 to do the inlining.
10279
10280 Note that specifying the @option{-gnatn} switch causes additional
10281 compilation dependencies. Consider the following:
10282
10283 @smallexample @c ada
10284 @cartouche
10285 package R is
10286    procedure Q;
10287    pragma Inline (Q);
10288 end R;
10289 package body R is
10290    @dots{}
10291 end R;
10292
10293 with R;
10294 procedure Main is
10295 begin
10296    @dots{}
10297    R.Q;
10298 end Main;
10299 @end cartouche
10300 @end smallexample
10301
10302 @noindent
10303 With the default behavior (no @option{-gnatn} switch specified), the
10304 compilation of the @code{Main} procedure depends only on its own source,
10305 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10306 means that editing the body of @code{R} does not require recompiling
10307 @code{Main}.
10308
10309 On the other hand, the call @code{R.Q} is not inlined under these
10310 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10311 is compiled, the call will be inlined if the body of @code{Q} is small
10312 enough, but now @code{Main} depends on the body of @code{R} in
10313 @file{r.adb} as well as on the spec. This means that if this body is edited,
10314 the main program must be recompiled. Note that this extra dependency
10315 occurs whether or not the call is in fact inlined by @command{gcc}.
10316
10317 The use of front end inlining with @option{-gnatN} generates similar
10318 additional dependencies.
10319
10320 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10321 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10322 can be used to prevent
10323 all inlining. This switch overrides all other conditions and ensures
10324 that no inlining occurs. The extra dependences resulting from
10325 @option{-gnatn} will still be active, even if
10326 this switch is used to suppress the resulting inlining actions.
10327
10328 @cindex @option{-fno-inline-functions} (@command{gcc})
10329 Note: The @option{-fno-inline-functions} switch can be used to prevent
10330 automatic inlining of small subprograms if @option{-O3} is used.
10331
10332 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10333 Note: The @option{-fno-inline-functions-called-once} switch
10334 can be used to prevent inlining of subprograms local to the unit
10335 and called once from within it if @option{-O1} is used.
10336
10337 Note regarding the use of @option{-O3}: There is no difference in inlining
10338 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10339 pragma @code{Inline} assuming the use of @option{-gnatn}
10340 or @option{-gnatN} (the switches that activate inlining). If you have used
10341 pragma @code{Inline} in appropriate cases, then it is usually much better
10342 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10343 in this case only has the effect of inlining subprograms you did not
10344 think should be inlined. We often find that the use of @option{-O3} slows
10345 down code by performing excessive inlining, leading to increased instruction
10346 cache pressure from the increased code size. So the bottom line here is
10347 that you should not automatically assume that @option{-O3} is better than
10348 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10349 it actually improves performance.
10350
10351 @node Other Optimization Switches
10352 @subsection Other Optimization Switches
10353 @cindex Optimization Switches
10354
10355 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10356 @command{gcc} optimization switches are potentially usable. These switches
10357 have not been extensively tested with GNAT but can generally be expected
10358 to work. Examples of switches in this category are
10359 @option{-funroll-loops} and
10360 the various target-specific @option{-m} options (in particular, it has been
10361 observed that @option{-march=pentium4} can significantly improve performance
10362 on appropriate machines). For full details of these switches, see
10363 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10364 the GNU Compiler Collection (GCC)}.
10365
10366 @node Optimization and Strict Aliasing
10367 @subsection Optimization and Strict Aliasing
10368 @cindex Aliasing
10369 @cindex Strict Aliasing
10370 @cindex No_Strict_Aliasing
10371
10372 @noindent
10373 The strong typing capabilities of Ada allow an optimizer to generate
10374 efficient code in situations where other languages would be forced to
10375 make worst case assumptions preventing such optimizations. Consider
10376 the following example:
10377
10378 @smallexample @c ada
10379 @cartouche
10380 procedure R is
10381    type Int1 is new Integer;
10382    type Int2 is new Integer;
10383    type Int1A is access Int1;
10384    type Int2A is access Int2;
10385    Int1V : Int1A;
10386    Int2V : Int2A;
10387    @dots{}
10388
10389 begin
10390    @dots{}
10391    for J in Data'Range loop
10392       if Data (J) = Int1V.all then
10393          Int2V.all := Int2V.all + 1;
10394       end if;
10395    end loop;
10396    @dots{}
10397 end R;
10398 @end cartouche
10399 @end smallexample
10400
10401 @noindent
10402 In this example, since the variable @code{Int1V} can only access objects
10403 of type @code{Int1}, and @code{Int2V} can only access objects of type
10404 @code{Int2}, there is no possibility that the assignment to
10405 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10406 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10407 for all iterations of the loop and avoid the extra memory reference
10408 required to dereference it each time through the loop.
10409
10410 This kind of optimization, called strict aliasing analysis, is
10411 triggered by specifying an optimization level of @option{-O2} or
10412 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10413 when access values are involved.
10414
10415 However, although this optimization is always correct in terms of
10416 the formal semantics of the Ada Reference Manual, difficulties can
10417 arise if features like @code{Unchecked_Conversion} are used to break
10418 the typing system. Consider the following complete program example:
10419
10420 @smallexample @c ada
10421 @cartouche
10422 package p1 is
10423    type int1 is new integer;
10424    type int2 is new integer;
10425    type a1 is access int1;
10426    type a2 is access int2;
10427 end p1;
10428
10429 with p1; use p1;
10430 package p2 is
10431    function to_a2 (Input : a1) return a2;
10432 end p2;
10433
10434 with Unchecked_Conversion;
10435 package body p2 is
10436    function to_a2 (Input : a1) return a2 is
10437       function to_a2u is
10438         new Unchecked_Conversion (a1, a2);
10439    begin
10440       return to_a2u (Input);
10441    end to_a2;
10442 end p2;
10443
10444 with p2; use p2;
10445 with p1; use p1;
10446 with Text_IO; use Text_IO;
10447 procedure m is
10448    v1 : a1 := new int1;
10449    v2 : a2 := to_a2 (v1);
10450 begin
10451    v1.all := 1;
10452    v2.all := 0;
10453    put_line (int1'image (v1.all));
10454 end;
10455 @end cartouche
10456 @end smallexample
10457
10458 @noindent
10459 This program prints out 0 in @option{-O0} or @option{-O1}
10460 mode, but it prints out 1 in @option{-O2} mode. That's
10461 because in strict aliasing mode, the compiler can and
10462 does assume that the assignment to @code{v2.all} could not
10463 affect the value of @code{v1.all}, since different types
10464 are involved.
10465
10466 This behavior is not a case of non-conformance with the standard, since
10467 the Ada RM specifies that an unchecked conversion where the resulting
10468 bit pattern is not a correct value of the target type can result in an
10469 abnormal value and attempting to reference an abnormal value makes the
10470 execution of a program erroneous.  That's the case here since the result
10471 does not point to an object of type @code{int2}.  This means that the
10472 effect is entirely unpredictable.
10473
10474 However, although that explanation may satisfy a language
10475 lawyer, in practice an applications programmer expects an
10476 unchecked conversion involving pointers to create true
10477 aliases and the behavior of printing 1 seems plain wrong.
10478 In this case, the strict aliasing optimization is unwelcome.
10479
10480 Indeed the compiler recognizes this possibility, and the
10481 unchecked conversion generates a warning:
10482
10483 @smallexample
10484 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10485 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10486 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10487 @end smallexample
10488
10489 @noindent
10490 Unfortunately the problem is recognized when compiling the body of
10491 package @code{p2}, but the actual "bad" code is generated while
10492 compiling the body of @code{m} and this latter compilation does not see
10493 the suspicious @code{Unchecked_Conversion}.
10494
10495 As implied by the warning message, there are approaches you can use to
10496 avoid the unwanted strict aliasing optimization in a case like this.
10497
10498 One possibility is to simply avoid the use of @option{-O2}, but
10499 that is a bit drastic, since it throws away a number of useful
10500 optimizations that do not involve strict aliasing assumptions.
10501
10502 A less drastic approach is to compile the program using the
10503 option @option{-fno-strict-aliasing}. Actually it is only the
10504 unit containing the dereferencing of the suspicious pointer
10505 that needs to be compiled. So in this case, if we compile
10506 unit @code{m} with this switch, then we get the expected
10507 value of zero printed. Analyzing which units might need
10508 the switch can be painful, so a more reasonable approach
10509 is to compile the entire program with options @option{-O2}
10510 and @option{-fno-strict-aliasing}. If the performance is
10511 satisfactory with this combination of options, then the
10512 advantage is that the entire issue of possible "wrong"
10513 optimization due to strict aliasing is avoided.
10514
10515 To avoid the use of compiler switches, the configuration
10516 pragma @code{No_Strict_Aliasing} with no parameters may be
10517 used to specify that for all access types, the strict
10518 aliasing optimization should be suppressed.
10519
10520 However, these approaches are still overkill, in that they causes
10521 all manipulations of all access values to be deoptimized. A more
10522 refined approach is to concentrate attention on the specific
10523 access type identified as problematic.
10524
10525 First, if a careful analysis of uses of the pointer shows
10526 that there are no possible problematic references, then
10527 the warning can be suppressed by bracketing the
10528 instantiation of @code{Unchecked_Conversion} to turn
10529 the warning off:
10530
10531 @smallexample @c ada
10532    pragma Warnings (Off);
10533    function to_a2u is
10534      new Unchecked_Conversion (a1, a2);
10535    pragma Warnings (On);
10536 @end smallexample
10537
10538 @noindent
10539 Of course that approach is not appropriate for this particular
10540 example, since indeed there is a problematic reference. In this
10541 case we can take one of two other approaches.
10542
10543 The first possibility is to move the instantiation of unchecked
10544 conversion to the unit in which the type is declared. In
10545 this example, we would move the instantiation of
10546 @code{Unchecked_Conversion} from the body of package
10547 @code{p2} to the spec of package @code{p1}. Now the
10548 warning disappears. That's because any use of the
10549 access type knows there is a suspicious unchecked
10550 conversion, and the strict aliasing optimization
10551 is automatically suppressed for the type.
10552
10553 If it is not practical to move the unchecked conversion to the same unit
10554 in which the destination access type is declared (perhaps because the
10555 source type is not visible in that unit), you may use pragma
10556 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10557 same declarative sequence as the declaration of the access type:
10558
10559 @smallexample @c ada
10560    type a2 is access int2;
10561    pragma No_Strict_Aliasing (a2);
10562 @end smallexample
10563
10564 @noindent
10565 Here again, the compiler now knows that the strict aliasing optimization
10566 should be suppressed for any reference to type @code{a2} and the
10567 expected behavior is obtained.
10568
10569 Finally, note that although the compiler can generate warnings for
10570 simple cases of unchecked conversions, there are tricker and more
10571 indirect ways of creating type incorrect aliases which the compiler
10572 cannot detect. Examples are the use of address overlays and unchecked
10573 conversions involving composite types containing access types as
10574 components. In such cases, no warnings are generated, but there can
10575 still be aliasing problems. One safe coding practice is to forbid the
10576 use of address clauses for type overlaying, and to allow unchecked
10577 conversion only for primitive types. This is not really a significant
10578 restriction since any possible desired effect can be achieved by
10579 unchecked conversion of access values.
10580
10581 The aliasing analysis done in strict aliasing mode can certainly
10582 have significant benefits. We have seen cases of large scale
10583 application code where the time is increased by up to 5% by turning
10584 this optimization off. If you have code that includes significant
10585 usage of unchecked conversion, you might want to just stick with
10586 @option{-O1} and avoid the entire issue. If you get adequate
10587 performance at this level of optimization level, that's probably
10588 the safest approach. If tests show that you really need higher
10589 levels of optimization, then you can experiment with @option{-O2}
10590 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10591 has on size and speed of the code. If you really need to use
10592 @option{-O2} with strict aliasing in effect, then you should
10593 review any uses of unchecked conversion of access types,
10594 particularly if you are getting the warnings described above.
10595
10596 @ifset vms
10597 @node Coverage Analysis
10598 @subsection Coverage Analysis
10599
10600 @noindent
10601 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10602 the user to determine the distribution of execution time across a program,
10603 @pxref{Profiling} for details of usage.
10604 @end ifset
10605
10606
10607 @node Text_IO Suggestions
10608 @section @code{Text_IO} Suggestions
10609 @cindex @code{Text_IO} and performance
10610
10611 @noindent
10612 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10613 the requirement of maintaining page and line counts. If performance
10614 is critical, a recommendation is to use @code{Stream_IO} instead of
10615 @code{Text_IO} for volume output, since this package has less overhead.
10616
10617 If @code{Text_IO} must be used, note that by default output to the standard
10618 output and standard error files is unbuffered (this provides better
10619 behavior when output statements are used for debugging, or if the
10620 progress of a program is observed by tracking the output, e.g. by
10621 using the Unix @command{tail -f} command to watch redirected output.
10622
10623 If you are generating large volumes of output with @code{Text_IO} and
10624 performance is an important factor, use a designated file instead
10625 of the standard output file, or change the standard output file to
10626 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10627
10628
10629
10630 @node Reducing Size of Ada Executables with gnatelim
10631 @section Reducing Size of Ada Executables with @code{gnatelim}
10632 @findex gnatelim
10633
10634 @noindent
10635 This section describes @command{gnatelim}, a tool which detects unused
10636 subprograms and helps the compiler to create a smaller executable for your
10637 program.
10638
10639 @menu
10640 * About gnatelim::
10641 * Running gnatelim::
10642 * Processing Precompiled Libraries::
10643 * Correcting the List of Eliminate Pragmas::
10644 * Making Your Executables Smaller::
10645 * Summary of the gnatelim Usage Cycle::
10646 @end menu
10647
10648 @node About gnatelim
10649 @subsection About @code{gnatelim}
10650
10651 @noindent
10652 When a program shares a set of Ada
10653 packages with other programs, it may happen that this program uses
10654 only a fraction of the subprograms defined in these packages. The code
10655 created for these unused subprograms increases the size of the executable.
10656
10657 @code{gnatelim} tracks unused subprograms in an Ada program and
10658 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10659 subprograms that are declared but never called. By placing the list of
10660 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10661 recompiling your program, you may decrease the size of its executable,
10662 because the compiler will not generate the code for 'eliminated' subprograms.
10663 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10664 information about this pragma.
10665
10666 @code{gnatelim} needs as its input data the name of the main subprogram.
10667
10668 If a set of source files is specified as @code{gnatelim} arguments, it
10669 treats these files as a complete set of sources making up a program to
10670 analyse, and analyses only these sources.
10671
10672 After a full successful build of the main subprogram @code{gnatelim} can be
10673 called without  specifying sources to analyse, in this case it computes
10674 the source closure of the main unit from the @file{ALI} files.
10675
10676 The following command will create the set of @file{ALI} files needed for
10677 @code{gnatelim}:
10678
10679 @smallexample
10680 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10681 @end smallexample
10682
10683 Note that @code{gnatelim} does not need object files.
10684
10685 @node Running gnatelim
10686 @subsection Running @code{gnatelim}
10687
10688 @noindent
10689 @code{gnatelim} has the following command-line interface:
10690
10691 @smallexample
10692 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10693 @end smallexample
10694
10695 @noindent
10696 @var{main_unit_name} should be a name of a source file that contains the main
10697 subprogram of a program (partition).
10698
10699 Each @var{filename} is the name (including the extension) of a source
10700 file to process. ``Wildcards'' are allowed, and
10701 the file name may contain path information.
10702
10703 @samp{@var{gcc_switches}} is a list of switches for
10704 @command{gcc}. They will be passed on to all compiler invocations made by
10705 @command{gnatelim} to generate the ASIS trees. Here you can provide
10706 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10707 use the @option{-gnatec} switch to set the configuration file etc.
10708
10709 @code{gnatelim} has the following switches:
10710
10711 @table @option
10712 @c !sort!
10713 @item ^-files^/FILES^=@var{filename}
10714 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10715 Take the argument source files from the specified file. This file should be an
10716 ordinary text file containing file names separated by spaces or
10717 line breaks. You can use this switch more than once in the same call to
10718 @command{gnatelim}. You also can combine this switch with
10719 an explicit list of files.
10720
10721 @item ^-log^/LOG^
10722 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10723 Duplicate all the output sent to @file{stderr} into a log file. The log file
10724 is named @file{gnatelim.log} and is located in the current directory.
10725
10726 @item ^-log^/LOGFILE^=@var{filename}
10727 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10728 Duplicate all the output sent to @file{stderr} into a specified log file.
10729
10730 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10731 @item ^--no-elim-dispatch^/NO_DISPATCH^
10732 Do not generate pragmas for dispatching operations.
10733
10734 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10735 @item ^-o^/OUTPUT^=@var{report_file}
10736 Put @command{gnatelim} output into a specified file. If this file already exists,
10737 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10738 into @file{stderr}
10739
10740 @item ^-q^/QUIET^
10741 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10742 Quiet mode: by default @code{gnatelim} outputs to the standard error
10743 stream the number of program units left to be processed. This option turns
10744 this trace off.
10745
10746 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10747 @item ^-t^/TIME^
10748 Print out execution time.
10749
10750 @item ^-v^/VERBOSE^
10751 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10752 Verbose mode: @code{gnatelim} version information is printed as Ada
10753 comments to the standard output stream. Also, in addition to the number of
10754 program units left @code{gnatelim} will output the name of the current unit
10755 being processed.
10756
10757 @item ^-wq^/WARNINGS=QUIET^
10758 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10759 Quet warning mode - some warnings are suppressed. In particular warnings that
10760 indicate that the analysed set of sources is incomplete to make up a
10761 partition and that some subprogram bodies are missing are not generated.
10762 @end table
10763
10764 @node Processing Precompiled Libraries
10765 @subsection Processing Precompiled Libraries
10766
10767 @noindent
10768 If some program uses a precompiled Ada library, it can be processed by
10769 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10770 Eliminate pragma for a subprogram if the body of this subprogram has not
10771 been analysed, this is a typical case for subprograms from precompiled
10772 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10773 warnings about missing source files and non-analyzed subprogram bodies
10774 that can be generated when processing precompiled Ada libraries.
10775
10776 @node Correcting the List of Eliminate Pragmas
10777 @subsection Correcting the List of Eliminate Pragmas
10778
10779 @noindent
10780 In some rare cases @code{gnatelim} may try to eliminate
10781 subprograms that are actually called in the program. In this case, the
10782 compiler will generate an error message of the form:
10783
10784 @smallexample
10785 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10786 @end smallexample
10787
10788 @noindent
10789 You will need to manually remove the wrong @code{Eliminate} pragmas from
10790 the configuration file indicated in the error message. You should recompile
10791 your program from scratch after that, because you need a consistent
10792 configuration file(s) during the entire compilation.
10793
10794 @node Making Your Executables Smaller
10795 @subsection Making Your Executables Smaller
10796
10797 @noindent
10798 In order to get a smaller executable for your program you now have to
10799 recompile the program completely with the configuration file containing
10800 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10801 @file{gnat.adc} file located in your current directory, just do:
10802
10803 @smallexample
10804 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10805 @end smallexample
10806
10807 @noindent
10808 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10809 recompile everything
10810 with the set of pragmas @code{Eliminate} that you have obtained with
10811 @command{gnatelim}).
10812
10813 Be aware that the set of @code{Eliminate} pragmas is specific to each
10814 program. It is not recommended to merge sets of @code{Eliminate}
10815 pragmas created for different programs in one configuration file.
10816
10817 @node Summary of the gnatelim Usage Cycle
10818 @subsection Summary of the @code{gnatelim} Usage Cycle
10819
10820 @noindent
10821 Here is a quick summary of the steps to be taken in order to reduce
10822 the size of your executables with @code{gnatelim}. You may use
10823 other GNAT options to control the optimization level,
10824 to produce the debugging information, to set search path, etc.
10825
10826 @enumerate
10827 @item
10828 Create a complete set of @file{ALI} files (if the program has not been
10829 built already)
10830
10831 @smallexample
10832 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10833 @end smallexample
10834
10835 @item
10836 Generate a list of @code{Eliminate} pragmas in default configuration file
10837 @file{gnat.adc} in the current directory
10838 @smallexample
10839 @ifset vms
10840 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10841 @end ifset
10842 @ifclear vms
10843 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10844 @end ifclear
10845 @end smallexample
10846
10847 @item
10848 Recompile the application
10849
10850 @smallexample
10851 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10852 @end smallexample
10853
10854 @end enumerate
10855
10856 @node Reducing Size of Executables with unused subprogram/data elimination
10857 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10858 @findex unused subprogram/data elimination
10859
10860 @noindent
10861 This section describes how you can eliminate unused subprograms and data from
10862 your executable just by setting options at compilation time.
10863
10864 @menu
10865 * About unused subprogram/data elimination::
10866 * Compilation options::
10867 * Example of unused subprogram/data elimination::
10868 @end menu
10869
10870 @node About unused subprogram/data elimination
10871 @subsection About unused subprogram/data elimination
10872
10873 @noindent
10874 By default, an executable contains all code and data of its composing objects
10875 (directly linked or coming from statically linked libraries), even data or code
10876 never used by this executable.
10877
10878 This feature will allow you to eliminate such unused code from your
10879 executable, making it smaller (in disk and in memory).
10880
10881 This functionality is available on all Linux platforms except for the IA-64
10882 architecture and on all cross platforms using the ELF binary file format.
10883 In both cases GNU binutils version 2.16 or later are required to enable it.
10884
10885 @node Compilation options
10886 @subsection Compilation options
10887
10888 @noindent
10889 The operation of eliminating the unused code and data from the final executable
10890 is directly performed by the linker.
10891
10892 In order to do this, it has to work with objects compiled with the
10893 following options:
10894 @option{-ffunction-sections} @option{-fdata-sections}.
10895 @cindex @option{-ffunction-sections} (@command{gcc})
10896 @cindex @option{-fdata-sections} (@command{gcc})
10897 These options are usable with C and Ada files.
10898 They will place respectively each
10899 function or data in a separate section in the resulting object file.
10900
10901 Once the objects and static libraries are created with these options, the
10902 linker can perform the dead code elimination. You can do this by setting
10903 the @option{-Wl,--gc-sections} option to gcc command or in the
10904 @option{-largs} section of @command{gnatmake}. This will perform a
10905 garbage collection of code and data never referenced.
10906
10907 If the linker performs a partial link (@option{-r} ld linker option), then you
10908 will need to provide one or several entry point using the
10909 @option{-e} / @option{--entry} ld option.
10910
10911 Note that objects compiled without the @option{-ffunction-sections} and
10912 @option{-fdata-sections} options can still be linked with the executable.
10913 However, no dead code elimination will be performed on those objects (they will
10914 be linked as is).
10915
10916 The GNAT static library is now compiled with -ffunction-sections and
10917 -fdata-sections on some platforms. This allows you to eliminate the unused code
10918 and data of the GNAT library from your executable.
10919
10920 @node Example of unused subprogram/data elimination
10921 @subsection Example of unused subprogram/data elimination
10922
10923 @noindent
10924 Here is a simple example:
10925
10926 @smallexample @c ada
10927 with Aux;
10928
10929 procedure Test is
10930 begin
10931    Aux.Used (10);
10932 end Test;
10933
10934 package Aux is
10935    Used_Data   : Integer;
10936    Unused_Data : Integer;
10937
10938    procedure Used   (Data : Integer);
10939    procedure Unused (Data : Integer);
10940 end Aux;
10941
10942 package body Aux is
10943    procedure Used (Data : Integer) is
10944    begin
10945       Used_Data := Data;
10946    end Used;
10947
10948    procedure Unused (Data : Integer) is
10949    begin
10950       Unused_Data := Data;
10951    end Unused;
10952 end Aux;
10953 @end smallexample
10954
10955 @noindent
10956 @code{Unused} and @code{Unused_Data} are never referenced in this code
10957 excerpt, and hence they may be safely removed from the final executable.
10958
10959 @smallexample
10960 $ gnatmake test
10961
10962 $ nm test | grep used
10963 020015f0 T aux__unused
10964 02005d88 B aux__unused_data
10965 020015cc T aux__used
10966 02005d84 B aux__used_data
10967
10968 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10969      -largs -Wl,--gc-sections
10970
10971 $ nm test | grep used
10972 02005350 T aux__used
10973 0201ffe0 B aux__used_data
10974 @end smallexample
10975
10976 @noindent
10977 It can be observed that the procedure @code{Unused} and the object
10978 @code{Unused_Data} are removed by the linker when using the
10979 appropriate options.
10980
10981 @c ********************************
10982 @node Renaming Files Using gnatchop
10983 @chapter Renaming Files Using @code{gnatchop}
10984 @findex gnatchop
10985
10986 @noindent
10987 This chapter discusses how to handle files with multiple units by using
10988 the @code{gnatchop} utility. This utility is also useful in renaming
10989 files to meet the standard GNAT default file naming conventions.
10990
10991 @menu
10992 * Handling Files with Multiple Units::
10993 * Operating gnatchop in Compilation Mode::
10994 * Command Line for gnatchop::
10995 * Switches for gnatchop::
10996 * Examples of gnatchop Usage::
10997 @end menu
10998
10999 @node Handling Files with Multiple Units
11000 @section Handling Files with Multiple Units
11001
11002 @noindent
11003 The basic compilation model of GNAT requires that a file submitted to the
11004 compiler have only one unit and there be a strict correspondence
11005 between the file name and the unit name.
11006
11007 The @code{gnatchop} utility allows both of these rules to be relaxed,
11008 allowing GNAT to process files which contain multiple compilation units
11009 and files with arbitrary file names. @code{gnatchop}
11010 reads the specified file and generates one or more output files,
11011 containing one unit per file. The unit and the file name correspond,
11012 as required by GNAT.
11013
11014 If you want to permanently restructure a set of ``foreign'' files so that
11015 they match the GNAT rules, and do the remaining development using the
11016 GNAT structure, you can simply use @command{gnatchop} once, generate the
11017 new set of files and work with them from that point on.
11018
11019 Alternatively, if you want to keep your files in the ``foreign'' format,
11020 perhaps to maintain compatibility with some other Ada compilation
11021 system, you can set up a procedure where you use @command{gnatchop} each
11022 time you compile, regarding the source files that it writes as temporary
11023 files that you throw away.
11024
11025 Note that if your file containing multiple units starts with a byte order
11026 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11027 will each start with a copy of this BOM, meaning that they can be compiled
11028 automatically in UTF-8 mode without needing to specify an explicit encoding.
11029
11030 @node Operating gnatchop in Compilation Mode
11031 @section Operating gnatchop in Compilation Mode
11032
11033 @noindent
11034 The basic function of @code{gnatchop} is to take a file with multiple units
11035 and split it into separate files. The boundary between files is reasonably
11036 clear, except for the issue of comments and pragmas. In default mode, the
11037 rule is that any pragmas between units belong to the previous unit, except
11038 that configuration pragmas always belong to the following unit. Any comments
11039 belong to the following unit. These rules
11040 almost always result in the right choice of
11041 the split point without needing to mark it explicitly and most users will
11042 find this default to be what they want. In this default mode it is incorrect to
11043 submit a file containing only configuration pragmas, or one that ends in
11044 configuration pragmas, to @code{gnatchop}.
11045
11046 However, using a special option to activate ``compilation mode'',
11047 @code{gnatchop}
11048 can perform another function, which is to provide exactly the semantics
11049 required by the RM for handling of configuration pragmas in a compilation.
11050 In the absence of configuration pragmas (at the main file level), this
11051 option has no effect, but it causes such configuration pragmas to be handled
11052 in a quite different manner.
11053
11054 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11055 only configuration pragmas, then this file is appended to the
11056 @file{gnat.adc} file in the current directory. This behavior provides
11057 the required behavior described in the RM for the actions to be taken
11058 on submitting such a file to the compiler, namely that these pragmas
11059 should apply to all subsequent compilations in the same compilation
11060 environment. Using GNAT, the current directory, possibly containing a
11061 @file{gnat.adc} file is the representation
11062 of a compilation environment. For more information on the
11063 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11064
11065 Second, in compilation mode, if @code{gnatchop}
11066 is given a file that starts with
11067 configuration pragmas, and contains one or more units, then these
11068 configuration pragmas are prepended to each of the chopped files. This
11069 behavior provides the required behavior described in the RM for the
11070 actions to be taken on compiling such a file, namely that the pragmas
11071 apply to all units in the compilation, but not to subsequently compiled
11072 units.
11073
11074 Finally, if configuration pragmas appear between units, they are appended
11075 to the previous unit. This results in the previous unit being illegal,
11076 since the compiler does not accept configuration pragmas that follow
11077 a unit. This provides the required RM behavior that forbids configuration
11078 pragmas other than those preceding the first compilation unit of a
11079 compilation.
11080
11081 For most purposes, @code{gnatchop} will be used in default mode. The
11082 compilation mode described above is used only if you need exactly
11083 accurate behavior with respect to compilations, and you have files
11084 that contain multiple units and configuration pragmas. In this
11085 circumstance the use of @code{gnatchop} with the compilation mode
11086 switch provides the required behavior, and is for example the mode
11087 in which GNAT processes the ACVC tests.
11088
11089 @node Command Line for gnatchop
11090 @section Command Line for @code{gnatchop}
11091
11092 @noindent
11093 The @code{gnatchop} command has the form:
11094
11095 @smallexample
11096 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11097 @c      @ovar{directory}
11098 @c Expanding @ovar macro inline (explanation in macro def comments)
11099 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11100       @r{[}@var{directory}@r{]}
11101 @end smallexample
11102
11103 @noindent
11104 The only required argument is the file name of the file to be chopped.
11105 There are no restrictions on the form of this file name. The file itself
11106 contains one or more Ada units, in normal GNAT format, concatenated
11107 together. As shown, more than one file may be presented to be chopped.
11108
11109 When run in default mode, @code{gnatchop} generates one output file in
11110 the current directory for each unit in each of the files.
11111
11112 @var{directory}, if specified, gives the name of the directory to which
11113 the output files will be written. If it is not specified, all files are
11114 written to the current directory.
11115
11116 For example, given a
11117 file called @file{hellofiles} containing
11118
11119 @smallexample @c ada
11120 @group
11121 @cartouche
11122 procedure hello;
11123
11124 with Text_IO; use Text_IO;
11125 procedure hello is
11126 begin
11127    Put_Line ("Hello");
11128 end hello;
11129 @end cartouche
11130 @end group
11131 @end smallexample
11132
11133 @noindent
11134 the command
11135
11136 @smallexample
11137 $ gnatchop ^hellofiles^HELLOFILES.^
11138 @end smallexample
11139
11140 @noindent
11141 generates two files in the current directory, one called
11142 @file{hello.ads} containing the single line that is the procedure spec,
11143 and the other called @file{hello.adb} containing the remaining text. The
11144 original file is not affected. The generated files can be compiled in
11145 the normal manner.
11146
11147 @noindent
11148 When gnatchop is invoked on a file that is empty or that contains only empty
11149 lines and/or comments, gnatchop will not fail, but will not produce any
11150 new sources.
11151
11152 For example, given a
11153 file called @file{toto.txt} containing
11154
11155 @smallexample @c ada
11156 @group
11157 @cartouche
11158 --  Just a comment
11159 @end cartouche
11160 @end group
11161 @end smallexample
11162
11163 @noindent
11164 the command
11165
11166 @smallexample
11167 $ gnatchop ^toto.txt^TOT.TXT^
11168 @end smallexample
11169
11170 @noindent
11171 will not produce any new file and will result in the following warnings:
11172
11173 @smallexample
11174 toto.txt:1:01: warning: empty file, contains no compilation units
11175 no compilation units found
11176 no source files written
11177 @end smallexample
11178
11179 @node Switches for gnatchop
11180 @section Switches for @code{gnatchop}
11181
11182 @noindent
11183 @command{gnatchop} recognizes the following switches:
11184
11185 @table @option
11186 @c !sort!
11187
11188 @item --version
11189 @cindex @option{--version} @command{gnatchop}
11190 Display Copyright and version, then exit disregarding all other options.
11191
11192 @item --help
11193 @cindex @option{--help} @command{gnatchop}
11194 If @option{--version} was not used, display usage, then exit disregarding
11195 all other options.
11196
11197 @item ^-c^/COMPILATION^
11198 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11199 Causes @code{gnatchop} to operate in compilation mode, in which
11200 configuration pragmas are handled according to strict RM rules. See
11201 previous section for a full description of this mode.
11202
11203 @ifclear vms
11204 @item -gnat@var{xxx}
11205 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11206 used to parse the given file. Not all @var{xxx} options make sense,
11207 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11208 process a source file that uses Latin-2 coding for identifiers.
11209 @end ifclear
11210
11211 @item ^-h^/HELP^
11212 Causes @code{gnatchop} to generate a brief help summary to the standard
11213 output file showing usage information.
11214
11215 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11216 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11217 Limit generated file names to the specified number @code{mm}
11218 of characters.
11219 This is useful if the
11220 resulting set of files is required to be interoperable with systems
11221 which limit the length of file names.
11222 @ifset vms
11223 If no value is given, or
11224 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11225 a default of 39, suitable for OpenVMS Alpha
11226 Systems, is assumed
11227 @end ifset
11228 @ifclear vms
11229 No space is allowed between the @option{-k} and the numeric value. The numeric
11230 value may be omitted in which case a default of @option{-k8},
11231 suitable for use
11232 with DOS-like file systems, is used. If no @option{-k} switch
11233 is present then
11234 there is no limit on the length of file names.
11235 @end ifclear
11236
11237 @item ^-p^/PRESERVE^
11238 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11239 Causes the file ^modification^creation^ time stamp of the input file to be
11240 preserved and used for the time stamp of the output file(s). This may be
11241 useful for preserving coherency of time stamps in an environment where
11242 @code{gnatchop} is used as part of a standard build process.
11243
11244 @item ^-q^/QUIET^
11245 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11246 Causes output of informational messages indicating the set of generated
11247 files to be suppressed. Warnings and error messages are unaffected.
11248
11249 @item ^-r^/REFERENCE^
11250 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11251 @findex Source_Reference
11252 Generate @code{Source_Reference} pragmas. Use this switch if the output
11253 files are regarded as temporary and development is to be done in terms
11254 of the original unchopped file. This switch causes
11255 @code{Source_Reference} pragmas to be inserted into each of the
11256 generated files to refers back to the original file name and line number.
11257 The result is that all error messages refer back to the original
11258 unchopped file.
11259 In addition, the debugging information placed into the object file (when
11260 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11261 specified)
11262 also refers back to this original file so that tools like profilers and
11263 debuggers will give information in terms of the original unchopped file.
11264
11265 If the original file to be chopped itself contains
11266 a @code{Source_Reference}
11267 pragma referencing a third file, then gnatchop respects
11268 this pragma, and the generated @code{Source_Reference} pragmas
11269 in the chopped file refer to the original file, with appropriate
11270 line numbers. This is particularly useful when @code{gnatchop}
11271 is used in conjunction with @code{gnatprep} to compile files that
11272 contain preprocessing statements and multiple units.
11273
11274 @item ^-v^/VERBOSE^
11275 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11276 Causes @code{gnatchop} to operate in verbose mode. The version
11277 number and copyright notice are output, as well as exact copies of
11278 the gnat1 commands spawned to obtain the chop control information.
11279
11280 @item ^-w^/OVERWRITE^
11281 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11282 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11283 fatal error if there is already a file with the same name as a
11284 file it would otherwise output, in other words if the files to be
11285 chopped contain duplicated units. This switch bypasses this
11286 check, and causes all but the last instance of such duplicated
11287 units to be skipped.
11288
11289 @ifclear vms
11290 @item --GCC=@var{xxxx}
11291 @cindex @option{--GCC=} (@code{gnatchop})
11292 Specify the path of the GNAT parser to be used. When this switch is used,
11293 no attempt is made to add the prefix to the GNAT parser executable.
11294 @end ifclear
11295 @end table
11296
11297 @node Examples of gnatchop Usage
11298 @section Examples of @code{gnatchop} Usage
11299
11300 @table @code
11301 @ifset vms
11302 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11303 @end ifset
11304 @ifclear vms
11305 @item gnatchop -w hello_s.ada prerelease/files
11306 @end ifclear
11307
11308 Chops the source file @file{hello_s.ada}. The output files will be
11309 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11310 overwriting any
11311 files with matching names in that directory (no files in the current
11312 directory are modified).
11313
11314 @item gnatchop ^archive^ARCHIVE.^
11315 Chops the source file @file{^archive^ARCHIVE.^}
11316 into the current directory. One
11317 useful application of @code{gnatchop} is in sending sets of sources
11318 around, for example in email messages. The required sources are simply
11319 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11320 command), and then
11321 @command{gnatchop} is used at the other end to reconstitute the original
11322 file names.
11323
11324 @item gnatchop file1 file2 file3 direc
11325 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11326 the resulting files in the directory @file{direc}. Note that if any units
11327 occur more than once anywhere within this set of files, an error message
11328 is generated, and no files are written. To override this check, use the
11329 @option{^-w^/OVERWRITE^} switch,
11330 in which case the last occurrence in the last file will
11331 be the one that is output, and earlier duplicate occurrences for a given
11332 unit will be skipped.
11333 @end table
11334
11335 @node Configuration Pragmas
11336 @chapter Configuration Pragmas
11337 @cindex Configuration pragmas
11338 @cindex Pragmas, configuration
11339
11340 @noindent
11341 Configuration pragmas include those pragmas described as
11342 such in the Ada Reference Manual, as well as
11343 implementation-dependent pragmas that are configuration pragmas.
11344 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11345 for details on these additional GNAT-specific configuration pragmas.
11346 Most notably, the pragma @code{Source_File_Name}, which allows
11347 specifying non-default names for source files, is a configuration
11348 pragma. The following is a complete list of configuration pragmas
11349 recognized by GNAT:
11350
11351 @smallexample
11352    Ada_83
11353    Ada_95
11354    Ada_05
11355    Ada_2005
11356    Assertion_Policy
11357    Assume_No_Invalid_Values
11358    C_Pass_By_Copy
11359    Check_Name
11360    Check_Policy
11361    Compile_Time_Error
11362    Compile_Time_Warning
11363    Compiler_Unit
11364    Component_Alignment
11365    Convention_Identifier
11366    Debug_Policy
11367    Detect_Blocking
11368    Discard_Names
11369    Elaboration_Checks
11370    Eliminate
11371    Extend_System
11372    Extensions_Allowed
11373    External_Name_Casing
11374    Fast_Math
11375    Favor_Top_Level
11376    Float_Representation
11377    Implicit_Packing
11378    Initialize_Scalars
11379    Interrupt_State
11380    License
11381    Locking_Policy
11382    Long_Float
11383    No_Run_Time
11384    No_Strict_Aliasing
11385    Normalize_Scalars
11386    Optimize_Alignment
11387    Persistent_BSS
11388    Polling
11389    Priority_Specific_Dispatching
11390    Profile
11391    Profile_Warnings
11392    Propagate_Exceptions
11393    Queuing_Policy
11394    Ravenscar
11395    Restricted_Run_Time
11396    Restrictions
11397    Restrictions_Warnings
11398    Reviewable
11399    Source_File_Name
11400    Source_File_Name_Project
11401    Style_Checks
11402    Suppress
11403    Suppress_Exception_Locations
11404    Task_Dispatching_Policy
11405    Universal_Data
11406    Unsuppress
11407    Use_VADS_Size
11408    Validity_Checks
11409    Warnings
11410    Wide_Character_Encoding
11411
11412 @end smallexample
11413
11414 @menu
11415 * Handling of Configuration Pragmas::
11416 * The Configuration Pragmas Files::
11417 @end menu
11418
11419 @node Handling of Configuration Pragmas
11420 @section Handling of Configuration Pragmas
11421
11422 Configuration pragmas may either appear at the start of a compilation
11423 unit, in which case they apply only to that unit, or they may apply to
11424 all compilations performed in a given compilation environment.
11425
11426 GNAT also provides the @code{gnatchop} utility to provide an automatic
11427 way to handle configuration pragmas following the semantics for
11428 compilations (that is, files with multiple units), described in the RM.
11429 See @ref{Operating gnatchop in Compilation Mode} for details.
11430 However, for most purposes, it will be more convenient to edit the
11431 @file{gnat.adc} file that contains configuration pragmas directly,
11432 as described in the following section.
11433
11434 @node The Configuration Pragmas Files
11435 @section The Configuration Pragmas Files
11436 @cindex @file{gnat.adc}
11437
11438 @noindent
11439 In GNAT a compilation environment is defined by the current
11440 directory at the time that a compile command is given. This current
11441 directory is searched for a file whose name is @file{gnat.adc}. If
11442 this file is present, it is expected to contain one or more
11443 configuration pragmas that will be applied to the current compilation.
11444 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11445 considered.
11446
11447 Configuration pragmas may be entered into the @file{gnat.adc} file
11448 either by running @code{gnatchop} on a source file that consists only of
11449 configuration pragmas, or more conveniently  by
11450 direct editing of the @file{gnat.adc} file, which is a standard format
11451 source file.
11452
11453 In addition to @file{gnat.adc}, additional files containing configuration
11454 pragmas may be applied to the current compilation using the switch
11455 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11456 contains only configuration pragmas. These configuration pragmas are
11457 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11458 is present and switch @option{-gnatA} is not used).
11459
11460 It is allowed to specify several switches @option{-gnatec}, all of which
11461 will be taken into account.
11462
11463 If you are using project file, a separate mechanism is provided using
11464 project attributes, see @ref{Specifying Configuration Pragmas} for more
11465 details.
11466
11467 @ifset vms
11468 Of special interest to GNAT OpenVMS Alpha is the following
11469 configuration pragma:
11470
11471 @smallexample @c ada
11472 @cartouche
11473 pragma Extend_System (Aux_DEC);
11474 @end cartouche
11475 @end smallexample
11476
11477 @noindent
11478 In the presence of this pragma, GNAT adds to the definition of the
11479 predefined package SYSTEM all the additional types and subprograms that are
11480 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11481 @end ifset
11482
11483 @node Handling Arbitrary File Naming Conventions Using gnatname
11484 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11485 @cindex Arbitrary File Naming Conventions
11486
11487 @menu
11488 * Arbitrary File Naming Conventions::
11489 * Running gnatname::
11490 * Switches for gnatname::
11491 * Examples of gnatname Usage::
11492 @end menu
11493
11494 @node Arbitrary File Naming Conventions
11495 @section Arbitrary File Naming Conventions
11496
11497 @noindent
11498 The GNAT compiler must be able to know the source file name of a compilation
11499 unit.  When using the standard GNAT default file naming conventions
11500 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11501 does not need additional information.
11502
11503 @noindent
11504 When the source file names do not follow the standard GNAT default file naming
11505 conventions, the GNAT compiler must be given additional information through
11506 a configuration pragmas file (@pxref{Configuration Pragmas})
11507 or a project file.
11508 When the non-standard file naming conventions are well-defined,
11509 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11510 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11511 if the file naming conventions are irregular or arbitrary, a number
11512 of pragma @code{Source_File_Name} for individual compilation units
11513 must be defined.
11514 To help maintain the correspondence between compilation unit names and
11515 source file names within the compiler,
11516 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11517 set of files.
11518
11519 @node Running gnatname
11520 @section Running @code{gnatname}
11521
11522 @noindent
11523 The usual form of the @code{gnatname} command is
11524
11525 @smallexample
11526 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11527 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11528 @c Expanding @ovar macro inline (explanation in macro def comments)
11529 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11530       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11531 @end smallexample
11532
11533 @noindent
11534 All of the arguments are optional. If invoked without any argument,
11535 @code{gnatname} will display its usage.
11536
11537 @noindent
11538 When used with at least one naming pattern, @code{gnatname} will attempt to
11539 find all the compilation units in files that follow at least one of the
11540 naming patterns. To find these compilation units,
11541 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11542 regular files.
11543
11544 @noindent
11545 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11546 Each Naming Pattern is enclosed between double quotes (or single
11547 quotes on Windows).
11548 A Naming Pattern is a regular expression similar to the wildcard patterns
11549 used in file names by the Unix shells or the DOS prompt.
11550
11551 @noindent
11552 @code{gnatname} may be called with several sections of directories/patterns.
11553 Sections are separated by switch @code{--and}. In each section, there must be
11554 at least one pattern. If no directory is specified in a section, the current
11555 directory (or the project directory is @code{-P} is used) is implied.
11556 The options other that the directory switches and the patterns apply globally
11557 even if they are in different sections.
11558
11559 @noindent
11560 Examples of Naming Patterns are
11561
11562 @smallexample
11563    "*.[12].ada"
11564    "*.ad[sb]*"
11565    "body_*"    "spec_*"
11566 @end smallexample
11567
11568 @noindent
11569 For a more complete description of the syntax of Naming Patterns,
11570 see the second kind of regular expressions described in @file{g-regexp.ads}
11571 (the ``Glob'' regular expressions).
11572
11573 @noindent
11574 When invoked with no switch @code{-P}, @code{gnatname} will create a
11575 configuration pragmas file @file{gnat.adc} in the current working directory,
11576 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11577 unit.
11578
11579 @node Switches for gnatname
11580 @section Switches for @code{gnatname}
11581
11582 @noindent
11583 Switches for @code{gnatname} must precede any specified Naming Pattern.
11584
11585 @noindent
11586 You may specify any of the following switches to @code{gnatname}:
11587
11588 @table @option
11589 @c !sort!
11590
11591 @item --version
11592 @cindex @option{--version} @command{gnatname}
11593 Display Copyright and version, then exit disregarding all other options.
11594
11595 @item --help
11596 @cindex @option{--help} @command{gnatname}
11597 If @option{--version} was not used, display usage, then exit disregarding
11598 all other options.
11599
11600 @item --and
11601 Start another section of directories/patterns.
11602
11603 @item ^-c^/CONFIG_FILE=^@file{file}
11604 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11605 Create a configuration pragmas file @file{file} (instead of the default
11606 @file{gnat.adc}).
11607 @ifclear vms
11608 There may be zero, one or more space between @option{-c} and
11609 @file{file}.
11610 @end ifclear
11611 @file{file} may include directory information. @file{file} must be
11612 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11613 When a switch @option{^-c^/CONFIG_FILE^} is
11614 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11615
11616 @item ^-d^/SOURCE_DIRS=^@file{dir}
11617 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11618 Look for source files in directory @file{dir}. There may be zero, one or more
11619 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11620 When a switch @option{^-d^/SOURCE_DIRS^}
11621 is specified, the current working directory will not be searched for source
11622 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11623 or @option{^-D^/DIR_FILES^} switch.
11624 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11625 If @file{dir} is a relative path, it is relative to the directory of
11626 the configuration pragmas file specified with switch
11627 @option{^-c^/CONFIG_FILE^},
11628 or to the directory of the project file specified with switch
11629 @option{^-P^/PROJECT_FILE^} or,
11630 if neither switch @option{^-c^/CONFIG_FILE^}
11631 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11632 current working directory. The directory
11633 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11634
11635 @item ^-D^/DIRS_FILE=^@file{file}
11636 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11637 Look for source files in all directories listed in text file @file{file}.
11638 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11639 and @file{file}.
11640 @file{file} must be an existing, readable text file.
11641 Each nonempty line in @file{file} must be a directory.
11642 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11643 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11644 @file{file}.
11645
11646 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11647 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11648 Foreign patterns. Using this switch, it is possible to add sources of languages
11649 other than Ada to the list of sources of a project file.
11650 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11651 For example,
11652 @smallexample
11653 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11654 @end smallexample
11655 @noindent
11656 will look for Ada units in all files with the @file{.ada} extension,
11657 and will add to the list of file for project @file{prj.gpr} the C files
11658 with extension @file{.^c^C^}.
11659
11660 @item ^-h^/HELP^
11661 @cindex @option{^-h^/HELP^} (@code{gnatname})
11662 Output usage (help) information. The output is written to @file{stdout}.
11663
11664 @item ^-P^/PROJECT_FILE=^@file{proj}
11665 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11666 Create or update project file @file{proj}. There may be zero, one or more space
11667 between @option{-P} and @file{proj}. @file{proj} may include directory
11668 information. @file{proj} must be writable.
11669 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11670 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11671 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11672
11673 @item ^-v^/VERBOSE^
11674 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11675 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11676 This includes name of the file written, the name of the directories to search
11677 and, for each file in those directories whose name matches at least one of
11678 the Naming Patterns, an indication of whether the file contains a unit,
11679 and if so the name of the unit.
11680
11681 @item ^-v -v^/VERBOSE /VERBOSE^
11682 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11683 Very Verbose mode. In addition to the output produced in verbose mode,
11684 for each file in the searched directories whose name matches none of
11685 the Naming Patterns, an indication is given that there is no match.
11686
11687 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11688 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11689 Excluded patterns. Using this switch, it is possible to exclude some files
11690 that would match the name patterns. For example,
11691 @smallexample
11692 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11693 @end smallexample
11694 @noindent
11695 will look for Ada units in all files with the @file{.ada} extension,
11696 except those whose names end with @file{_nt.ada}.
11697
11698 @end table
11699
11700 @node Examples of gnatname Usage
11701 @section Examples of @code{gnatname} Usage
11702
11703 @ifset vms
11704 @smallexample
11705 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11706 @end smallexample
11707 @end ifset
11708
11709 @ifclear vms
11710 @smallexample
11711 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11712 @end smallexample
11713 @end ifclear
11714
11715 @noindent
11716 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11717 and be writable. In addition, the directory
11718 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11719 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11720
11721 @ifclear vms
11722 Note the optional spaces after @option{-c} and @option{-d}.
11723 @end ifclear
11724
11725 @smallexample
11726 @ifclear vms
11727 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11728   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11729 @end ifclear
11730 @ifset vms
11731 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11732   /EXCLUDED_PATTERN=*_nt_body.ada
11733   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11734   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11735 @end ifset
11736 @end smallexample
11737
11738 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11739 even in conjunction with one or several switches
11740 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11741 are used in this example.
11742
11743 @c *****************************************
11744 @c * G N A T  P r o j e c t  M a n a g e r *
11745 @c *****************************************
11746
11747 @c ------ macros for projects.texi
11748 @c These macros are needed when building the gprbuild documentation, but
11749 @c should have no effect in the gnat user's guide
11750
11751 @macro CODESAMPLE{TXT}
11752 @smallexample
11753 @group
11754 \TXT\
11755 @end group
11756 @end smallexample
11757 @end macro
11758
11759 @macro PROJECTFILE{TXT}
11760 @CODESAMPLE{\TXT\}
11761 @end macro
11762
11763 @c simulates a newline when in a @CODESAMPLE
11764 @macro NL{}
11765 @end macro
11766
11767 @macro TIP{TXT}
11768 @quotation
11769 @noindent
11770 \TXT\
11771 @end quotation
11772 @end macro
11773
11774 @macro TIPHTML{TXT}
11775 \TXT\
11776 @end macro
11777
11778 @macro IMPORTANT{TXT}
11779 @quotation
11780 @noindent
11781 \TXT\
11782 @end quotation
11783
11784 @end macro
11785
11786 @macro NOTE{TXT}
11787 @quotation
11788 @noindent
11789 \TXT\
11790 @end quotation
11791 @end macro
11792
11793 @include projects.texi
11794
11795 @c *****************************************
11796 @c * Cross-referencing tools
11797 @c *****************************************
11798
11799 @node The Cross-Referencing Tools gnatxref and gnatfind
11800 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11801 @findex gnatxref
11802 @findex gnatfind
11803
11804 @noindent
11805 The compiler generates cross-referencing information (unless
11806 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11807 This information indicates where in the source each entity is declared and
11808 referenced. Note that entities in package Standard are not included, but
11809 entities in all other predefined units are included in the output.
11810
11811 Before using any of these two tools, you need to compile successfully your
11812 application, so that GNAT gets a chance to generate the cross-referencing
11813 information.
11814
11815 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11816 information to provide the user with the capability to easily locate the
11817 declaration and references to an entity. These tools are quite similar,
11818 the difference being that @code{gnatfind} is intended for locating
11819 definitions and/or references to a specified entity or entities, whereas
11820 @code{gnatxref} is oriented to generating a full report of all
11821 cross-references.
11822
11823 To use these tools, you must not compile your application using the
11824 @option{-gnatx} switch on the @command{gnatmake} command line
11825 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11826 information will not be generated.
11827
11828 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11829 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11830
11831 @menu
11832 * Switches for gnatxref::
11833 * Switches for gnatfind::
11834 * Project Files for gnatxref and gnatfind::
11835 * Regular Expressions in gnatfind and gnatxref::
11836 * Examples of gnatxref Usage::
11837 * Examples of gnatfind Usage::
11838 @end menu
11839
11840 @node Switches for gnatxref
11841 @section @code{gnatxref} Switches
11842
11843 @noindent
11844 The command invocation for @code{gnatxref} is:
11845 @smallexample
11846 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11847 @c Expanding @ovar macro inline (explanation in macro def comments)
11848 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11849 @end smallexample
11850
11851 @noindent
11852 where
11853
11854 @table @var
11855 @item sourcefile1
11856 @itemx sourcefile2
11857 identifies the source files for which a report is to be generated. The
11858 ``with''ed units will be processed too. You must provide at least one file.
11859
11860 These file names are considered to be regular expressions, so for instance
11861 specifying @file{source*.adb} is the same as giving every file in the current
11862 directory whose name starts with @file{source} and whose extension is
11863 @file{adb}.
11864
11865 You shouldn't specify any directory name, just base names. @command{gnatxref}
11866 and @command{gnatfind} will be able to locate these files by themselves using
11867 the source path. If you specify directories, no result is produced.
11868
11869 @end table
11870
11871 @noindent
11872 The switches can be:
11873 @table @option
11874 @c !sort!
11875 @item --version
11876 @cindex @option{--version} @command{gnatxref}
11877 Display Copyright and version, then exit disregarding all other options.
11878
11879 @item --help
11880 @cindex @option{--help} @command{gnatxref}
11881 If @option{--version} was not used, display usage, then exit disregarding
11882 all other options.
11883
11884 @item ^-a^/ALL_FILES^
11885 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
11886 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
11887 the read-only files found in the library search path. Otherwise, these files
11888 will be ignored. This option can be used to protect Gnat sources or your own
11889 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
11890 much faster, and their output much smaller. Read-only here refers to access
11891 or permissions status in the file system for the current user.
11892
11893 @item -aIDIR
11894 @cindex @option{-aIDIR} (@command{gnatxref})
11895 When looking for source files also look in directory DIR. The order in which
11896 source file search is undertaken is the same as for @command{gnatmake}.
11897
11898 @item -aODIR
11899 @cindex @option{-aODIR} (@command{gnatxref})
11900 When searching for library and object files, look in directory
11901 DIR. The order in which library files are searched is the same as for
11902 @command{gnatmake}.
11903
11904 @item -nostdinc
11905 @cindex @option{-nostdinc} (@command{gnatxref})
11906 Do not look for sources in the system default directory.
11907
11908 @item -nostdlib
11909 @cindex @option{-nostdlib} (@command{gnatxref})
11910 Do not look for library files in the system default directory.
11911
11912 @item --ext=@var{extension}
11913 @cindex @option{--ext} (@command{gnatxref})
11914 Specify an alternate ali file extension. The default is @code{ali} and other
11915 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
11916 switch. Note that if this switch overrides the default, which means that only
11917 the new extension will be considered.
11918
11919 @item --RTS=@var{rts-path}
11920 @cindex @option{--RTS} (@command{gnatxref})
11921 Specifies the default location of the runtime library. Same meaning as the
11922 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
11923
11924 @item ^-d^/DERIVED_TYPES^
11925 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
11926 If this switch is set @code{gnatxref} will output the parent type
11927 reference for each matching derived types.
11928
11929 @item ^-f^/FULL_PATHNAME^
11930 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
11931 If this switch is set, the output file names will be preceded by their
11932 directory (if the file was found in the search path). If this switch is
11933 not set, the directory will not be printed.
11934
11935 @item ^-g^/IGNORE_LOCALS^
11936 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
11937 If this switch is set, information is output only for library-level
11938 entities, ignoring local entities. The use of this switch may accelerate
11939 @code{gnatfind} and @code{gnatxref}.
11940
11941 @item -IDIR
11942 @cindex @option{-IDIR} (@command{gnatxref})
11943 Equivalent to @samp{-aODIR -aIDIR}.
11944
11945 @item -pFILE
11946 @cindex @option{-pFILE} (@command{gnatxref})
11947 Specify a project file to use @xref{GNAT Project Manager}.
11948 If you need to use the @file{.gpr}
11949 project files, you should use gnatxref through the GNAT driver
11950 (@command{gnat xref -Pproject}).
11951
11952 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
11953 project file in the current directory.
11954
11955 If a project file is either specified or found by the tools, then the content
11956 of the source directory and object directory lines are added as if they
11957 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
11958 and @samp{^-aO^OBJECT_SEARCH^}.
11959 @item ^-u^/UNUSED^
11960 Output only unused symbols. This may be really useful if you give your
11961 main compilation unit on the command line, as @code{gnatxref} will then
11962 display every unused entity and 'with'ed package.
11963
11964 @ifclear vms
11965 @item -v
11966 Instead of producing the default output, @code{gnatxref} will generate a
11967 @file{tags} file that can be used by vi. For examples how to use this
11968 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
11969 to the standard output, thus you will have to redirect it to a file.
11970 @end ifclear
11971
11972 @end table
11973
11974 @noindent
11975 All these switches may be in any order on the command line, and may even
11976 appear after the file names. They need not be separated by spaces, thus
11977 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
11978 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
11979
11980 @node Switches for gnatfind
11981 @section @code{gnatfind} Switches
11982
11983 @noindent
11984 The command line for @code{gnatfind} is:
11985
11986 @smallexample
11987 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
11988 @c       @r{[}@var{file1} @var{file2} @dots{}]
11989 @c Expanding @ovar macro inline (explanation in macro def comments)
11990 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
11991       @r{[}@var{file1} @var{file2} @dots{}@r{]}
11992 @end smallexample
11993
11994 @noindent
11995 where
11996
11997 @table @var
11998 @item pattern
11999 An entity will be output only if it matches the regular expression found
12000 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12001
12002 Omitting the pattern is equivalent to specifying @samp{*}, which
12003 will match any entity. Note that if you do not provide a pattern, you
12004 have to provide both a sourcefile and a line.
12005
12006 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12007 for matching purposes. At the current time there is no support for
12008 8-bit codes other than Latin-1, or for wide characters in identifiers.
12009
12010 @item sourcefile
12011 @code{gnatfind} will look for references, bodies or declarations
12012 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12013 and column @var{column}. See @ref{Examples of gnatfind Usage}
12014 for syntax examples.
12015
12016 @item line
12017 is a decimal integer identifying the line number containing
12018 the reference to the entity (or entities) to be located.
12019
12020 @item column
12021 is a decimal integer identifying the exact location on the
12022 line of the first character of the identifier for the
12023 entity reference. Columns are numbered from 1.
12024
12025 @item file1 file2 @dots{}
12026 The search will be restricted to these source files. If none are given, then
12027 the search will be done for every library file in the search path.
12028 These file must appear only after the pattern or sourcefile.
12029
12030 These file names are considered to be regular expressions, so for instance
12031 specifying @file{source*.adb} is the same as giving every file in the current
12032 directory whose name starts with @file{source} and whose extension is
12033 @file{adb}.
12034
12035 The location of the spec of the entity will always be displayed, even if it
12036 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12037 occurrences of the entity in the separate units of the ones given on the
12038 command line will also be displayed.
12039
12040 Note that if you specify at least one file in this part, @code{gnatfind} may
12041 sometimes not be able to find the body of the subprograms.
12042
12043 @end table
12044
12045 @noindent
12046 At least one of 'sourcefile' or 'pattern' has to be present on
12047 the command line.
12048
12049 The following switches are available:
12050 @table @option
12051 @c !sort!
12052
12053 @cindex @option{--version} @command{gnatfind}
12054 Display Copyright and version, then exit disregarding all other options.
12055
12056 @item --help
12057 @cindex @option{--help} @command{gnatfind}
12058 If @option{--version} was not used, display usage, then exit disregarding
12059 all other options.
12060
12061 @item ^-a^/ALL_FILES^
12062 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12063 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12064 the read-only files found in the library search path. Otherwise, these files
12065 will be ignored. This option can be used to protect Gnat sources or your own
12066 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12067 much faster, and their output much smaller. Read-only here refers to access
12068 or permission status in the file system for the current user.
12069
12070 @item -aIDIR
12071 @cindex @option{-aIDIR} (@command{gnatfind})
12072 When looking for source files also look in directory DIR. The order in which
12073 source file search is undertaken is the same as for @command{gnatmake}.
12074
12075 @item -aODIR
12076 @cindex @option{-aODIR} (@command{gnatfind})
12077 When searching for library and object files, look in directory
12078 DIR. The order in which library files are searched is the same as for
12079 @command{gnatmake}.
12080
12081 @item -nostdinc
12082 @cindex @option{-nostdinc} (@command{gnatfind})
12083 Do not look for sources in the system default directory.
12084
12085 @item -nostdlib
12086 @cindex @option{-nostdlib} (@command{gnatfind})
12087 Do not look for library files in the system default directory.
12088
12089 @item --ext=@var{extension}
12090 @cindex @option{--ext} (@command{gnatfind})
12091 Specify an alternate ali file extension. The default is @code{ali} and other
12092 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12093 switch. Note that if this switch overrides the default, which means that only
12094 the new extension will be considered.
12095
12096 @item --RTS=@var{rts-path}
12097 @cindex @option{--RTS} (@command{gnatfind})
12098 Specifies the default location of the runtime library. Same meaning as the
12099 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12100
12101 @item ^-d^/DERIVED_TYPE_INFORMATION^
12102 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12103 If this switch is set, then @code{gnatfind} will output the parent type
12104 reference for each matching derived types.
12105
12106 @item ^-e^/EXPRESSIONS^
12107 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12108 By default, @code{gnatfind} accept the simple regular expression set for
12109 @samp{pattern}. If this switch is set, then the pattern will be
12110 considered as full Unix-style regular expression.
12111
12112 @item ^-f^/FULL_PATHNAME^
12113 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12114 If this switch is set, the output file names will be preceded by their
12115 directory (if the file was found in the search path). If this switch is
12116 not set, the directory will not be printed.
12117
12118 @item ^-g^/IGNORE_LOCALS^
12119 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12120 If this switch is set, information is output only for library-level
12121 entities, ignoring local entities. The use of this switch may accelerate
12122 @code{gnatfind} and @code{gnatxref}.
12123
12124 @item -IDIR
12125 @cindex @option{-IDIR} (@command{gnatfind})
12126 Equivalent to @samp{-aODIR -aIDIR}.
12127
12128 @item -pFILE
12129 @cindex @option{-pFILE} (@command{gnatfind})
12130 Specify a project file (@pxref{GNAT Project Manager}) to use.
12131 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12132 project file in the current directory.
12133
12134 If a project file is either specified or found by the tools, then the content
12135 of the source directory and object directory lines are added as if they
12136 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12137 @samp{^-aO^/OBJECT_SEARCH^}.
12138
12139 @item ^-r^/REFERENCES^
12140 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12141 By default, @code{gnatfind} will output only the information about the
12142 declaration, body or type completion of the entities. If this switch is
12143 set, the @code{gnatfind} will locate every reference to the entities in
12144 the files specified on the command line (or in every file in the search
12145 path if no file is given on the command line).
12146
12147 @item ^-s^/PRINT_LINES^
12148 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12149 If this switch is set, then @code{gnatfind} will output the content
12150 of the Ada source file lines were the entity was found.
12151
12152 @item ^-t^/TYPE_HIERARCHY^
12153 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12154 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12155 the specified type. It act like -d option but recursively from parent
12156 type to parent type. When this switch is set it is not possible to
12157 specify more than one file.
12158
12159 @end table
12160
12161 @noindent
12162 All these switches may be in any order on the command line, and may even
12163 appear after the file names. They need not be separated by spaces, thus
12164 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12165 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12166
12167 As stated previously, gnatfind will search in every directory in the
12168 search path. You can force it to look only in the current directory if
12169 you specify @code{*} at the end of the command line.
12170
12171 @node Project Files for gnatxref and gnatfind
12172 @section Project Files for @command{gnatxref} and @command{gnatfind}
12173
12174 @noindent
12175 Project files allow a programmer to specify how to compile its
12176 application, where to find sources, etc.  These files are used
12177 @ifclear vms
12178 primarily by GPS, but they can also be used
12179 @end ifclear
12180 by the two tools
12181 @code{gnatxref} and @code{gnatfind}.
12182
12183 A project file name must end with @file{.gpr}. If a single one is
12184 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12185 extract the information from it. If multiple project files are found, none of
12186 them is read, and you have to use the @samp{-p} switch to specify the one
12187 you want to use.
12188
12189 The following lines can be included, even though most of them have default
12190 values which can be used in most cases.
12191 The lines can be entered in any order in the file.
12192 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12193 each line. If you have multiple instances, only the last one is taken into
12194 account.
12195
12196 @table @code
12197 @item src_dir=DIR
12198 [default: @code{"^./^[]^"}]
12199 specifies a directory where to look for source files. Multiple @code{src_dir}
12200 lines can be specified and they will be searched in the order they
12201 are specified.
12202
12203 @item obj_dir=DIR
12204 [default: @code{"^./^[]^"}]
12205 specifies a directory where to look for object and library files. Multiple
12206 @code{obj_dir} lines can be specified, and they will be searched in the order
12207 they are specified
12208
12209 @item comp_opt=SWITCHES
12210 [default: @code{""}]
12211 creates a variable which can be referred to subsequently by using
12212 the @code{$@{comp_opt@}} notation. This is intended to store the default
12213 switches given to @command{gnatmake} and @command{gcc}.
12214
12215 @item bind_opt=SWITCHES
12216 [default: @code{""}]
12217 creates a variable which can be referred to subsequently by using
12218 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12219 switches given to @command{gnatbind}.
12220
12221 @item link_opt=SWITCHES
12222 [default: @code{""}]
12223 creates a variable which can be referred to subsequently by using
12224 the @samp{$@{link_opt@}} notation. This is intended to store the default
12225 switches given to @command{gnatlink}.
12226
12227 @item main=EXECUTABLE
12228 [default: @code{""}]
12229 specifies the name of the executable for the application. This variable can
12230 be referred to in the following lines by using the @samp{$@{main@}} notation.
12231
12232 @ifset vms
12233 @item comp_cmd=COMMAND
12234 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12235 @end ifset
12236 @ifclear vms
12237 @item comp_cmd=COMMAND
12238 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12239 @end ifclear
12240 specifies the command used to compile a single file in the application.
12241
12242 @ifset vms
12243 @item make_cmd=COMMAND
12244 [default: @code{"GNAT MAKE $@{main@}
12245 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12246 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12247 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12248 @end ifset
12249 @ifclear vms
12250 @item make_cmd=COMMAND
12251 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12252 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12253 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12254 @end ifclear
12255 specifies the command used to recompile the whole application.
12256
12257 @item run_cmd=COMMAND
12258 [default: @code{"$@{main@}"}]
12259 specifies the command used to run the application.
12260
12261 @item debug_cmd=COMMAND
12262 [default: @code{"gdb $@{main@}"}]
12263 specifies the command used to debug the application
12264
12265 @end table
12266
12267 @noindent
12268 @command{gnatxref} and @command{gnatfind} only take into account the
12269 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12270
12271 @node Regular Expressions in gnatfind and gnatxref
12272 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12273
12274 @noindent
12275 As specified in the section about @command{gnatfind}, the pattern can be a
12276 regular expression. Actually, there are to set of regular expressions
12277 which are recognized by the program:
12278
12279 @table @code
12280 @item globbing patterns
12281 These are the most usual regular expression. They are the same that you
12282 generally used in a Unix shell command line, or in a DOS session.
12283
12284 Here is a more formal grammar:
12285 @smallexample
12286 @group
12287 @iftex
12288 @leftskip=.5cm
12289 @end iftex
12290 regexp ::= term
12291 term   ::= elmt            -- matches elmt
12292 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12293 term   ::= *               -- any string of 0 or more characters
12294 term   ::= ?               -- matches any character
12295 term   ::= [char @{char@}]   -- matches any character listed
12296 term   ::= [char - char]   -- matches any character in range
12297 @end group
12298 @end smallexample
12299
12300 @item full regular expression
12301 The second set of regular expressions is much more powerful. This is the
12302 type of regular expressions recognized by utilities such a @file{grep}.
12303
12304 The following is the form of a regular expression, expressed in Ada
12305 reference manual style BNF is as follows
12306
12307 @smallexample
12308 @iftex
12309 @leftskip=.5cm
12310 @end iftex
12311 @group
12312 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12313
12314 term ::= item @{item@}       -- concatenation (item then item)
12315
12316 item ::= elmt              -- match elmt
12317 item ::= elmt *            -- zero or more elmt's
12318 item ::= elmt +            -- one or more elmt's
12319 item ::= elmt ?            -- matches elmt or nothing
12320 @end group
12321 @group
12322 elmt ::= nschar            -- matches given character
12323 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12324 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12325 elmt ::= [char - char]     -- matches chars in given range
12326 elmt ::= \ char            -- matches given character
12327 elmt ::= .                 -- matches any single character
12328 elmt ::= ( regexp )        -- parens used for grouping
12329
12330 char ::= any character, including special characters
12331 nschar ::= any character except ()[].*+?^^^
12332 @end group
12333 @end smallexample
12334
12335 Following are a few examples:
12336
12337 @table @samp
12338 @item abcde|fghi
12339 will match any of the two strings @samp{abcde} and @samp{fghi},
12340
12341 @item abc*d
12342 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12343 @samp{abcccd}, and so on,
12344
12345 @item [a-z]+
12346 will match any string which has only lowercase characters in it (and at
12347 least one character.
12348
12349 @end table
12350 @end table
12351
12352 @node Examples of gnatxref Usage
12353 @section Examples of @code{gnatxref} Usage
12354
12355 @subsection General Usage
12356
12357 @noindent
12358 For the following examples, we will consider the following units:
12359
12360 @smallexample @c ada
12361 @group
12362 @cartouche
12363 main.ads:
12364 1: with Bar;
12365 2: package Main is
12366 3:     procedure Foo (B : in Integer);
12367 4:     C : Integer;
12368 5: private
12369 6:     D : Integer;
12370 7: end Main;
12371
12372 main.adb:
12373 1: package body Main is
12374 2:     procedure Foo (B : in Integer) is
12375 3:     begin
12376 4:        C := B;
12377 5:        D := B;
12378 6:        Bar.Print (B);
12379 7:        Bar.Print (C);
12380 8:     end Foo;
12381 9: end Main;
12382
12383 bar.ads:
12384 1: package Bar is
12385 2:     procedure Print (B : Integer);
12386 3: end bar;
12387 @end cartouche
12388 @end group
12389 @end smallexample
12390
12391 @table @code
12392
12393 @noindent
12394 The first thing to do is to recompile your application (for instance, in
12395 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12396 the cross-referencing information.
12397 You can then issue any of the following commands:
12398
12399 @item gnatxref main.adb
12400 @code{gnatxref} generates cross-reference information for main.adb
12401 and every unit 'with'ed by main.adb.
12402
12403 The output would be:
12404 @smallexample
12405 @iftex
12406 @leftskip=0cm
12407 @end iftex
12408 B                                                      Type: Integer
12409   Decl: bar.ads           2:22
12410 B                                                      Type: Integer
12411   Decl: main.ads          3:20
12412   Body: main.adb          2:20
12413   Ref:  main.adb          4:13     5:13     6:19
12414 Bar                                                    Type: Unit
12415   Decl: bar.ads           1:9
12416   Ref:  main.adb          6:8      7:8
12417        main.ads           1:6
12418 C                                                      Type: Integer
12419   Decl: main.ads          4:5
12420   Modi: main.adb          4:8
12421   Ref:  main.adb          7:19
12422 D                                                      Type: Integer
12423   Decl: main.ads          6:5
12424   Modi: main.adb          5:8
12425 Foo                                                    Type: Unit
12426   Decl: main.ads          3:15
12427   Body: main.adb          2:15
12428 Main                                                    Type: Unit
12429   Decl: main.ads          2:9
12430   Body: main.adb          1:14
12431 Print                                                   Type: Unit
12432   Decl: bar.ads           2:15
12433   Ref:  main.adb          6:12     7:12
12434 @end smallexample
12435
12436 @noindent
12437 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12438 its body is in main.adb, line 1, column 14 and is not referenced any where.
12439
12440 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12441 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12442
12443 @item gnatxref package1.adb package2.ads
12444 @code{gnatxref} will generates cross-reference information for
12445 package1.adb, package2.ads and any other package 'with'ed by any
12446 of these.
12447
12448 @end table
12449
12450 @ifclear vms
12451 @subsection Using gnatxref with vi
12452
12453 @code{gnatxref} can generate a tags file output, which can be used
12454 directly from @command{vi}. Note that the standard version of @command{vi}
12455 will not work properly with overloaded symbols. Consider using another
12456 free implementation of @command{vi}, such as @command{vim}.
12457
12458 @smallexample
12459 $ gnatxref -v gnatfind.adb > tags
12460 @end smallexample
12461
12462 @noindent
12463 will generate the tags file for @code{gnatfind} itself (if the sources
12464 are in the search path!).
12465
12466 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12467 (replacing @var{entity} by whatever you are looking for), and vi will
12468 display a new file with the corresponding declaration of entity.
12469 @end ifclear
12470
12471 @node Examples of gnatfind Usage
12472 @section Examples of @code{gnatfind} Usage
12473
12474 @table @code
12475
12476 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12477 Find declarations for all entities xyz referenced at least once in
12478 main.adb. The references are search in every library file in the search
12479 path.
12480
12481 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12482 switch is set)
12483
12484 The output will look like:
12485 @smallexample
12486 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12487 ^directory/^[directory]^main.adb:24:10: xyz <= body
12488 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12489 @end smallexample
12490
12491 @noindent
12492 that is to say, one of the entities xyz found in main.adb is declared at
12493 line 12 of main.ads (and its body is in main.adb), and another one is
12494 declared at line 45 of foo.ads
12495
12496 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12497 This is the same command as the previous one, instead @code{gnatfind} will
12498 display the content of the Ada source file lines.
12499
12500 The output will look like:
12501
12502 @smallexample
12503 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12504    procedure xyz;
12505 ^directory/^[directory]^main.adb:24:10: xyz <= body
12506    procedure xyz is
12507 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12508    xyz : Integer;
12509 @end smallexample
12510
12511 @noindent
12512 This can make it easier to find exactly the location your are looking
12513 for.
12514
12515 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12516 Find references to all entities containing an x that are
12517 referenced on line 123 of main.ads.
12518 The references will be searched only in main.ads and foo.adb.
12519
12520 @item gnatfind main.ads:123
12521 Find declarations and bodies for all entities that are referenced on
12522 line 123 of main.ads.
12523
12524 This is the same as @code{gnatfind "*":main.adb:123}.
12525
12526 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12527 Find the declaration for the entity referenced at column 45 in
12528 line 123 of file main.adb in directory mydir. Note that it
12529 is usual to omit the identifier name when the column is given,
12530 since the column position identifies a unique reference.
12531
12532 The column has to be the beginning of the identifier, and should not
12533 point to any character in the middle of the identifier.
12534
12535 @end table
12536
12537 @c *********************************
12538 @node The GNAT Pretty-Printer gnatpp
12539 @chapter The GNAT Pretty-Printer @command{gnatpp}
12540 @findex gnatpp
12541 @cindex Pretty-Printer
12542
12543 @noindent
12544 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12545 for source reformatting / pretty-printing.
12546 It takes an Ada source file as input and generates a reformatted
12547 version as output.
12548 You can specify various style directives via switches; e.g.,
12549 identifier case conventions, rules of indentation, and comment layout.
12550
12551 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12552 tree for the input source and thus requires the input to be syntactically and
12553 semantically legal.
12554 If this condition is not met, @command{gnatpp} will terminate with an
12555 error message; no output file will be generated.
12556
12557 If the source files presented to @command{gnatpp} contain
12558 preprocessing directives, then the output file will
12559 correspond to the generated source after all
12560 preprocessing is carried out. There is no way
12561 using @command{gnatpp} to obtain pretty printed files that
12562 include the preprocessing directives.
12563
12564 If the compilation unit
12565 contained in the input source depends semantically upon units located
12566 outside the current directory, you have to provide the source search path
12567 when invoking @command{gnatpp}, if these units are contained in files with
12568 names that do not follow the GNAT file naming rules, you have to provide
12569 the configuration file describing the corresponding naming scheme;
12570 see the description of the @command{gnatpp}
12571 switches below. Another possibility is to use a project file and to
12572 call @command{gnatpp} through the @command{gnat} driver
12573
12574 The @command{gnatpp} command has the form
12575
12576 @smallexample
12577 @c $ gnatpp @ovar{switches} @var{filename}
12578 @c Expanding @ovar macro inline (explanation in macro def comments)
12579 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12580 @end smallexample
12581
12582 @noindent
12583 where
12584 @itemize @bullet
12585 @item
12586 @var{switches} is an optional sequence of switches defining such properties as
12587 the formatting rules, the source search path, and the destination for the
12588 output source file
12589
12590 @item
12591 @var{filename} is the name (including the extension) of the source file to
12592 reformat; ``wildcards'' or several file names on the same gnatpp command are
12593 allowed.  The file name may contain path information; it does not have to
12594 follow the GNAT file naming rules
12595
12596 @item
12597 @samp{@var{gcc_switches}} is a list of switches for
12598 @command{gcc}. They will be passed on to all compiler invocations made by
12599 @command{gnatelim} to generate the ASIS trees. Here you can provide
12600 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12601 use the @option{-gnatec} switch to set the configuration file etc.
12602 @end itemize
12603
12604 @menu
12605 * Switches for gnatpp::
12606 * Formatting Rules::
12607 @end menu
12608
12609 @node Switches for gnatpp
12610 @section Switches for @command{gnatpp}
12611
12612 @noindent
12613 The following subsections describe the various switches accepted by
12614 @command{gnatpp}, organized by category.
12615
12616 @ifclear vms
12617 You specify a switch by supplying a name and generally also a value.
12618 In many cases the values for a switch with a given name are incompatible with
12619 each other
12620 (for example the switch that controls the casing of a reserved word may have
12621 exactly one value: upper case, lower case, or
12622 mixed case) and thus exactly one such switch can be in effect for an
12623 invocation of @command{gnatpp}.
12624 If more than one is supplied, the last one is used.
12625 However, some values for the same switch are mutually compatible.
12626 You may supply several such switches to @command{gnatpp}, but then
12627 each must be specified in full, with both the name and the value.
12628 Abbreviated forms (the name appearing once, followed by each value) are
12629 not permitted.
12630 For example, to set
12631 the alignment of the assignment delimiter both in declarations and in
12632 assignment statements, you must write @option{-A2A3}
12633 (or @option{-A2 -A3}), but not @option{-A23}.
12634 @end ifclear
12635
12636 @ifset vms
12637 In many cases the set of options for a given qualifier are incompatible with
12638 each other (for example the qualifier that controls the casing of a reserved
12639 word may have exactly one option, which specifies either upper case, lower
12640 case, or mixed case), and thus exactly one such option can be in effect for
12641 an invocation of @command{gnatpp}.
12642 If more than one is supplied, the last one is used.
12643 However, some qualifiers have options that are mutually compatible,
12644 and then you may then supply several such options when invoking
12645 @command{gnatpp}.
12646 @end ifset
12647
12648 In most cases, it is obvious whether or not the
12649 ^values for a switch with a given name^options for a given qualifier^
12650 are compatible with each other.
12651 When the semantics might not be evident, the summaries below explicitly
12652 indicate the effect.
12653
12654 @menu
12655 * Alignment Control::
12656 * Casing Control::
12657 * Construct Layout Control::
12658 * General Text Layout Control::
12659 * Other Formatting Options::
12660 * Setting the Source Search Path::
12661 * Output File Control::
12662 * Other gnatpp Switches::
12663 @end menu
12664
12665 @node Alignment Control
12666 @subsection Alignment Control
12667 @cindex Alignment control in @command{gnatpp}
12668
12669 @noindent
12670 Programs can be easier to read if certain constructs are vertically aligned.
12671 By default all alignments are set ON.
12672 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12673 OFF, and then use one or more of the other
12674 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12675 to activate alignment for specific constructs.
12676
12677 @table @option
12678 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12679
12680 @ifset vms
12681 @item /ALIGN=ON
12682 Set all alignments to ON
12683 @end ifset
12684
12685 @item ^-A0^/ALIGN=OFF^
12686 Set all alignments to OFF
12687
12688 @item ^-A1^/ALIGN=COLONS^
12689 Align @code{:} in declarations
12690
12691 @item ^-A2^/ALIGN=DECLARATIONS^
12692 Align @code{:=} in initializations in declarations
12693
12694 @item ^-A3^/ALIGN=STATEMENTS^
12695 Align @code{:=} in assignment statements
12696
12697 @item ^-A4^/ALIGN=ARROWS^
12698 Align @code{=>} in associations
12699
12700 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12701 Align @code{at} keywords in the component clauses in record
12702 representation clauses
12703 @end table
12704
12705 @noindent
12706 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12707 is allowed.
12708
12709 @node Casing Control
12710 @subsection Casing Control
12711 @cindex Casing control in @command{gnatpp}
12712
12713 @noindent
12714 @command{gnatpp} allows you to specify the casing for reserved words,
12715 pragma names, attribute designators and identifiers.
12716 For identifiers you may define a
12717 general rule for name casing but also override this rule
12718 via a set of dictionary files.
12719
12720 Three types of casing are supported: lower case, upper case, and mixed case.
12721 Lower and upper case are self-explanatory (but since some letters in
12722 Latin1 and other GNAT-supported character sets
12723 exist only in lower-case form, an upper case conversion will have no
12724 effect on them.)
12725 ``Mixed case'' means that the first letter, and also each letter immediately
12726 following an underscore, are converted to their uppercase forms;
12727 all the other letters are converted to their lowercase forms.
12728
12729 @table @option
12730 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12731 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12732 Attribute designators are lower case
12733
12734 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12735 Attribute designators are upper case
12736
12737 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12738 Attribute designators are mixed case (this is the default)
12739
12740 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12741 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12742 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12743 lower case (this is the default)
12744
12745 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12746 Keywords are upper case
12747
12748 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12749 @item ^-nD^/NAME_CASING=AS_DECLARED^
12750 Name casing for defining occurrences are as they appear in the source file
12751 (this is the default)
12752
12753 @item ^-nU^/NAME_CASING=UPPER_CASE^
12754 Names are in upper case
12755
12756 @item ^-nL^/NAME_CASING=LOWER_CASE^
12757 Names are in lower case
12758
12759 @item ^-nM^/NAME_CASING=MIXED_CASE^
12760 Names are in mixed case
12761
12762 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12763 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12764 Pragma names are lower case
12765
12766 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12767 Pragma names are upper case
12768
12769 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12770 Pragma names are mixed case (this is the default)
12771
12772 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12773 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12774 Use @var{file} as a @emph{dictionary file} that defines
12775 the casing for a set of specified names,
12776 thereby overriding the effect on these names by
12777 any explicit or implicit
12778 ^-n^/NAME_CASING^ switch.
12779 To supply more than one dictionary file,
12780 use ^several @option{-D} switches^a list of files as options^.
12781
12782 @noindent
12783 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12784 to define the casing for the Ada predefined names and
12785 the names declared in the GNAT libraries.
12786
12787 @item ^-D-^/SPECIFIC_CASING^
12788 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12789 Do not use the default dictionary file;
12790 instead, use the casing
12791 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12792 dictionary file(s)
12793 @end table
12794
12795 @noindent
12796 The structure of a dictionary file, and details on the conventions
12797 used in the default dictionary file, are defined in @ref{Name Casing}.
12798
12799 The @option{^-D-^/SPECIFIC_CASING^} and
12800 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12801 compatible.
12802
12803 @node Construct Layout Control
12804 @subsection Construct Layout Control
12805 @cindex Layout control in @command{gnatpp}
12806
12807 @noindent
12808 This group of @command{gnatpp} switches controls the layout of comments and
12809 complex syntactic constructs.  See @ref{Formatting Comments} for details
12810 on their effect.
12811
12812 @table @option
12813 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12814 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12815 All the comments remain unchanged
12816
12817 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12818 GNAT-style comment line indentation (this is the default).
12819
12820 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12821 Reference-manual comment line indentation.
12822
12823 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12824 GNAT-style comment beginning
12825
12826 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12827 Reformat comment blocks
12828
12829 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12830 Keep unchanged special form comments
12831
12832 Reformat comment blocks
12833
12834 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12835 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12836 GNAT-style layout (this is the default)
12837
12838 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12839 Compact layout
12840
12841 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12842 Uncompact layout
12843
12844 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12845 @item ^-N^/NOTABS^
12846 All the VT characters are removed from the comment text. All the HT characters
12847 are expanded with the sequences of space characters to get to the next tab
12848 stops.
12849
12850 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12851 @item ^--no-separate-is^/NO_SEPARATE_IS^
12852 Do not place the keyword @code{is} on a separate line in a subprogram body in
12853 case if the spec occupies more then one line.
12854
12855 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12856 @item ^--separate-label^/SEPARATE_LABEL^
12857 Place statement label(s) on a separate line, with the following statement
12858 on the next line.
12859
12860 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12861 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12862 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12863 keyword @code{then} in IF statements on a separate line.
12864
12865 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12866 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12867 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12868 keyword @code{then} in IF statements on a separate line. This option is
12869 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12870
12871 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12872 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
12873 Start each USE clause in a context clause from a separate line.
12874
12875 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
12876 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
12877 Use a separate line for a loop or block statement name, but do not use an extra
12878 indentation level for the statement itself.
12879
12880 @end table
12881
12882 @ifclear vms
12883 @noindent
12884 The @option{-c1} and @option{-c2} switches are incompatible.
12885 The @option{-c3} and @option{-c4} switches are compatible with each other and
12886 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
12887 the other comment formatting switches.
12888
12889 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
12890 @end ifclear
12891
12892 @ifset vms
12893 @noindent
12894 For the @option{/COMMENTS_LAYOUT} qualifier:
12895 @itemize @bullet
12896 @item
12897 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
12898 @item
12899 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
12900 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
12901 @end itemize
12902
12903 @noindent
12904 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
12905 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
12906 @end ifset
12907
12908 @node General Text Layout Control
12909 @subsection General Text Layout Control
12910
12911 @noindent
12912 These switches allow control over line length and indentation.
12913
12914 @table @option
12915 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
12916 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
12917 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
12918
12919 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
12920 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
12921 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
12922
12923 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
12924 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
12925 Indentation level for continuation lines (relative to the line being
12926 continued), @var{nnn} from 1@dots{}9.
12927 The default
12928 value is one less then the (normal) indentation level, unless the
12929 indentation is set to 1 (in which case the default value for continuation
12930 line indentation is also 1)
12931 @end table
12932
12933 @node Other Formatting Options
12934 @subsection Other Formatting Options
12935
12936 @noindent
12937 These switches control the inclusion of missing end/exit labels, and
12938 the indentation level in @b{case} statements.
12939
12940 @table @option
12941 @item ^-e^/NO_MISSED_LABELS^
12942 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
12943 Do not insert missing end/exit labels. An end label is the name of
12944 a construct that may optionally be repeated at the end of the
12945 construct's declaration;
12946 e.g., the names of packages, subprograms, and tasks.
12947 An exit label is the name of a loop that may appear as target
12948 of an exit statement within the loop.
12949 By default, @command{gnatpp} inserts these end/exit labels when
12950 they are absent from the original source. This option suppresses such
12951 insertion, so that the formatted source reflects the original.
12952
12953 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
12954 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
12955 Insert a Form Feed character after a pragma Page.
12956
12957 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
12958 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
12959 Do not use an additional indentation level for @b{case} alternatives
12960 and variants if there are @var{nnn} or more (the default
12961 value is 10).
12962 If @var{nnn} is 0, an additional indentation level is
12963 used for @b{case} alternatives and variants regardless of their number.
12964 @end table
12965
12966 @node Setting the Source Search Path
12967 @subsection Setting the Source Search Path
12968
12969 @noindent
12970 To define the search path for the input source file, @command{gnatpp}
12971 uses the same switches as the GNAT compiler, with the same effects.
12972
12973 @table @option
12974 @item ^-I^/SEARCH=^@var{dir}
12975 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
12976 The same as the corresponding gcc switch
12977
12978 @item ^-I-^/NOCURRENT_DIRECTORY^
12979 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
12980 The same as the corresponding gcc switch
12981
12982 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
12983 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
12984 The same as the corresponding gcc switch
12985
12986 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
12987 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
12988 The same as the corresponding gcc switch
12989
12990 @end table
12991
12992 @node Output File Control
12993 @subsection Output File Control
12994
12995 @noindent
12996 By default the output is sent to the file whose name is obtained by appending
12997 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
12998 (if the file with this name already exists, it is unconditionally overwritten).
12999 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13000 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13001 as output file.
13002 The output may be redirected by the following switches:
13003
13004 @table @option
13005 @item ^-pipe^/STANDARD_OUTPUT^
13006 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13007 Send the output to @code{Standard_Output}
13008
13009 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13010 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13011 Write the output into @var{output_file}.
13012 If @var{output_file} already exists, @command{gnatpp} terminates without
13013 reading or processing the input file.
13014
13015 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13016 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13017 Write the output into @var{output_file}, overwriting the existing file
13018 (if one is present).
13019
13020 @item ^-r^/REPLACE^
13021 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13022 Replace the input source file with the reformatted output, and copy the
13023 original input source into the file whose name is obtained by appending the
13024 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13025 If a file with this name already exists, @command{gnatpp} terminates without
13026 reading or processing the input file.
13027
13028 @item ^-rf^/OVERRIDING_REPLACE^
13029 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13030 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13031 already exists, it is overwritten.
13032
13033 @item ^-rnb^/REPLACE_NO_BACKUP^
13034 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13035 Replace the input source file with the reformatted output without
13036 creating any backup copy of the input source.
13037
13038 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13039 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13040 Specifies the format of the reformatted output file. The @var{xxx}
13041 ^string specified with the switch^option^ may be either
13042 @itemize @bullet
13043 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13044 @item ``@option{^crlf^CRLF^}''
13045 the same as @option{^crlf^CRLF^}
13046 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13047 @item ``@option{^lf^LF^}''
13048 the same as @option{^unix^UNIX^}
13049 @end itemize
13050
13051 @item ^-W^/RESULT_ENCODING=^@var{e}
13052 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13053 Specify the wide character encoding method used to write the code in the
13054 result file
13055 @var{e} is one of the following:
13056
13057 @itemize @bullet
13058
13059 @item ^h^HEX^
13060 Hex encoding
13061
13062 @item ^u^UPPER^
13063 Upper half encoding
13064
13065 @item ^s^SHIFT_JIS^
13066 Shift/JIS encoding
13067
13068 @item ^e^EUC^
13069 EUC encoding
13070
13071 @item ^8^UTF8^
13072 UTF-8 encoding
13073
13074 @item ^b^BRACKETS^
13075 Brackets encoding (default value)
13076 @end itemize
13077
13078 @end table
13079
13080 @noindent
13081 Options @option{^-pipe^/STANDARD_OUTPUT^},
13082 @option{^-o^/OUTPUT^} and
13083 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13084 contains only one file to reformat.
13085 Option
13086 @option{^--eol^/END_OF_LINE^}
13087 and
13088 @option{^-W^/RESULT_ENCODING^}
13089 cannot be used together
13090 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13091
13092 @node Other gnatpp Switches
13093 @subsection Other @code{gnatpp} Switches
13094
13095 @noindent
13096 The additional @command{gnatpp} switches are defined in this subsection.
13097
13098 @table @option
13099 @item ^-files @var{filename}^/FILES=@var{filename}^
13100 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13101 Take the argument source files from the specified file. This file should be an
13102 ordinary text file containing file names separated by spaces or
13103 line breaks. You can use this switch more than once in the same call to
13104 @command{gnatpp}. You also can combine this switch with an explicit list of
13105 files.
13106
13107 @item ^-v^/VERBOSE^
13108 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13109 Verbose mode;
13110 @command{gnatpp} generates version information and then
13111 a trace of the actions it takes to produce or obtain the ASIS tree.
13112
13113 @item ^-w^/WARNINGS^
13114 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13115 Warning mode;
13116 @command{gnatpp} generates a warning whenever it cannot provide
13117 a required layout in the result source.
13118 @end table
13119
13120 @node Formatting Rules
13121 @section Formatting Rules
13122
13123 @noindent
13124 The following subsections show how @command{gnatpp} treats ``white space'',
13125 comments, program layout, and name casing.
13126 They provide the detailed descriptions of the switches shown above.
13127
13128 @menu
13129 * White Space and Empty Lines::
13130 * Formatting Comments::
13131 * Construct Layout::
13132 * Name Casing::
13133 @end menu
13134
13135 @node White Space and Empty Lines
13136 @subsection White Space and Empty Lines
13137
13138 @noindent
13139 @command{gnatpp} does not have an option to control space characters.
13140 It will add or remove spaces according to the style illustrated by the
13141 examples in the @cite{Ada Reference Manual}.
13142
13143 The only format effectors
13144 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13145 that will appear in the output file are platform-specific line breaks,
13146 and also format effectors within (but not at the end of) comments.
13147 In particular, each horizontal tab character that is not inside
13148 a comment will be treated as a space and thus will appear in the
13149 output file as zero or more spaces depending on
13150 the reformatting of the line in which it appears.
13151 The only exception is a Form Feed character, which is inserted after a
13152 pragma @code{Page} when @option{-ff} is set.
13153
13154 The output file will contain no lines with trailing ``white space'' (spaces,
13155 format effectors).
13156
13157 Empty lines in the original source are preserved
13158 only if they separate declarations or statements.
13159 In such contexts, a
13160 sequence of two or more empty lines is replaced by exactly one empty line.
13161 Note that a blank line will be removed if it separates two ``comment blocks''
13162 (a comment block is a sequence of whole-line comments).
13163 In order to preserve a visual separation between comment blocks, use an
13164 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13165 Likewise, if for some reason you wish to have a sequence of empty lines,
13166 use a sequence of empty comments instead.
13167
13168 @node Formatting Comments
13169 @subsection Formatting Comments
13170
13171 @noindent
13172 Comments in Ada code are of two kinds:
13173 @itemize @bullet
13174 @item
13175 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13176 ``white space'') on a line
13177
13178 @item
13179 an @emph{end-of-line comment}, which follows some other Ada lexical element
13180 on the same line.
13181 @end itemize
13182
13183 @noindent
13184 The indentation of a whole-line comment is that of either
13185 the preceding or following line in
13186 the formatted source, depending on switch settings as will be described below.
13187
13188 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13189 between the end of the preceding Ada lexical element and the beginning
13190 of the comment as appear in the original source,
13191 unless either the comment has to be split to
13192 satisfy the line length limitation, or else the next line contains a
13193 whole line comment that is considered a continuation of this end-of-line
13194 comment (because it starts at the same position).
13195 In the latter two
13196 cases, the start of the end-of-line comment is moved right to the nearest
13197 multiple of the indentation level.
13198 This may result in a ``line overflow'' (the right-shifted comment extending
13199 beyond the maximum line length), in which case the comment is split as
13200 described below.
13201
13202 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13203 (GNAT-style comment line indentation)
13204 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13205 (reference-manual comment line indentation).
13206 With reference-manual style, a whole-line comment is indented as if it
13207 were a declaration or statement at the same place
13208 (i.e., according to the indentation of the preceding line(s)).
13209 With GNAT style, a whole-line comment that is immediately followed by an
13210 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13211 word @b{begin}, is indented based on the construct that follows it.
13212
13213 For example:
13214 @smallexample @c ada
13215 @cartouche
13216 if A then
13217     null;
13218        -- some comment
13219 else
13220    null;
13221 end if;
13222 @end cartouche
13223 @end smallexample
13224
13225 @noindent
13226 Reference-manual indentation produces:
13227
13228 @smallexample @c ada
13229 @cartouche
13230 if A then
13231    null;
13232    --  some comment
13233 else
13234    null;
13235 end if;
13236 @end cartouche
13237 @end smallexample
13238
13239 @noindent
13240 while GNAT-style indentation produces:
13241
13242 @smallexample @c ada
13243 @cartouche
13244 if A then
13245    null;
13246 --  some comment
13247 else
13248    null;
13249 end if;
13250 @end cartouche
13251 @end smallexample
13252
13253 @noindent
13254 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13255 (GNAT style comment beginning) has the following
13256 effect:
13257
13258 @itemize @bullet
13259 @item
13260 For each whole-line comment that does not end with two hyphens,
13261 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13262 to ensure that there are at least two spaces between these hyphens and the
13263 first non-blank character of the comment.
13264 @end itemize
13265
13266 @noindent
13267 For an end-of-line comment, if in the original source the next line is a
13268 whole-line comment that starts at the same position
13269 as the end-of-line comment,
13270 then the whole-line comment (and all whole-line comments
13271 that follow it and that start at the same position)
13272 will start at this position in the output file.
13273
13274 @noindent
13275 That is, if in the original source we have:
13276
13277 @smallexample @c ada
13278 @cartouche
13279 begin
13280 A := B + C;            --  B must be in the range Low1..High1
13281                        --  C must be in the range Low2..High2
13282              --B+C will be in the range Low1+Low2..High1+High2
13283 X := X + 1;
13284 @end cartouche
13285 @end smallexample
13286
13287 @noindent
13288 Then in the formatted source we get
13289
13290 @smallexample @c ada
13291 @cartouche
13292 begin
13293    A := B + C;            --  B must be in the range Low1..High1
13294                           --  C must be in the range Low2..High2
13295    --  B+C will be in the range Low1+Low2..High1+High2
13296    X := X + 1;
13297 @end cartouche
13298 @end smallexample
13299
13300 @noindent
13301 A comment that exceeds the line length limit will be split.
13302 Unless switch
13303 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13304 the line belongs to a reformattable block, splitting the line generates a
13305 @command{gnatpp} warning.
13306 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13307 comments may be reformatted in typical
13308 word processor style (that is, moving words between lines and putting as
13309 many words in a line as possible).
13310
13311 @noindent
13312 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13313 that has a special format (that is, a character that is neither a letter nor digit
13314 not white space nor line break immediately following the leading @code{--} of
13315 the comment) should be without any change moved from the argument source
13316 into reformatted source. This switch allows to preserve comments that are used
13317 as a special marks in the code (e.g.@: SPARK annotation).
13318
13319 @node Construct Layout
13320 @subsection Construct Layout
13321
13322 @noindent
13323 In several cases the suggested layout in the Ada Reference Manual includes
13324 an extra level of indentation that many programmers prefer to avoid. The
13325 affected cases include:
13326
13327 @itemize @bullet
13328
13329 @item Record type declaration (RM 3.8)
13330
13331 @item Record representation clause (RM 13.5.1)
13332
13333 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13334
13335 @item Block statement in case if a block has a statement identifier (RM 5.6)
13336 @end itemize
13337
13338 @noindent
13339 In compact mode (when GNAT style layout or compact layout is set),
13340 the pretty printer uses one level of indentation instead
13341 of two. This is achieved in the record definition and record representation
13342 clause cases by putting the @code{record} keyword on the same line as the
13343 start of the declaration or representation clause, and in the block and loop
13344 case by putting the block or loop header on the same line as the statement
13345 identifier.
13346
13347 @noindent
13348 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13349 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13350 layout on the one hand, and uncompact layout
13351 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13352 can be illustrated by the following examples:
13353
13354 @iftex
13355 @cartouche
13356 @multitable @columnfractions .5 .5
13357 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13358
13359 @item
13360 @smallexample @c ada
13361 type q is record
13362    a : integer;
13363    b : integer;
13364 end record;
13365 @end smallexample
13366 @tab
13367 @smallexample @c ada
13368 type q is
13369    record
13370       a : integer;
13371       b : integer;
13372    end record;
13373 @end smallexample
13374
13375 @item
13376 @smallexample @c ada
13377 for q use record
13378    a at 0 range  0 .. 31;
13379    b at 4 range  0 .. 31;
13380 end record;
13381 @end smallexample
13382 @tab
13383 @smallexample @c ada
13384 for q use
13385    record
13386       a at 0 range  0 .. 31;
13387       b at 4 range  0 .. 31;
13388    end record;
13389 @end smallexample
13390
13391 @item
13392 @smallexample @c ada
13393 Block : declare
13394    A : Integer := 3;
13395 begin
13396    Proc (A, A);
13397 end Block;
13398 @end smallexample
13399 @tab
13400 @smallexample @c ada
13401 Block :
13402    declare
13403       A : Integer := 3;
13404    begin
13405       Proc (A, A);
13406    end Block;
13407 @end smallexample
13408
13409 @item
13410 @smallexample @c ada
13411 Clear : for J in 1 .. 10 loop
13412    A (J) := 0;
13413 end loop Clear;
13414 @end smallexample
13415 @tab
13416 @smallexample @c ada
13417 Clear :
13418    for J in 1 .. 10 loop
13419       A (J) := 0;
13420    end loop Clear;
13421 @end smallexample
13422 @end multitable
13423 @end cartouche
13424 @end iftex
13425
13426 @ifnottex
13427 @smallexample
13428 @cartouche
13429 GNAT style, compact layout              Uncompact layout
13430
13431 type q is record                        type q is
13432    a : integer;                            record
13433    b : integer;                               a : integer;
13434 end record;                                   b : integer;
13435                                            end record;
13436
13437 for q use record                        for q use
13438    a at 0 range  0 .. 31;                  record
13439    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13440 end record;                                   b at 4 range  0 .. 31;
13441                                            end record;
13442
13443 Block : declare                         Block :
13444    A : Integer := 3;                       declare
13445 begin                                         A : Integer := 3;
13446    Proc (A, A);                            begin
13447 end Block;                                    Proc (A, A);
13448                                            end Block;
13449
13450 Clear : for J in 1 .. 10 loop           Clear :
13451    A (J) := 0;                             for J in 1 .. 10 loop
13452 end loop Clear;                               A (J) := 0;
13453                                            end loop Clear;
13454 @end cartouche
13455 @end smallexample
13456 @end ifnottex
13457
13458 @noindent
13459 A further difference between GNAT style layout and compact layout is that
13460 GNAT style layout inserts empty lines as separation for
13461 compound statements, return statements and bodies.
13462
13463 Note that the layout specified by
13464 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13465 for named block and loop statements overrides the layout defined by these
13466 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13467 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13468 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13469
13470 @node Name Casing
13471 @subsection Name Casing
13472
13473 @noindent
13474 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13475 the same casing as the corresponding defining identifier.
13476
13477 You control the casing for defining occurrences via the
13478 @option{^-n^/NAME_CASING^} switch.
13479 @ifclear vms
13480 With @option{-nD} (``as declared'', which is the default),
13481 @end ifclear
13482 @ifset vms
13483 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13484 @end ifset
13485 defining occurrences appear exactly as in the source file
13486 where they are declared.
13487 The other ^values for this switch^options for this qualifier^ ---
13488 @option{^-nU^UPPER_CASE^},
13489 @option{^-nL^LOWER_CASE^},
13490 @option{^-nM^MIXED_CASE^} ---
13491 result in
13492 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13493 If @command{gnatpp} changes the casing of a defining
13494 occurrence, it analogously changes the casing of all the
13495 usage occurrences of this name.
13496
13497 If the defining occurrence of a name is not in the source compilation unit
13498 currently being processed by @command{gnatpp}, the casing of each reference to
13499 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13500 switch (subject to the dictionary file mechanism described below).
13501 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13502 had affected the
13503 casing for the defining occurrence of the name.
13504
13505 Some names may need to be spelled with casing conventions that are not
13506 covered by the upper-, lower-, and mixed-case transformations.
13507 You can arrange correct casing by placing such names in a
13508 @emph{dictionary file},
13509 and then supplying a @option{^-D^/DICTIONARY^} switch.
13510 The casing of names from dictionary files overrides
13511 any @option{^-n^/NAME_CASING^} switch.
13512
13513 To handle the casing of Ada predefined names and the names from GNAT libraries,
13514 @command{gnatpp} assumes a default dictionary file.
13515 The name of each predefined entity is spelled with the same casing as is used
13516 for the entity in the @cite{Ada Reference Manual}.
13517 The name of each entity in the GNAT libraries is spelled with the same casing
13518 as is used in the declaration of that entity.
13519
13520 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13521 default dictionary file.
13522 Instead, the casing for predefined and GNAT-defined names will be established
13523 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13524 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13525 will appear as just shown,
13526 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13527 To ensure that even such names are rendered in uppercase,
13528 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13529 (or else, less conveniently, place these names in upper case in a dictionary
13530 file).
13531
13532 A dictionary file is
13533 a plain text file; each line in this file can be either a blank line
13534 (containing only space characters and ASCII.HT characters), an Ada comment
13535 line, or the specification of exactly one @emph{casing schema}.
13536
13537 A casing schema is a string that has the following syntax:
13538
13539 @smallexample
13540 @cartouche
13541   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13542
13543   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13544 @end cartouche
13545 @end smallexample
13546
13547 @noindent
13548 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13549 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13550
13551 The casing schema string can be followed by white space and/or an Ada-style
13552 comment; any amount of white space is allowed before the string.
13553
13554 If a dictionary file is passed as
13555 @ifclear vms
13556 the value of a @option{-D@var{file}} switch
13557 @end ifclear
13558 @ifset vms
13559 an option to the @option{/DICTIONARY} qualifier
13560 @end ifset
13561 then for every
13562 simple name and every identifier, @command{gnatpp} checks if the dictionary
13563 defines the casing for the name or for some of its parts (the term ``subword''
13564 is used below to denote the part of a name which is delimited by ``_'' or by
13565 the beginning or end of the word and which does not contain any ``_'' inside):
13566
13567 @itemize @bullet
13568 @item
13569 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13570 the casing defined by the dictionary; no subwords are checked for this word
13571
13572 @item
13573 for every subword @command{gnatpp} checks if the dictionary contains the
13574 corresponding string of the form @code{*@var{simple_identifier}*},
13575 and if it does, the casing of this @var{simple_identifier} is used
13576 for this subword
13577
13578 @item
13579 if the whole name does not contain any ``_'' inside, and if for this name
13580 the dictionary contains two entries - one of the form @var{identifier},
13581 and another - of the form *@var{simple_identifier}*, then the first one
13582 is applied to define the casing of this name
13583
13584 @item
13585 if more than one dictionary file is passed as @command{gnatpp} switches, each
13586 dictionary adds new casing exceptions and overrides all the existing casing
13587 exceptions set by the previous dictionaries
13588
13589 @item
13590 when @command{gnatpp} checks if the word or subword is in the dictionary,
13591 this check is not case sensitive
13592 @end itemize
13593
13594 @noindent
13595 For example, suppose we have the following source to reformat:
13596
13597 @smallexample @c ada
13598 @cartouche
13599 procedure test is
13600    name1 : integer := 1;
13601    name4_name3_name2 : integer := 2;
13602    name2_name3_name4 : Boolean;
13603    name1_var : Float;
13604 begin
13605    name2_name3_name4 := name4_name3_name2 > name1;
13606 end;
13607 @end cartouche
13608 @end smallexample
13609
13610 @noindent
13611 And suppose we have two dictionaries:
13612
13613 @smallexample
13614 @cartouche
13615 @i{dict1:}
13616    NAME1
13617    *NaMe3*
13618    *Name1*
13619 @end cartouche
13620
13621 @cartouche
13622 @i{dict2:}
13623   *NAME3*
13624 @end cartouche
13625 @end smallexample
13626
13627 @noindent
13628 If @command{gnatpp} is called with the following switches:
13629
13630 @smallexample
13631 @ifclear vms
13632 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13633 @end ifclear
13634 @ifset vms
13635 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13636 @end ifset
13637 @end smallexample
13638
13639 @noindent
13640 then we will get the following name casing in the @command{gnatpp} output:
13641
13642 @smallexample @c ada
13643 @cartouche
13644 procedure Test is
13645    NAME1             : Integer := 1;
13646    Name4_NAME3_Name2 : Integer := 2;
13647    Name2_NAME3_Name4 : Boolean;
13648    Name1_Var         : Float;
13649 begin
13650    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13651 end Test;
13652 @end cartouche
13653 @end smallexample
13654
13655 @c *********************************
13656 @node The GNAT Metric Tool gnatmetric
13657 @chapter The GNAT Metric Tool @command{gnatmetric}
13658 @findex gnatmetric
13659 @cindex Metric tool
13660
13661 @noindent
13662 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13663 for computing various program metrics.
13664 It takes an Ada source file as input and generates a file containing the
13665 metrics data as output. Various switches control which
13666 metrics are computed and output.
13667
13668 @command{gnatmetric} generates and uses the ASIS
13669 tree for the input source and thus requires the input to be syntactically and
13670 semantically legal.
13671 If this condition is not met, @command{gnatmetric} will generate
13672 an error message; no metric information for this file will be
13673 computed and reported.
13674
13675 If the compilation unit contained in the input source depends semantically
13676 upon units in files located outside the current directory, you have to provide
13677 the source search path when invoking @command{gnatmetric}.
13678 If it depends semantically upon units that are contained
13679 in files with names that do not follow the GNAT file naming rules, you have to
13680 provide the configuration file describing the corresponding naming scheme (see
13681 the description of the @command{gnatmetric} switches below.)
13682 Alternatively, you may use a project file and invoke @command{gnatmetric}
13683 through the @command{gnat} driver.
13684
13685 The @command{gnatmetric} command has the form
13686
13687 @smallexample
13688 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13689 @c Expanding @ovar macro inline (explanation in macro def comments)
13690 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13691 @end smallexample
13692
13693 @noindent
13694 where
13695 @itemize @bullet
13696 @item
13697 @var{switches} specify the metrics to compute and define the destination for
13698 the output
13699
13700 @item
13701 Each @var{filename} is the name (including the extension) of a source
13702 file to process. ``Wildcards'' are allowed, and
13703 the file name may contain path information.
13704 If no @var{filename} is supplied, then the @var{switches} list must contain
13705 at least one
13706 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13707 Including both a @option{-files} switch and one or more
13708 @var{filename} arguments is permitted.
13709
13710 @item
13711 @samp{@var{gcc_switches}} is a list of switches for
13712 @command{gcc}. They will be passed on to all compiler invocations made by
13713 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13714 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13715 and use the @option{-gnatec} switch to set the configuration file.
13716 @end itemize
13717
13718 @menu
13719 * Switches for gnatmetric::
13720 @end menu
13721
13722 @node Switches for gnatmetric
13723 @section Switches for @command{gnatmetric}
13724
13725 @noindent
13726 The following subsections describe the various switches accepted by
13727 @command{gnatmetric}, organized by category.
13728
13729 @menu
13730 * Output Files Control::
13731 * Disable Metrics For Local Units::
13732 * Specifying a set of metrics to compute::
13733 * Other gnatmetric Switches::
13734 * Generate project-wide metrics::
13735 @end menu
13736
13737 @node Output Files Control
13738 @subsection Output File Control
13739 @cindex Output file control in @command{gnatmetric}
13740
13741 @noindent
13742 @command{gnatmetric} has two output formats. It can generate a
13743 textual (human-readable) form, and also XML. By default only textual
13744 output is generated.
13745
13746 When generating the output in textual form, @command{gnatmetric} creates
13747 for each Ada source file a corresponding text file
13748 containing the computed metrics, except for the case when the set of metrics
13749 specified by gnatmetric parameters consists only of metrics that are computed
13750 for the whole set of analyzed sources, but not for each Ada source.
13751 By default, this file is placed in the same directory as where the source
13752 file is located, and its name is obtained
13753 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13754 input file.
13755
13756 All the output information generated in XML format is placed in a single
13757 file. By default this file is placed in the current directory and has the
13758 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13759
13760 Some of the computed metrics are summed over the units passed to
13761 @command{gnatmetric}; for example, the total number of lines of code.
13762 By default this information is sent to @file{stdout}, but a file
13763 can be specified with the @option{-og} switch.
13764
13765 The following switches control the @command{gnatmetric} output:
13766
13767 @table @option
13768 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13769 @item ^-x^/XML^
13770 Generate the XML output
13771
13772 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13773 @item ^-xs^/XSD^
13774 Generate the XML output and the XML schema file that describes the structure
13775 of the XML metric report, this schema is assigned to the XML file. The schema
13776 file has the same name as the XML output file with @file{.xml} suffix replaced
13777 with @file{.xsd}
13778
13779 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13780 @item ^-nt^/NO_TEXT^
13781 Do not generate the output in text form (implies @option{^-x^/XML^})
13782
13783 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13784 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13785 Put text files with detailed metrics into @var{output_dir}
13786
13787 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13788 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13789 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13790 in the name of the output file.
13791
13792 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13793 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13794 Put global metrics into @var{file_name}
13795
13796 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13797 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13798 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13799
13800 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13801 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13802 Use ``short'' source file names in the output.  (The @command{gnatmetric}
13803 output includes the name(s) of the Ada source file(s) from which the metrics
13804 are computed.  By default each name includes the absolute path. The
13805 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13806 to exclude all directory information from the file names that are output.)
13807
13808 @end table
13809
13810 @node Disable Metrics For Local Units
13811 @subsection Disable Metrics For Local Units
13812 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13813
13814 @noindent
13815 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13816 one compilation
13817 unit per one source file. It computes line metrics for the whole source
13818 file, and it also computes syntax
13819 and complexity metrics for the file's outermost unit.
13820
13821 By default, @command{gnatmetric} will also compute all metrics for certain
13822 kinds of locally declared program units:
13823
13824 @itemize @bullet
13825 @item
13826 subprogram (and generic subprogram) bodies;
13827
13828 @item
13829 package (and generic package) specs and bodies;
13830
13831 @item
13832 task object and type specifications and bodies;
13833
13834 @item
13835 protected object and type specifications and bodies.
13836 @end itemize
13837
13838 @noindent
13839 These kinds of entities will be referred to as
13840 @emph{eligible local program units}, or simply @emph{eligible local units},
13841 @cindex Eligible local unit (for @command{gnatmetric})
13842 in the discussion below.
13843
13844 Note that a subprogram declaration, generic instantiation,
13845 or renaming declaration only receives metrics
13846 computation when it appear as the outermost entity
13847 in a source file.
13848
13849 Suppression of metrics computation for eligible local units can be
13850 obtained via the following switch:
13851
13852 @table @option
13853 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13854 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13855 Do not compute detailed metrics for eligible local program units
13856
13857 @end table
13858
13859 @node Specifying a set of metrics to compute
13860 @subsection Specifying a set of metrics to compute
13861
13862 @noindent
13863 By default all the metrics are computed and reported. The switches
13864 described in this subsection allow you to control, on an individual
13865 basis, whether metrics are computed and
13866 reported. If at least one positive metric
13867 switch is specified (that is, a switch that defines that a given
13868 metric or set of metrics is to be computed), then only
13869 explicitly specified metrics are reported.
13870
13871 @menu
13872 * Line Metrics Control::
13873 * Syntax Metrics Control::
13874 * Complexity Metrics Control::
13875 * Object-Oriented Metrics Control::
13876 @end menu
13877
13878 @node Line Metrics Control
13879 @subsubsection Line Metrics Control
13880 @cindex Line metrics control in @command{gnatmetric}
13881
13882 @noindent
13883 For any (legal) source file, and for each of its
13884 eligible local program units, @command{gnatmetric} computes the following
13885 metrics:
13886
13887 @itemize @bullet
13888 @item
13889 the total number of lines;
13890
13891 @item
13892 the total number of code lines (i.e., non-blank lines that are not comments)
13893
13894 @item
13895 the number of comment lines
13896
13897 @item
13898 the number of code lines containing end-of-line comments;
13899
13900 @item
13901 the comment percentage: the ratio between the number of lines that contain
13902 comments and the number of all non-blank lines, expressed as a percentage;
13903
13904 @item
13905 the number of empty lines and lines containing only space characters and/or
13906 format effectors (blank lines)
13907
13908 @item
13909 the average number of code lines in subprogram bodies, task bodies, entry
13910 bodies and statement sequences in package bodies (this metric is only computed
13911 across the whole set of the analyzed units)
13912
13913 @end itemize
13914
13915 @noindent
13916 @command{gnatmetric} sums the values of the line metrics for all the
13917 files being processed and then generates the cumulative results. The tool
13918 also computes for all the files being processed the average number of code
13919 lines in bodies.
13920
13921 You can use the following switches to select the specific line metrics
13922 to be computed and reported.
13923
13924 @table @option
13925 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
13926
13927 @ifclear vms
13928 @cindex @option{--no-lines@var{x}}
13929 @end ifclear
13930
13931 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
13932 Report all the line metrics
13933
13934 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
13935 Do not report any of line metrics
13936
13937 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
13938 Report the number of all lines
13939
13940 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
13941 Do not report the number of all lines
13942
13943 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
13944 Report the number of code lines
13945
13946 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
13947 Do not report the number of code lines
13948
13949 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
13950 Report the number of comment lines
13951
13952 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
13953 Do not report the number of comment lines
13954
13955 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
13956 Report the number of code lines containing
13957 end-of-line comments
13958
13959 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
13960 Do not report the number of code lines containing
13961 end-of-line comments
13962
13963 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
13964 Report the comment percentage in the program text
13965
13966 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
13967 Do not report the comment percentage in the program text
13968
13969 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
13970 Report the number of blank lines
13971
13972 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
13973 Do not report the number of blank lines
13974
13975 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
13976 Report the average number of code lines in subprogram bodies, task bodies,
13977 entry bodies and statement sequences in package bodies. The metric is computed
13978 and reported for the whole set of processed Ada sources only.
13979
13980 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
13981 Do not report the average number of code lines in subprogram bodies,
13982 task bodies, entry bodies and statement sequences in package bodies.
13983
13984 @end table
13985
13986 @node Syntax Metrics Control
13987 @subsubsection Syntax Metrics Control
13988 @cindex Syntax metrics control in @command{gnatmetric}
13989
13990 @noindent
13991 @command{gnatmetric} computes various syntactic metrics for the
13992 outermost unit and for each eligible local unit:
13993
13994 @table @emph
13995 @item LSLOC (``Logical Source Lines Of Code'')
13996 The total number of declarations and the total number of statements
13997
13998 @item Maximal static nesting level of inner program units
13999 According to
14000 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14001 package, a task unit, a protected unit, a
14002 protected entry, a generic unit, or an explicitly declared subprogram other
14003 than an enumeration literal.''
14004
14005 @item Maximal nesting level of composite syntactic constructs
14006 This corresponds to the notion of the
14007 maximum nesting level in the GNAT built-in style checks
14008 (@pxref{Style Checking})
14009 @end table
14010
14011 @noindent
14012 For the outermost unit in the file, @command{gnatmetric} additionally computes
14013 the following metrics:
14014
14015 @table @emph
14016 @item Public subprograms
14017 This metric is computed for package specs. It is the
14018 number of subprograms and generic subprograms declared in the visible
14019 part (including the visible part of nested packages, protected objects, and
14020 protected types).
14021
14022 @item All subprograms
14023 This metric is computed for bodies and subunits. The
14024 metric is equal to a total number of subprogram bodies in the compilation
14025 unit.
14026 Neither generic instantiations nor renamings-as-a-body nor body stubs
14027 are counted. Any subprogram body is counted, independently of its nesting
14028 level and enclosing constructs. Generic bodies and bodies of protected
14029 subprograms are counted in the same way as ``usual'' subprogram bodies.
14030
14031 @item Public types
14032 This metric is computed for package specs and
14033 generic package declarations. It is the total number of types
14034 that can be referenced from outside this compilation unit, plus the
14035 number of types from all the visible parts of all the visible generic
14036 packages. Generic formal types are not counted.  Only types, not subtypes,
14037 are included.
14038
14039 @noindent
14040 Along with the total number of public types, the following
14041 types are counted and reported separately:
14042
14043 @itemize @bullet
14044 @item
14045 Abstract types
14046
14047 @item
14048 Root tagged types (abstract, non-abstract, private, non-private). Type
14049 extensions are @emph{not} counted
14050
14051 @item
14052 Private types (including private extensions)
14053
14054 @item
14055 Task types
14056
14057 @item
14058 Protected types
14059
14060 @end itemize
14061
14062 @item All types
14063 This metric is computed for any compilation unit. It is equal to the total
14064 number of the declarations of different types given in the compilation unit.
14065 The private and the corresponding full type declaration are counted as one
14066 type declaration. Incomplete type declarations and generic formal types
14067 are not counted.
14068 No distinction is made among different kinds of types (abstract,
14069 private etc.); the total number of types is computed and reported.
14070
14071 @end table
14072
14073 @noindent
14074 By default, all the syntax metrics are computed and reported. You can use the
14075 following switches to select specific syntax metrics.
14076
14077 @table @option
14078
14079 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14080
14081 @ifclear vms
14082 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14083 @end ifclear
14084
14085 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14086 Report all the syntax metrics
14087
14088 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14089 Do not report any of syntax metrics
14090
14091 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14092 Report the total number of declarations
14093
14094 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14095 Do not report the total number of declarations
14096
14097 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14098 Report the total number of statements
14099
14100 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14101 Do not report the total number of statements
14102
14103 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14104 Report the number of public subprograms in a compilation unit
14105
14106 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14107 Do not report the number of public subprograms in a compilation unit
14108
14109 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14110 Report the number of all the subprograms in a compilation unit
14111
14112 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14113 Do not report the number of all the subprograms in a compilation unit
14114
14115 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14116 Report the number of public types in a compilation unit
14117
14118 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14119 Do not report the number of public types in a compilation unit
14120
14121 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14122 Report the number of all the types in a compilation unit
14123
14124 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14125 Do not report the number of all the types in a compilation unit
14126
14127 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14128 Report the maximal program unit nesting level
14129
14130 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14131 Do not report the maximal program unit nesting level
14132
14133 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14134 Report the maximal construct nesting level
14135
14136 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14137 Do not report the maximal construct nesting level
14138
14139 @end table
14140
14141 @node Complexity Metrics Control
14142 @subsubsection Complexity Metrics Control
14143 @cindex Complexity metrics control in @command{gnatmetric}
14144
14145 @noindent
14146 For a program unit that is an executable body (a subprogram body (including
14147 generic bodies), task body, entry body or a package body containing
14148 its own statement sequence) @command{gnatmetric} computes the following
14149 complexity metrics:
14150
14151 @itemize @bullet
14152 @item
14153 McCabe cyclomatic complexity;
14154
14155 @item
14156 McCabe essential complexity;
14157
14158 @item
14159 maximal loop nesting level
14160
14161 @end itemize
14162
14163 @noindent
14164 The McCabe complexity metrics are defined
14165 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14166
14167 According to McCabe, both control statements and short-circuit control forms
14168 should be taken into account when computing cyclomatic complexity. For each
14169 body, we compute three metric values:
14170
14171 @itemize @bullet
14172 @item
14173 the complexity introduced by control
14174 statements only, without taking into account short-circuit forms,
14175
14176 @item
14177 the complexity introduced by short-circuit control forms only, and
14178
14179 @item
14180 the total
14181 cyclomatic complexity, which is the sum of these two values.
14182 @end itemize
14183
14184 @noindent
14185 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14186 the code in the exception handlers and in all the nested program units.
14187
14188 By default, all the complexity metrics are computed and reported.
14189 For more fine-grained control you can use
14190 the following switches:
14191
14192 @table @option
14193 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14194
14195 @ifclear vms
14196 @cindex @option{--no-complexity@var{x}}
14197 @end ifclear
14198
14199 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14200 Report all the complexity metrics
14201
14202 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14203 Do not report any of complexity metrics
14204
14205 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14206 Report the McCabe Cyclomatic Complexity
14207
14208 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14209 Do not report the McCabe Cyclomatic Complexity
14210
14211 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14212 Report the Essential Complexity
14213
14214 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14215 Do not report the Essential Complexity
14216
14217 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14218 Report maximal loop nesting level
14219
14220 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14221 Do not report maximal loop nesting level
14222
14223 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14224 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14225 task bodies, entry bodies and statement sequences in package bodies.
14226 The metric is computed and reported for whole set of processed Ada sources
14227 only.
14228
14229 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14230 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14231 bodies, task bodies, entry bodies and statement sequences in package bodies
14232
14233 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14234 @item ^-ne^/NO_EXITS_AS_GOTOS^
14235 Do not consider @code{exit} statements as @code{goto}s when
14236 computing Essential Complexity
14237
14238 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14239 Report the extra exit points for subprogram bodies. As an exit point, this
14240 metric counts @code{return} statements and raise statements in case when the
14241 raised exception is not handled in the same body. In case of a function this
14242 metric subtracts 1 from the number of exit points, because a function body
14243 must contain at least one @code{return} statement.
14244
14245 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14246 Do not report the extra exit points for subprogram bodies
14247 @end table
14248
14249
14250 @node Object-Oriented Metrics Control
14251 @subsubsection Object-Oriented Metrics Control
14252 @cindex Object-Oriented metrics control in @command{gnatmetric}
14253
14254 @noindent
14255 @cindex Coupling metrics (in in @command{gnatmetric})
14256 Coupling metrics are object-oriented metrics that measure the
14257 dependencies between a given class (or a group of classes) and the
14258 ``external world'' (that is, the other classes in the program). In this
14259 subsection the term ``class'' is used in its
14260 traditional object-oriented programming sense
14261 (an instantiable module that contains data and/or method members).
14262 A @emph{category} (of classes)
14263 is a group of closely related classes that are reused and/or
14264 modified together.
14265
14266 A class @code{K}'s @emph{efferent coupling} is the number of classes
14267 that @code{K} depends upon.
14268 A category's efferent coupling is the number of classes outside the
14269 category that the classes inside the category depend upon.
14270
14271 A class @code{K}'s @emph{afferent coupling} is the number of classes
14272 that depend upon @code{K}.
14273 A category's afferent coupling is the number of classes outside the
14274 category that depend on classes belonging to the category.
14275
14276 Ada's implementation of the object-oriented paradigm does not use the
14277 traditional class notion, so the definition of the coupling
14278 metrics for Ada maps the class and class category notions
14279 onto Ada constructs.
14280
14281 For the coupling metrics, several kinds of modules -- a library package,
14282 a library generic package, and a library generic package instantiation --
14283 that define a tagged type or an interface type are
14284 considered to be a class. A category consists of a library package (or
14285 a library generic package) that defines a tagged or an interface type,
14286 together with all its descendant (generic) packages that define tagged
14287 or interface types. For any package counted as a class,
14288 its body and subunits (if any) are considered
14289 together with its spec when counting the dependencies, and coupling
14290 metrics are reported for spec units only. For dependencies
14291 between classes, the Ada semantic dependencies are considered.
14292 For coupling metrics, only dependencies on units that are considered as
14293 classes, are considered.
14294
14295 When computing coupling metrics, @command{gnatmetric} counts only
14296 dependencies between units that are arguments of the gnatmetric call.
14297 Coupling metrics are program-wide (or project-wide) metrics, so to
14298 get a valid result, you should call @command{gnatmetric} for
14299 the whole set of sources that make up your program. It can be done
14300 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14301 option (see See @ref{The GNAT Driver and Project Files} for details.
14302
14303 By default, all the coupling metrics are disabled. You can use the following
14304 switches to specify the coupling metrics to be computed and reported:
14305
14306 @table @option
14307
14308 @ifclear vms
14309 @cindex @option{--package@var{x}} (@command{gnatmetric})
14310 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14311 @cindex @option{--category@var{x}} (@command{gnatmetric})
14312 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14313 @end ifclear
14314
14315 @ifset vms
14316 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14317 @end ifset
14318
14319 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14320 Report all the coupling metrics
14321
14322 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14323 Do not report any of  metrics
14324
14325 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14326 Report package efferent coupling
14327
14328 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14329 Do not report package efferent coupling
14330
14331 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14332 Report package afferent coupling
14333
14334 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14335 Do not report package afferent coupling
14336
14337 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14338 Report category efferent coupling
14339
14340 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14341 Do not report category efferent coupling
14342
14343 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14344 Report category afferent coupling
14345
14346 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14347 Do not report category afferent coupling
14348
14349 @end table
14350
14351 @node Other gnatmetric Switches
14352 @subsection Other @code{gnatmetric} Switches
14353
14354 @noindent
14355 Additional @command{gnatmetric} switches are as follows:
14356
14357 @table @option
14358 @item ^-files @var{filename}^/FILES=@var{filename}^
14359 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14360 Take the argument source files from the specified file. This file should be an
14361 ordinary text file containing file names separated by spaces or
14362 line breaks. You can use this switch more than once in the same call to
14363 @command{gnatmetric}. You also can combine this switch with
14364 an explicit list of files.
14365
14366 @item ^-v^/VERBOSE^
14367 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14368 Verbose mode;
14369 @command{gnatmetric} generates version information and then
14370 a trace of sources being processed.
14371
14372 @item ^-dv^/DEBUG_OUTPUT^
14373 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14374 Debug mode;
14375 @command{gnatmetric} generates various messages useful to understand what
14376 happens during the metrics computation
14377
14378 @item ^-q^/QUIET^
14379 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14380 Quiet mode.
14381 @end table
14382
14383 @node Generate project-wide metrics
14384 @subsection Generate project-wide metrics
14385
14386 In order to compute metrics on all units of a given project, you can use
14387 the @command{gnat} driver along with the @option{-P} option:
14388 @smallexample
14389    gnat metric -Pproj
14390 @end smallexample
14391
14392 @noindent
14393 If the project @code{proj} depends upon other projects, you can compute
14394 the metrics on the project closure using the @option{-U} option:
14395 @smallexample
14396    gnat metric -Pproj -U
14397 @end smallexample
14398
14399 @noindent
14400 Finally, if not all the units are relevant to a particular main
14401 program in the project closure, you can generate metrics for the set
14402 of units needed to create a given main program (unit closure) using
14403 the @option{-U} option followed by the name of the main unit:
14404 @smallexample
14405    gnat metric -Pproj -U main
14406 @end smallexample
14407
14408
14409 @c ***********************************
14410 @node File Name Krunching Using gnatkr
14411 @chapter File Name Krunching Using @code{gnatkr}
14412 @findex gnatkr
14413
14414 @noindent
14415 This chapter discusses the method used by the compiler to shorten
14416 the default file names chosen for Ada units so that they do not
14417 exceed the maximum length permitted. It also describes the
14418 @code{gnatkr} utility that can be used to determine the result of
14419 applying this shortening.
14420 @menu
14421 * About gnatkr::
14422 * Using gnatkr::
14423 * Krunching Method::
14424 * Examples of gnatkr Usage::
14425 @end menu
14426
14427 @node About gnatkr
14428 @section About @code{gnatkr}
14429
14430 @noindent
14431 The default file naming rule in GNAT
14432 is that the file name must be derived from
14433 the unit name. The exact default rule is as follows:
14434 @itemize @bullet
14435 @item
14436 Take the unit name and replace all dots by hyphens.
14437 @item
14438 If such a replacement occurs in the
14439 second character position of a name, and the first character is
14440 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14441 then replace the dot by the character
14442 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14443 instead of a minus.
14444 @end itemize
14445 The reason for this exception is to avoid clashes
14446 with the standard names for children of System, Ada, Interfaces,
14447 and GNAT, which use the prefixes
14448 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14449 respectively.
14450
14451 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14452 switch of the compiler activates a ``krunching''
14453 circuit that limits file names to nn characters (where nn is a decimal
14454 integer). For example, using OpenVMS,
14455 where the maximum file name length is
14456 39, the value of nn is usually set to 39, but if you want to generate
14457 a set of files that would be usable if ported to a system with some
14458 different maximum file length, then a different value can be specified.
14459 The default value of 39 for OpenVMS need not be specified.
14460
14461 The @code{gnatkr} utility can be used to determine the krunched name for
14462 a given file, when krunched to a specified maximum length.
14463
14464 @node Using gnatkr
14465 @section Using @code{gnatkr}
14466
14467 @noindent
14468 The @code{gnatkr} command has the form
14469
14470 @ifclear vms
14471 @smallexample
14472 @c $ gnatkr @var{name} @ovar{length}
14473 @c Expanding @ovar macro inline (explanation in macro def comments)
14474 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14475 @end smallexample
14476 @end ifclear
14477
14478 @ifset vms
14479 @smallexample
14480 $ gnatkr @var{name} /COUNT=nn
14481 @end smallexample
14482 @end ifset
14483
14484 @noindent
14485 @var{name} is the uncrunched file name, derived from the name of the unit
14486 in the standard manner described in the previous section (i.e., in particular
14487 all dots are replaced by hyphens). The file name may or may not have an
14488 extension (defined as a suffix of the form period followed by arbitrary
14489 characters other than period). If an extension is present then it will
14490 be preserved in the output. For example, when krunching @file{hellofile.ads}
14491 to eight characters, the result will be hellofil.ads.
14492
14493 Note: for compatibility with previous versions of @code{gnatkr} dots may
14494 appear in the name instead of hyphens, but the last dot will always be
14495 taken as the start of an extension. So if @code{gnatkr} is given an argument
14496 such as @file{Hello.World.adb} it will be treated exactly as if the first
14497 period had been a hyphen, and for example krunching to eight characters
14498 gives the result @file{hellworl.adb}.
14499
14500 Note that the result is always all lower case (except on OpenVMS where it is
14501 all upper case). Characters of the other case are folded as required.
14502
14503 @var{length} represents the length of the krunched name. The default
14504 when no argument is given is ^8^39^ characters. A length of zero stands for
14505 unlimited, in other words do not chop except for system files where the
14506 implied crunching length is always eight characters.
14507
14508 @noindent
14509 The output is the krunched name. The output has an extension only if the
14510 original argument was a file name with an extension.
14511
14512 @node Krunching Method
14513 @section Krunching Method
14514
14515 @noindent
14516 The initial file name is determined by the name of the unit that the file
14517 contains. The name is formed by taking the full expanded name of the
14518 unit and replacing the separating dots with hyphens and
14519 using ^lowercase^uppercase^
14520 for all letters, except that a hyphen in the second character position is
14521 replaced by a ^tilde^dollar sign^ if the first character is
14522 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14523 The extension is @code{.ads} for a
14524 spec and @code{.adb} for a body.
14525 Krunching does not affect the extension, but the file name is shortened to
14526 the specified length by following these rules:
14527
14528 @itemize @bullet
14529 @item
14530 The name is divided into segments separated by hyphens, tildes or
14531 underscores and all hyphens, tildes, and underscores are
14532 eliminated. If this leaves the name short enough, we are done.
14533
14534 @item
14535 If the name is too long, the longest segment is located (left-most
14536 if there are two of equal length), and shortened by dropping
14537 its last character. This is repeated until the name is short enough.
14538
14539 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14540 to fit the name into 8 characters as required by some operating systems.
14541
14542 @smallexample
14543 our-strings-wide_fixed 22
14544 our strings wide fixed 19
14545 our string  wide fixed 18
14546 our strin   wide fixed 17
14547 our stri    wide fixed 16
14548 our stri    wide fixe  15
14549 our str     wide fixe  14
14550 our str     wid  fixe  13
14551 our str     wid  fix   12
14552 ou  str     wid  fix   11
14553 ou  st      wid  fix   10
14554 ou  st      wi   fix   9
14555 ou  st      wi   fi    8
14556 Final file name: oustwifi.adb
14557 @end smallexample
14558
14559 @item
14560 The file names for all predefined units are always krunched to eight
14561 characters. The krunching of these predefined units uses the following
14562 special prefix replacements:
14563
14564 @table @file
14565 @item ada-
14566 replaced by @file{^a^A^-}
14567
14568 @item gnat-
14569 replaced by @file{^g^G^-}
14570
14571 @item interfaces-
14572 replaced by @file{^i^I^-}
14573
14574 @item system-
14575 replaced by @file{^s^S^-}
14576 @end table
14577
14578 These system files have a hyphen in the second character position. That
14579 is why normal user files replace such a character with a
14580 ^tilde^dollar sign^, to
14581 avoid confusion with system file names.
14582
14583 As an example of this special rule, consider
14584 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14585
14586 @smallexample
14587 ada-strings-wide_fixed 22
14588 a-  strings wide fixed 18
14589 a-  string  wide fixed 17
14590 a-  strin   wide fixed 16
14591 a-  stri    wide fixed 15
14592 a-  stri    wide fixe  14
14593 a-  str     wide fixe  13
14594 a-  str     wid  fixe  12
14595 a-  str     wid  fix   11
14596 a-  st      wid  fix   10
14597 a-  st      wi   fix   9
14598 a-  st      wi   fi    8
14599 Final file name: a-stwifi.adb
14600 @end smallexample
14601 @end itemize
14602
14603 Of course no file shortening algorithm can guarantee uniqueness over all
14604 possible unit names, and if file name krunching is used then it is your
14605 responsibility to ensure that no name clashes occur. The utility
14606 program @code{gnatkr} is supplied for conveniently determining the
14607 krunched name of a file.
14608
14609 @node Examples of gnatkr Usage
14610 @section Examples of @code{gnatkr} Usage
14611
14612 @smallexample
14613 @iftex
14614 @leftskip=0cm
14615 @end iftex
14616 @ifclear vms
14617 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14618 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14619 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14620 $ gnatkr grandparent-parent-child     --> grparchi
14621 @end ifclear
14622 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14623 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14624 @end smallexample
14625
14626 @node Preprocessing Using gnatprep
14627 @chapter Preprocessing Using @code{gnatprep}
14628 @findex gnatprep
14629
14630 @noindent
14631 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14632 preprocessing.
14633 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14634 special GNAT features.
14635 For further discussion of conditional compilation in general, see
14636 @ref{Conditional Compilation}.
14637
14638 @menu
14639 * Preprocessing Symbols::
14640 * Using gnatprep::
14641 * Switches for gnatprep::
14642 * Form of Definitions File::
14643 * Form of Input Text for gnatprep::
14644 @end menu
14645
14646 @node Preprocessing Symbols
14647 @section Preprocessing Symbols
14648
14649 @noindent
14650 Preprocessing symbols are defined in definition files and referred to in
14651 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14652 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14653 all characters need to be in the ASCII set (no accented letters).
14654
14655 @node Using gnatprep
14656 @section Using @code{gnatprep}
14657
14658 @noindent
14659 To call @code{gnatprep} use
14660
14661 @smallexample
14662 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14663 @c Expanding @ovar macro inline (explanation in macro def comments)
14664 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14665 @end smallexample
14666
14667 @noindent
14668 where
14669 @table @var
14670 @item switches
14671 is an optional sequence of switches as described in the next section.
14672
14673 @item infile
14674 is the full name of the input file, which is an Ada source
14675 file containing preprocessor directives.
14676
14677 @item outfile
14678 is the full name of the output file, which is an Ada source
14679 in standard Ada form. When used with GNAT, this file name will
14680 normally have an ads or adb suffix.
14681
14682 @item deffile
14683 is the full name of a text file containing definitions of
14684 preprocessing symbols to be referenced by the preprocessor. This argument is
14685 optional, and can be replaced by the use of the @option{-D} switch.
14686
14687 @end table
14688
14689 @node Switches for gnatprep
14690 @section Switches for @code{gnatprep}
14691
14692 @table @option
14693 @c !sort!
14694
14695 @item ^-b^/BLANK_LINES^
14696 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14697 Causes both preprocessor lines and the lines deleted by
14698 preprocessing to be replaced by blank lines in the output source file,
14699 preserving line numbers in the output file.
14700
14701 @item ^-c^/COMMENTS^
14702 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14703 Causes both preprocessor lines and the lines deleted
14704 by preprocessing to be retained in the output source as comments marked
14705 with the special string @code{"--! "}. This option will result in line numbers
14706 being preserved in the output file.
14707
14708 @item ^-C^/REPLACE_IN_COMMENTS^
14709 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14710 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14711 If this option is specified, then comments are scanned and any $symbol
14712 substitutions performed as in program text. This is particularly useful
14713 when structured comments are used (e.g., when writing programs in the
14714 SPARK dialect of Ada). Note that this switch is not available when
14715 doing integrated preprocessing (it would be useless in this context
14716 since comments are ignored by the compiler in any case).
14717
14718 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14719 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14720 Defines a new preprocessing symbol, associated with value. If no value is given
14721 on the command line, then symbol is considered to be @code{True}. This switch
14722 can be used in place of a definition file.
14723
14724 @ifset vms
14725 @item /REMOVE
14726 @cindex @option{/REMOVE} (@command{gnatprep})
14727 This is the default setting which causes lines deleted by preprocessing
14728 to be entirely removed from the output file.
14729 @end ifset
14730
14731 @item ^-r^/REFERENCE^
14732 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14733 Causes a @code{Source_Reference} pragma to be generated that
14734 references the original input file, so that error messages will use
14735 the file name of this original file. The use of this switch implies
14736 that preprocessor lines are not to be removed from the file, so its
14737 use will force @option{^-b^/BLANK_LINES^} mode if
14738 @option{^-c^/COMMENTS^}
14739 has not been specified explicitly.
14740
14741 Note that if the file to be preprocessed contains multiple units, then
14742 it will be necessary to @code{gnatchop} the output file from
14743 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14744 in the preprocessed file, it will be respected by
14745 @code{gnatchop ^-r^/REFERENCE^}
14746 so that the final chopped files will correctly refer to the original
14747 input source file for @code{gnatprep}.
14748
14749 @item ^-s^/SYMBOLS^
14750 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14751 Causes a sorted list of symbol names and values to be
14752 listed on the standard output file.
14753
14754 @item ^-u^/UNDEFINED^
14755 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14756 Causes undefined symbols to be treated as having the value FALSE in the context
14757 of a preprocessor test. In the absence of this option, an undefined symbol in
14758 a @code{#if} or @code{#elsif} test will be treated as an error.
14759
14760 @end table
14761
14762 @ifclear vms
14763 @noindent
14764 Note: if neither @option{-b} nor @option{-c} is present,
14765 then preprocessor lines and
14766 deleted lines are completely removed from the output, unless -r is
14767 specified, in which case -b is assumed.
14768 @end ifclear
14769
14770 @node Form of Definitions File
14771 @section Form of Definitions File
14772
14773 @noindent
14774 The definitions file contains lines of the form
14775
14776 @smallexample
14777 symbol := value
14778 @end smallexample
14779
14780 @noindent
14781 where symbol is a preprocessing symbol, and value is one of the following:
14782
14783 @itemize @bullet
14784 @item
14785 Empty, corresponding to a null substitution
14786 @item
14787 A string literal using normal Ada syntax
14788 @item
14789 Any sequence of characters from the set
14790 (letters, digits, period, underline).
14791 @end itemize
14792
14793 @noindent
14794 Comment lines may also appear in the definitions file, starting with
14795 the usual @code{--},
14796 and comments may be added to the definitions lines.
14797
14798 @node Form of Input Text for gnatprep
14799 @section Form of Input Text for @code{gnatprep}
14800
14801 @noindent
14802 The input text may contain preprocessor conditional inclusion lines,
14803 as well as general symbol substitution sequences.
14804
14805 The preprocessor conditional inclusion commands have the form
14806
14807 @smallexample
14808 @group
14809 @cartouche
14810 #if @i{expression} @r{[}then@r{]}
14811    lines
14812 #elsif @i{expression} @r{[}then@r{]}
14813    lines
14814 #elsif @i{expression} @r{[}then@r{]}
14815    lines
14816 @dots{}
14817 #else
14818    lines
14819 #end if;
14820 @end cartouche
14821 @end group
14822 @end smallexample
14823
14824 @noindent
14825 In this example, @i{expression} is defined by the following grammar:
14826 @smallexample
14827 @i{expression} ::=  <symbol>
14828 @i{expression} ::=  <symbol> = "<value>"
14829 @i{expression} ::=  <symbol> = <symbol>
14830 @i{expression} ::=  <symbol> 'Defined
14831 @i{expression} ::=  not @i{expression}
14832 @i{expression} ::=  @i{expression} and @i{expression}
14833 @i{expression} ::=  @i{expression} or @i{expression}
14834 @i{expression} ::=  @i{expression} and then @i{expression}
14835 @i{expression} ::=  @i{expression} or else @i{expression}
14836 @i{expression} ::=  ( @i{expression} )
14837 @end smallexample
14838
14839 The following restriction exists: it is not allowed to have "and" or "or"
14840 following "not" in the same expression without parentheses. For example, this
14841 is not allowed:
14842
14843 @smallexample
14844    not X or Y
14845 @end smallexample
14846
14847 This should be one of the following:
14848
14849 @smallexample
14850    (not X) or Y
14851    not (X or Y)
14852 @end smallexample
14853
14854 @noindent
14855 For the first test (@i{expression} ::= <symbol>) the symbol must have
14856 either the value true or false, that is to say the right-hand of the
14857 symbol definition must be one of the (case-insensitive) literals
14858 @code{True} or @code{False}. If the value is true, then the
14859 corresponding lines are included, and if the value is false, they are
14860 excluded.
14861
14862 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14863 the symbol has been defined in the definition file or by a @option{-D}
14864 switch on the command line. Otherwise, the test is false.
14865
14866 The equality tests are case insensitive, as are all the preprocessor lines.
14867
14868 If the symbol referenced is not defined in the symbol definitions file,
14869 then the effect depends on whether or not switch @option{-u}
14870 is specified. If so, then the symbol is treated as if it had the value
14871 false and the test fails. If this switch is not specified, then
14872 it is an error to reference an undefined symbol. It is also an error to
14873 reference a symbol that is defined with a value other than @code{True}
14874 or @code{False}.
14875
14876 The use of the @code{not} operator inverts the sense of this logical test.
14877 The @code{not} operator cannot be combined with the @code{or} or @code{and}
14878 operators, without parentheses. For example, "if not X or Y then" is not
14879 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
14880
14881 The @code{then} keyword is optional as shown
14882
14883 The @code{#} must be the first non-blank character on a line, but
14884 otherwise the format is free form. Spaces or tabs may appear between
14885 the @code{#} and the keyword. The keywords and the symbols are case
14886 insensitive as in normal Ada code. Comments may be used on a
14887 preprocessor line, but other than that, no other tokens may appear on a
14888 preprocessor line. Any number of @code{elsif} clauses can be present,
14889 including none at all. The @code{else} is optional, as in Ada.
14890
14891 The @code{#} marking the start of a preprocessor line must be the first
14892 non-blank character on the line, i.e., it must be preceded only by
14893 spaces or horizontal tabs.
14894
14895 Symbol substitution outside of preprocessor lines is obtained by using
14896 the sequence
14897
14898 @smallexample
14899 $symbol
14900 @end smallexample
14901
14902 @noindent
14903 anywhere within a source line, except in a comment or within a
14904 string literal. The identifier
14905 following the @code{$} must match one of the symbols defined in the symbol
14906 definition file, and the result is to substitute the value of the
14907 symbol in place of @code{$symbol} in the output file.
14908
14909 Note that although the substitution of strings within a string literal
14910 is not possible, it is possible to have a symbol whose defined value is
14911 a string literal. So instead of setting XYZ to @code{hello} and writing:
14912
14913 @smallexample
14914 Header : String := "$XYZ";
14915 @end smallexample
14916
14917 @noindent
14918 you should set XYZ to @code{"hello"} and write:
14919
14920 @smallexample
14921 Header : String := $XYZ;
14922 @end smallexample
14923
14924 @noindent
14925 and then the substitution will occur as desired.
14926
14927 @ifset vms
14928 @node The GNAT Run-Time Library Builder gnatlbr
14929 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
14930 @findex gnatlbr
14931 @cindex Library builder
14932
14933 @noindent
14934 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
14935 supplied configuration pragmas.
14936
14937 @menu
14938 * Running gnatlbr::
14939 * Switches for gnatlbr::
14940 * Examples of gnatlbr Usage::
14941 @end menu
14942
14943 @node Running gnatlbr
14944 @section Running @code{gnatlbr}
14945
14946 @noindent
14947 The @code{gnatlbr} command has the form
14948
14949 @smallexample
14950 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
14951 @end smallexample
14952
14953 @node Switches for gnatlbr
14954 @section Switches for @code{gnatlbr}
14955
14956 @noindent
14957 @code{gnatlbr} recognizes the following switches:
14958
14959 @table @option
14960 @c !sort!
14961 @item /CREATE=directory
14962 @cindex @code{/CREATE} (@code{gnatlbr})
14963 Create the new run-time library in the specified directory.
14964
14965 @item /SET=directory
14966 @cindex @code{/SET} (@code{gnatlbr})
14967 Make the library in the specified directory the current run-time library.
14968
14969 @item /DELETE=directory
14970 @cindex @code{/DELETE} (@code{gnatlbr})
14971 Delete the run-time library in the specified directory.
14972
14973 @item /CONFIG=file
14974 @cindex @code{/CONFIG} (@code{gnatlbr})
14975 With /CREATE: Use the configuration pragmas in the specified file when
14976 building the library.
14977
14978 With /SET: Use the configuration pragmas in the specified file when
14979 compiling.
14980
14981 @end table
14982
14983 @node Examples of gnatlbr Usage
14984 @section Example of @code{gnatlbr} Usage
14985
14986 @smallexample
14987 Contents of VAXFLOAT.ADC:
14988 pragma Float_Representation (VAX_Float);
14989
14990 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
14991
14992 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
14993
14994 @end smallexample
14995 @end ifset
14996
14997 @node The GNAT Library Browser gnatls
14998 @chapter The GNAT Library Browser @code{gnatls}
14999 @findex gnatls
15000 @cindex Library browser
15001
15002 @noindent
15003 @code{gnatls} is a tool that outputs information about compiled
15004 units. It gives the relationship between objects, unit names and source
15005 files. It can also be used to check the source dependencies of a unit
15006 as well as various characteristics.
15007
15008 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15009 driver (see @ref{The GNAT Driver and Project Files}).
15010
15011 @menu
15012 * Running gnatls::
15013 * Switches for gnatls::
15014 * Examples of gnatls Usage::
15015 @end menu
15016
15017 @node Running gnatls
15018 @section Running @code{gnatls}
15019
15020 @noindent
15021 The @code{gnatls} command has the form
15022
15023 @smallexample
15024 $ gnatls switches @var{object_or_ali_file}
15025 @end smallexample
15026
15027 @noindent
15028 The main argument is the list of object or @file{ali} files
15029 (@pxref{The Ada Library Information Files})
15030 for which information is requested.
15031
15032 In normal mode, without additional option, @code{gnatls} produces a
15033 four-column listing. Each line represents information for a specific
15034 object. The first column gives the full path of the object, the second
15035 column gives the name of the principal unit in this object, the third
15036 column gives the status of the source and the fourth column gives the
15037 full path of the source representing this unit.
15038 Here is a simple example of use:
15039
15040 @smallexample
15041 $ gnatls *.o
15042 ^./^[]^demo1.o            demo1            DIF demo1.adb
15043 ^./^[]^demo2.o            demo2             OK demo2.adb
15044 ^./^[]^hello.o            h1                OK hello.adb
15045 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15046 ^./^[]^instr.o            instr             OK instr.adb
15047 ^./^[]^tef.o              tef              DIF tef.adb
15048 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15049 ^./^[]^tgef.o             tgef             DIF tgef.adb
15050 @end smallexample
15051
15052 @noindent
15053 The first line can be interpreted as follows: the main unit which is
15054 contained in
15055 object file @file{demo1.o} is demo1, whose main source is in
15056 @file{demo1.adb}. Furthermore, the version of the source used for the
15057 compilation of demo1 has been modified (DIF). Each source file has a status
15058 qualifier which can be:
15059
15060 @table @code
15061 @item OK (unchanged)
15062 The version of the source file used for the compilation of the
15063 specified unit corresponds exactly to the actual source file.
15064
15065 @item MOK (slightly modified)
15066 The version of the source file used for the compilation of the
15067 specified unit differs from the actual source file but not enough to
15068 require recompilation. If you use gnatmake with the qualifier
15069 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15070 MOK will not be recompiled.
15071
15072 @item DIF (modified)
15073 No version of the source found on the path corresponds to the source
15074 used to build this object.
15075
15076 @item ??? (file not found)
15077 No source file was found for this unit.
15078
15079 @item HID (hidden,  unchanged version not first on PATH)
15080 The version of the source that corresponds exactly to the source used
15081 for compilation has been found on the path but it is hidden by another
15082 version of the same source that has been modified.
15083
15084 @end table
15085
15086 @node Switches for gnatls
15087 @section Switches for @code{gnatls}
15088
15089 @noindent
15090 @code{gnatls} recognizes the following switches:
15091
15092 @table @option
15093 @c !sort!
15094 @cindex @option{--version} @command{gnatls}
15095 Display Copyright and version, then exit disregarding all other options.
15096
15097 @item --help
15098 @cindex @option{--help} @command{gnatls}
15099 If @option{--version} was not used, display usage, then exit disregarding
15100 all other options.
15101
15102 @item ^-a^/ALL_UNITS^
15103 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15104 Consider all units, including those of the predefined Ada library.
15105 Especially useful with @option{^-d^/DEPENDENCIES^}.
15106
15107 @item ^-d^/DEPENDENCIES^
15108 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15109 List sources from which specified units depend on.
15110
15111 @item ^-h^/OUTPUT=OPTIONS^
15112 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15113 Output the list of options.
15114
15115 @item ^-o^/OUTPUT=OBJECTS^
15116 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15117 Only output information about object files.
15118
15119 @item ^-s^/OUTPUT=SOURCES^
15120 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15121 Only output information about source files.
15122
15123 @item ^-u^/OUTPUT=UNITS^
15124 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15125 Only output information about compilation units.
15126
15127 @item ^-files^/FILES^=@var{file}
15128 @cindex @option{^-files^/FILES^} (@code{gnatls})
15129 Take as arguments the files listed in text file @var{file}.
15130 Text file @var{file} may contain empty lines that are ignored.
15131 Each nonempty line should contain the name of an existing file.
15132 Several such switches may be specified simultaneously.
15133
15134 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15135 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15136 @itemx ^-I^/SEARCH=^@var{dir}
15137 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15138 @itemx -nostdinc
15139 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15140 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15141 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15142 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15143 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15144 flags (@pxref{Switches for gnatmake}).
15145
15146 @item --RTS=@var{rts-path}
15147 @cindex @option{--RTS} (@code{gnatls})
15148 Specifies the default location of the runtime library. Same meaning as the
15149 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15150
15151 @item ^-v^/OUTPUT=VERBOSE^
15152 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15153 Verbose mode. Output the complete source, object and project paths. Do not use
15154 the default column layout but instead use long format giving as much as
15155 information possible on each requested units, including special
15156 characteristics such as:
15157
15158 @table @code
15159 @item  Preelaborable
15160 The unit is preelaborable in the Ada sense.
15161
15162 @item No_Elab_Code
15163 No elaboration code has been produced by the compiler for this unit.
15164
15165 @item Pure
15166 The unit is pure in the Ada sense.
15167
15168 @item Elaborate_Body
15169 The unit contains a pragma Elaborate_Body.
15170
15171 @item Remote_Types
15172 The unit contains a pragma Remote_Types.
15173
15174 @item Shared_Passive
15175 The unit contains a pragma Shared_Passive.
15176
15177 @item Predefined
15178 This unit is part of the predefined environment and cannot be modified
15179 by the user.
15180
15181 @item Remote_Call_Interface
15182 The unit contains a pragma Remote_Call_Interface.
15183
15184 @end table
15185
15186 @end table
15187
15188 @node Examples of gnatls Usage
15189 @section Example of @code{gnatls} Usage
15190 @ifclear vms
15191
15192 @noindent
15193 Example of using the verbose switch. Note how the source and
15194 object paths are affected by the -I switch.
15195
15196 @smallexample
15197 $ gnatls -v -I.. demo1.o
15198
15199 GNATLS 5.03w (20041123-34)
15200 Copyright 1997-2004 Free Software Foundation, Inc.
15201
15202 Source Search Path:
15203    <Current_Directory>
15204    ../
15205    /home/comar/local/adainclude/
15206
15207 Object Search Path:
15208    <Current_Directory>
15209    ../
15210    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15211
15212 Project Search Path:
15213    <Current_Directory>
15214    /home/comar/local/lib/gnat/
15215
15216 ./demo1.o
15217    Unit =>
15218      Name   => demo1
15219      Kind   => subprogram body
15220      Flags  => No_Elab_Code
15221      Source => demo1.adb    modified
15222 @end smallexample
15223
15224 @noindent
15225 The following is an example of use of the dependency list.
15226 Note the use of the -s switch
15227 which gives a straight list of source files. This can be useful for
15228 building specialized scripts.
15229
15230 @smallexample
15231 $ gnatls -d demo2.o
15232 ./demo2.o   demo2        OK demo2.adb
15233                          OK gen_list.ads
15234                          OK gen_list.adb
15235                          OK instr.ads
15236                          OK instr-child.ads
15237
15238 $ gnatls -d -s -a demo1.o
15239 demo1.adb
15240 /home/comar/local/adainclude/ada.ads
15241 /home/comar/local/adainclude/a-finali.ads
15242 /home/comar/local/adainclude/a-filico.ads
15243 /home/comar/local/adainclude/a-stream.ads
15244 /home/comar/local/adainclude/a-tags.ads
15245 gen_list.ads
15246 gen_list.adb
15247 /home/comar/local/adainclude/gnat.ads
15248 /home/comar/local/adainclude/g-io.ads
15249 instr.ads
15250 /home/comar/local/adainclude/system.ads
15251 /home/comar/local/adainclude/s-exctab.ads
15252 /home/comar/local/adainclude/s-finimp.ads
15253 /home/comar/local/adainclude/s-finroo.ads
15254 /home/comar/local/adainclude/s-secsta.ads
15255 /home/comar/local/adainclude/s-stalib.ads
15256 /home/comar/local/adainclude/s-stoele.ads
15257 /home/comar/local/adainclude/s-stratt.ads
15258 /home/comar/local/adainclude/s-tasoli.ads
15259 /home/comar/local/adainclude/s-unstyp.ads
15260 /home/comar/local/adainclude/unchconv.ads
15261 @end smallexample
15262 @end ifclear
15263
15264 @ifset vms
15265 @smallexample
15266 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15267
15268 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15269 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15270 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15271 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15272 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15273 demo1.adb
15274 gen_list.ads
15275 gen_list.adb
15276 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15277 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15278 instr.ads
15279 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15280 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15281 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15282 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15283 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15284 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15285 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15286 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15287 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15288 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15289 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15290 @end smallexample
15291 @end ifset
15292
15293 @node Cleaning Up Using gnatclean
15294 @chapter Cleaning Up Using @code{gnatclean}
15295 @findex gnatclean
15296 @cindex Cleaning tool
15297
15298 @noindent
15299 @code{gnatclean} is a tool that allows the deletion of files produced by the
15300 compiler, binder and linker, including ALI files, object files, tree files,
15301 expanded source files, library files, interface copy source files, binder
15302 generated files and executable files.
15303
15304 @menu
15305 * Running gnatclean::
15306 * Switches for gnatclean::
15307 @c * Examples of gnatclean Usage::
15308 @end menu
15309
15310 @node Running gnatclean
15311 @section Running @code{gnatclean}
15312
15313 @noindent
15314 The @code{gnatclean} command has the form:
15315
15316 @smallexample
15317 $ gnatclean switches @var{names}
15318 @end smallexample
15319
15320 @noindent
15321 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15322 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15323 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15324
15325 @noindent
15326 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15327 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15328 the linker. In informative-only mode, specified by switch
15329 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15330 normal mode is listed, but no file is actually deleted.
15331
15332 @node Switches for gnatclean
15333 @section Switches for @code{gnatclean}
15334
15335 @noindent
15336 @code{gnatclean} recognizes the following switches:
15337
15338 @table @option
15339 @c !sort!
15340 @cindex @option{--version} @command{gnatclean}
15341 Display Copyright and version, then exit disregarding all other options.
15342
15343 @item --help
15344 @cindex @option{--help} @command{gnatclean}
15345 If @option{--version} was not used, display usage, then exit disregarding
15346 all other options.
15347
15348 @item ^--subdirs^/SUBDIRS^=subdir
15349 Actual object directory of each project file is the subdirectory subdir of the
15350 object directory specified or defauted in the project file.
15351
15352 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15353 By default, shared library projects are not allowed to import static library
15354 projects. When this switch is used on the command line, this restriction is
15355 relaxed.
15356
15357 @item ^-c^/COMPILER_FILES_ONLY^
15358 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15359 Only attempt to delete the files produced by the compiler, not those produced
15360 by the binder or the linker. The files that are not to be deleted are library
15361 files, interface copy files, binder generated files and executable files.
15362
15363 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15364 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15365 Indicate that ALI and object files should normally be found in directory
15366 @var{dir}.
15367
15368 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15369 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15370 When using project files, if some errors or warnings are detected during
15371 parsing and verbose mode is not in effect (no use of switch
15372 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15373 file, rather than its simple file name.
15374
15375 @item ^-h^/HELP^
15376 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15377 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15378
15379 @item ^-n^/NODELETE^
15380 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15381 Informative-only mode. Do not delete any files. Output the list of the files
15382 that would have been deleted if this switch was not specified.
15383
15384 @item ^-P^/PROJECT_FILE=^@var{project}
15385 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15386 Use project file @var{project}. Only one such switch can be used.
15387 When cleaning a project file, the files produced by the compilation of the
15388 immediate sources or inherited sources of the project files are to be
15389 deleted. This is not depending on the presence or not of executable names
15390 on the command line.
15391
15392 @item ^-q^/QUIET^
15393 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15394 Quiet output. If there are no errors, do not output anything, except in
15395 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15396 (switch ^-n^/NODELETE^).
15397
15398 @item ^-r^/RECURSIVE^
15399 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15400 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15401 clean all imported and extended project files, recursively. If this switch
15402 is not specified, only the files related to the main project file are to be
15403 deleted. This switch has no effect if no project file is specified.
15404
15405 @item ^-v^/VERBOSE^
15406 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15407 Verbose mode.
15408
15409 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15410 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15411 Indicates the verbosity of the parsing of GNAT project files.
15412 @xref{Switches Related to Project Files}.
15413
15414 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15415 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15416 Indicates that external variable @var{name} has the value @var{value}.
15417 The Project Manager will use this value for occurrences of
15418 @code{external(name)} when parsing the project file.
15419 @xref{Switches Related to Project Files}.
15420
15421 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15422 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15423 When searching for ALI and object files, look in directory
15424 @var{dir}.
15425
15426 @item ^-I^/SEARCH=^@var{dir}
15427 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15428 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15429
15430 @item ^-I-^/NOCURRENT_DIRECTORY^
15431 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15432 @cindex Source files, suppressing search
15433 Do not look for ALI or object files in the directory
15434 where @code{gnatclean} was invoked.
15435
15436 @end table
15437
15438 @c @node Examples of gnatclean Usage
15439 @c @section Examples of @code{gnatclean} Usage
15440
15441 @ifclear vms
15442 @node GNAT and Libraries
15443 @chapter GNAT and Libraries
15444 @cindex Library, building, installing, using
15445
15446 @noindent
15447 This chapter describes how to build and use libraries with GNAT, and also shows
15448 how to recompile the GNAT run-time library. You should be familiar with the
15449 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15450 chapter.
15451
15452 @menu
15453 * Introduction to Libraries in GNAT::
15454 * General Ada Libraries::
15455 * Stand-alone Ada Libraries::
15456 * Rebuilding the GNAT Run-Time Library::
15457 @end menu
15458
15459 @node Introduction to Libraries in GNAT
15460 @section Introduction to Libraries in GNAT
15461
15462 @noindent
15463 A library is, conceptually, a collection of objects which does not have its
15464 own main thread of execution, but rather provides certain services to the
15465 applications that use it. A library can be either statically linked with the
15466 application, in which case its code is directly included in the application,
15467 or, on platforms that support it, be dynamically linked, in which case
15468 its code is shared by all applications making use of this library.
15469
15470 GNAT supports both types of libraries.
15471 In the static case, the compiled code can be provided in different ways. The
15472 simplest approach is to provide directly the set of objects resulting from
15473 compilation of the library source files. Alternatively, you can group the
15474 objects into an archive using whatever commands are provided by the operating
15475 system. For the latter case, the objects are grouped into a shared library.
15476
15477 In the GNAT environment, a library has three types of components:
15478 @itemize @bullet
15479 @item
15480 Source files.
15481 @item
15482 @file{ALI} files.
15483 @xref{The Ada Library Information Files}.
15484 @item
15485 Object files, an archive or a shared library.
15486 @end itemize
15487
15488 @noindent
15489 A GNAT library may expose all its source files, which is useful for
15490 documentation purposes. Alternatively, it may expose only the units needed by
15491 an external user to make use of the library. That is to say, the specs
15492 reflecting the library services along with all the units needed to compile
15493 those specs, which can include generic bodies or any body implementing an
15494 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15495 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15496
15497 All compilation units comprising an application, including those in a library,
15498 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15499 computes the elaboration order from the @file{ALI} files and this is why they
15500 constitute a mandatory part of GNAT libraries.
15501 @emph{Stand-alone libraries} are the exception to this rule because a specific
15502 library elaboration routine is produced independently of the application(s)
15503 using the library.
15504
15505 @node General Ada Libraries
15506 @section General Ada Libraries
15507
15508 @menu
15509 * Building a library::
15510 * Installing a library::
15511 * Using a library::
15512 @end menu
15513
15514 @node Building a library
15515 @subsection Building a library
15516
15517 @noindent
15518 The easiest way to build a library is to use the Project Manager,
15519 which supports a special type of project called a @emph{Library Project}
15520 (@pxref{Library Projects}).
15521
15522 A project is considered a library project, when two project-level attributes
15523 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15524 control different aspects of library configuration, additional optional
15525 project-level attributes can be specified:
15526 @table @code
15527 @item Library_Kind
15528 This attribute controls whether the library is to be static or dynamic
15529
15530 @item Library_Version
15531 This attribute specifies the library version; this value is used
15532 during dynamic linking of shared libraries to determine if the currently
15533 installed versions of the binaries are compatible.
15534
15535 @item Library_Options
15536 @item Library_GCC
15537 These attributes specify additional low-level options to be used during
15538 library generation, and redefine the actual application used to generate
15539 library.
15540 @end table
15541
15542 @noindent
15543 The GNAT Project Manager takes full care of the library maintenance task,
15544 including recompilation of the source files for which objects do not exist
15545 or are not up to date, assembly of the library archive, and installation of
15546 the library (i.e., copying associated source, object and @file{ALI} files
15547 to the specified location).
15548
15549 Here is a simple library project file:
15550 @smallexample @c ada
15551 project My_Lib is
15552    for Source_Dirs use ("src1", "src2");
15553    for Object_Dir use "obj";
15554    for Library_Name use "mylib";
15555    for Library_Dir use "lib";
15556    for Library_Kind use "dynamic";
15557 end My_lib;
15558 @end smallexample
15559
15560 @noindent
15561 and the compilation command to build and install the library:
15562
15563 @smallexample @c ada
15564   $ gnatmake -Pmy_lib
15565 @end smallexample
15566
15567 @noindent
15568 It is not entirely trivial to perform manually all the steps required to
15569 produce a library. We recommend that you use the GNAT Project Manager
15570 for this task. In special cases where this is not desired, the necessary
15571 steps are discussed below.
15572
15573 There are various possibilities for compiling the units that make up the
15574 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15575 with a conventional script. For simple libraries, it is also possible to create
15576 a dummy main program which depends upon all the packages that comprise the
15577 interface of the library. This dummy main program can then be given to
15578 @command{gnatmake}, which will ensure that all necessary objects are built.
15579
15580 After this task is accomplished, you should follow the standard procedure
15581 of the underlying operating system to produce the static or shared library.
15582
15583 Here is an example of such a dummy program:
15584 @smallexample @c ada
15585 @group
15586 with My_Lib.Service1;
15587 with My_Lib.Service2;
15588 with My_Lib.Service3;
15589 procedure My_Lib_Dummy is
15590 begin
15591    null;
15592 end;
15593 @end group
15594 @end smallexample
15595
15596 @noindent
15597 Here are the generic commands that will build an archive or a shared library.
15598
15599 @smallexample
15600 # compiling the library
15601 $ gnatmake -c my_lib_dummy.adb
15602
15603 # we don't need the dummy object itself
15604 $ rm my_lib_dummy.o my_lib_dummy.ali
15605
15606 # create an archive with the remaining objects
15607 $ ar rc libmy_lib.a *.o
15608 # some systems may require "ranlib" to be run as well
15609
15610 # or create a shared library
15611 $ gcc -shared -o libmy_lib.so *.o
15612 # some systems may require the code to have been compiled with -fPIC
15613
15614 # remove the object files that are now in the library
15615 $ rm *.o
15616
15617 # Make the ALI files read-only so that gnatmake will not try to
15618 # regenerate the objects that are in the library
15619 $ chmod -w *.ali
15620 @end smallexample
15621
15622 @noindent
15623 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15624 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15625 be accessed by the directive @option{-l@var{xxx}} at link time.
15626
15627 @node Installing a library
15628 @subsection Installing a library
15629 @cindex @code{ADA_PROJECT_PATH}
15630 @cindex @code{GPR_PROJECT_PATH}
15631
15632 @noindent
15633 If you use project files, library installation is part of the library build
15634 process (@pxref{Installing a library with project files}).
15635
15636 When project files are not an option, it is also possible, but not recommended,
15637 to install the library so that the sources needed to use the library are on the
15638 Ada source path and the ALI files & libraries be on the Ada Object path (see
15639 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15640 administrator can place general-purpose libraries in the default compiler
15641 paths, by specifying the libraries' location in the configuration files
15642 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15643 must be located in the GNAT installation tree at the same place as the gcc spec
15644 file. The location of the gcc spec file can be determined as follows:
15645 @smallexample
15646 $ gcc -v
15647 @end smallexample
15648
15649 @noindent
15650 The configuration files mentioned above have a simple format: each line
15651 must contain one unique directory name.
15652 Those names are added to the corresponding path
15653 in their order of appearance in the file. The names can be either absolute
15654 or relative; in the latter case, they are relative to where theses files
15655 are located.
15656
15657 The files @file{ada_source_path} and @file{ada_object_path} might not be
15658 present in a
15659 GNAT installation, in which case, GNAT will look for its run-time library in
15660 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15661 objects and @file{ALI} files). When the files exist, the compiler does not
15662 look in @file{adainclude} and @file{adalib}, and thus the
15663 @file{ada_source_path} file
15664 must contain the location for the GNAT run-time sources (which can simply
15665 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15666 contain the location for the GNAT run-time objects (which can simply
15667 be @file{adalib}).
15668
15669 You can also specify a new default path to the run-time library at compilation
15670 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15671 the run-time library you want your program to be compiled with. This switch is
15672 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15673 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15674
15675 It is possible to install a library before or after the standard GNAT
15676 library, by reordering the lines in the configuration files. In general, a
15677 library must be installed before the GNAT library if it redefines
15678 any part of it.
15679
15680 @node Using a library
15681 @subsection Using a library
15682
15683 @noindent Once again, the project facility greatly simplifies the use of
15684 libraries. In this context, using a library is just a matter of adding a
15685 @code{with} clause in the user project. For instance, to make use of the
15686 library @code{My_Lib} shown in examples in earlier sections, you can
15687 write:
15688
15689 @smallexample @c projectfile
15690 with "my_lib";
15691 project My_Proj is
15692   @dots{}
15693 end My_Proj;
15694 @end smallexample
15695
15696 Even if you have a third-party, non-Ada library, you can still use GNAT's
15697 Project Manager facility to provide a wrapper for it. For example, the
15698 following project, when @code{with}ed by your main project, will link with the
15699 third-party library @file{liba.a}:
15700
15701 @smallexample @c projectfile
15702 @group
15703 project Liba is
15704    for Externally_Built use "true";
15705    for Source_Files use ();
15706    for Library_Dir use "lib";
15707    for Library_Name use "a";
15708    for Library_Kind use "static";
15709 end Liba;
15710 @end group
15711 @end smallexample
15712 This is an alternative to the use of @code{pragma Linker_Options}. It is
15713 especially interesting in the context of systems with several interdependent
15714 static libraries where finding a proper linker order is not easy and best be
15715 left to the tools having visibility over project dependence information.
15716
15717 @noindent
15718 In order to use an Ada library manually, you need to make sure that this
15719 library is on both your source and object path
15720 (see @ref{Search Paths and the Run-Time Library (RTL)}
15721 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15722 in an archive or a shared library, you need to specify the desired
15723 library at link time.
15724
15725 For example, you can use the library @file{mylib} installed in
15726 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15727
15728 @smallexample
15729 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15730   -largs -lmy_lib
15731 @end smallexample
15732
15733 @noindent
15734 This can be expressed more simply:
15735 @smallexample
15736 $ gnatmake my_appl
15737 @end smallexample
15738 @noindent
15739 when the following conditions are met:
15740 @itemize @bullet
15741 @item
15742 @file{/dir/my_lib_src} has been added by the user to the environment
15743 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15744 @file{ada_source_path}
15745 @item
15746 @file{/dir/my_lib_obj} has been added by the user to the environment
15747 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15748 @file{ada_object_path}
15749 @item
15750 a pragma @code{Linker_Options} has been added to one of the sources.
15751 For example:
15752
15753 @smallexample @c ada
15754 pragma Linker_Options ("-lmy_lib");
15755 @end smallexample
15756 @end itemize
15757
15758 @node Stand-alone Ada Libraries
15759 @section Stand-alone Ada Libraries
15760 @cindex Stand-alone library, building, using
15761
15762 @menu
15763 * Introduction to Stand-alone Libraries::
15764 * Building a Stand-alone Library::
15765 * Creating a Stand-alone Library to be used in a non-Ada context::
15766 * Restrictions in Stand-alone Libraries::
15767 @end menu
15768
15769 @node Introduction to Stand-alone Libraries
15770 @subsection Introduction to Stand-alone Libraries
15771
15772 @noindent
15773 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15774 necessary code to
15775 elaborate the Ada units that are included in the library. In contrast with
15776 an ordinary library, which consists of all sources, objects and @file{ALI}
15777 files of the
15778 library, a SAL may specify a restricted subset of compilation units
15779 to serve as a library interface. In this case, the fully
15780 self-sufficient set of files will normally consist of an objects
15781 archive, the sources of interface units' specs, and the @file{ALI}
15782 files of interface units.
15783 If an interface spec contains a generic unit or an inlined subprogram,
15784 the body's
15785 source must also be provided; if the units that must be provided in the source
15786 form depend on other units, the source and @file{ALI} files of those must
15787 also be provided.
15788
15789 The main purpose of a SAL is to minimize the recompilation overhead of client
15790 applications when a new version of the library is installed. Specifically,
15791 if the interface sources have not changed, client applications do not need to
15792 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15793 version, controlled by @code{Library_Version} attribute, is not changed,
15794 then the clients do not need to be relinked.
15795
15796 SALs also allow the library providers to minimize the amount of library source
15797 text exposed to the clients.  Such ``information hiding'' might be useful or
15798 necessary for various reasons.
15799
15800 Stand-alone libraries are also well suited to be used in an executable whose
15801 main routine is not written in Ada.
15802
15803 @node Building a Stand-alone Library
15804 @subsection Building a Stand-alone Library
15805
15806 @noindent
15807 GNAT's Project facility provides a simple way of building and installing
15808 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15809 To be a Stand-alone Library Project, in addition to the two attributes
15810 that make a project a Library Project (@code{Library_Name} and
15811 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15812 @code{Library_Interface} must be defined.  For example:
15813
15814 @smallexample @c projectfile
15815 @group
15816    for Library_Dir use "lib_dir";
15817    for Library_Name use "dummy";
15818    for Library_Interface use ("int1", "int1.child");
15819 @end group
15820 @end smallexample
15821
15822 @noindent
15823 Attribute @code{Library_Interface} has a non-empty string list value,
15824 each string in the list designating a unit contained in an immediate source
15825 of the project file.
15826
15827 When a Stand-alone Library is built, first the binder is invoked to build
15828 a package whose name depends on the library name
15829 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15830 This binder-generated package includes initialization and
15831 finalization procedures whose
15832 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15833 in the example
15834 above). The object corresponding to this package is included in the library.
15835
15836 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15837 calling of these procedures if a static SAL is built, or if a shared SAL
15838 is built
15839 with the project-level attribute @code{Library_Auto_Init} set to
15840 @code{"false"}.
15841
15842 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15843 (those that are listed in attribute @code{Library_Interface}) are copied to
15844 the Library Directory. As a consequence, only the Interface Units may be
15845 imported from Ada units outside of the library. If other units are imported,
15846 the binding phase will fail.
15847
15848 The attribute @code{Library_Src_Dir} may be specified for a
15849 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15850 single string value. Its value must be the path (absolute or relative to the
15851 project directory) of an existing directory. This directory cannot be the
15852 object directory or one of the source directories, but it can be the same as
15853 the library directory. The sources of the Interface
15854 Units of the library that are needed by an Ada client of the library will be
15855 copied to the designated directory, called the Interface Copy directory.
15856 These sources include the specs of the Interface Units, but they may also
15857 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15858 are used, or when there is a generic unit in the spec. Before the sources
15859 are copied to the Interface Copy directory, an attempt is made to delete all
15860 files in the Interface Copy directory.
15861
15862 Building stand-alone libraries by hand is somewhat tedious, but for those
15863 occasions when it is necessary here are the steps that you need to perform:
15864 @itemize @bullet
15865 @item
15866 Compile all library sources.
15867
15868 @item
15869 Invoke the binder with the switch @option{-n} (No Ada main program),
15870 with all the @file{ALI} files of the interfaces, and
15871 with the switch @option{-L} to give specific names to the @code{init}
15872 and @code{final} procedures.  For example:
15873 @smallexample
15874   gnatbind -n int1.ali int2.ali -Lsal1
15875 @end smallexample
15876
15877 @item
15878 Compile the binder generated file:
15879 @smallexample
15880   gcc -c b~int2.adb
15881 @end smallexample
15882
15883 @item
15884 Link the dynamic library with all the necessary object files,
15885 indicating to the linker the names of the @code{init} (and possibly
15886 @code{final}) procedures for automatic initialization (and finalization).
15887 The built library should be placed in a directory different from
15888 the object directory.
15889
15890 @item
15891 Copy the @code{ALI} files of the interface to the library directory,
15892 add in this copy an indication that it is an interface to a SAL
15893 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15894 with letter ``P'') and make the modified copy of the @file{ALI} file
15895 read-only.
15896 @end itemize
15897
15898 @noindent
15899 Using SALs is not different from using other libraries
15900 (see @ref{Using a library}).
15901
15902 @node Creating a Stand-alone Library to be used in a non-Ada context
15903 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15904
15905 @noindent
15906 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15907 a non-Ada context.
15908
15909 The only extra step required is to ensure that library interface subprograms
15910 are compatible with the main program, by means of @code{pragma Export}
15911 or @code{pragma Convention}.
15912
15913 Here is an example of simple library interface for use with C main program:
15914
15915 @smallexample @c ada
15916 package My_Package is
15917
15918    procedure Do_Something;
15919    pragma Export (C, Do_Something, "do_something");
15920
15921    procedure Do_Something_Else;
15922    pragma Export (C, Do_Something_Else, "do_something_else");
15923
15924 end My_Package;
15925 @end smallexample
15926
15927 @noindent
15928 On the foreign language side, you must provide a ``foreign'' view of the
15929 library interface; remember that it should contain elaboration routines in
15930 addition to interface subprograms.
15931
15932 The example below shows the content of @code{mylib_interface.h} (note
15933 that there is no rule for the naming of this file, any name can be used)
15934 @smallexample
15935 /* the library elaboration procedure */
15936 extern void mylibinit (void);
15937
15938 /* the library finalization procedure */
15939 extern void mylibfinal (void);
15940
15941 /* the interface exported by the library */
15942 extern void do_something (void);
15943 extern void do_something_else (void);
15944 @end smallexample
15945
15946 @noindent
15947 Libraries built as explained above can be used from any program, provided
15948 that the elaboration procedures (named @code{mylibinit} in the previous
15949 example) are called before the library services are used. Any number of
15950 libraries can be used simultaneously, as long as the elaboration
15951 procedure of each library is called.
15952
15953 Below is an example of a C program that uses the @code{mylib} library.
15954
15955 @smallexample
15956 #include "mylib_interface.h"
15957
15958 int
15959 main (void)
15960 @{
15961    /* First, elaborate the library before using it */
15962    mylibinit ();
15963
15964    /* Main program, using the library exported entities */
15965    do_something ();
15966    do_something_else ();
15967
15968    /* Library finalization at the end of the program */
15969    mylibfinal ();
15970    return 0;
15971 @}
15972 @end smallexample
15973
15974 @noindent
15975 Note that invoking any library finalization procedure generated by
15976 @code{gnatbind} shuts down the Ada run-time environment.
15977 Consequently, the
15978 finalization of all Ada libraries must be performed at the end of the program.
15979 No call to these libraries or to the Ada run-time library should be made
15980 after the finalization phase.
15981
15982 @node Restrictions in Stand-alone Libraries
15983 @subsection Restrictions in Stand-alone Libraries
15984
15985 @noindent
15986 The pragmas listed below should be used with caution inside libraries,
15987 as they can create incompatibilities with other Ada libraries:
15988 @itemize @bullet
15989 @item pragma @code{Locking_Policy}
15990 @item pragma @code{Queuing_Policy}
15991 @item pragma @code{Task_Dispatching_Policy}
15992 @item pragma @code{Unreserve_All_Interrupts}
15993 @end itemize
15994
15995 @noindent
15996 When using a library that contains such pragmas, the user must make sure
15997 that all libraries use the same pragmas with the same values. Otherwise,
15998 @code{Program_Error} will
15999 be raised during the elaboration of the conflicting
16000 libraries. The usage of these pragmas and its consequences for the user
16001 should therefore be well documented.
16002
16003 Similarly, the traceback in the exception occurrence mechanism should be
16004 enabled or disabled in a consistent manner across all libraries.
16005 Otherwise, Program_Error will be raised during the elaboration of the
16006 conflicting libraries.
16007
16008 If the @code{Version} or @code{Body_Version}
16009 attributes are used inside a library, then you need to
16010 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16011 libraries, so that version identifiers can be properly computed.
16012 In practice these attributes are rarely used, so this is unlikely
16013 to be a consideration.
16014
16015 @node  Rebuilding the GNAT Run-Time Library
16016 @section Rebuilding the GNAT Run-Time Library
16017 @cindex GNAT Run-Time Library, rebuilding
16018 @cindex Building the GNAT Run-Time Library
16019 @cindex Rebuilding the GNAT Run-Time Library
16020 @cindex Run-Time Library, rebuilding
16021
16022 @noindent
16023 It may be useful to recompile the GNAT library in various contexts, the
16024 most important one being the use of partition-wide configuration pragmas
16025 such as @code{Normalize_Scalars}. A special Makefile called
16026 @code{Makefile.adalib} is provided to that effect and can be found in
16027 the directory containing the GNAT library. The location of this
16028 directory depends on the way the GNAT environment has been installed and can
16029 be determined by means of the command:
16030
16031 @smallexample
16032 $ gnatls -v
16033 @end smallexample
16034
16035 @noindent
16036 The last entry in the object search path usually contains the
16037 gnat library. This Makefile contains its own documentation and in
16038 particular the set of instructions needed to rebuild a new library and
16039 to use it.
16040
16041 @node Using the GNU make Utility
16042 @chapter Using the GNU @code{make} Utility
16043 @findex make
16044
16045 @noindent
16046 This chapter offers some examples of makefiles that solve specific
16047 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16048 make, make, GNU @code{make}}), nor does it try to replace the
16049 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16050
16051 All the examples in this section are specific to the GNU version of
16052 make. Although @command{make} is a standard utility, and the basic language
16053 is the same, these examples use some advanced features found only in
16054 @code{GNU make}.
16055
16056 @menu
16057 * Using gnatmake in a Makefile::
16058 * Automatically Creating a List of Directories::
16059 * Generating the Command Line Switches::
16060 * Overcoming Command Line Length Limits::
16061 @end menu
16062
16063 @node Using gnatmake in a Makefile
16064 @section Using gnatmake in a Makefile
16065 @findex makefile
16066 @cindex GNU make
16067
16068 @noindent
16069 Complex project organizations can be handled in a very powerful way by
16070 using GNU make combined with gnatmake. For instance, here is a Makefile
16071 which allows you to build each subsystem of a big project into a separate
16072 shared library. Such a makefile allows you to significantly reduce the link
16073 time of very big applications while maintaining full coherence at
16074 each step of the build process.
16075
16076 The list of dependencies are handled automatically by
16077 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16078 the appropriate directories.
16079
16080 Note that you should also read the example on how to automatically
16081 create the list of directories
16082 (@pxref{Automatically Creating a List of Directories})
16083 which might help you in case your project has a lot of subdirectories.
16084
16085 @smallexample
16086 @iftex
16087 @leftskip=0cm
16088 @font@heightrm=cmr8
16089 @heightrm
16090 @end iftex
16091 ## This Makefile is intended to be used with the following directory
16092 ## configuration:
16093 ##  - The sources are split into a series of csc (computer software components)
16094 ##    Each of these csc is put in its own directory.
16095 ##    Their name are referenced by the directory names.
16096 ##    They will be compiled into shared library (although this would also work
16097 ##    with static libraries
16098 ##  - The main program (and possibly other packages that do not belong to any
16099 ##    csc is put in the top level directory (where the Makefile is).
16100 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16101 ##                    \_ second_csc (sources) __ lib (will contain the library)
16102 ##                    \_ @dots{}
16103 ## Although this Makefile is build for shared library, it is easy to modify
16104 ## to build partial link objects instead (modify the lines with -shared and
16105 ## gnatlink below)
16106 ##
16107 ## With this makefile, you can change any file in the system or add any new
16108 ## file, and everything will be recompiled correctly (only the relevant shared
16109 ## objects will be recompiled, and the main program will be re-linked).
16110
16111 # The list of computer software component for your project. This might be
16112 # generated automatically.
16113 CSC_LIST=aa bb cc
16114
16115 # Name of the main program (no extension)
16116 MAIN=main
16117
16118 # If we need to build objects with -fPIC, uncomment the following line
16119 #NEED_FPIC=-fPIC
16120
16121 # The following variable should give the directory containing libgnat.so
16122 # You can get this directory through 'gnatls -v'. This is usually the last
16123 # directory in the Object_Path.
16124 GLIB=@dots{}
16125
16126 # The directories for the libraries
16127 # (This macro expands the list of CSC to the list of shared libraries, you
16128 # could simply use the expanded form:
16129 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16130 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16131
16132 $@{MAIN@}: objects $@{LIB_DIR@}
16133     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16134     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16135
16136 objects::
16137     # recompile the sources
16138     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16139
16140 # Note: In a future version of GNAT, the following commands will be simplified
16141 # by a new tool, gnatmlib
16142 $@{LIB_DIR@}:
16143     mkdir -p $@{dir $@@ @}
16144     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16145     cd $@{dir $@@ @} && cp -f ../*.ali .
16146
16147 # The dependencies for the modules
16148 # Note that we have to force the expansion of *.o, since in some cases
16149 # make won't be able to do it itself.
16150 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16151 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16152 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16153
16154 # Make sure all of the shared libraries are in the path before starting the
16155 # program
16156 run::
16157     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16158
16159 clean::
16160     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16161     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16162     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16163     $@{RM@} *.o *.ali $@{MAIN@}
16164 @end smallexample
16165
16166 @node Automatically Creating a List of Directories
16167 @section Automatically Creating a List of Directories
16168
16169 @noindent
16170 In most makefiles, you will have to specify a list of directories, and
16171 store it in a variable. For small projects, it is often easier to
16172 specify each of them by hand, since you then have full control over what
16173 is the proper order for these directories, which ones should be
16174 included.
16175
16176 However, in larger projects, which might involve hundreds of
16177 subdirectories, it might be more convenient to generate this list
16178 automatically.
16179
16180 The example below presents two methods. The first one, although less
16181 general, gives you more control over the list. It involves wildcard
16182 characters, that are automatically expanded by @command{make}. Its
16183 shortcoming is that you need to explicitly specify some of the
16184 organization of your project, such as for instance the directory tree
16185 depth, whether some directories are found in a separate tree, @enddots{}
16186
16187 The second method is the most general one. It requires an external
16188 program, called @command{find}, which is standard on all Unix systems. All
16189 the directories found under a given root directory will be added to the
16190 list.
16191
16192 @smallexample
16193 @iftex
16194 @leftskip=0cm
16195 @font@heightrm=cmr8
16196 @heightrm
16197 @end iftex
16198 # The examples below are based on the following directory hierarchy:
16199 # All the directories can contain any number of files
16200 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16201 #                       ->  ab
16202 #                       ->  ac
16203 #                ->  b  ->  ba  ->  baa
16204 #                       ->  bb
16205 #                       ->  bc
16206 # This Makefile creates a variable called DIRS, that can be reused any time
16207 # you need this list (see the other examples in this section)
16208
16209 # The root of your project's directory hierarchy
16210 ROOT_DIRECTORY=.
16211
16212 ####
16213 # First method: specify explicitly the list of directories
16214 # This allows you to specify any subset of all the directories you need.
16215 ####
16216
16217 DIRS := a/aa/ a/ab/ b/ba/
16218
16219 ####
16220 # Second method: use wildcards
16221 # Note that the argument(s) to wildcard below should end with a '/'.
16222 # Since wildcards also return file names, we have to filter them out
16223 # to avoid duplicate directory names.
16224 # We thus use make's @code{dir} and @code{sort} functions.
16225 # It sets DIRs to the following value (note that the directories aaa and baa
16226 # are not given, unless you change the arguments to wildcard).
16227 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16228 ####
16229
16230 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16231                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16232
16233 ####
16234 # Third method: use an external program
16235 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16236 # This is the most complete command: it sets DIRs to the following value:
16237 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16238 ####
16239
16240 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16241
16242 @end smallexample
16243
16244 @node Generating the Command Line Switches
16245 @section Generating the Command Line Switches
16246
16247 @noindent
16248 Once you have created the list of directories as explained in the
16249 previous section (@pxref{Automatically Creating a List of Directories}),
16250 you can easily generate the command line arguments to pass to gnatmake.
16251
16252 For the sake of completeness, this example assumes that the source path
16253 is not the same as the object path, and that you have two separate lists
16254 of directories.
16255
16256 @smallexample
16257 # see "Automatically creating a list of directories" to create
16258 # these variables
16259 SOURCE_DIRS=
16260 OBJECT_DIRS=
16261
16262 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16263 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16264
16265 all:
16266         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16267 @end smallexample
16268
16269 @node Overcoming Command Line Length Limits
16270 @section Overcoming Command Line Length Limits
16271
16272 @noindent
16273 One problem that might be encountered on big projects is that many
16274 operating systems limit the length of the command line. It is thus hard to give
16275 gnatmake the list of source and object directories.
16276
16277 This example shows how you can set up environment variables, which will
16278 make @command{gnatmake} behave exactly as if the directories had been
16279 specified on the command line, but have a much higher length limit (or
16280 even none on most systems).
16281
16282 It assumes that you have created a list of directories in your Makefile,
16283 using one of the methods presented in
16284 @ref{Automatically Creating a List of Directories}.
16285 For the sake of completeness, we assume that the object
16286 path (where the ALI files are found) is different from the sources patch.
16287
16288 Note a small trick in the Makefile below: for efficiency reasons, we
16289 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16290 expanded immediately by @code{make}. This way we overcome the standard
16291 make behavior which is to expand the variables only when they are
16292 actually used.
16293
16294 On Windows, if you are using the standard Windows command shell, you must
16295 replace colons with semicolons in the assignments to these variables.
16296
16297 @smallexample
16298 @iftex
16299 @leftskip=0cm
16300 @font@heightrm=cmr8
16301 @heightrm
16302 @end iftex
16303 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16304 # This is the same thing as putting the -I arguments on the command line.
16305 # (the equivalent of using -aI on the command line would be to define
16306 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16307 # You can of course have different values for these variables.
16308 #
16309 # Note also that we need to keep the previous values of these variables, since
16310 # they might have been set before running 'make' to specify where the GNAT
16311 # library is installed.
16312
16313 # see "Automatically creating a list of directories" to create these
16314 # variables
16315 SOURCE_DIRS=
16316 OBJECT_DIRS=
16317
16318 empty:=
16319 space:=$@{empty@} $@{empty@}
16320 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16321 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16322 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16323 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16324 export ADA_INCLUDE_PATH
16325 export ADA_OBJECT_PATH
16326
16327 all:
16328         gnatmake main_unit
16329 @end smallexample
16330 @end ifclear
16331
16332 @node Memory Management Issues
16333 @chapter Memory Management Issues
16334
16335 @noindent
16336 This chapter describes some useful memory pools provided in the GNAT library
16337 and in particular the GNAT Debug Pool facility, which can be used to detect
16338 incorrect uses of access values (including ``dangling references'').
16339 @ifclear vms
16340 It also describes the @command{gnatmem} tool, which can be used to track down
16341 ``memory leaks''.
16342 @end ifclear
16343
16344 @menu
16345 * Some Useful Memory Pools::
16346 * The GNAT Debug Pool Facility::
16347 @ifclear vms
16348 * The gnatmem Tool::
16349 @end ifclear
16350 @end menu
16351
16352 @node Some Useful Memory Pools
16353 @section Some Useful Memory Pools
16354 @findex Memory Pool
16355 @cindex storage, pool
16356
16357 @noindent
16358 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16359 storage pool. Allocations use the standard system call @code{malloc} while
16360 deallocations use the standard system call @code{free}. No reclamation is
16361 performed when the pool goes out of scope. For performance reasons, the
16362 standard default Ada allocators/deallocators do not use any explicit storage
16363 pools but if they did, they could use this storage pool without any change in
16364 behavior. That is why this storage pool is used  when the user
16365 manages to make the default implicit allocator explicit as in this example:
16366 @smallexample @c ada
16367    type T1 is access Something;
16368     -- no Storage pool is defined for T2
16369    type T2 is access Something_Else;
16370    for T2'Storage_Pool use T1'Storage_Pool;
16371    -- the above is equivalent to
16372    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16373 @end smallexample
16374
16375 @noindent
16376 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16377 pool. The allocation strategy is similar to @code{Pool_Local}'s
16378 except that the all
16379 storage allocated with this pool is reclaimed when the pool object goes out of
16380 scope. This pool provides a explicit mechanism similar to the implicit one
16381 provided by several Ada 83 compilers for allocations performed through a local
16382 access type and whose purpose was to reclaim memory when exiting the
16383 scope of a given local access. As an example, the following program does not
16384 leak memory even though it does not perform explicit deallocation:
16385
16386 @smallexample @c ada
16387 with System.Pool_Local;
16388 procedure Pooloc1 is
16389    procedure Internal is
16390       type A is access Integer;
16391       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16392       for A'Storage_Pool use X;
16393       v : A;
16394    begin
16395       for I in  1 .. 50 loop
16396          v := new Integer;
16397       end loop;
16398    end Internal;
16399 begin
16400    for I in  1 .. 100 loop
16401       Internal;
16402    end loop;
16403 end Pooloc1;
16404 @end smallexample
16405
16406 @noindent
16407 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16408 @code{Storage_Size} is specified for an access type.
16409 The whole storage for the pool is
16410 allocated at once, usually on the stack at the point where the access type is
16411 elaborated. It is automatically reclaimed when exiting the scope where the
16412 access type is defined. This package is not intended to be used directly by the
16413 user and it is implicitly used for each such declaration:
16414
16415 @smallexample @c ada
16416    type T1 is access Something;
16417    for T1'Storage_Size use 10_000;
16418 @end smallexample
16419
16420 @node The GNAT Debug Pool Facility
16421 @section The GNAT Debug Pool Facility
16422 @findex Debug Pool
16423 @cindex storage, pool, memory corruption
16424
16425 @noindent
16426 The use of unchecked deallocation and unchecked conversion can easily
16427 lead to incorrect memory references. The problems generated by such
16428 references are usually difficult to tackle because the symptoms can be
16429 very remote from the origin of the problem. In such cases, it is
16430 very helpful to detect the problem as early as possible. This is the
16431 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16432
16433 In order to use the GNAT specific debugging pool, the user must
16434 associate a debug pool object with each of the access types that may be
16435 related to suspected memory problems. See Ada Reference Manual 13.11.
16436 @smallexample @c ada
16437 type Ptr is access Some_Type;
16438 Pool : GNAT.Debug_Pools.Debug_Pool;
16439 for Ptr'Storage_Pool use Pool;
16440 @end smallexample
16441
16442 @noindent
16443 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16444 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16445 allow the user to redefine allocation and deallocation strategies. They
16446 also provide a checkpoint for each dereference, through the use of
16447 the primitive operation @code{Dereference} which is implicitly called at
16448 each dereference of an access value.
16449
16450 Once an access type has been associated with a debug pool, operations on
16451 values of the type may raise four distinct exceptions,
16452 which correspond to four potential kinds of memory corruption:
16453 @itemize @bullet
16454 @item
16455 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16456 @item
16457 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16458 @item
16459 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16460 @item
16461 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16462 @end itemize
16463
16464 @noindent
16465 For types associated with a Debug_Pool, dynamic allocation is performed using
16466 the standard GNAT allocation routine. References to all allocated chunks of
16467 memory are kept in an internal dictionary. Several deallocation strategies are
16468 provided, whereupon the user can choose to release the memory to the system,
16469 keep it allocated for further invalid access checks, or fill it with an easily
16470 recognizable pattern for debug sessions. The memory pattern is the old IBM
16471 hexadecimal convention: @code{16#DEADBEEF#}.
16472
16473 See the documentation in the file g-debpoo.ads for more information on the
16474 various strategies.
16475
16476 Upon each dereference, a check is made that the access value denotes a
16477 properly allocated memory location. Here is a complete example of use of
16478 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16479 @smallexample @c ada
16480 @iftex
16481 @leftskip=0cm
16482 @end iftex
16483 with Gnat.Io; use Gnat.Io;
16484 with Unchecked_Deallocation;
16485 with Unchecked_Conversion;
16486 with GNAT.Debug_Pools;
16487 with System.Storage_Elements;
16488 with Ada.Exceptions; use Ada.Exceptions;
16489 procedure Debug_Pool_Test is
16490
16491    type T is access Integer;
16492    type U is access all T;
16493
16494    P : GNAT.Debug_Pools.Debug_Pool;
16495    for T'Storage_Pool use P;
16496
16497    procedure Free is new Unchecked_Deallocation (Integer, T);
16498    function UC is new Unchecked_Conversion (U, T);
16499    A, B : aliased T;
16500
16501    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16502
16503 begin
16504    Info (P);
16505    A := new Integer;
16506    B := new Integer;
16507    B := A;
16508    Info (P);
16509    Free (A);
16510    begin
16511       Put_Line (Integer'Image(B.all));
16512    exception
16513       when E : others => Put_Line ("raised: " & Exception_Name (E));
16514    end;
16515    begin
16516       Free (B);
16517    exception
16518       when E : others => Put_Line ("raised: " & Exception_Name (E));
16519    end;
16520    B := UC(A'Access);
16521    begin
16522       Put_Line (Integer'Image(B.all));
16523    exception
16524       when E : others => Put_Line ("raised: " & Exception_Name (E));
16525    end;
16526    begin
16527       Free (B);
16528    exception
16529       when E : others => Put_Line ("raised: " & Exception_Name (E));
16530    end;
16531    Info (P);
16532 end Debug_Pool_Test;
16533 @end smallexample
16534
16535 @noindent
16536 The debug pool mechanism provides the following precise diagnostics on the
16537 execution of this erroneous program:
16538 @smallexample
16539 Debug Pool info:
16540   Total allocated bytes :  0
16541   Total deallocated bytes :  0
16542   Current Water Mark:  0
16543   High Water Mark:  0
16544
16545 Debug Pool info:
16546   Total allocated bytes :  8
16547   Total deallocated bytes :  0
16548   Current Water Mark:  8
16549   High Water Mark:  8
16550
16551 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16552 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16553 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16554 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16555 Debug Pool info:
16556   Total allocated bytes :  8
16557   Total deallocated bytes :  4
16558   Current Water Mark:  4
16559   High Water Mark:  8
16560 @end smallexample
16561
16562 @ifclear vms
16563 @node The gnatmem Tool
16564 @section The @command{gnatmem} Tool
16565 @findex gnatmem
16566
16567 @noindent
16568 The @code{gnatmem} utility monitors dynamic allocation and
16569 deallocation activity in a program, and displays information about
16570 incorrect deallocations and possible sources of memory leaks.
16571 It is designed to work in association with a static runtime library
16572 only and in this context provides three types of information:
16573 @itemize @bullet
16574 @item
16575 General information concerning memory management, such as the total
16576 number of allocations and deallocations, the amount of allocated
16577 memory and the high water mark, i.e.@: the largest amount of allocated
16578 memory in the course of program execution.
16579
16580 @item
16581 Backtraces for all incorrect deallocations, that is to say deallocations
16582 which do not correspond to a valid allocation.
16583
16584 @item
16585 Information on each allocation that is potentially the origin of a memory
16586 leak.
16587 @end itemize
16588
16589 @menu
16590 * Running gnatmem::
16591 * Switches for gnatmem::
16592 * Example of gnatmem Usage::
16593 @end menu
16594
16595 @node Running gnatmem
16596 @subsection Running @code{gnatmem}
16597
16598 @noindent
16599 @code{gnatmem} makes use of the output created by the special version of
16600 allocation and deallocation routines that record call information. This
16601 allows to obtain accurate dynamic memory usage history at a minimal cost to
16602 the execution speed. Note however, that @code{gnatmem} is not supported on
16603 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16604 Solaris and Windows NT/2000/XP (x86).
16605
16606 @noindent
16607 The @code{gnatmem} command has the form
16608
16609 @smallexample
16610 @c    $ gnatmem @ovar{switches} user_program
16611 @c Expanding @ovar macro inline (explanation in macro def comments)
16612       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16613 @end smallexample
16614
16615 @noindent
16616 The program must have been linked with the instrumented version of the
16617 allocation and deallocation routines. This is done by linking with the
16618 @file{libgmem.a} library. For correct symbolic backtrace information,
16619 the user program should be compiled with debugging options
16620 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16621
16622 @smallexample
16623 $ gnatmake -g my_program -largs -lgmem
16624 @end smallexample
16625
16626 @noindent
16627 As library @file{libgmem.a} contains an alternate body for package
16628 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16629 when an executable is linked with library @file{libgmem.a}. It is then not
16630 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16631
16632 @noindent
16633 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16634 This file contains information about all allocations and deallocations
16635 performed by the program. It is produced by the instrumented allocations and
16636 deallocations routines and will be used by @code{gnatmem}.
16637
16638 In order to produce symbolic backtrace information for allocations and
16639 deallocations performed by the GNAT run-time library, you need to use a
16640 version of that library that has been compiled with the @option{-g} switch
16641 (see @ref{Rebuilding the GNAT Run-Time Library}).
16642
16643 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16644 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16645 @option{-i} switch, gnatmem will assume that this file can be found in the
16646 current directory. For example, after you have executed @file{my_program},
16647 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16648
16649 @smallexample
16650 $ gnatmem my_program
16651 @end smallexample
16652
16653 @noindent
16654 This will produce the output with the following format:
16655
16656 *************** debut cc
16657 @smallexample
16658 $ gnatmem my_program
16659
16660 Global information
16661 ------------------
16662    Total number of allocations        :  45
16663    Total number of deallocations      :   6
16664    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16665    High Water Mark                    :  11.40 Kilobytes
16666
16667 .
16668 .
16669 .
16670 Allocation Root # 2
16671 -------------------
16672  Number of non freed allocations    :  11
16673  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16674  High Water Mark                    :   1.27 Kilobytes
16675  Backtrace                          :
16676    my_program.adb:23 my_program.alloc
16677 .
16678 .
16679 .
16680 @end smallexample
16681
16682 The first block of output gives general information. In this case, the
16683 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16684 Unchecked_Deallocation routine occurred.
16685
16686 @noindent
16687 Subsequent paragraphs display  information on all allocation roots.
16688 An allocation root is a specific point in the execution of the program
16689 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16690 construct. This root is represented by an execution backtrace (or subprogram
16691 call stack). By default the backtrace depth for allocations roots is 1, so
16692 that a root corresponds exactly to a source location. The backtrace can
16693 be made deeper, to make the root more specific.
16694
16695 @node Switches for gnatmem
16696 @subsection Switches for @code{gnatmem}
16697
16698 @noindent
16699 @code{gnatmem} recognizes the following switches:
16700
16701 @table @option
16702
16703 @item -q
16704 @cindex @option{-q} (@code{gnatmem})
16705 Quiet. Gives the minimum output needed to identify the origin of the
16706 memory leaks. Omits statistical information.
16707
16708 @item @var{N}
16709 @cindex @var{N} (@code{gnatmem})
16710 N is an integer literal (usually between 1 and 10) which controls the
16711 depth of the backtraces defining allocation root. The default value for
16712 N is 1. The deeper the backtrace, the more precise the localization of
16713 the root. Note that the total number of roots can depend on this
16714 parameter. This parameter must be specified @emph{before} the name of the
16715 executable to be analyzed, to avoid ambiguity.
16716
16717 @item -b n
16718 @cindex @option{-b} (@code{gnatmem})
16719 This switch has the same effect as just depth parameter.
16720
16721 @item -i @var{file}
16722 @cindex @option{-i} (@code{gnatmem})
16723 Do the @code{gnatmem} processing starting from @file{file}, rather than
16724 @file{gmem.out} in the current directory.
16725
16726 @item -m n
16727 @cindex @option{-m} (@code{gnatmem})
16728 This switch causes @code{gnatmem} to mask the allocation roots that have less
16729 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16730 examine even the roots that didn't result in leaks.
16731
16732 @item -s order
16733 @cindex @option{-s} (@code{gnatmem})
16734 This switch causes @code{gnatmem} to sort the allocation roots according to the
16735 specified order of sort criteria, each identified by a single letter. The
16736 currently supported criteria are @code{n, h, w} standing respectively for
16737 number of unfreed allocations, high watermark, and final watermark
16738 corresponding to a specific root. The default order is @code{nwh}.
16739
16740 @end table
16741
16742 @node Example of gnatmem Usage
16743 @subsection Example of @code{gnatmem} Usage
16744
16745 @noindent
16746 The following example shows the use of @code{gnatmem}
16747 on a simple memory-leaking program.
16748 Suppose that we have the following Ada program:
16749
16750 @smallexample @c ada
16751 @group
16752 @cartouche
16753 with Unchecked_Deallocation;
16754 procedure Test_Gm is
16755
16756    type T is array (1..1000) of Integer;
16757    type Ptr is access T;
16758    procedure Free is new Unchecked_Deallocation (T, Ptr);
16759    A : Ptr;
16760
16761    procedure My_Alloc is
16762    begin
16763       A := new T;
16764    end My_Alloc;
16765
16766    procedure My_DeAlloc is
16767       B : Ptr := A;
16768    begin
16769       Free (B);
16770    end My_DeAlloc;
16771
16772 begin
16773    My_Alloc;
16774    for I in 1 .. 5 loop
16775       for J in I .. 5 loop
16776          My_Alloc;
16777       end loop;
16778       My_Dealloc;
16779    end loop;
16780 end;
16781 @end cartouche
16782 @end group
16783 @end smallexample
16784
16785 @noindent
16786 The program needs to be compiled with debugging option and linked with
16787 @code{gmem} library:
16788
16789 @smallexample
16790 $ gnatmake -g test_gm -largs -lgmem
16791 @end smallexample
16792
16793 @noindent
16794 Then we execute the program as usual:
16795
16796 @smallexample
16797 $ test_gm
16798 @end smallexample
16799
16800 @noindent
16801 Then @code{gnatmem} is invoked simply with
16802 @smallexample
16803 $ gnatmem test_gm
16804 @end smallexample
16805
16806 @noindent
16807 which produces the following output (result may vary on different platforms):
16808
16809 @smallexample
16810 Global information
16811 ------------------
16812    Total number of allocations        :  18
16813    Total number of deallocations      :   5
16814    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16815    High Water Mark                    :  56.90 Kilobytes
16816
16817 Allocation Root # 1
16818 -------------------
16819  Number of non freed allocations    :  11
16820  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16821  High Water Mark                    :  46.88 Kilobytes
16822  Backtrace                          :
16823    test_gm.adb:11 test_gm.my_alloc
16824
16825 Allocation Root # 2
16826 -------------------
16827  Number of non freed allocations    :   1
16828  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16829  High Water Mark                    :  10.02 Kilobytes
16830  Backtrace                          :
16831    s-secsta.adb:81 system.secondary_stack.ss_init
16832
16833 Allocation Root # 3
16834 -------------------
16835  Number of non freed allocations    :   1
16836  Final Water Mark (non freed mem)   :  12 Bytes
16837  High Water Mark                    :  12 Bytes
16838  Backtrace                          :
16839    s-secsta.adb:181 system.secondary_stack.ss_init
16840 @end smallexample
16841
16842 @noindent
16843 Note that the GNAT run time contains itself a certain number of
16844 allocations that have no  corresponding deallocation,
16845 as shown here for root #2 and root
16846 #3. This is a normal behavior when the number of non-freed allocations
16847 is one, it allocates dynamic data structures that the run time needs for
16848 the complete lifetime of the program. Note also that there is only one
16849 allocation root in the user program with a single line back trace:
16850 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16851 program shows that 'My_Alloc' is called at 2 different points in the
16852 source (line 21 and line 24). If those two allocation roots need to be
16853 distinguished, the backtrace depth parameter can be used:
16854
16855 @smallexample
16856 $ gnatmem 3 test_gm
16857 @end smallexample
16858
16859 @noindent
16860 which will give the following output:
16861
16862 @smallexample
16863 Global information
16864 ------------------
16865    Total number of allocations        :  18
16866    Total number of deallocations      :   5
16867    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16868    High Water Mark                    :  56.90 Kilobytes
16869
16870 Allocation Root # 1
16871 -------------------
16872  Number of non freed allocations    :  10
16873  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16874  High Water Mark                    :  42.97 Kilobytes
16875  Backtrace                          :
16876    test_gm.adb:11 test_gm.my_alloc
16877    test_gm.adb:24 test_gm
16878    b_test_gm.c:52 main
16879
16880 Allocation Root # 2
16881 -------------------
16882  Number of non freed allocations    :   1
16883  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16884  High Water Mark                    :  10.02 Kilobytes
16885  Backtrace                          :
16886    s-secsta.adb:81  system.secondary_stack.ss_init
16887    s-secsta.adb:283 <system__secondary_stack___elabb>
16888    b_test_gm.c:33   adainit
16889
16890 Allocation Root # 3
16891 -------------------
16892  Number of non freed allocations    :   1
16893  Final Water Mark (non freed mem)   :   3.91 Kilobytes
16894  High Water Mark                    :   3.91 Kilobytes
16895  Backtrace                          :
16896    test_gm.adb:11 test_gm.my_alloc
16897    test_gm.adb:21 test_gm
16898    b_test_gm.c:52 main
16899
16900 Allocation Root # 4
16901 -------------------
16902  Number of non freed allocations    :   1
16903  Final Water Mark (non freed mem)   :  12 Bytes
16904  High Water Mark                    :  12 Bytes
16905  Backtrace                          :
16906    s-secsta.adb:181 system.secondary_stack.ss_init
16907    s-secsta.adb:283 <system__secondary_stack___elabb>
16908    b_test_gm.c:33   adainit
16909 @end smallexample
16910
16911 @noindent
16912 The allocation root #1 of the first example has been split in 2 roots #1
16913 and #3 thanks to the more precise associated backtrace.
16914
16915 @end ifclear
16916
16917 @node Stack Related Facilities
16918 @chapter Stack Related Facilities
16919
16920 @noindent
16921 This chapter describes some useful tools associated with stack
16922 checking and analysis. In
16923 particular, it deals with dynamic and static stack usage measurements.
16924
16925 @menu
16926 * Stack Overflow Checking::
16927 * Static Stack Usage Analysis::
16928 * Dynamic Stack Usage Analysis::
16929 @end menu
16930
16931 @node Stack Overflow Checking
16932 @section Stack Overflow Checking
16933 @cindex Stack Overflow Checking
16934 @cindex -fstack-check
16935
16936 @noindent
16937 For most operating systems, @command{gcc} does not perform stack overflow
16938 checking by default. This means that if the main environment task or
16939 some other task exceeds the available stack space, then unpredictable
16940 behavior will occur. Most native systems offer some level of protection by
16941 adding a guard page at the end of each task stack. This mechanism is usually
16942 not enough for dealing properly with stack overflow situations because
16943 a large local variable could ``jump'' above the guard page.
16944 Furthermore, when the
16945 guard page is hit, there may not be any space left on the stack for executing
16946 the exception propagation code. Enabling stack checking avoids
16947 such situations.
16948
16949 To activate stack checking, compile all units with the gcc option
16950 @option{-fstack-check}. For example:
16951
16952 @smallexample
16953 gcc -c -fstack-check package1.adb
16954 @end smallexample
16955
16956 @noindent
16957 Units compiled with this option will generate extra instructions to check
16958 that any use of the stack (for procedure calls or for declaring local
16959 variables in declare blocks) does not exceed the available stack space.
16960 If the space is exceeded, then a @code{Storage_Error} exception is raised.
16961
16962 For declared tasks, the stack size is controlled by the size
16963 given in an applicable @code{Storage_Size} pragma or by the value specified
16964 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
16965 the default size as defined in the GNAT runtime otherwise.
16966
16967 For the environment task, the stack size depends on
16968 system defaults and is unknown to the compiler. Stack checking
16969 may still work correctly if a fixed
16970 size stack is allocated, but this cannot be guaranteed.
16971 @ifclear vms
16972 To ensure that a clean exception is signalled for stack
16973 overflow, set the environment variable
16974 @env{GNAT_STACK_LIMIT} to indicate the maximum
16975 stack area that can be used, as in:
16976 @cindex GNAT_STACK_LIMIT
16977
16978 @smallexample
16979 SET GNAT_STACK_LIMIT 1600
16980 @end smallexample
16981
16982 @noindent
16983 The limit is given in kilobytes, so the above declaration would
16984 set the stack limit of the environment task to 1.6 megabytes.
16985 Note that the only purpose of this usage is to limit the amount
16986 of stack used by the environment task. If it is necessary to
16987 increase the amount of stack for the environment task, then this
16988 is an operating systems issue, and must be addressed with the
16989 appropriate operating systems commands.
16990 @end ifclear
16991 @ifset vms
16992 To have a fixed size stack in the environment task, the stack must be put
16993 in the P0 address space and its size specified.  Use these switches to
16994 create a p0 image:
16995
16996 @smallexample
16997 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
16998 @end smallexample
16999
17000 @noindent
17001 The quotes are required to keep case.  The number after @samp{STACK=} is the
17002 size of the environmental task stack in pagelets (512 bytes).  In this example
17003 the stack size is about 2 megabytes.
17004
17005 @noindent
17006 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17007 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17008 more details about the @option{/p0image} qualifier and the @option{stack}
17009 option.
17010 @end ifset
17011
17012 @node Static Stack Usage Analysis
17013 @section Static Stack Usage Analysis
17014 @cindex Static Stack Usage Analysis
17015 @cindex -fstack-usage
17016
17017 @noindent
17018 A unit compiled with @option{-fstack-usage} will generate an extra file
17019 that specifies
17020 the maximum amount of stack used, on a per-function basis.
17021 The file has the same
17022 basename as the target object file with a @file{.su} extension.
17023 Each line of this file is made up of three fields:
17024
17025 @itemize
17026 @item
17027 The name of the function.
17028 @item
17029 A number of bytes.
17030 @item
17031 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17032 @end itemize
17033
17034 The second field corresponds to the size of the known part of the function
17035 frame.
17036
17037 The qualifier @code{static} means that the function frame size
17038 is purely static.
17039 It usually means that all local variables have a static size.
17040 In this case, the second field is a reliable measure of the function stack
17041 utilization.
17042
17043 The qualifier @code{dynamic} means that the function frame size is not static.
17044 It happens mainly when some local variables have a dynamic size. When this
17045 qualifier appears alone, the second field is not a reliable measure
17046 of the function stack analysis. When it is qualified with  @code{bounded}, it
17047 means that the second field is a reliable maximum of the function stack
17048 utilization.
17049
17050 @node Dynamic Stack Usage Analysis
17051 @section Dynamic Stack Usage Analysis
17052
17053 @noindent
17054 It is possible to measure the maximum amount of stack used by a task, by
17055 adding a switch to @command{gnatbind}, as:
17056
17057 @smallexample
17058 $ gnatbind -u0 file
17059 @end smallexample
17060
17061 @noindent
17062 With this option, at each task termination, its stack usage is  output on
17063 @file{stderr}.
17064 It is not always convenient to output the stack usage when the program
17065 is still running. Hence, it is possible to delay this output until program
17066 termination. for a given number of tasks specified as the argument of the
17067 @option{-u} option. For instance:
17068
17069 @smallexample
17070 $ gnatbind -u100 file
17071 @end smallexample
17072
17073 @noindent
17074 will buffer the stack usage information of the first 100 tasks to terminate and
17075 output this info at program termination. Results are displayed in four
17076 columns:
17077
17078 @noindent
17079 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17080
17081 @noindent
17082 where:
17083
17084 @table @emph
17085 @item Index
17086 is a number associated with each task.
17087
17088 @item Task Name
17089 is the name of the task analyzed.
17090
17091 @item Stack Size
17092 is the maximum size for the stack.
17093
17094 @item Stack Usage
17095 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17096 is not entirely analyzed, and it's not possible to know exactly how
17097 much has actually been used. The report thus contains the theoretical stack usage
17098 (Value) and the possible variation (Variation) around this value.
17099
17100 @end table
17101
17102 @noindent
17103 The environment task stack, e.g., the stack that contains the main unit, is
17104 only processed when the environment variable GNAT_STACK_LIMIT is set.
17105
17106
17107 @c *********************************
17108 @c *            GNATCHECK          *
17109 @c *********************************
17110 @node Verifying Properties Using gnatcheck
17111 @chapter Verifying Properties Using @command{gnatcheck}
17112 @findex gnatcheck
17113 @cindex @command{gnatcheck}
17114
17115 @noindent
17116 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17117 of Ada source files according to a given set of semantic rules.
17118 @cindex ASIS
17119
17120 In order to check compliance with a given rule, @command{gnatcheck} has to
17121 semantically analyze the Ada sources.
17122 Therefore, checks can only be performed on
17123 legal Ada units. Moreover, when a unit depends semantically upon units located
17124 outside the current directory, the source search path has to be provided when
17125 calling @command{gnatcheck}, either through a specified project file or
17126 through @command{gnatcheck} switches as described below.
17127
17128 A number of rules are predefined in @command{gnatcheck} and are described
17129 later in this chapter.
17130 You can also add new rules, by modifying the @command{gnatcheck} code and
17131 rebuilding the tool. In order to add a simple rule making some local checks,
17132 a small amount of straightforward ASIS-based programming is usually needed.
17133
17134 Project support for @command{gnatcheck} is provided by the GNAT
17135 driver (see @ref{The GNAT Driver and Project Files}).
17136
17137 Invoking @command{gnatcheck} on the command line has the form:
17138
17139 @smallexample
17140 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
17141 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17142 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17143 @c Expanding @ovar macro inline (explanation in macro def comments)
17144 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
17145       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17146       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17147 @end smallexample
17148
17149 @noindent
17150 where
17151 @itemize @bullet
17152 @item
17153 @var{switches} specify the general tool options
17154
17155 @item
17156 Each @var{filename} is the name (including the extension) of a source
17157 file to process. ``Wildcards'' are allowed, and
17158 the file name may contain path information.
17159
17160 @item
17161 Each @var{arg_list_filename} is the name (including the extension) of a text
17162 file containing the names of the source files to process, separated by spaces
17163 or line breaks.
17164
17165 @item
17166 @var{gcc_switches} is a list of switches for
17167 @command{gcc}. They will be passed on to all compiler invocations made by
17168 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17169 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17170 and use the @option{-gnatec} switch to set the configuration file.
17171
17172 @item
17173 @var{rule_options} is a list of options for controlling a set of
17174 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17175 @end itemize
17176
17177 @noindent
17178 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17179 supplied.
17180
17181 @menu
17182 * Format of the Report File::
17183 * General gnatcheck Switches::
17184 * gnatcheck Rule Options::
17185 * Adding the Results of Compiler Checks to gnatcheck Output::
17186 * Project-Wide Checks::
17187 * Rule exemption::
17188 * Predefined Rules::
17189 * Example of gnatcheck Usage::
17190 @end menu
17191
17192 @node Format of the Report File
17193 @section Format of the Report File
17194 @cindex Report file (for @code{gnatcheck})
17195
17196 @noindent
17197 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17198 rule violations.
17199 It also creates a text file  that
17200 contains the complete report of the last gnatcheck run. By default this file
17201 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17202 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17203 name and/or location of the report file. This report contains:
17204 @itemize @bullet
17205 @item date and time of @command{gnatcheck} run, the version of
17206 the tool that has generated this report and the full parameters
17207 of the  @command{gnatcheck} invocation;
17208 @item list of enabled rules;
17209 @item total number of detected violations;
17210 @item list of source files where rule violations have been detected;
17211 @item list of source files where no violations have been detected.
17212 @end itemize
17213
17214 @node General gnatcheck Switches
17215 @section General @command{gnatcheck} Switches
17216
17217 @noindent
17218 The following switches control the general @command{gnatcheck} behavior
17219
17220 @table @option
17221 @c !sort!
17222 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17223 @item ^-a^/ALL^
17224 Process all units including those with read-only ALI files such as
17225 those from the GNAT Run-Time library.
17226
17227 @ifclear vms
17228 @ignore
17229 @cindex @option{-d} (@command{gnatcheck})
17230 @item -d
17231 Debug mode
17232 @end ignore
17233
17234 @cindex @option{-dd} (@command{gnatcheck})
17235 @item -dd
17236 Progress indicator mode (for use in GPS).
17237 @end ifclear
17238
17239 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17240 @item ^-h^/HELP^
17241 List the predefined and user-defined rules. For more details see
17242 @ref{Predefined Rules}.
17243
17244 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17245 @item ^-l^/LOCS^
17246 Use full source locations references in the report file. For a construct from
17247 a generic instantiation a full source location is a chain from the location
17248 of this construct in the generic unit to the place where this unit is
17249 instantiated.
17250
17251 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17252 @item ^-log^/LOG^
17253 Duplicate all the output sent to @file{stderr} into a log file. The log file
17254 is named @file{gnatcheck.log} and is located in the current directory.
17255
17256 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17257 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17258 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17259 the range 0@dots{}1000;
17260 the default value is 500. Zero means that there is no limitation on
17261 the number of diagnostic messages to be output.
17262
17263 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17264 @item ^-q^/QUIET^
17265 Quiet mode. All the diagnostics about rule violations are placed in the
17266 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17267
17268 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17269 @item ^-s^/SHORT^
17270 Short format of the report file (no version information, no list of applied
17271 rules, no list of checked sources is included)
17272
17273 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17274 @item ^--include-file^/INCLUDE_FILE^
17275 Append the content of the specified text file to the report file
17276
17277 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17278 @item ^-t^/TIME^
17279 Print out execution time.
17280
17281 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17282 @item ^-v^/VERBOSE^
17283 Verbose mode; @command{gnatcheck} generates version information and then
17284 a trace of sources being processed.
17285
17286 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17287 @item ^-o ^/OUTPUT=^@var{report_file}
17288 Set name of report file file to @var{report_file} .
17289
17290 @end table
17291
17292 @node gnatcheck Rule Options
17293 @section @command{gnatcheck} Rule Options
17294
17295 @noindent
17296 The following options control the processing performed by
17297 @command{gnatcheck}.
17298
17299 @table @option
17300 @cindex @option{+ALL} (@command{gnatcheck})
17301 @item +ALL
17302 Turn all the rule checks ON.
17303
17304 @cindex @option{-ALL} (@command{gnatcheck})
17305 @item -ALL
17306 Turn all the rule checks OFF.
17307
17308 @cindex @option{+R} (@command{gnatcheck})
17309 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17310 Turn on the check for a specified rule with the specified parameter, if any.
17311 @var{rule_id} must be the identifier of one of the currently implemented rules
17312 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17313 are not case-sensitive. The @var{param} item must
17314 be a string representing a valid parameter(s) for the specified rule.
17315 If it contains any space characters then this string must be enclosed in
17316 quotation marks.
17317
17318 @cindex @option{-R} (@command{gnatcheck})
17319 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17320 Turn off the check for a specified rule with the specified parameter, if any.
17321
17322 @cindex @option{-from} (@command{gnatcheck})
17323 @item -from=@var{rule_option_filename}
17324 Read the rule options from the text file @var{rule_option_filename}, referred
17325 to as a ``coding standard file'' below.
17326
17327 @end table
17328
17329 @noindent
17330 The default behavior is that all the rule checks are disabled.
17331
17332 A coding standard file is a text file that contains a set of rule options
17333 described above.
17334 @cindex Coding standard file (for @code{gnatcheck})
17335 The file may contain empty lines and Ada-style comments (comment
17336 lines and end-of-line comments). There can be several rule options on a
17337 single line (separated by a space).
17338
17339 A coding standard file may reference other coding standard files by including
17340 more @option{-from=@var{rule_option_filename}}
17341 options, each such option being replaced with the content of the
17342 corresponding coding standard file during processing. In case a
17343 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17344 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17345 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17346 processing fails with an error message.
17347
17348
17349 @node Adding the Results of Compiler Checks to gnatcheck Output
17350 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17351
17352 @noindent
17353 The @command{gnatcheck} tool can include in the generated diagnostic messages
17354 and in
17355 the report file the results of the checks performed by the compiler. Though
17356 disabled by default, this effect may be obtained by using @option{+R} with
17357 the following rule identifiers and parameters:
17358
17359 @table @option
17360 @item Restrictions
17361 To record restrictions violations (which are performed by the compiler if the
17362 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17363 use the @code{Restrictions} rule
17364 with the same parameters as pragma
17365 @code{Restrictions} or @code{Restriction_Warnings}.
17366
17367 @item Style_Checks
17368 To record compiler style checks (@pxref{Style Checking}), use the
17369 @code{Style_Checks} rule.
17370 This rule takes a parameter in one of the following forms:
17371 @itemize
17372 @item
17373 @code{All_Checks},
17374 which enables the standard style checks corresponding to the @option{-gnatyy}
17375 GNAT style check option, or
17376
17377 @item
17378 a string with the same
17379 structure and semantics as the @code{string_LITERAL} parameter of the
17380 GNAT pragma @code{Style_Checks}
17381 (for further information about this pragma,
17382 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17383 @end itemize
17384
17385 @noindent
17386 For example, the
17387 @code{+RStyle_Checks:O} rule option activates
17388 the compiler style check that corresponds to
17389 @code{-gnatyO} style check option.
17390
17391 @item Warnings
17392 To record compiler warnings (@pxref{Warning Message Control}), use the
17393 @code{Warnings} rule with a parameter that is a valid
17394 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17395 (for further information about this pragma,
17396 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17397 Note that in case of gnatcheck
17398 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17399 all the specific warnings, but not suppresses the warning mode,
17400 and 'e' parameter, corresponding to @option{-gnatwe} that means
17401 "treat warnings as errors", does not have any effect.
17402
17403 @end table
17404
17405 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17406 option with the corresponding restriction name as a parameter. @code{-R} is
17407 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17408 warnings and style checks, use the corresponding warning and style options.
17409
17410 @node Project-Wide Checks
17411 @section Project-Wide Checks
17412 @cindex Project-wide checks (for @command{gnatcheck})
17413
17414 @noindent
17415 In order to perform checks on all units of a given project, you can use
17416 the GNAT driver along with the @option{-P} option:
17417 @smallexample
17418    gnat check -Pproj -rules -from=my_rules
17419 @end smallexample
17420
17421 @noindent
17422 If the project @code{proj} depends upon other projects, you can perform
17423 checks on the project closure using the @option{-U} option:
17424 @smallexample
17425    gnat check -Pproj -U -rules -from=my_rules
17426 @end smallexample
17427
17428 @noindent
17429 Finally, if not all the units are relevant to a particular main
17430 program in the project closure, you can perform checks for the set
17431 of units needed to create a given main program (unit closure) using
17432 the @option{-U} option followed by the name of the main unit:
17433 @smallexample
17434    gnat check -Pproj -U main -rules -from=my_rules
17435 @end smallexample
17436
17437
17438 @node Rule exemption
17439 @section Rule exemption
17440 @cindex Rule exemption (for @command{gnatcheck})
17441
17442 @noindent
17443 One of the most useful applications of @command{gnatcheck} is to
17444 automate the enforcement of project-specific coding standards,
17445 for example in safety-critical systems where particular features
17446 must be restricted in order to simplify the certification effort.
17447 However, it may sometimes be appropriate to violate a coding standard rule,
17448 and in such cases the rationale for the violation should be provided
17449 in the source program itself so that the individuals
17450 reviewing or maintaining the program can immediately understand the intent.
17451
17452 The @command{gnatcheck} tool supports this practice with the notion of
17453 a ``rule exemption'' covering a specific source code section. Normally
17454 rule violation messages are issued both on @file{stderr}
17455 and in a report file. In contrast, exempted violations are not listed on
17456 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17457 (e.g. in its GPS interface) do not need to pay attention to known and
17458 justified violations. However, exempted violations along with their
17459 justification are documented in a special section of the report file that
17460 @command{gnatcheck} generates.
17461
17462 @menu
17463 * Using pragma Annotate to Control Rule Exemption::
17464 * gnatcheck Annotations Rules::
17465 @end menu
17466
17467 @node Using pragma Annotate to Control Rule Exemption
17468 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17469 @cindex Using pragma Annotate to control rule exemption
17470
17471 @noindent
17472 Rule exemption is controlled by pragma @code{Annotate} when its first
17473 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17474 exemption control annotations is as follows:
17475
17476 @smallexample @c ada
17477 @group
17478 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17479
17480 @i{exemption_control} ::= Exempt_On | Exempt_Off
17481
17482 @i{Rule_Name}         ::= string_literal
17483
17484 @i{justification}     ::= string_literal
17485 @end group
17486 @end smallexample
17487
17488 @noindent
17489 When a @command{gnatcheck} annotation has more then four arguments,
17490 @command{gnatcheck} issues a warning and ignores the additional arguments.
17491 If the additional arguments do not follow the syntax above,
17492 @command{gnatcheck} emits a warning and ignores the annotation.
17493
17494 The @i{@code{Rule_Name}} argument should be the name of some existing
17495 @command{gnatcheck} rule.
17496 Otherwise a warning message is generated and the pragma is
17497 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17498 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17499
17500 A source code section where an exemption is active for a given rule is
17501 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17502
17503 @smallexample @c ada
17504 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17505 -- source code section
17506 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17507 @end smallexample
17508
17509
17510 @node gnatcheck Annotations Rules
17511 @subsection @command{gnatcheck} Annotations Rules
17512 @cindex @command{gnatcheck} annotations rules
17513
17514 @itemize @bullet
17515
17516 @item
17517 An ``Exempt_Off'' annotation can only appear after a corresponding
17518 ``Exempt_On'' annotation.
17519
17520 @item
17521 Exempted source code sections are only based on the source location of the
17522 annotations. Any source construct between the two
17523 annotations is part of the exempted source code section.
17524
17525 @item
17526 Exempted source code sections for different rules are independent. They can
17527 be nested or intersect with one another without limitation.
17528 Creating nested or intersecting source code sections for the same rule is
17529 not allowed.
17530
17531 @item
17532 Malformed exempted source code sections are reported by a warning, and
17533 the corresponding rule exemptions are ignored.
17534
17535 @item
17536 When an exempted source code section does not contain at least one violation
17537 of the exempted rule, a warning is emitted on @file{stderr}.
17538
17539 @item
17540 If an ``Exempt_On'' annotation pragma does not have a matching
17541 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17542 exemption for the given rule is ignored and a warning is issued.
17543 @end itemize
17544
17545
17546 @node Predefined Rules
17547 @section Predefined Rules
17548 @cindex Predefined rules (for @command{gnatcheck})
17549
17550 @ignore
17551 @c (Jan 2007) Since the global rules are still under development and are not
17552 @c documented, there is no point in explaining the difference between
17553 @c global and local rules
17554 @noindent
17555 A rule in @command{gnatcheck} is either local or global.
17556 A @emph{local rule} is a rule that applies to a well-defined section
17557 of a program and that can be checked by analyzing only this section.
17558 A @emph{global rule} requires analysis of some global properties of the
17559 whole program (mostly related to the program call graph).
17560 As of @value{NOW}, the implementation of global rules should be
17561 considered to be at a preliminary stage. You can use the
17562 @option{+GLOBAL} option to enable all the global rules, and the
17563 @option{-GLOBAL} rule option to disable all the global rules.
17564
17565 All the global rules in the list below are
17566 so indicated by marking them ``GLOBAL''.
17567 This +GLOBAL and -GLOBAL options are not
17568 included in the list of gnatcheck options above, because at the moment they
17569 are considered as a temporary debug options.
17570
17571 @command{gnatcheck} performs rule checks for generic
17572 instances only for global rules.  This limitation may be relaxed in a later
17573 release.
17574 @end ignore
17575
17576 @noindent
17577 The predefined rules implemented in @command{gnatcheck}
17578 are described in a companion document,
17579 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17580 The rule identifier is
17581 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17582 switches.
17583
17584
17585 @node Example of gnatcheck Usage
17586 @section Example of @command{gnatcheck} Usage
17587
17588 @noindent
17589 Here is a simple example. Suppose that in the current directory we have a
17590 project file named @file{gnatcheck_example.gpr} with the following content:
17591
17592 @smallexample @c projectfile
17593 project Gnatcheck_Example is
17594
17595    for Source_Dirs use ("src");
17596    for Object_Dir use "obj";
17597    for Main use ("main.adb");
17598
17599    package Check is
17600       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17601    end Check;
17602
17603 end Gnatcheck_Example;
17604 @end smallexample
17605
17606 @noindent
17607 And the file named @file{coding_standard} is also located in the current
17608 directory and has the following content:
17609
17610 @smallexample
17611 -----------------------------------------------------
17612 -- This is a sample gnatcheck coding standard file --
17613 -----------------------------------------------------
17614
17615 --  First, turning on rules, that are directly implemented in gnatcheck
17616 +RAbstract_Type_Declarations
17617 +RAnonymous_Arrays
17618 +RLocal_Packages
17619 +RFloat_Equality_Checks
17620 +REXIT_Statements_With_No_Loop_Name
17621
17622 --  Then, activating compiler checks of interest:
17623 +RStyle_Checks:e
17624 --  This style check checks if a unit name is present on END keyword that
17625 --  is the end of the unit declaration
17626 @end smallexample
17627
17628 @noindent
17629 And the subdirectory @file{src} contains the following Ada sources:
17630
17631 @file{pack.ads}:
17632
17633 @smallexample @c ada
17634 package Pack is
17635    type T is abstract tagged private;
17636    procedure P (X : T) is abstract;
17637
17638    package Inner is
17639       type My_Float is digits 8;
17640       function Is_Equal (L, R : My_Float) return Boolean;
17641    end Inner;
17642 private
17643    type T is abstract tagged null record;
17644 end;
17645 @end smallexample
17646
17647 @noindent
17648 @file{pack.adb}:
17649
17650 @smallexample @c ada
17651 package body Pack is
17652    package body Inner is
17653       function Is_Equal (L, R : My_Float) return Boolean is
17654       begin
17655          return L = R;
17656       end;
17657    end Inner;
17658 end Pack;
17659 @end smallexample
17660
17661 @noindent
17662 and @file{main.adb}
17663
17664 @smallexample @c ada
17665 with Pack; use Pack;
17666 procedure Main is
17667
17668    pragma Annotate
17669      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17670    Float_Array : array (1 .. 10) of Inner.My_Float;
17671    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17672
17673    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17674
17675    use Inner;
17676
17677    B : Boolean := False;
17678
17679 begin
17680    for J in Float_Array'Range loop
17681       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17682          B := True;
17683          exit;
17684       end if;
17685    end loop;
17686 end Main;
17687 @end smallexample
17688
17689 @noindent
17690 And suppose we call @command{gnatcheck} from the current directory using
17691 the @command{gnat} driver:
17692
17693 @smallexample
17694    gnat check -Pgnatcheck_example.gpr
17695 @end smallexample
17696
17697 @noindent
17698 As a result, @command{gnatcheck} is called to check all the files from the
17699 project @file{gnatcheck_example.gpr} using the coding standard defined by
17700 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17701 report file named @file{gnatcheck.out} will be created in the current
17702 directory, and it will have the following content:
17703
17704 @smallexample
17705 RULE CHECKING REPORT
17706
17707 1. OVERVIEW
17708
17709 Date and time of execution: 2009.10.28 14:17
17710 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17711 Command line:
17712
17713 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17714
17715 Coding standard (applied rules):
17716    Abstract_Type_Declarations
17717    Anonymous_Arrays
17718    EXIT_Statements_With_No_Loop_Name
17719    Float_Equality_Checks
17720    Local_Packages
17721
17722    Compiler style checks: -gnatye
17723
17724 Number of coding standard violations: 6
17725 Number of exempted coding standard violations: 1
17726
17727 2. DETECTED RULE VIOLATIONS
17728
17729 2.1. NON-EXEMPTED VIOLATIONS
17730
17731 Source files with non-exempted violations
17732    pack.ads
17733    pack.adb
17734    main.adb
17735
17736 List of violations grouped by files, and ordered by increasing source location:
17737
17738 pack.ads:2:4: declaration of abstract type
17739 pack.ads:5:4: declaration of local package
17740 pack.ads:10:30: declaration of abstract type
17741 pack.ads:11:1: (style) "end Pack" required
17742 pack.adb:5:19: use of equality operation for float values
17743 pack.adb:6:7: (style) "end Is_Equal" required
17744 main.adb:9:26: anonymous array type
17745 main.adb:19:10: exit statement with no loop name
17746
17747 2.2. EXEMPTED VIOLATIONS
17748
17749 Source files with exempted violations
17750    main.adb
17751
17752 List of violations grouped by files, and ordered by increasing source location:
17753
17754 main.adb:6:18: anonymous array type
17755    (this one is fine)
17756
17757 2.3. SOURCE FILES WITH NO VIOLATION
17758
17759    No files without violations
17760
17761 END OF REPORT
17762 @end smallexample
17763
17764
17765 @c *********************************
17766 @node Creating Sample Bodies Using gnatstub
17767 @chapter Creating Sample Bodies Using @command{gnatstub}
17768 @findex gnatstub
17769
17770 @noindent
17771 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17772 for library unit declarations.
17773
17774 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17775 driver (see @ref{The GNAT Driver and Project Files}).
17776
17777 To create a body stub, @command{gnatstub} has to compile the library
17778 unit declaration. Therefore, bodies can be created only for legal
17779 library units. Moreover, if a library unit depends semantically upon
17780 units located outside the current directory, you have to provide
17781 the source search path when calling @command{gnatstub}, see the description
17782 of @command{gnatstub} switches below.
17783
17784 By default, all the program unit body stubs generated by @code{gnatstub}
17785 raise the predefined @code{Program_Error} exception, which will catch
17786 accidental calls of generated stubs. This behavior can be changed with
17787 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17788
17789 @menu
17790 * Running gnatstub::
17791 * Switches for gnatstub::
17792 @end menu
17793
17794 @node Running gnatstub
17795 @section Running @command{gnatstub}
17796
17797 @noindent
17798 @command{gnatstub} has the command-line interface of the form
17799
17800 @smallexample
17801 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17802 @c Expanding @ovar macro inline (explanation in macro def comments)
17803 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17804 @end smallexample
17805
17806 @noindent
17807 where
17808 @table @var
17809 @item filename
17810 is the name of the source file that contains a library unit declaration
17811 for which a body must be created. The file name may contain the path
17812 information.
17813 The file name does not have to follow the GNAT file name conventions. If the
17814 name
17815 does not follow GNAT file naming conventions, the name of the body file must
17816 be provided
17817 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17818 If the file name follows the GNAT file naming
17819 conventions and the name of the body file is not provided,
17820 @command{gnatstub}
17821 creates the name
17822 of the body file from the argument file name by replacing the @file{.ads}
17823 suffix
17824 with the @file{.adb} suffix.
17825
17826 @item directory
17827 indicates the directory in which the body stub is to be placed (the default
17828 is the
17829 current directory)
17830
17831 @item @samp{@var{gcc_switches}} is a list of switches for
17832 @command{gcc}. They will be passed on to all compiler invocations made by
17833 @command{gnatelim} to generate the ASIS trees. Here you can provide
17834 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17835 use the @option{-gnatec} switch to set the configuration file etc.
17836
17837 @item switches
17838 is an optional sequence of switches as described in the next section
17839 @end table
17840
17841 @node Switches for gnatstub
17842 @section Switches for @command{gnatstub}
17843
17844 @table @option
17845 @c !sort!
17846
17847 @item ^-f^/FULL^
17848 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17849 If the destination directory already contains a file with the name of the
17850 body file
17851 for the argument spec file, replace it with the generated body stub.
17852
17853 @item ^-hs^/HEADER=SPEC^
17854 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17855 Put the comment header (i.e., all the comments preceding the
17856 compilation unit) from the source of the library unit declaration
17857 into the body stub.
17858
17859 @item ^-hg^/HEADER=GENERAL^
17860 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17861 Put a sample comment header into the body stub.
17862
17863 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17864 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17865 Use the content of the file as the comment header for a generated body stub.
17866
17867 @ifclear vms
17868 @item -IDIR
17869 @cindex @option{-IDIR} (@command{gnatstub})
17870 @itemx -I-
17871 @cindex @option{-I-} (@command{gnatstub})
17872 @end ifclear
17873 @ifset vms
17874 @item /NOCURRENT_DIRECTORY
17875 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17876 @end ifset
17877 ^These switches have ^This switch has^ the same meaning as in calls to
17878 @command{gcc}.
17879 ^They define ^It defines ^ the source search path in the call to
17880 @command{gcc} issued
17881 by @command{gnatstub} to compile an argument source file.
17882
17883 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17884 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17885 This switch has the same meaning as in calls to @command{gcc}.
17886 It defines the additional configuration file to be passed to the call to
17887 @command{gcc} issued
17888 by @command{gnatstub} to compile an argument source file.
17889
17890 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17891 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17892 (@var{n} is a non-negative integer). Set the maximum line length in the
17893 body stub to @var{n}; the default is 79. The maximum value that can be
17894 specified is 32767. Note that in the special case of configuration
17895 pragma files, the maximum is always 32767 regardless of whether or
17896 not this switch appears.
17897
17898 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17899 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17900 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17901 the generated body sample to @var{n}.
17902 The default indentation is 3.
17903
17904 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17905 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17906 Order local bodies alphabetically. (By default local bodies are ordered
17907 in the same way as the corresponding local specs in the argument spec file.)
17908
17909 @item ^-i^/INDENTATION=^@var{n}
17910 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17911 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17912
17913 @item ^-k^/TREE_FILE=SAVE^
17914 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17915 Do not remove the tree file (i.e., the snapshot of the compiler internal
17916 structures used by @command{gnatstub}) after creating the body stub.
17917
17918 @item ^-l^/LINE_LENGTH=^@var{n}
17919 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17920 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17921
17922 @item ^--no-exception^/NO_EXCEPTION^
17923 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17924 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17925 This is not always possible for function stubs.
17926
17927 @item ^--no-local-header^/NO_LOCAL_HEADER^
17928 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17929 Do not place local comment header with unit name before body stub for a
17930 unit.
17931
17932 @item ^-o ^/BODY=^@var{body-name}
17933 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17934 Body file name.  This should be set if the argument file name does not
17935 follow
17936 the GNAT file naming
17937 conventions. If this switch is omitted the default name for the body will be
17938 obtained
17939 from the argument file name according to the GNAT file naming conventions.
17940
17941 @item ^-q^/QUIET^
17942 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17943 Quiet mode: do not generate a confirmation when a body is
17944 successfully created, and do not generate a message when a body is not
17945 required for an
17946 argument unit.
17947
17948 @item ^-r^/TREE_FILE=REUSE^
17949 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17950 Reuse the tree file (if it exists) instead of creating it.  Instead of
17951 creating the tree file for the library unit declaration, @command{gnatstub}
17952 tries to find it in the current directory and use it for creating
17953 a body. If the tree file is not found, no body is created. This option
17954 also implies @option{^-k^/SAVE^}, whether or not
17955 the latter is set explicitly.
17956
17957 @item ^-t^/TREE_FILE=OVERWRITE^
17958 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17959 Overwrite the existing tree file.  If the current directory already
17960 contains the file which, according to the GNAT file naming rules should
17961 be considered as a tree file for the argument source file,
17962 @command{gnatstub}
17963 will refuse to create the tree file needed to create a sample body
17964 unless this option is set.
17965
17966 @item ^-v^/VERBOSE^
17967 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17968 Verbose mode: generate version information.
17969
17970 @end table
17971
17972 @c *********************************
17973 @node Generating Ada Bindings for C and C++ headers
17974 @chapter Generating Ada Bindings for C and C++ headers
17975 @findex binding
17976
17977 @noindent
17978 GNAT now comes with a binding generator for C and C++ headers which is
17979 intended to do 95% of the tedious work of generating Ada specs from C
17980 or C++ header files.
17981
17982 Note that this capability is not intended to generate 100% correct Ada specs,
17983 and will is some cases require manual adjustments, although it can often
17984 be used out of the box in practice.
17985
17986 Some of the known limitations include:
17987
17988 @itemize @bullet
17989 @item only very simple character constant macros are translated into Ada
17990 constants. Function macros (macros with arguments) are partially translated
17991 as comments, to be completed manually if needed.
17992 @item some extensions (e.g. vector types) are not supported
17993 @item pointers to pointers or complex structures are mapped to System.Address
17994 @end itemize
17995
17996 The code generated is using the Ada 2005 syntax, which makes it
17997 easier to interface with other languages than previous versions of Ada.
17998
17999 @menu
18000 * Running the binding generator::
18001 * Generating bindings for C++ headers::
18002 * Switches::
18003 @end menu
18004
18005 @node Running the binding generator
18006 @section Running the binding generator
18007
18008 @noindent
18009 The binding generator is part of the @command{gcc} compiler and can be
18010 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18011 spec files for the header files specified on the command line, and all
18012 header files needed by these files transitivitely. For example:
18013
18014 @smallexample
18015 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18016 $ gcc -c -gnat05 *.ads
18017 @end smallexample
18018
18019 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18020 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18021 correspond to the files @file{/usr/include/time.h},
18022 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18023 mode these Ada specs.
18024
18025 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18026 and will attempt to generate corresponding Ada comments.
18027
18028 If you want to generate a single Ada file and not the transitive closure, you
18029 can use instead the @option{-fdump-ada-spec-slim} switch.
18030
18031 Note that we recommend when possible to use the @command{g++} driver to
18032 generate bindings, even for most C headers, since this will in general
18033 generate better Ada specs. For generating bindings for C++ headers, it is
18034 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18035 is equivalent in this case. If @command{g++} cannot work on your C headers
18036 because of incompatibilities between C and C++, then you can fallback to
18037 @command{gcc} instead.
18038
18039 For an example of better bindings generated from the C++ front-end,
18040 the name of the parameters (when available) are actually ignored by the C
18041 front-end. Consider the following C header:
18042
18043 @smallexample
18044 extern void foo (int variable);
18045 @end smallexample
18046
18047 with the C front-end, @code{variable} is ignored, and the above is handled as:
18048
18049 @smallexample
18050 extern void foo (int);
18051 @end smallexample
18052
18053 generating a generic:
18054
18055 @smallexample
18056 procedure foo (param1 : int);
18057 @end smallexample
18058
18059 with the C++ front-end, the name is available, and we generate:
18060
18061 @smallexample
18062 procedure foo (variable : int);
18063 @end smallexample
18064
18065 In some cases, the generated bindings will be more complete or more meaningful
18066 when defining some macros, which you can do via the @option{-D} switch. This
18067 is for example the case with @file{Xlib.h} under GNU/Linux:
18068
18069 @smallexample
18070 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18071 @end smallexample
18072
18073 The above will generate more complete bindings than a straight call without
18074 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18075
18076 In other cases, it is not possible to parse a header file in a stand alone
18077 manner, because other include files need to be included first. In this
18078 case, the solution is to create a small header file including the needed
18079 @code{#include} and possible @code{#define} directives. For example, to
18080 generate Ada bindings for @file{readline/readline.h}, you need to first
18081 include @file{stdio.h}, so you can create a file with the following two
18082 lines in e.g. @file{readline1.h}:
18083
18084 @smallexample
18085 #include <stdio.h>
18086 #include <readline/readline.h>
18087 @end smallexample
18088
18089 and then generate Ada bindings from this file:
18090
18091 @smallexample
18092 $ g++ -c -fdump-ada-spec readline1.h
18093 @end smallexample
18094
18095 @node Generating bindings for C++ headers
18096 @section Generating bindings for C++ headers
18097
18098 @noindent
18099 Generating bindings for C++ headers is done using the same options, always
18100 with the @command{g++} compiler.
18101
18102 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18103 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18104 multiple inheritance of abstract classes will be mapped to Ada interfaces
18105 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18106 information on interfacing to C++).
18107
18108 For example, given the following C++ header file:
18109
18110 @smallexample
18111 @group
18112 @cartouche
18113 class Carnivore @{
18114 public:
18115    virtual int Number_Of_Teeth () = 0;
18116 @};
18117
18118 class Domestic @{
18119 public:
18120    virtual void Set_Owner (char* Name) = 0;
18121 @};
18122
18123 class Animal @{
18124 public:
18125   int Age_Count;
18126   virtual void Set_Age (int New_Age);
18127 @};
18128
18129 class Dog : Animal, Carnivore, Domestic @{
18130  public:
18131   int  Tooth_Count;
18132   char *Owner;
18133
18134   virtual int  Number_Of_Teeth ();
18135   virtual void Set_Owner (char* Name);
18136
18137   Dog();
18138 @};
18139 @end cartouche
18140 @end group
18141 @end smallexample
18142
18143 The corresponding Ada code is generated:
18144
18145 @smallexample @c ada
18146 @group
18147 @cartouche
18148   package Class_Carnivore is
18149     type Carnivore is limited interface;
18150     pragma Import (CPP, Carnivore);
18151
18152     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18153   end;
18154   use Class_Carnivore;
18155
18156   package Class_Domestic is
18157     type Domestic is limited interface;
18158     pragma Import (CPP, Domestic);
18159
18160     procedure Set_Owner
18161       (this : access Domestic;
18162        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18163   end;
18164   use Class_Domestic;
18165
18166   package Class_Animal is
18167     type Animal is tagged limited record
18168       Age_Count : aliased int;
18169     end record;
18170     pragma Import (CPP, Animal);
18171
18172     procedure Set_Age (this : access Animal; New_Age : int);
18173     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18174   end;
18175   use Class_Animal;
18176
18177   package Class_Dog is
18178     type Dog is new Animal and Carnivore and Domestic with record
18179       Tooth_Count : aliased int;
18180       Owner : Interfaces.C.Strings.chars_ptr;
18181     end record;
18182     pragma Import (CPP, Dog);
18183
18184     function Number_Of_Teeth (this : access Dog) return int;
18185     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18186
18187     procedure Set_Owner
18188       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18189     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18190
18191     function New_Dog return Dog;
18192     pragma CPP_Constructor (New_Dog);
18193     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18194   end;
18195   use Class_Dog;
18196 @end cartouche
18197 @end group
18198 @end smallexample
18199
18200 @node Switches
18201 @section Switches
18202
18203 @table @option
18204 @item -fdump-ada-spec
18205 @cindex @option{-fdump-ada-spec} (@command{gcc})
18206 Generate Ada spec files for the given header files transitively (including
18207 all header files that these headers depend upon).
18208
18209 @item -fdump-ada-spec-slim
18210 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18211 Generate Ada spec files for the header files specified on the command line
18212 only.
18213
18214 @item -C
18215 @cindex @option{-C} (@command{gcc})
18216 Extract comments from headers and generate Ada comments in the Ada spec files.
18217 @end table
18218
18219 @node Other Utility Programs
18220 @chapter Other Utility Programs
18221
18222 @noindent
18223 This chapter discusses some other utility programs available in the Ada
18224 environment.
18225
18226 @menu
18227 * Using Other Utility Programs with GNAT::
18228 * The External Symbol Naming Scheme of GNAT::
18229 * Converting Ada Files to html with gnathtml::
18230 * Installing gnathtml::
18231 @ifset vms
18232 * LSE::
18233 * Profiling::
18234 @end ifset
18235 @end menu
18236
18237 @node Using Other Utility Programs with GNAT
18238 @section Using Other Utility Programs with GNAT
18239
18240 @noindent
18241 The object files generated by GNAT are in standard system format and in
18242 particular the debugging information uses this format. This means
18243 programs generated by GNAT can be used with existing utilities that
18244 depend on these formats.
18245
18246 @ifclear vms
18247 In general, any utility program that works with C will also often work with
18248 Ada programs generated by GNAT. This includes software utilities such as
18249 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18250 as Purify.
18251 @end ifclear
18252
18253 @node The External Symbol Naming Scheme of GNAT
18254 @section The External Symbol Naming Scheme of GNAT
18255
18256 @noindent
18257 In order to interpret the output from GNAT, when using tools that are
18258 originally intended for use with other languages, it is useful to
18259 understand the conventions used to generate link names from the Ada
18260 entity names.
18261
18262 All link names are in all lowercase letters. With the exception of library
18263 procedure names, the mechanism used is simply to use the full expanded
18264 Ada name with dots replaced by double underscores. For example, suppose
18265 we have the following package spec:
18266
18267 @smallexample @c ada
18268 @group
18269 @cartouche
18270 package QRS is
18271    MN : Integer;
18272 end QRS;
18273 @end cartouche
18274 @end group
18275 @end smallexample
18276
18277 @noindent
18278 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18279 the corresponding link name is @code{qrs__mn}.
18280 @findex Export
18281 Of course if a @code{pragma Export} is used this may be overridden:
18282
18283 @smallexample @c ada
18284 @group
18285 @cartouche
18286 package Exports is
18287    Var1 : Integer;
18288    pragma Export (Var1, C, External_Name => "var1_name");
18289    Var2 : Integer;
18290    pragma Export (Var2, C, Link_Name => "var2_link_name");
18291 end Exports;
18292 @end cartouche
18293 @end group
18294 @end smallexample
18295
18296 @noindent
18297 In this case, the link name for @var{Var1} is whatever link name the
18298 C compiler would assign for the C function @var{var1_name}. This typically
18299 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18300 system conventions, but other possibilities exist. The link name for
18301 @var{Var2} is @var{var2_link_name}, and this is not operating system
18302 dependent.
18303
18304 @findex _main
18305 One exception occurs for library level procedures. A potential ambiguity
18306 arises between the required name @code{_main} for the C main program,
18307 and the name we would otherwise assign to an Ada library level procedure
18308 called @code{Main} (which might well not be the main program).
18309
18310 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18311 names. So if we have a library level procedure such as
18312
18313 @smallexample @c ada
18314 @group
18315 @cartouche
18316 procedure Hello (S : String);
18317 @end cartouche
18318 @end group
18319 @end smallexample
18320
18321 @noindent
18322 the external name of this procedure will be @var{_ada_hello}.
18323
18324
18325 @node Converting Ada Files to html with gnathtml
18326 @section Converting Ada Files to HTML with @code{gnathtml}
18327
18328 @noindent
18329 This @code{Perl} script allows Ada source files to be browsed using
18330 standard Web browsers. For installation procedure, see the section
18331 @xref{Installing gnathtml}.
18332
18333 Ada reserved keywords are highlighted in a bold font and Ada comments in
18334 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18335 switch to suppress the generation of cross-referencing information, user
18336 defined variables and types will appear in a different color; you will
18337 be able to click on any identifier and go to its declaration.
18338
18339 The command line is as follow:
18340 @smallexample
18341 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18342 @c Expanding @ovar macro inline (explanation in macro def comments)
18343 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18344 @end smallexample
18345
18346 @noindent
18347 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18348 an html file for every ada file, and a global file called @file{index.htm}.
18349 This file is an index of every identifier defined in the files.
18350
18351 The available ^switches^options^ are the following ones:
18352
18353 @table @option
18354 @item -83
18355 @cindex @option{-83} (@code{gnathtml})
18356 Only the Ada 83 subset of keywords will be highlighted.
18357
18358 @item -cc @var{color}
18359 @cindex @option{-cc} (@code{gnathtml})
18360 This option allows you to change the color used for comments. The default
18361 value is green. The color argument can be any name accepted by html.
18362
18363 @item -d
18364 @cindex @option{-d} (@code{gnathtml})
18365 If the Ada files depend on some other files (for instance through
18366 @code{with} clauses, the latter files will also be converted to html.
18367 Only the files in the user project will be converted to html, not the files
18368 in the run-time library itself.
18369
18370 @item -D
18371 @cindex @option{-D} (@code{gnathtml})
18372 This command is the same as @option{-d} above, but @command{gnathtml} will
18373 also look for files in the run-time library, and generate html files for them.
18374
18375 @item -ext @var{extension}
18376 @cindex @option{-ext} (@code{gnathtml})
18377 This option allows you to change the extension of the generated HTML files.
18378 If you do not specify an extension, it will default to @file{htm}.
18379
18380 @item -f
18381 @cindex @option{-f} (@code{gnathtml})
18382 By default, gnathtml will generate html links only for global entities
18383 ('with'ed units, global variables and types,@dots{}).  If you specify
18384 @option{-f} on the command line, then links will be generated for local
18385 entities too.
18386
18387 @item -l @var{number}
18388 @cindex @option{-l} (@code{gnathtml})
18389 If this ^switch^option^ is provided and @var{number} is not 0, then
18390 @code{gnathtml} will number the html files every @var{number} line.
18391
18392 @item -I @var{dir}
18393 @cindex @option{-I} (@code{gnathtml})
18394 Specify a directory to search for library files (@file{.ALI} files) and
18395 source files. You can provide several -I switches on the command line,
18396 and the directories will be parsed in the order of the command line.
18397
18398 @item -o @var{dir}
18399 @cindex @option{-o} (@code{gnathtml})
18400 Specify the output directory for html files. By default, gnathtml will
18401 saved the generated html files in a subdirectory named @file{html/}.
18402
18403 @item -p @var{file}
18404 @cindex @option{-p} (@code{gnathtml})
18405 If you are using Emacs and the most recent Emacs Ada mode, which provides
18406 a full Integrated Development Environment for compiling, checking,
18407 running and debugging applications, you may use @file{.gpr} files
18408 to give the directories where Emacs can find sources and object files.
18409
18410 Using this ^switch^option^, you can tell gnathtml to use these files.
18411 This allows you to get an html version of your application, even if it
18412 is spread over multiple directories.
18413
18414 @item -sc @var{color}
18415 @cindex @option{-sc} (@code{gnathtml})
18416 This ^switch^option^ allows you to change the color used for symbol
18417 definitions.
18418 The default value is red. The color argument can be any name accepted by html.
18419
18420 @item -t @var{file}
18421 @cindex @option{-t} (@code{gnathtml})
18422 This ^switch^option^ provides the name of a file. This file contains a list of
18423 file names to be converted, and the effect is exactly as though they had
18424 appeared explicitly on the command line. This
18425 is the recommended way to work around the command line length limit on some
18426 systems.
18427
18428 @end table
18429
18430 @node Installing gnathtml
18431 @section Installing @code{gnathtml}
18432
18433 @noindent
18434 @code{Perl} needs to be installed on your machine to run this script.
18435 @code{Perl} is freely available for almost every architecture and
18436 Operating System via the Internet.
18437
18438 On Unix systems, you  may want to modify  the  first line of  the script
18439 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18440 is. The syntax of this line is:
18441 @smallexample
18442 #!full_path_name_to_perl
18443 @end smallexample
18444
18445 @noindent
18446 Alternatively, you may run the script using the following command line:
18447
18448 @smallexample
18449 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18450 @c Expanding @ovar macro inline (explanation in macro def comments)
18451 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18452 @end smallexample
18453
18454 @ifset vms
18455 @node LSE
18456 @section LSE
18457 @findex LSE
18458
18459 @noindent
18460 The GNAT distribution provides an Ada 95 template for the HP Language
18461 Sensitive Editor (LSE), a component of DECset. In order to
18462 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18463
18464 @node Profiling
18465 @section Profiling
18466 @findex PCA
18467
18468 @noindent
18469 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18470 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18471 the collection phase with the /DEBUG qualifier.
18472
18473 @smallexample
18474 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18475 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18476 $ RUN/DEBUG <PROGRAM_NAME>
18477 @end smallexample
18478 @noindent
18479 @end ifset
18480
18481 @ifclear vms
18482 @c ******************************
18483 @node Code Coverage and Profiling
18484 @chapter Code Coverage and Profiling
18485 @cindex Code Coverage
18486 @cindex Profiling
18487
18488 @noindent
18489 This chapter describes how to use @code{gcov} - coverage testing tool - and
18490 @code{gprof} - profiler tool - on your Ada programs.
18491
18492 @menu
18493 * Code Coverage of Ada Programs using gcov::
18494 * Profiling an Ada Program using gprof::
18495 @end menu
18496
18497 @node Code Coverage of Ada Programs using gcov
18498 @section Code Coverage of Ada Programs using gcov
18499 @cindex gcov
18500 @cindex -fprofile-arcs
18501 @cindex -ftest-coverage
18502 @cindex -coverage
18503 @cindex Code Coverage
18504
18505 @noindent
18506 @code{gcov} is a test coverage program: it analyzes the execution of a given
18507 program on selected tests, to help you determine the portions of the program
18508 that are still untested.
18509
18510 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18511 User's Guide. You can refer to this documentation for a more complete
18512 description.
18513
18514 This chapter provides a quick startup guide, and
18515 details some Gnat-specific features.
18516
18517 @menu
18518 * Quick startup guide::
18519 * Gnat specifics::
18520 @end menu
18521
18522 @node Quick startup guide
18523 @subsection Quick startup guide
18524
18525 In order to perform coverage analysis of a program using @code{gcov}, 3
18526 steps are needed:
18527
18528 @itemize @bullet
18529 @item
18530 Code instrumentation during the compilation process
18531 @item
18532 Execution of the instrumented program
18533 @item
18534 Execution of the @code{gcov} tool to generate the result.
18535 @end itemize
18536
18537 The code instrumentation needed by gcov is created at the object level:
18538 The source code is not modified in any way, because the instrumentation code is
18539 inserted by gcc during the compilation process. To compile your code with code
18540 coverage activated, you need to recompile your whole project using the
18541 switches
18542 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18543 @code{-fprofile-arcs}.
18544
18545 @smallexample
18546 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18547    -largs -fprofile-arcs
18548 @end smallexample
18549
18550 This compilation process will create @file{.gcno} files together with
18551 the usual object files.
18552
18553 Once the program is compiled with coverage instrumentation, you can
18554 run it as many times as needed - on portions of a test suite for
18555 example. The first execution will produce @file{.gcda} files at the
18556 same location as the @file{.gcno} files.  The following executions
18557 will update those files, so that a cumulative result of the covered
18558 portions of the program is generated.
18559
18560 Finally, you need to call the @code{gcov} tool. The different options of
18561 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18562
18563 This will create annotated source files with a @file{.gcov} extension:
18564 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18565
18566 @node Gnat specifics
18567 @subsection Gnat specifics
18568
18569 Because Ada semantics, portions of the source code may be shared among
18570 several object files. This is the case for example when generics are
18571 involved, when inlining is active  or when declarations generate  initialisation
18572 calls. In order to take
18573 into account this shared code, you need to call @code{gcov} on all
18574 source files of the tested program at once.
18575
18576 The list of source files might exceed the system's maximum command line
18577 length. In order to bypass this limitation, a new mechanism has been
18578 implemented in @code{gcov}: you can now list all your project's files into a
18579 text file, and provide this file to gcov as a parameter,  preceded by a @@
18580 (e.g. @samp{gcov @@mysrclist.txt}).
18581
18582 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18583 not supported as there can be unresolved symbols during the final link.
18584
18585 @node Profiling an Ada Program using gprof
18586 @section Profiling an Ada Program using gprof
18587 @cindex gprof
18588 @cindex -pg
18589 @cindex Profiling
18590
18591 @noindent
18592 This section is not meant to be an exhaustive documentation of @code{gprof}.
18593 Full documentation for it can be found in the GNU Profiler User's Guide
18594 documentation that is part of this GNAT distribution.
18595
18596 Profiling a program helps determine the parts of a program that are executed
18597 most often, and are therefore the most time-consuming.
18598
18599 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18600 better handle Ada programs and multitasking.
18601 It is currently supported on the following platforms
18602 @itemize @bullet
18603 @item
18604 linux x86/x86_64
18605 @item
18606 solaris sparc/sparc64/x86
18607 @item
18608 windows x86
18609 @end itemize
18610
18611 @noindent
18612 In order to profile a program using @code{gprof}, 3 steps are needed:
18613
18614 @itemize @bullet
18615 @item
18616 Code instrumentation, requiring a full recompilation of the project with the
18617 proper switches.
18618 @item
18619 Execution of the program under the analysis conditions, i.e. with the desired
18620 input.
18621 @item
18622 Analysis of the results using the @code{gprof} tool.
18623 @end itemize
18624
18625 @noindent
18626 The following sections detail the different steps, and indicate how
18627 to interpret the results:
18628 @menu
18629 * Compilation for profiling::
18630 * Program execution::
18631 * Running gprof::
18632 * Interpretation of profiling results::
18633 @end menu
18634
18635 @node Compilation for profiling
18636 @subsection Compilation for profiling
18637 @cindex -pg
18638 @cindex Profiling
18639
18640 In order to profile a program the first step is to tell the compiler
18641 to generate the necessary profiling information. The compiler switch to be used
18642 is @code{-pg}, which must be added to other compilation switches. This
18643 switch needs to be specified both during compilation and link stages, and can
18644 be specified once when using gnatmake:
18645
18646 @smallexample
18647 gnatmake -f -pg -P my_project
18648 @end smallexample
18649
18650 @noindent
18651 Note that only the objects that were compiled with the @samp{-pg} switch will be
18652 profiled; if you need to profile your whole project, use the
18653 @samp{-f} gnatmake switch to force full recompilation.
18654
18655 @node Program execution
18656 @subsection Program execution
18657
18658 @noindent
18659 Once the program has been compiled for profiling, you can run it as usual.
18660
18661 The only constraint imposed by profiling is that the program must terminate
18662 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18663 properly analyzed.
18664
18665 Once the program completes execution, a data file called @file{gmon.out} is
18666 generated in the directory where the program was launched from. If this file
18667 already exists, it will be overwritten.
18668
18669 @node Running gprof
18670 @subsection Running gprof
18671
18672 @noindent
18673 The @code{gprof} tool is called as follow:
18674
18675 @smallexample
18676 gprof my_prog gmon.out
18677 @end smallexample
18678
18679 @noindent
18680 or simpler:
18681
18682 @smallexample
18683 gprof my_prog
18684 @end smallexample
18685
18686 @noindent
18687 The complete form of the gprof command line is the following:
18688
18689 @smallexample
18690 gprof [^switches^options^] [executable [data-file]]
18691 @end smallexample
18692
18693 @noindent
18694 @code{gprof} supports numerous ^switch^options^. The order of these
18695 ^switch^options^ does not matter. The full list of options can be found in
18696 the GNU Profiler User's Guide documentation that comes with this documentation.
18697
18698 The following is the subset of those switches that is most relevant:
18699
18700 @table @option
18701
18702 @item --demangle[=@var{style}]
18703 @itemx --no-demangle
18704 @cindex @option{--demangle} (@code{gprof})
18705 These options control whether symbol names should be demangled when
18706 printing output.  The default is to demangle C++ symbols.  The
18707 @code{--no-demangle} option may be used to turn off demangling. Different
18708 compilers have different mangling styles.  The optional demangling style
18709 argument can be used to choose an appropriate demangling style for your
18710 compiler, in particular Ada symbols generated by GNAT can be demangled using
18711 @code{--demangle=gnat}.
18712
18713 @item -e @var{function_name}
18714 @cindex @option{-e} (@code{gprof})
18715 The @samp{-e @var{function}} option tells @code{gprof} not to print
18716 information about the function @var{function_name} (and its
18717 children@dots{}) in the call graph.  The function will still be listed
18718 as a child of any functions that call it, but its index number will be
18719 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18720 given; only one @var{function_name} may be indicated with each @samp{-e}
18721 option.
18722
18723 @item -E @var{function_name}
18724 @cindex @option{-E} (@code{gprof})
18725 The @code{-E @var{function}} option works like the @code{-e} option, but
18726 execution time spent in the function (and children who were not called from
18727 anywhere else), will not be used to compute the percentages-of-time for
18728 the call graph.  More than one @samp{-E} option may be given; only one
18729 @var{function_name} may be indicated with each @samp{-E} option.
18730
18731 @item -f @var{function_name}
18732 @cindex @option{-f} (@code{gprof})
18733 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18734 call graph to the function @var{function_name} and its children (and
18735 their children@dots{}).  More than one @samp{-f} option may be given;
18736 only one @var{function_name} may be indicated with each @samp{-f}
18737 option.
18738
18739 @item -F @var{function_name}
18740 @cindex @option{-F} (@code{gprof})
18741 The @samp{-F @var{function}} option works like the @code{-f} option, but
18742 only time spent in the function and its children (and their
18743 children@dots{}) will be used to determine total-time and
18744 percentages-of-time for the call graph.  More than one @samp{-F} option
18745 may be given; only one @var{function_name} may be indicated with each
18746 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18747
18748 @end table
18749
18750 @node Interpretation of profiling results
18751 @subsection Interpretation of profiling results
18752
18753 @noindent
18754
18755 The results of the profiling analysis are represented by two arrays: the
18756 'flat profile' and the 'call graph'. Full documentation of those outputs
18757 can be found in the GNU Profiler User's Guide.
18758
18759 The flat profile shows the time spent in each function of the program, and how
18760 many time it has been called. This allows you to locate easily the most
18761 time-consuming functions.
18762
18763 The call graph shows, for each subprogram, the subprograms that call it,
18764 and the subprograms that it calls. It also provides an estimate of the time
18765 spent in each of those callers/called subprograms.
18766 @end ifclear
18767
18768 @c ******************************
18769 @node Running and Debugging Ada Programs
18770 @chapter Running and Debugging Ada Programs
18771 @cindex Debugging
18772
18773 @noindent
18774 This chapter discusses how to debug Ada programs.
18775 @ifset vms
18776 It applies to GNAT on the Alpha OpenVMS platform;
18777 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18778 since HP has implemented Ada support in the OpenVMS debugger on I64.
18779 @end ifset
18780
18781 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18782
18783 @enumerate
18784 @item
18785 The illegality may be a violation of the static semantics of Ada. In
18786 that case GNAT diagnoses the constructs in the program that are illegal.
18787 It is then a straightforward matter for the user to modify those parts of
18788 the program.
18789
18790 @item
18791 The illegality may be a violation of the dynamic semantics of Ada. In
18792 that case the program compiles and executes, but may generate incorrect
18793 results, or may terminate abnormally with some exception.
18794
18795 @item
18796 When presented with a program that contains convoluted errors, GNAT
18797 itself may terminate abnormally without providing full diagnostics on
18798 the incorrect user program.
18799 @end enumerate
18800
18801 @menu
18802 * The GNAT Debugger GDB::
18803 * Running GDB::
18804 * Introduction to GDB Commands::
18805 * Using Ada Expressions::
18806 * Calling User-Defined Subprograms::
18807 * Using the Next Command in a Function::
18808 * Ada Exceptions::
18809 * Ada Tasks::
18810 * Debugging Generic Units::
18811 * Remote Debugging using gdbserver::
18812 * GNAT Abnormal Termination or Failure to Terminate::
18813 * Naming Conventions for GNAT Source Files::
18814 * Getting Internal Debugging Information::
18815 * Stack Traceback::
18816 @end menu
18817
18818 @cindex Debugger
18819 @findex gdb
18820
18821 @node The GNAT Debugger GDB
18822 @section The GNAT Debugger GDB
18823
18824 @noindent
18825 @code{GDB} is a general purpose, platform-independent debugger that
18826 can be used to debug mixed-language programs compiled with @command{gcc},
18827 and in particular is capable of debugging Ada programs compiled with
18828 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18829 complex Ada data structures.
18830
18831 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18832 @ifset vms
18833 located in the GNU:[DOCS] directory,
18834 @end ifset
18835 for full details on the usage of @code{GDB}, including a section on
18836 its usage on programs. This manual should be consulted for full
18837 details. The section that follows is a brief introduction to the
18838 philosophy and use of @code{GDB}.
18839
18840 When GNAT programs are compiled, the compiler optionally writes debugging
18841 information into the generated object file, including information on
18842 line numbers, and on declared types and variables. This information is
18843 separate from the generated code. It makes the object files considerably
18844 larger, but it does not add to the size of the actual executable that
18845 will be loaded into memory, and has no impact on run-time performance. The
18846 generation of debug information is triggered by the use of the
18847 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18848 used to carry out the compilations. It is important to emphasize that
18849 the use of these options does not change the generated code.
18850
18851 The debugging information is written in standard system formats that
18852 are used by many tools, including debuggers and profilers. The format
18853 of the information is typically designed to describe C types and
18854 semantics, but GNAT implements a translation scheme which allows full
18855 details about Ada types and variables to be encoded into these
18856 standard C formats. Details of this encoding scheme may be found in
18857 the file exp_dbug.ads in the GNAT source distribution. However, the
18858 details of this encoding are, in general, of no interest to a user,
18859 since @code{GDB} automatically performs the necessary decoding.
18860
18861 When a program is bound and linked, the debugging information is
18862 collected from the object files, and stored in the executable image of
18863 the program. Again, this process significantly increases the size of
18864 the generated executable file, but it does not increase the size of
18865 the executable program itself. Furthermore, if this program is run in
18866 the normal manner, it runs exactly as if the debug information were
18867 not present, and takes no more actual memory.
18868
18869 However, if the program is run under control of @code{GDB}, the
18870 debugger is activated.  The image of the program is loaded, at which
18871 point it is ready to run.  If a run command is given, then the program
18872 will run exactly as it would have if @code{GDB} were not present. This
18873 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18874 entirely non-intrusive until a breakpoint is encountered.  If no
18875 breakpoint is ever hit, the program will run exactly as it would if no
18876 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18877 the debugging information and can respond to user commands to inspect
18878 variables, and more generally to report on the state of execution.
18879
18880 @c **************
18881 @node Running GDB
18882 @section Running GDB
18883
18884 @noindent
18885 This section describes how to initiate the debugger.
18886 @c The above sentence is really just filler, but it was otherwise
18887 @c clumsy to get the first paragraph nonindented given the conditional
18888 @c nature of the description
18889
18890 @ifclear vms
18891 The debugger can be launched from a @code{GPS} menu or
18892 directly from the command line. The description below covers the latter use.
18893 All the commands shown can be used in the @code{GPS} debug console window,
18894 but there are usually more GUI-based ways to achieve the same effect.
18895 @end ifclear
18896
18897 The command to run @code{GDB} is
18898
18899 @smallexample
18900 $ ^gdb program^GDB PROGRAM^
18901 @end smallexample
18902
18903 @noindent
18904 where @code{^program^PROGRAM^} is the name of the executable file. This
18905 activates the debugger and results in a prompt for debugger commands.
18906 The simplest command is simply @code{run}, which causes the program to run
18907 exactly as if the debugger were not present. The following section
18908 describes some of the additional commands that can be given to @code{GDB}.
18909
18910 @c *******************************
18911 @node Introduction to GDB Commands
18912 @section Introduction to GDB Commands
18913
18914 @noindent
18915 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18916 Debugging with GDB, gdb, Debugging with GDB},
18917 @ifset vms
18918 located in the GNU:[DOCS] directory,
18919 @end ifset
18920 for extensive documentation on the use
18921 of these commands, together with examples of their use. Furthermore,
18922 the command @command{help} invoked from within GDB activates a simple help
18923 facility which summarizes the available commands and their options.
18924 In this section we summarize a few of the most commonly
18925 used commands to give an idea of what @code{GDB} is about. You should create
18926 a simple program with debugging information and experiment with the use of
18927 these @code{GDB} commands on the program as you read through the
18928 following section.
18929
18930 @table @code
18931 @item set args @var{arguments}
18932 The @var{arguments} list above is a list of arguments to be passed to
18933 the program on a subsequent run command, just as though the arguments
18934 had been entered on a normal invocation of the program. The @code{set args}
18935 command is not needed if the program does not require arguments.
18936
18937 @item run
18938 The @code{run} command causes execution of the program to start from
18939 the beginning. If the program is already running, that is to say if
18940 you are currently positioned at a breakpoint, then a prompt will ask
18941 for confirmation that you want to abandon the current execution and
18942 restart.
18943
18944 @item breakpoint @var{location}
18945 The breakpoint command sets a breakpoint, that is to say a point at which
18946 execution will halt and @code{GDB} will await further
18947 commands. @var{location} is
18948 either a line number within a file, given in the format @code{file:linenumber},
18949 or it is the name of a subprogram. If you request that a breakpoint be set on
18950 a subprogram that is overloaded, a prompt will ask you to specify on which of
18951 those subprograms you want to breakpoint. You can also
18952 specify that all of them should be breakpointed. If the program is run
18953 and execution encounters the breakpoint, then the program
18954 stops and @code{GDB} signals that the breakpoint was encountered by
18955 printing the line of code before which the program is halted.
18956
18957 @item catch exception @var{name}
18958 This command causes the program execution to stop whenever exception
18959 @var{name} is raised.  If @var{name} is omitted, then the execution is
18960 suspended when any exception is raised.
18961
18962 @item print @var{expression}
18963 This will print the value of the given expression. Most simple
18964 Ada expression formats are properly handled by @code{GDB}, so the expression
18965 can contain function calls, variables, operators, and attribute references.
18966
18967 @item continue
18968 Continues execution following a breakpoint, until the next breakpoint or the
18969 termination of the program.
18970
18971 @item step
18972 Executes a single line after a breakpoint. If the next statement
18973 is a subprogram call, execution continues into (the first statement of)
18974 the called subprogram.
18975
18976 @item next
18977 Executes a single line. If this line is a subprogram call, executes and
18978 returns from the call.
18979
18980 @item list
18981 Lists a few lines around the current source location. In practice, it
18982 is usually more convenient to have a separate edit window open with the
18983 relevant source file displayed. Successive applications of this command
18984 print subsequent lines. The command can be given an argument which is a
18985 line number, in which case it displays a few lines around the specified one.
18986
18987 @item backtrace
18988 Displays a backtrace of the call chain. This command is typically
18989 used after a breakpoint has occurred, to examine the sequence of calls that
18990 leads to the current breakpoint. The display includes one line for each
18991 activation record (frame) corresponding to an active subprogram.
18992
18993 @item up
18994 At a breakpoint, @code{GDB} can display the values of variables local
18995 to the current frame. The command @code{up} can be used to
18996 examine the contents of other active frames, by moving the focus up
18997 the stack, that is to say from callee to caller, one frame at a time.
18998
18999 @item down
19000 Moves the focus of @code{GDB} down from the frame currently being
19001 examined to the frame of its callee (the reverse of the previous command),
19002
19003 @item frame @var{n}
19004 Inspect the frame with the given number. The value 0 denotes the frame
19005 of the current breakpoint, that is to say the top of the call stack.
19006
19007 @end table
19008
19009 @noindent
19010 The above list is a very short introduction to the commands that
19011 @code{GDB} provides. Important additional capabilities, including conditional
19012 breakpoints, the ability to execute command sequences on a breakpoint,
19013 the ability to debug at the machine instruction level and many other
19014 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19015 Debugging with GDB}.  Note that most commands can be abbreviated
19016 (for example, c for continue, bt for backtrace).
19017
19018 @node Using Ada Expressions
19019 @section Using Ada Expressions
19020 @cindex Ada expressions
19021
19022 @noindent
19023 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19024 extensions. The philosophy behind the design of this subset is
19025
19026 @itemize @bullet
19027 @item
19028 That @code{GDB} should provide basic literals and access to operations for
19029 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19030 leaving more sophisticated computations to subprograms written into the
19031 program (which therefore may be called from @code{GDB}).
19032
19033 @item
19034 That type safety and strict adherence to Ada language restrictions
19035 are not particularly important to the @code{GDB} user.
19036
19037 @item
19038 That brevity is important to the @code{GDB} user.
19039 @end itemize
19040
19041 @noindent
19042 Thus, for brevity, the debugger acts as if there were
19043 implicit @code{with} and @code{use} clauses in effect for all user-written
19044 packages, thus making it unnecessary to fully qualify most names with
19045 their packages, regardless of context. Where this causes ambiguity,
19046 @code{GDB} asks the user's intent.
19047
19048 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19049 GDB, gdb, Debugging with GDB}.
19050
19051 @node Calling User-Defined Subprograms
19052 @section Calling User-Defined Subprograms
19053
19054 @noindent
19055 An important capability of @code{GDB} is the ability to call user-defined
19056 subprograms while debugging. This is achieved simply by entering
19057 a subprogram call statement in the form:
19058
19059 @smallexample
19060 call subprogram-name (parameters)
19061 @end smallexample
19062
19063 @noindent
19064 The keyword @code{call} can be omitted in the normal case where the
19065 @code{subprogram-name} does not coincide with any of the predefined
19066 @code{GDB} commands.
19067
19068 The effect is to invoke the given subprogram, passing it the
19069 list of parameters that is supplied. The parameters can be expressions and
19070 can include variables from the program being debugged. The
19071 subprogram must be defined
19072 at the library level within your program, and @code{GDB} will call the
19073 subprogram within the environment of your program execution (which
19074 means that the subprogram is free to access or even modify variables
19075 within your program).
19076
19077 The most important use of this facility is in allowing the inclusion of
19078 debugging routines that are tailored to particular data structures
19079 in your program. Such debugging routines can be written to provide a suitably
19080 high-level description of an abstract type, rather than a low-level dump
19081 of its physical layout. After all, the standard
19082 @code{GDB print} command only knows the physical layout of your
19083 types, not their abstract meaning. Debugging routines can provide information
19084 at the desired semantic level and are thus enormously useful.
19085
19086 For example, when debugging GNAT itself, it is crucial to have access to
19087 the contents of the tree nodes used to represent the program internally.
19088 But tree nodes are represented simply by an integer value (which in turn
19089 is an index into a table of nodes).
19090 Using the @code{print} command on a tree node would simply print this integer
19091 value, which is not very useful. But the PN routine (defined in file
19092 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19093 a useful high level representation of the tree node, which includes the
19094 syntactic category of the node, its position in the source, the integers
19095 that denote descendant nodes and parent node, as well as varied
19096 semantic information. To study this example in more detail, you might want to
19097 look at the body of the PN procedure in the stated file.
19098
19099 @node Using the Next Command in a Function
19100 @section Using the Next Command in a Function
19101
19102 @noindent
19103 When you use the @code{next} command in a function, the current source
19104 location will advance to the next statement as usual. A special case
19105 arises in the case of a @code{return} statement.
19106
19107 Part of the code for a return statement is the ``epilog'' of the function.
19108 This is the code that returns to the caller. There is only one copy of
19109 this epilog code, and it is typically associated with the last return
19110 statement in the function if there is more than one return. In some
19111 implementations, this epilog is associated with the first statement
19112 of the function.
19113
19114 The result is that if you use the @code{next} command from a return
19115 statement that is not the last return statement of the function you
19116 may see a strange apparent jump to the last return statement or to
19117 the start of the function. You should simply ignore this odd jump.
19118 The value returned is always that from the first return statement
19119 that was stepped through.
19120
19121 @node Ada Exceptions
19122 @section Stopping when Ada Exceptions are Raised
19123 @cindex Exceptions
19124
19125 @noindent
19126 You can set catchpoints that stop the program execution when your program
19127 raises selected exceptions.
19128
19129 @table @code
19130 @item catch exception
19131 Set a catchpoint that stops execution whenever (any task in the) program
19132 raises any exception.
19133
19134 @item catch exception @var{name}
19135 Set a catchpoint that stops execution whenever (any task in the) program
19136 raises the exception @var{name}.
19137
19138 @item catch exception unhandled
19139 Set a catchpoint that stops executino whenever (any task in the) program
19140 raises an exception for which there is no handler.
19141
19142 @item info exceptions
19143 @itemx info exceptions @var{regexp}
19144 The @code{info exceptions} command permits the user to examine all defined
19145 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19146 argument, prints out only those exceptions whose name matches @var{regexp}.
19147 @end table
19148
19149 @node Ada Tasks
19150 @section Ada Tasks
19151 @cindex Tasks
19152
19153 @noindent
19154 @code{GDB} allows the following task-related commands:
19155
19156 @table @code
19157 @item info tasks
19158 This command shows a list of current Ada tasks, as in the following example:
19159
19160 @smallexample
19161 @iftex
19162 @leftskip=0cm
19163 @end iftex
19164 (gdb) info tasks
19165   ID       TID P-ID   Thread Pri State                 Name
19166    1   8088000   0   807e000  15 Child Activation Wait main_task
19167    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19168    3   809a800   1   80a4800  15 Child Activation Wait a
19169 *  4   80ae800   3   80b8000  15 Running               c
19170 @end smallexample
19171
19172 @noindent
19173 In this listing, the asterisk before the first task indicates it to be the
19174 currently running task. The first column lists the task ID that is used
19175 to refer to tasks in the following commands.
19176
19177 @item break @var{linespec} task @var{taskid}
19178 @itemx break @var{linespec} task @var{taskid} if @dots{}
19179 @cindex Breakpoints and tasks
19180 These commands are like the @code{break @dots{} thread @dots{}}.
19181 @var{linespec} specifies source lines.
19182
19183 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19184 to specify that you only want @code{GDB} to stop the program when a
19185 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19186 numeric task identifiers assigned by @code{GDB}, shown in the first
19187 column of the @samp{info tasks} display.
19188
19189 If you do not specify @samp{task @var{taskid}} when you set a
19190 breakpoint, the breakpoint applies to @emph{all} tasks of your
19191 program.
19192
19193 You can use the @code{task} qualifier on conditional breakpoints as
19194 well; in this case, place @samp{task @var{taskid}} before the
19195 breakpoint condition (before the @code{if}).
19196
19197 @item task @var{taskno}
19198 @cindex Task switching
19199
19200 This command allows to switch to the task referred by @var{taskno}. In
19201 particular, This allows to browse the backtrace of the specified
19202 task. It is advised to switch back to the original task before
19203 continuing execution otherwise the scheduling of the program may be
19204 perturbed.
19205 @end table
19206
19207 @noindent
19208 For more detailed information on the tasking support,
19209 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19210
19211 @node Debugging Generic Units
19212 @section Debugging Generic Units
19213 @cindex Debugging Generic Units
19214 @cindex Generics
19215
19216 @noindent
19217 GNAT always uses code expansion for generic instantiation. This means that
19218 each time an instantiation occurs, a complete copy of the original code is
19219 made, with appropriate substitutions of formals by actuals.
19220
19221 It is not possible to refer to the original generic entities in
19222 @code{GDB}, but it is always possible to debug a particular instance of
19223 a generic, by using the appropriate expanded names. For example, if we have
19224
19225 @smallexample @c ada
19226 @group
19227 @cartouche
19228 procedure g is
19229
19230    generic package k is
19231       procedure kp (v1 : in out integer);
19232    end k;
19233
19234    package body k is
19235       procedure kp (v1 : in out integer) is
19236       begin
19237          v1 := v1 + 1;
19238       end kp;
19239    end k;
19240
19241    package k1 is new k;
19242    package k2 is new k;
19243
19244    var : integer := 1;
19245
19246 begin
19247    k1.kp (var);
19248    k2.kp (var);
19249    k1.kp (var);
19250    k2.kp (var);
19251 end;
19252 @end cartouche
19253 @end group
19254 @end smallexample
19255
19256 @noindent
19257 Then to break on a call to procedure kp in the k2 instance, simply
19258 use the command:
19259
19260 @smallexample
19261 (gdb) break g.k2.kp
19262 @end smallexample
19263
19264 @noindent
19265 When the breakpoint occurs, you can step through the code of the
19266 instance in the normal manner and examine the values of local variables, as for
19267 other units.
19268
19269 @node Remote Debugging using gdbserver
19270 @section Remote Debugging using gdbserver
19271 @cindex Remote Debugging using gdbserver
19272
19273 @noindent
19274 On platforms where gdbserver is supported, it is possible to use this tool
19275 to debug your application remotely.  This can be useful in situations
19276 where the program needs to be run on a target host that is different
19277 from the host used for development, particularly when the target has
19278 a limited amount of resources (either CPU and/or memory).
19279
19280 To do so, start your program using gdbserver on the target machine.
19281 gdbserver then automatically suspends the execution of your program
19282 at its entry point, waiting for a debugger to connect to it.  The
19283 following commands starts an application and tells gdbserver to
19284 wait for a connection with the debugger on localhost port 4444.
19285
19286 @smallexample
19287 $ gdbserver localhost:4444 program
19288 Process program created; pid = 5685
19289 Listening on port 4444
19290 @end smallexample
19291
19292 Once gdbserver has started listening, we can tell the debugger to establish
19293 a connection with this gdbserver, and then start the same debugging session
19294 as if the program was being debugged on the same host, directly under
19295 the control of GDB.
19296
19297 @smallexample
19298 $ gdb program
19299 (gdb) target remote targethost:4444
19300 Remote debugging using targethost:4444
19301 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19302 (gdb) b foo.adb:3
19303 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19304 (gdb) continue
19305 Continuing.
19306
19307 Breakpoint 1, foo () at foo.adb:4
19308 4       end foo;
19309 @end smallexample
19310
19311 It is also possible to use gdbserver to attach to an already running
19312 program, in which case the execution of that program is simply suspended
19313 until the connection between the debugger and gdbserver is established.
19314
19315 For more information on how to use gdbserver, @ref{Top, Server, Using
19316 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
19317 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19318
19319 @node GNAT Abnormal Termination or Failure to Terminate
19320 @section GNAT Abnormal Termination or Failure to Terminate
19321 @cindex GNAT Abnormal Termination or Failure to Terminate
19322
19323 @noindent
19324 When presented with programs that contain serious errors in syntax
19325 or semantics,
19326 GNAT may on rare occasions  experience problems in operation, such
19327 as aborting with a
19328 segmentation fault or illegal memory access, raising an internal
19329 exception, terminating abnormally, or failing to terminate at all.
19330 In such cases, you can activate
19331 various features of GNAT that can help you pinpoint the construct in your
19332 program that is the likely source of the problem.
19333
19334 The following strategies are presented in increasing order of
19335 difficulty, corresponding to your experience in using GNAT and your
19336 familiarity with compiler internals.
19337
19338 @enumerate
19339 @item
19340 Run @command{gcc} with the @option{-gnatf}. This first
19341 switch causes all errors on a given line to be reported. In its absence,
19342 only the first error on a line is displayed.
19343
19344 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19345 are encountered, rather than after compilation is terminated. If GNAT
19346 terminates prematurely or goes into an infinite loop, the last error
19347 message displayed may help to pinpoint the culprit.
19348
19349 @item
19350 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19351 mode, @command{gcc} produces ongoing information about the progress of the
19352 compilation and provides the name of each procedure as code is
19353 generated. This switch allows you to find which Ada procedure was being
19354 compiled when it encountered a code generation problem.
19355
19356 @item
19357 @cindex @option{-gnatdc} switch
19358 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19359 switch that does for the front-end what @option{^-v^VERBOSE^} does
19360 for the back end. The system prints the name of each unit,
19361 either a compilation unit or nested unit, as it is being analyzed.
19362 @item
19363 Finally, you can start
19364 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19365 front-end of GNAT, and can be run independently (normally it is just
19366 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19367 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19368 @code{where} command is the first line of attack; the variable
19369 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19370 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19371 which the execution stopped, and @code{input_file name} indicates the name of
19372 the source file.
19373 @end enumerate
19374
19375 @node Naming Conventions for GNAT Source Files
19376 @section Naming Conventions for GNAT Source Files
19377
19378 @noindent
19379 In order to examine the workings of the GNAT system, the following
19380 brief description of its organization may be helpful:
19381
19382 @itemize @bullet
19383 @item
19384 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19385
19386 @item
19387 All files prefixed with @file{^par^PAR^} are components of the parser. The
19388 numbers correspond to chapters of the Ada Reference Manual. For example,
19389 parsing of select statements can be found in @file{par-ch9.adb}.
19390
19391 @item
19392 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19393 numbers correspond to chapters of the Ada standard. For example, all
19394 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19395 addition, some features of the language require sufficient special processing
19396 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19397 dynamic dispatching, etc.
19398
19399 @item
19400 All files prefixed with @file{^exp^EXP^} perform normalization and
19401 expansion of the intermediate representation (abstract syntax tree, or AST).
19402 these files use the same numbering scheme as the parser and semantics files.
19403 For example, the construction of record initialization procedures is done in
19404 @file{exp_ch3.adb}.
19405
19406 @item
19407 The files prefixed with @file{^bind^BIND^} implement the binder, which
19408 verifies the consistency of the compilation, determines an order of
19409 elaboration, and generates the bind file.
19410
19411 @item
19412 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19413 data structures used by the front-end.
19414
19415 @item
19416 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19417 the abstract syntax tree as produced by the parser.
19418
19419 @item
19420 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19421 all entities, computed during semantic analysis.
19422
19423 @item
19424 Library management issues are dealt with in files with prefix
19425 @file{^lib^LIB^}.
19426
19427 @item
19428 @findex Ada
19429 @cindex Annex A
19430 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19431 defined in Annex A.
19432
19433 @item
19434 @findex Interfaces
19435 @cindex Annex B
19436 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19437 defined in Annex B.
19438
19439 @item
19440 @findex System
19441 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19442 both language-defined children and GNAT run-time routines.
19443
19444 @item
19445 @findex GNAT
19446 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19447 general-purpose packages, fully documented in their specs. All
19448 the other @file{.c} files are modifications of common @command{gcc} files.
19449 @end itemize
19450
19451 @node Getting Internal Debugging Information
19452 @section Getting Internal Debugging Information
19453
19454 @noindent
19455 Most compilers have internal debugging switches and modes. GNAT
19456 does also, except GNAT internal debugging switches and modes are not
19457 secret. A summary and full description of all the compiler and binder
19458 debug flags are in the file @file{debug.adb}. You must obtain the
19459 sources of the compiler to see the full detailed effects of these flags.
19460
19461 The switches that print the source of the program (reconstructed from
19462 the internal tree) are of general interest for user programs, as are the
19463 options to print
19464 the full internal tree, and the entity table (the symbol table
19465 information). The reconstructed source provides a readable version of the
19466 program after the front-end has completed analysis and  expansion,
19467 and is useful when studying the performance of specific constructs.
19468 For example, constraint checks are indicated, complex aggregates
19469 are replaced with loops and assignments, and tasking primitives
19470 are replaced with run-time calls.
19471
19472 @node Stack Traceback
19473 @section Stack Traceback
19474 @cindex traceback
19475 @cindex stack traceback
19476 @cindex stack unwinding
19477
19478 @noindent
19479 Traceback is a mechanism to display the sequence of subprogram calls that
19480 leads to a specified execution point in a program. Often (but not always)
19481 the execution point is an instruction at which an exception has been raised.
19482 This mechanism is also known as @i{stack unwinding} because it obtains
19483 its information by scanning the run-time stack and recovering the activation
19484 records of all active subprograms. Stack unwinding is one of the most
19485 important tools for program debugging.
19486
19487 The first entry stored in traceback corresponds to the deepest calling level,
19488 that is to say the subprogram currently executing the instruction
19489 from which we want to obtain the traceback.
19490
19491 Note that there is no runtime performance penalty when stack traceback
19492 is enabled, and no exception is raised during program execution.
19493
19494 @menu
19495 * Non-Symbolic Traceback::
19496 * Symbolic Traceback::
19497 @end menu
19498
19499 @node Non-Symbolic Traceback
19500 @subsection Non-Symbolic Traceback
19501 @cindex traceback, non-symbolic
19502
19503 @noindent
19504 Note: this feature is not supported on all platforms. See
19505 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19506 platforms.
19507
19508 @menu
19509 * Tracebacks From an Unhandled Exception::
19510 * Tracebacks From Exception Occurrences (non-symbolic)::
19511 * Tracebacks From Anywhere in a Program (non-symbolic)::
19512 @end menu
19513
19514 @node Tracebacks From an Unhandled Exception
19515 @subsubsection Tracebacks From an Unhandled Exception
19516
19517 @noindent
19518 A runtime non-symbolic traceback is a list of addresses of call instructions.
19519 To enable this feature you must use the @option{-E}
19520 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19521 of exception information. You can retrieve this information using the
19522 @code{addr2line} tool.
19523
19524 Here is a simple example:
19525
19526 @smallexample @c ada
19527 @cartouche
19528 procedure STB is
19529
19530    procedure P1 is
19531    begin
19532       raise Constraint_Error;
19533    end P1;
19534
19535    procedure P2 is
19536    begin
19537       P1;
19538    end P2;
19539
19540 begin
19541    P2;
19542 end STB;
19543 @end cartouche
19544 @end smallexample
19545
19546 @smallexample
19547 $ gnatmake stb -bargs -E
19548 $ stb
19549
19550 Execution terminated by unhandled exception
19551 Exception name: CONSTRAINT_ERROR
19552 Message: stb.adb:5
19553 Call stack traceback locations:
19554 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19555 @end smallexample
19556
19557 @noindent
19558 As we see the traceback lists a sequence of addresses for the unhandled
19559 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19560 guess that this exception come from procedure P1. To translate these
19561 addresses into the source lines where the calls appear, the
19562 @code{addr2line} tool, described below, is invaluable. The use of this tool
19563 requires the program to be compiled with debug information.
19564
19565 @smallexample
19566 $ gnatmake -g stb -bargs -E
19567 $ stb
19568
19569 Execution terminated by unhandled exception
19570 Exception name: CONSTRAINT_ERROR
19571 Message: stb.adb:5
19572 Call stack traceback locations:
19573 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19574
19575 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19576    0x4011f1 0x77e892a4
19577
19578 00401373 at d:/stb/stb.adb:5
19579 0040138B at d:/stb/stb.adb:10
19580 0040139C at d:/stb/stb.adb:14
19581 00401335 at d:/stb/b~stb.adb:104
19582 004011C4 at /build/@dots{}/crt1.c:200
19583 004011F1 at /build/@dots{}/crt1.c:222
19584 77E892A4 in ?? at ??:0
19585 @end smallexample
19586
19587 @noindent
19588 The @code{addr2line} tool has several other useful options:
19589
19590 @table @code
19591 @item --functions
19592 to get the function name corresponding to any location
19593
19594 @item --demangle=gnat
19595 to use the gnat decoding mode for the function names. Note that
19596 for binutils version 2.9.x the option is simply @option{--demangle}.
19597 @end table
19598
19599 @smallexample
19600 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19601    0x40139c 0x401335 0x4011c4 0x4011f1
19602
19603 00401373 in stb.p1 at d:/stb/stb.adb:5
19604 0040138B in stb.p2 at d:/stb/stb.adb:10
19605 0040139C in stb at d:/stb/stb.adb:14
19606 00401335 in main at d:/stb/b~stb.adb:104
19607 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19608 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19609 @end smallexample
19610
19611 @noindent
19612 From this traceback we can see that the exception was raised in
19613 @file{stb.adb} at line 5, which was reached from a procedure call in
19614 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19615 which contains the call to the main program.
19616 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19617 and the output will vary from platform to platform.
19618
19619 It is also possible to use @code{GDB} with these traceback addresses to debug
19620 the program. For example, we can break at a given code location, as reported
19621 in the stack traceback:
19622
19623 @smallexample
19624 $ gdb -nw stb
19625 @ifclear vms
19626 @noindent
19627 Furthermore, this feature is not implemented inside Windows DLL. Only
19628 the non-symbolic traceback is reported in this case.
19629 @end ifclear
19630
19631 (gdb) break *0x401373
19632 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19633 @end smallexample
19634
19635 @noindent
19636 It is important to note that the stack traceback addresses
19637 do not change when debug information is included. This is particularly useful
19638 because it makes it possible to release software without debug information (to
19639 minimize object size), get a field report that includes a stack traceback
19640 whenever an internal bug occurs, and then be able to retrieve the sequence
19641 of calls with the same program compiled with debug information.
19642
19643 @node Tracebacks From Exception Occurrences (non-symbolic)
19644 @subsubsection Tracebacks From Exception Occurrences
19645
19646 @noindent
19647 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19648 The stack traceback is attached to the exception information string, and can
19649 be retrieved in an exception handler within the Ada program, by means of the
19650 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19651
19652 @smallexample @c ada
19653 with Ada.Text_IO;
19654 with Ada.Exceptions;
19655
19656 procedure STB is
19657
19658    use Ada;
19659    use Ada.Exceptions;
19660
19661    procedure P1 is
19662       K : Positive := 1;
19663    begin
19664       K := K - 1;
19665    exception
19666       when E : others =>
19667          Text_IO.Put_Line (Exception_Information (E));
19668    end P1;
19669
19670    procedure P2 is
19671    begin
19672       P1;
19673    end P2;
19674
19675 begin
19676    P2;
19677 end STB;
19678 @end smallexample
19679
19680 @noindent
19681 This program will output:
19682
19683 @smallexample
19684 $ stb
19685
19686 Exception name: CONSTRAINT_ERROR
19687 Message: stb.adb:12
19688 Call stack traceback locations:
19689 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19690 @end smallexample
19691
19692 @node Tracebacks From Anywhere in a Program (non-symbolic)
19693 @subsubsection Tracebacks From Anywhere in a Program
19694
19695 @noindent
19696 It is also possible to retrieve a stack traceback from anywhere in a
19697 program. For this you need to
19698 use the @code{GNAT.Traceback} API. This package includes a procedure called
19699 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19700 display procedures described below. It is not necessary to use the
19701 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19702 is invoked explicitly.
19703
19704 @noindent
19705 In the following example we compute a traceback at a specific location in
19706 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19707 convert addresses to strings:
19708
19709 @smallexample @c ada
19710 with Ada.Text_IO;
19711 with GNAT.Traceback;
19712 with GNAT.Debug_Utilities;
19713
19714 procedure STB is
19715
19716    use Ada;
19717    use GNAT;
19718    use GNAT.Traceback;
19719
19720    procedure P1 is
19721       TB  : Tracebacks_Array (1 .. 10);
19722       --  We are asking for a maximum of 10 stack frames.
19723       Len : Natural;
19724       --  Len will receive the actual number of stack frames returned.
19725    begin
19726       Call_Chain (TB, Len);
19727
19728       Text_IO.Put ("In STB.P1 : ");
19729
19730       for K in 1 .. Len loop
19731          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19732          Text_IO.Put (' ');
19733       end loop;
19734
19735       Text_IO.New_Line;
19736    end P1;
19737
19738    procedure P2 is
19739    begin
19740       P1;
19741    end P2;
19742
19743 begin
19744    P2;
19745 end STB;
19746 @end smallexample
19747
19748 @smallexample
19749 $ gnatmake -g stb
19750 $ stb
19751
19752 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19753 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19754 @end smallexample
19755
19756 @noindent
19757 You can then get further information by invoking the @code{addr2line}
19758 tool as described earlier (note that the hexadecimal addresses
19759 need to be specified in C format, with a leading ``0x'').
19760
19761 @node Symbolic Traceback
19762 @subsection Symbolic Traceback
19763 @cindex traceback, symbolic
19764
19765 @noindent
19766 A symbolic traceback is a stack traceback in which procedure names are
19767 associated with each code location.
19768
19769 @noindent
19770 Note that this feature is not supported on all platforms. See
19771 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19772 list of currently supported platforms.
19773
19774 @noindent
19775 Note that the symbolic traceback requires that the program be compiled
19776 with debug information. If it is not compiled with debug information
19777 only the non-symbolic information will be valid.
19778
19779 @menu
19780 * Tracebacks From Exception Occurrences (symbolic)::
19781 * Tracebacks From Anywhere in a Program (symbolic)::
19782 @end menu
19783
19784 @node Tracebacks From Exception Occurrences (symbolic)
19785 @subsubsection Tracebacks From Exception Occurrences
19786
19787 @smallexample @c ada
19788 with Ada.Text_IO;
19789 with GNAT.Traceback.Symbolic;
19790
19791 procedure STB is
19792
19793    procedure P1 is
19794    begin
19795       raise Constraint_Error;
19796    end P1;
19797
19798    procedure P2 is
19799    begin
19800       P1;
19801    end P2;
19802
19803    procedure P3 is
19804    begin
19805       P2;
19806    end P3;
19807
19808 begin
19809    P3;
19810 exception
19811    when E : others =>
19812       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19813 end STB;
19814 @end smallexample
19815
19816 @smallexample
19817 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19818 $ stb
19819
19820 0040149F in stb.p1 at stb.adb:8
19821 004014B7 in stb.p2 at stb.adb:13
19822 004014CF in stb.p3 at stb.adb:18
19823 004015DD in ada.stb at stb.adb:22
19824 00401461 in main at b~stb.adb:168
19825 004011C4 in __mingw_CRTStartup at crt1.c:200
19826 004011F1 in mainCRTStartup at crt1.c:222
19827 77E892A4 in ?? at ??:0
19828 @end smallexample
19829
19830 @noindent
19831 In the above example the ``.\'' syntax in the @command{gnatmake} command
19832 is currently required by @command{addr2line} for files that are in
19833 the current working directory.
19834 Moreover, the exact sequence of linker options may vary from platform
19835 to platform.
19836 The above @option{-largs} section is for Windows platforms. By contrast,
19837 under Unix there is no need for the @option{-largs} section.
19838 Differences across platforms are due to details of linker implementation.
19839
19840 @node Tracebacks From Anywhere in a Program (symbolic)
19841 @subsubsection Tracebacks From Anywhere in a Program
19842
19843 @noindent
19844 It is possible to get a symbolic stack traceback
19845 from anywhere in a program, just as for non-symbolic tracebacks.
19846 The first step is to obtain a non-symbolic
19847 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19848 information. Here is an example:
19849
19850 @smallexample @c ada
19851 with Ada.Text_IO;
19852 with GNAT.Traceback;
19853 with GNAT.Traceback.Symbolic;
19854
19855 procedure STB is
19856
19857    use Ada;
19858    use GNAT.Traceback;
19859    use GNAT.Traceback.Symbolic;
19860
19861    procedure P1 is
19862       TB  : Tracebacks_Array (1 .. 10);
19863       --  We are asking for a maximum of 10 stack frames.
19864       Len : Natural;
19865       --  Len will receive the actual number of stack frames returned.
19866    begin
19867       Call_Chain (TB, Len);
19868       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19869    end P1;
19870
19871    procedure P2 is
19872    begin
19873       P1;
19874    end P2;
19875
19876 begin
19877    P2;
19878 end STB;
19879 @end smallexample
19880
19881 @c ******************************
19882 @ifset vms
19883 @node Compatibility with HP Ada
19884 @chapter Compatibility with HP Ada
19885 @cindex Compatibility
19886
19887 @noindent
19888 @cindex DEC Ada
19889 @cindex HP Ada
19890 @cindex Compatibility between GNAT and HP Ada
19891 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19892 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19893 GNAT is highly compatible
19894 with HP Ada, and it should generally be straightforward to port code
19895 from the HP Ada environment to GNAT. However, there are a few language
19896 and implementation differences of which the user must be aware. These
19897 differences are discussed in this chapter. In
19898 addition, the operating environment and command structure for the
19899 compiler are different, and these differences are also discussed.
19900
19901 For further details on these and other compatibility issues,
19902 see Appendix E of the HP publication
19903 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19904
19905 Except where otherwise indicated, the description of GNAT for OpenVMS
19906 applies to both the Alpha and I64 platforms.
19907
19908 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19909 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19910
19911 The discussion in this chapter addresses specifically the implementation
19912 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19913 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19914 GNAT always follows the Alpha implementation.
19915
19916 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19917 attributes are recognized, although only a subset of them can sensibly
19918 be implemented.  The description of pragmas in
19919 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19920 indicates whether or not they are applicable to non-VMS systems.
19921
19922 @menu
19923 * Ada Language Compatibility::
19924 * Differences in the Definition of Package System::
19925 * Language-Related Features::
19926 * The Package STANDARD::
19927 * The Package SYSTEM::
19928 * Tasking and Task-Related Features::
19929 * Pragmas and Pragma-Related Features::
19930 * Library of Predefined Units::
19931 * Bindings::
19932 * Main Program Definition::
19933 * Implementation-Defined Attributes::
19934 * Compiler and Run-Time Interfacing::
19935 * Program Compilation and Library Management::
19936 * Input-Output::
19937 * Implementation Limits::
19938 * Tools and Utilities::
19939 @end menu
19940
19941 @node Ada Language Compatibility
19942 @section Ada Language Compatibility
19943
19944 @noindent
19945 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19946 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19947 with Ada 83, and therefore Ada 83 programs will compile
19948 and run under GNAT with
19949 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19950 provides details on specific incompatibilities.
19951
19952 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19953 as well as the pragma @code{ADA_83}, to force the compiler to
19954 operate in Ada 83 mode. This mode does not guarantee complete
19955 conformance to Ada 83, but in practice is sufficient to
19956 eliminate most sources of incompatibilities.
19957 In particular, it eliminates the recognition of the
19958 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19959 in Ada 83 programs is legal, and handles the cases of packages
19960 with optional bodies, and generics that instantiate unconstrained
19961 types without the use of @code{(<>)}.
19962
19963 @node Differences in the Definition of Package System
19964 @section Differences in the Definition of Package @code{System}
19965
19966 @noindent
19967 An Ada compiler is allowed to add
19968 implementation-dependent declarations to package @code{System}.
19969 In normal mode,
19970 GNAT does not take advantage of this permission, and the version of
19971 @code{System} provided by GNAT exactly matches that defined in the Ada
19972 Reference Manual.
19973
19974 However, HP Ada adds an extensive set of declarations to package
19975 @code{System},
19976 as fully documented in the HP Ada manuals. To minimize changes required
19977 for programs that make use of these extensions, GNAT provides the pragma
19978 @code{Extend_System} for extending the definition of package System. By using:
19979 @cindex pragma @code{Extend_System}
19980 @cindex @code{Extend_System} pragma
19981
19982 @smallexample @c ada
19983 @group
19984 @cartouche
19985 pragma Extend_System (Aux_DEC);
19986 @end cartouche
19987 @end group
19988 @end smallexample
19989
19990 @noindent
19991 the set of definitions in @code{System} is extended to include those in
19992 package @code{System.Aux_DEC}.
19993 @cindex @code{System.Aux_DEC} package
19994 @cindex @code{Aux_DEC} package (child of @code{System})
19995 These definitions are incorporated directly into package @code{System},
19996 as though they had been declared there. For a
19997 list of the declarations added, see the spec of this package,
19998 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19999 @cindex @file{s-auxdec.ads} file
20000 The pragma @code{Extend_System} is a configuration pragma, which means that
20001 it can be placed in the file @file{gnat.adc}, so that it will automatically
20002 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20003 for further details.
20004
20005 An alternative approach that avoids the use of the non-standard
20006 @code{Extend_System} pragma is to add a context clause to the unit that
20007 references these facilities:
20008
20009 @smallexample @c ada
20010 @cartouche
20011 with System.Aux_DEC;
20012 use  System.Aux_DEC;
20013 @end cartouche
20014 @end smallexample
20015
20016 @noindent
20017 The effect is not quite semantically identical to incorporating
20018 the declarations directly into package @code{System},
20019 but most programs will not notice a difference
20020 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20021 to reference the entities directly in package @code{System}.
20022 For units containing such references,
20023 the prefixes must either be removed, or the pragma @code{Extend_System}
20024 must be used.
20025
20026 @node Language-Related Features
20027 @section Language-Related Features
20028
20029 @noindent
20030 The following sections highlight differences in types,
20031 representations of types, operations, alignment, and
20032 related topics.
20033
20034 @menu
20035 * Integer Types and Representations::
20036 * Floating-Point Types and Representations::
20037 * Pragmas Float_Representation and Long_Float::
20038 * Fixed-Point Types and Representations::
20039 * Record and Array Component Alignment::
20040 * Address Clauses::
20041 * Other Representation Clauses::
20042 @end menu
20043
20044 @node Integer Types and Representations
20045 @subsection Integer Types and Representations
20046
20047 @noindent
20048 The set of predefined integer types is identical in HP Ada and GNAT.
20049 Furthermore the representation of these integer types is also identical,
20050 including the capability of size clauses forcing biased representation.
20051
20052 In addition,
20053 HP Ada for OpenVMS Alpha systems has defined the
20054 following additional integer types in package @code{System}:
20055
20056 @itemize @bullet
20057
20058 @item
20059 @code{INTEGER_8}
20060
20061 @item
20062 @code{INTEGER_16}
20063
20064 @item
20065 @code{INTEGER_32}
20066
20067 @item
20068 @code{INTEGER_64}
20069
20070 @item
20071 @code{LARGEST_INTEGER}
20072 @end itemize
20073
20074 @noindent
20075 In GNAT, the first four of these types may be obtained from the
20076 standard Ada package @code{Interfaces}.
20077 Alternatively, by use of the pragma @code{Extend_System}, identical
20078 declarations can be referenced directly in package @code{System}.
20079 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20080
20081 @node Floating-Point Types and Representations
20082 @subsection Floating-Point Types and Representations
20083 @cindex Floating-Point types
20084
20085 @noindent
20086 The set of predefined floating-point types is identical in HP Ada and GNAT.
20087 Furthermore the representation of these floating-point
20088 types is also identical. One important difference is that the default
20089 representation for HP Ada is @code{VAX_Float}, but the default representation
20090 for GNAT is IEEE.
20091
20092 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20093 pragma @code{Float_Representation} as described in the HP Ada
20094 documentation.
20095 For example, the declarations:
20096
20097 @smallexample @c ada
20098 @cartouche
20099 type F_Float is digits 6;
20100 pragma Float_Representation (VAX_Float, F_Float);
20101 @end cartouche
20102 @end smallexample
20103
20104 @noindent
20105 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20106 format.
20107 This set of declarations actually appears in @code{System.Aux_DEC},
20108 which contains
20109 the full set of additional floating-point declarations provided in
20110 the HP Ada version of package @code{System}.
20111 This and similar declarations may be accessed in a user program
20112 by using pragma @code{Extend_System}. The use of this
20113 pragma, and the related pragma @code{Long_Float} is described in further
20114 detail in the following section.
20115
20116 @node Pragmas Float_Representation and Long_Float
20117 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20118
20119 @noindent
20120 HP Ada provides the pragma @code{Float_Representation}, which
20121 acts as a program library switch to allow control over
20122 the internal representation chosen for the predefined
20123 floating-point types declared in the package @code{Standard}.
20124 The format of this pragma is as follows:
20125
20126 @smallexample @c ada
20127 @cartouche
20128 pragma Float_Representation(VAX_Float | IEEE_Float);
20129 @end cartouche
20130 @end smallexample
20131
20132 @noindent
20133 This pragma controls the representation of floating-point
20134 types as follows:
20135
20136 @itemize @bullet
20137 @item
20138 @code{VAX_Float} specifies that floating-point
20139 types are represented by default with the VAX system hardware types
20140 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20141 Note that the @code{H-floating}
20142 type was available only on VAX systems, and is not available
20143 in either HP Ada or GNAT.
20144
20145 @item
20146 @code{IEEE_Float} specifies that floating-point
20147 types are represented by default with the IEEE single and
20148 double floating-point types.
20149 @end itemize
20150
20151 @noindent
20152 GNAT provides an identical implementation of the pragma
20153 @code{Float_Representation}, except that it functions as a
20154 configuration pragma. Note that the
20155 notion of configuration pragma corresponds closely to the
20156 HP Ada notion of a program library switch.
20157
20158 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20159 which is different
20160 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20161 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20162 advisable to change the format of numbers passed to standard library
20163 routines, and if necessary explicit type conversions may be needed.
20164
20165 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20166 efficient, and (given that it conforms to an international standard)
20167 potentially more portable.
20168 The situation in which @code{VAX_Float} may be useful is in interfacing
20169 to existing code and data that expect the use of @code{VAX_Float}.
20170 In such a situation use the predefined @code{VAX_Float}
20171 types in package @code{System}, as extended by
20172 @code{Extend_System}. For example, use @code{System.F_Float}
20173 to specify the 32-bit @code{F-Float} format.
20174
20175 @noindent
20176 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20177 to allow control over the internal representation chosen
20178 for the predefined type @code{Long_Float} and for floating-point
20179 type declarations with digits specified in the range 7 .. 15.
20180 The format of this pragma is as follows:
20181
20182 @smallexample @c ada
20183 @cartouche
20184 pragma Long_Float (D_FLOAT | G_FLOAT);
20185 @end cartouche
20186 @end smallexample
20187
20188 @node Fixed-Point Types and Representations
20189 @subsection Fixed-Point Types and Representations
20190
20191 @noindent
20192 On HP Ada for OpenVMS Alpha systems, rounding is
20193 away from zero for both positive and negative numbers.
20194 Therefore, @code{+0.5} rounds to @code{1},
20195 and @code{-0.5} rounds to @code{-1}.
20196
20197 On GNAT the results of operations
20198 on fixed-point types are in accordance with the Ada
20199 rules. In particular, results of operations on decimal
20200 fixed-point types are truncated.
20201
20202 @node Record and Array Component Alignment
20203 @subsection Record and Array Component Alignment
20204
20205 @noindent
20206 On HP Ada for OpenVMS Alpha, all non-composite components
20207 are aligned on natural boundaries. For example, 1-byte
20208 components are aligned on byte boundaries, 2-byte
20209 components on 2-byte boundaries, 4-byte components on 4-byte
20210 byte boundaries, and so on. The OpenVMS Alpha hardware
20211 runs more efficiently with naturally aligned data.
20212
20213 On GNAT, alignment rules are compatible
20214 with HP Ada for OpenVMS Alpha.
20215
20216 @node Address Clauses
20217 @subsection Address Clauses
20218
20219 @noindent
20220 In HP Ada and GNAT, address clauses are supported for
20221 objects and imported subprograms.
20222 The predefined type @code{System.Address} is a private type
20223 in both compilers on Alpha OpenVMS, with the same representation
20224 (it is simply a machine pointer). Addition, subtraction, and comparison
20225 operations are available in the standard Ada package
20226 @code{System.Storage_Elements}, or in package @code{System}
20227 if it is extended to include @code{System.Aux_DEC} using a
20228 pragma @code{Extend_System} as previously described.
20229
20230 Note that code that @code{with}'s both this extended package @code{System}
20231 and the package @code{System.Storage_Elements} should not @code{use}
20232 both packages, or ambiguities will result. In general it is better
20233 not to mix these two sets of facilities. The Ada package was
20234 designed specifically to provide the kind of features that HP Ada
20235 adds directly to package @code{System}.
20236
20237 The type @code{System.Address} is a 64-bit integer type in GNAT for
20238 I64 OpenVMS.  For more information,
20239 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20240
20241 GNAT is compatible with HP Ada in its handling of address
20242 clauses, except for some limitations in
20243 the form of address clauses for composite objects with
20244 initialization. Such address clauses are easily replaced
20245 by the use of an explicitly-defined constant as described
20246 in the Ada Reference Manual (13.1(22)). For example, the sequence
20247 of declarations:
20248
20249 @smallexample @c ada
20250 @cartouche
20251 X, Y : Integer := Init_Func;
20252 Q : String (X .. Y) := "abc";
20253 @dots{}
20254 for Q'Address use Compute_Address;
20255 @end cartouche
20256 @end smallexample
20257
20258 @noindent
20259 will be rejected by GNAT, since the address cannot be computed at the time
20260 that @code{Q} is declared. To achieve the intended effect, write instead:
20261
20262 @smallexample @c ada
20263 @group
20264 @cartouche
20265 X, Y : Integer := Init_Func;
20266 Q_Address : constant Address := Compute_Address;
20267 Q : String (X .. Y) := "abc";
20268 @dots{}
20269 for Q'Address use Q_Address;
20270 @end cartouche
20271 @end group
20272 @end smallexample
20273
20274 @noindent
20275 which will be accepted by GNAT (and other Ada compilers), and is also
20276 compatible with Ada 83. A fuller description of the restrictions
20277 on address specifications is found in @ref{Top, GNAT Reference Manual,
20278 About This Guide, gnat_rm, GNAT Reference Manual}.
20279
20280 @node Other Representation Clauses
20281 @subsection Other Representation Clauses
20282
20283 @noindent
20284 GNAT implements in a compatible manner all the representation
20285 clauses supported by HP Ada. In addition, GNAT
20286 implements the representation clause forms that were introduced in Ada 95,
20287 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20288
20289 @node The Package STANDARD
20290 @section The Package @code{STANDARD}
20291
20292 @noindent
20293 The package @code{STANDARD}, as implemented by HP Ada, is fully
20294 described in the @cite{Ada Reference Manual} and in the
20295 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20296 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20297
20298 In addition, HP Ada supports the Latin-1 character set in
20299 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20300 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20301 the type @code{WIDE_CHARACTER}.
20302
20303 The floating-point types supported by GNAT are those
20304 supported by HP Ada, but the defaults are different, and are controlled by
20305 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20306
20307 @node The Package SYSTEM
20308 @section The Package @code{SYSTEM}
20309
20310 @noindent
20311 HP Ada provides a specific version of the package
20312 @code{SYSTEM} for each platform on which the language is implemented.
20313 For the complete spec of the package @code{SYSTEM}, see
20314 Appendix F of the @cite{HP Ada Language Reference Manual}.
20315
20316 On HP Ada, the package @code{SYSTEM} includes the following conversion
20317 functions:
20318 @itemize @bullet
20319 @item @code{TO_ADDRESS(INTEGER)}
20320
20321 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20322
20323 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20324
20325 @item @code{TO_INTEGER(ADDRESS)}
20326
20327 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20328
20329 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20330 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20331 @end itemize
20332
20333 @noindent
20334 By default, GNAT supplies a version of @code{SYSTEM} that matches
20335 the definition given in the @cite{Ada Reference Manual}.
20336 This
20337 is a subset of the HP system definitions, which is as
20338 close as possible to the original definitions. The only difference
20339 is that the definition of @code{SYSTEM_NAME} is different:
20340
20341 @smallexample @c ada
20342 @cartouche
20343 type Name is (SYSTEM_NAME_GNAT);
20344 System_Name : constant Name := SYSTEM_NAME_GNAT;
20345 @end cartouche
20346 @end smallexample
20347
20348 @noindent
20349 Also, GNAT adds the Ada declarations for
20350 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20351
20352 However, the use of the following pragma causes GNAT
20353 to extend the definition of package @code{SYSTEM} so that it
20354 encompasses the full set of HP-specific extensions,
20355 including the functions listed above:
20356
20357 @smallexample @c ada
20358 @cartouche
20359 pragma Extend_System (Aux_DEC);
20360 @end cartouche
20361 @end smallexample
20362
20363 @noindent
20364 The pragma @code{Extend_System} is a configuration pragma that
20365 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20366 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20367
20368 HP Ada does not allow the recompilation of the package
20369 @code{SYSTEM}. Instead HP Ada provides several pragmas
20370 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20371 to modify values in the package @code{SYSTEM}.
20372 On OpenVMS Alpha systems, the pragma
20373 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20374 its single argument.
20375
20376 GNAT does permit the recompilation of package @code{SYSTEM} using
20377 the special switch @option{-gnatg}, and this switch can be used if
20378 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20379 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20380 or @code{MEMORY_SIZE} by any other means.
20381
20382 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20383 enumeration literal @code{SYSTEM_NAME_GNAT}.
20384
20385 The definitions provided by the use of
20386
20387 @smallexample @c ada
20388 pragma Extend_System (AUX_Dec);
20389 @end smallexample
20390
20391 @noindent
20392 are virtually identical to those provided by the HP Ada 83 package
20393 @code{SYSTEM}. One important difference is that the name of the
20394 @code{TO_ADDRESS}
20395 function for type @code{UNSIGNED_LONGWORD} is changed to
20396 @code{TO_ADDRESS_LONG}.
20397 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20398 discussion of why this change was necessary.
20399
20400 @noindent
20401 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20402 is in fact
20403 an extension to Ada 83 not strictly compatible with the reference manual.
20404 GNAT, in order to be exactly compatible with the standard,
20405 does not provide this capability. In HP Ada 83, the
20406 point of this definition is to deal with a call like:
20407
20408 @smallexample @c ada
20409 TO_ADDRESS (16#12777#);
20410 @end smallexample
20411
20412 @noindent
20413 Normally, according to Ada 83 semantics, one would expect this to be
20414 ambiguous, since it matches both the @code{INTEGER} and
20415 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20416 However, in HP Ada 83, there is no ambiguity, since the
20417 definition using @i{universal_integer} takes precedence.
20418
20419 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20420 it is
20421 not possible to be 100% compatible. Since there are many programs using
20422 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20423 GNAT was
20424 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20425 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20426
20427 @smallexample @c ada
20428 function To_Address (X : Integer) return Address;
20429 pragma Pure_Function (To_Address);
20430
20431 function To_Address_Long (X : Unsigned_Longword) return Address;
20432 pragma Pure_Function (To_Address_Long);
20433 @end smallexample
20434
20435 @noindent
20436 This means that programs using @code{TO_ADDRESS} for
20437 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20438
20439 @node Tasking and Task-Related Features
20440 @section Tasking and Task-Related Features
20441
20442 @noindent
20443 This section compares the treatment of tasking in GNAT
20444 and in HP Ada for OpenVMS Alpha.
20445 The GNAT description applies to both Alpha and I64 OpenVMS.
20446 For detailed information on tasking in
20447 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20448 relevant run-time reference manual.
20449
20450 @menu
20451 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20452 * Assigning Task IDs::
20453 * Task IDs and Delays::
20454 * Task-Related Pragmas::
20455 * Scheduling and Task Priority::
20456 * The Task Stack::
20457 * External Interrupts::
20458 @end menu
20459
20460 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20461 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20462
20463 @noindent
20464 On OpenVMS Alpha systems, each Ada task (except a passive
20465 task) is implemented as a single stream of execution
20466 that is created and managed by the kernel. On these
20467 systems, HP Ada tasking support is based on DECthreads,
20468 an implementation of the POSIX standard for threads.
20469
20470 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20471 code that calls DECthreads routines can be used together.
20472 The interaction between Ada tasks and DECthreads routines
20473 can have some benefits. For example when on OpenVMS Alpha,
20474 HP Ada can call C code that is already threaded.
20475
20476 GNAT uses the facilities of DECthreads,
20477 and Ada tasks are mapped to threads.
20478
20479 @node Assigning Task IDs
20480 @subsection Assigning Task IDs
20481
20482 @noindent
20483 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20484 the environment task that executes the main program. On
20485 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20486 that have been created but are not yet activated.
20487
20488 On OpenVMS Alpha systems, task IDs are assigned at
20489 activation. On GNAT systems, task IDs are also assigned at
20490 task creation but do not have the same form or values as
20491 task ID values in HP Ada. There is no null task, and the
20492 environment task does not have a specific task ID value.
20493
20494 @node Task IDs and Delays
20495 @subsection Task IDs and Delays
20496
20497 @noindent
20498 On OpenVMS Alpha systems, tasking delays are implemented
20499 using Timer System Services. The Task ID is used for the
20500 identification of the timer request (the @code{REQIDT} parameter).
20501 If Timers are used in the application take care not to use
20502 @code{0} for the identification, because cancelling such a timer
20503 will cancel all timers and may lead to unpredictable results.
20504
20505 @node Task-Related Pragmas
20506 @subsection Task-Related Pragmas
20507
20508 @noindent
20509 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20510 specification of the size of the guard area for a task
20511 stack. (The guard area forms an area of memory that has no
20512 read or write access and thus helps in the detection of
20513 stack overflow.) On OpenVMS Alpha systems, if the pragma
20514 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20515 area is created. In the absence of a pragma @code{TASK_STORAGE},
20516 a default guard area is created.
20517
20518 GNAT supplies the following task-related pragmas:
20519
20520 @itemize @bullet
20521 @item  @code{TASK_INFO}
20522
20523 This pragma appears within a task definition and
20524 applies to the task in which it appears. The argument
20525 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20526
20527 @item  @code{TASK_STORAGE}
20528
20529 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20530 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20531 @code{SUPPRESS}, and @code{VOLATILE}.
20532 @end itemize
20533 @node Scheduling and Task Priority
20534 @subsection Scheduling and Task Priority
20535
20536 @noindent
20537 HP Ada implements the Ada language requirement that
20538 when two tasks are eligible for execution and they have
20539 different priorities, the lower priority task does not
20540 execute while the higher priority task is waiting. The HP
20541 Ada Run-Time Library keeps a task running until either the
20542 task is suspended or a higher priority task becomes ready.
20543
20544 On OpenVMS Alpha systems, the default strategy is round-
20545 robin with preemption. Tasks of equal priority take turns
20546 at the processor. A task is run for a certain period of
20547 time and then placed at the tail of the ready queue for
20548 its priority level.
20549
20550 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20551 which can be used to enable or disable round-robin
20552 scheduling of tasks with the same priority.
20553 See the relevant HP Ada run-time reference manual for
20554 information on using the pragmas to control HP Ada task
20555 scheduling.
20556
20557 GNAT follows the scheduling rules of Annex D (Real-Time
20558 Annex) of the @cite{Ada Reference Manual}. In general, this
20559 scheduling strategy is fully compatible with HP Ada
20560 although it provides some additional constraints (as
20561 fully documented in Annex D).
20562 GNAT implements time slicing control in a manner compatible with
20563 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20564 are identical to the HP Ada 83 pragma of the same name.
20565 Note that it is not possible to mix GNAT tasking and
20566 HP Ada 83 tasking in the same program, since the two run-time
20567 libraries are not compatible.
20568
20569 @node The Task Stack
20570 @subsection The Task Stack
20571
20572 @noindent
20573 In HP Ada, a task stack is allocated each time a
20574 non-passive task is activated. As soon as the task is
20575 terminated, the storage for the task stack is deallocated.
20576 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20577 a default stack size is used. Also, regardless of the size
20578 specified, some additional space is allocated for task
20579 management purposes. On OpenVMS Alpha systems, at least
20580 one page is allocated.
20581
20582 GNAT handles task stacks in a similar manner. In accordance with
20583 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20584 an alternative method for controlling the task stack size.
20585 The specification of the attribute @code{T'STORAGE_SIZE} is also
20586 supported in a manner compatible with HP Ada.
20587
20588 @node External Interrupts
20589 @subsection External Interrupts
20590
20591 @noindent
20592 On HP Ada, external interrupts can be associated with task entries.
20593 GNAT is compatible with HP Ada in its handling of external interrupts.
20594
20595 @node Pragmas and Pragma-Related Features
20596 @section Pragmas and Pragma-Related Features
20597
20598 @noindent
20599 Both HP Ada and GNAT supply all language-defined pragmas
20600 as specified by the Ada 83 standard. GNAT also supplies all
20601 language-defined pragmas introduced by Ada 95 and Ada 2005.
20602 In addition, GNAT implements the implementation-defined pragmas
20603 from HP Ada 83.
20604
20605 @itemize @bullet
20606 @item  @code{AST_ENTRY}
20607
20608 @item  @code{COMMON_OBJECT}
20609
20610 @item  @code{COMPONENT_ALIGNMENT}
20611
20612 @item  @code{EXPORT_EXCEPTION}
20613
20614 @item  @code{EXPORT_FUNCTION}
20615
20616 @item  @code{EXPORT_OBJECT}
20617
20618 @item  @code{EXPORT_PROCEDURE}
20619
20620 @item  @code{EXPORT_VALUED_PROCEDURE}
20621
20622 @item  @code{FLOAT_REPRESENTATION}
20623
20624 @item  @code{IDENT}
20625
20626 @item  @code{IMPORT_EXCEPTION}
20627
20628 @item  @code{IMPORT_FUNCTION}
20629
20630 @item  @code{IMPORT_OBJECT}
20631
20632 @item  @code{IMPORT_PROCEDURE}
20633
20634 @item  @code{IMPORT_VALUED_PROCEDURE}
20635
20636 @item  @code{INLINE_GENERIC}
20637
20638 @item  @code{INTERFACE_NAME}
20639
20640 @item  @code{LONG_FLOAT}
20641
20642 @item  @code{MAIN_STORAGE}
20643
20644 @item  @code{PASSIVE}
20645
20646 @item  @code{PSECT_OBJECT}
20647
20648 @item  @code{SHARE_GENERIC}
20649
20650 @item  @code{SUPPRESS_ALL}
20651
20652 @item  @code{TASK_STORAGE}
20653
20654 @item  @code{TIME_SLICE}
20655
20656 @item  @code{TITLE}
20657 @end itemize
20658
20659 @noindent
20660 These pragmas are all fully implemented, with the exception of @code{TITLE},
20661 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20662 recognized, but which have no
20663 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20664 use of Ada protected objects. In GNAT, all generics are inlined.
20665
20666 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20667 a separate subprogram specification which must appear before the
20668 subprogram body.
20669
20670 GNAT also supplies a number of implementation-defined pragmas as follows:
20671 @itemize @bullet
20672 @item  @code{ABORT_DEFER}
20673
20674 @item  @code{ADA_83}
20675
20676 @item  @code{ADA_95}
20677
20678 @item  @code{ADA_05}
20679
20680 @item  @code{ANNOTATE}
20681
20682 @item  @code{ASSERT}
20683
20684 @item  @code{C_PASS_BY_COPY}
20685
20686 @item  @code{CPP_CLASS}
20687
20688 @item  @code{CPP_CONSTRUCTOR}
20689
20690 @item  @code{CPP_DESTRUCTOR}
20691
20692 @item  @code{DEBUG}
20693
20694 @item  @code{EXTEND_SYSTEM}
20695
20696 @item  @code{LINKER_ALIAS}
20697
20698 @item  @code{LINKER_SECTION}
20699
20700 @item  @code{MACHINE_ATTRIBUTE}
20701
20702 @item  @code{NO_RETURN}
20703
20704 @item  @code{PURE_FUNCTION}
20705
20706 @item  @code{SOURCE_FILE_NAME}
20707
20708 @item  @code{SOURCE_REFERENCE}
20709
20710 @item  @code{TASK_INFO}
20711
20712 @item  @code{UNCHECKED_UNION}
20713
20714 @item  @code{UNIMPLEMENTED_UNIT}
20715
20716 @item  @code{UNIVERSAL_DATA}
20717
20718 @item  @code{UNSUPPRESS}
20719
20720 @item  @code{WARNINGS}
20721
20722 @item  @code{WEAK_EXTERNAL}
20723 @end itemize
20724
20725 @noindent
20726 For full details on these GNAT implementation-defined pragmas,
20727 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20728 Manual}.
20729
20730 @menu
20731 * Restrictions on the Pragma INLINE::
20732 * Restrictions on the Pragma INTERFACE::
20733 * Restrictions on the Pragma SYSTEM_NAME::
20734 @end menu
20735
20736 @node Restrictions on the Pragma INLINE
20737 @subsection Restrictions on Pragma @code{INLINE}
20738
20739 @noindent
20740 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20741 @itemize @bullet
20742 @item  Parameters cannot have a task type.
20743
20744 @item  Function results cannot be task types, unconstrained
20745 array types, or unconstrained types with discriminants.
20746
20747 @item  Bodies cannot declare the following:
20748 @itemize @bullet
20749 @item  Subprogram body or stub (imported subprogram is allowed)
20750
20751 @item  Tasks
20752
20753 @item  Generic declarations
20754
20755 @item  Instantiations
20756
20757 @item  Exceptions
20758
20759 @item  Access types (types derived from access types allowed)
20760
20761 @item  Array or record types
20762
20763 @item  Dependent tasks
20764
20765 @item  Direct recursive calls of subprogram or containing
20766 subprogram, directly or via a renaming
20767
20768 @end itemize
20769 @end itemize
20770
20771 @noindent
20772 In GNAT, the only restriction on pragma @code{INLINE} is that the
20773 body must occur before the call if both are in the same
20774 unit, and the size must be appropriately small. There are
20775 no other specific restrictions which cause subprograms to
20776 be incapable of being inlined.
20777
20778 @node  Restrictions on the Pragma INTERFACE
20779 @subsection  Restrictions on Pragma @code{INTERFACE}
20780
20781 @noindent
20782 The following restrictions on pragma @code{INTERFACE}
20783 are enforced by both HP Ada and GNAT:
20784 @itemize @bullet
20785 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20786 Default is the default on OpenVMS Alpha systems.
20787
20788 @item  Parameter passing: Language specifies default
20789 mechanisms but can be overridden with an @code{EXPORT} pragma.
20790
20791 @itemize @bullet
20792 @item  Ada: Use internal Ada rules.
20793
20794 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20795 record or task type. Result cannot be a string, an
20796 array, or a record.
20797
20798 @item  Fortran: Parameters cannot have a task type. Result cannot
20799 be a string, an array, or a record.
20800 @end itemize
20801 @end itemize
20802
20803 @noindent
20804 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20805 record parameters for all languages.
20806
20807 @node  Restrictions on the Pragma SYSTEM_NAME
20808 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20809
20810 @noindent
20811 For HP Ada for OpenVMS Alpha, the enumeration literal
20812 for the type @code{NAME} is @code{OPENVMS_AXP}.
20813 In GNAT, the enumeration
20814 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20815
20816 @node  Library of Predefined Units
20817 @section  Library of Predefined Units
20818
20819 @noindent
20820 A library of predefined units is provided as part of the
20821 HP Ada and GNAT implementations. HP Ada does not provide
20822 the package @code{MACHINE_CODE} but instead recommends importing
20823 assembler code.
20824
20825 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20826 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20827 version.
20828 The HP Ada Predefined Library units are modified to remove post-Ada 83
20829 incompatibilities and to make them interoperable with GNAT
20830 (@pxref{Changes to DECLIB}, for details).
20831 The units are located in the @file{DECLIB} directory.
20832
20833 The GNAT RTL is contained in
20834 the @file{ADALIB} directory, and
20835 the default search path is set up to find @code{DECLIB} units in preference
20836 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20837 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20838
20839 @menu
20840 * Changes to DECLIB::
20841 @end menu
20842
20843 @node Changes to DECLIB
20844 @subsection Changes to @code{DECLIB}
20845
20846 @noindent
20847 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20848 compatibility are minor and include the following:
20849
20850 @itemize @bullet
20851 @item  Adjusting the location of pragmas and record representation
20852 clauses to obey Ada 95 (and thus Ada 2005) rules
20853
20854 @item  Adding the proper notation to generic formal parameters
20855 that take unconstrained types in instantiation
20856
20857 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20858 that have package bodies not otherwise allowed
20859
20860 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20861 ``@code{PROTECTD}''.
20862 Currently these are found only in the @code{STARLET} package spec.
20863
20864 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20865 where the address size is constrained to 32 bits.
20866 @end itemize
20867
20868 @noindent
20869 None of the above changes is visible to users.
20870
20871 @node Bindings
20872 @section Bindings
20873
20874 @noindent
20875 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20876 @itemize @bullet
20877
20878 @item  Command Language Interpreter (CLI interface)
20879
20880 @item  DECtalk Run-Time Library (DTK interface)
20881
20882 @item  Librarian utility routines (LBR interface)
20883
20884 @item  General Purpose Run-Time Library (LIB interface)
20885
20886 @item  Math Run-Time Library (MTH interface)
20887
20888 @item  National Character Set Run-Time Library (NCS interface)
20889
20890 @item  Compiled Code Support Run-Time Library (OTS interface)
20891
20892 @item  Parallel Processing Run-Time Library (PPL interface)
20893
20894 @item  Screen Management Run-Time Library (SMG interface)
20895
20896 @item  Sort Run-Time Library (SOR interface)
20897
20898 @item  String Run-Time Library (STR interface)
20899
20900 @item STARLET System Library
20901 @findex Starlet
20902
20903 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20904
20905 @item  X Windows Toolkit (XT interface)
20906
20907 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20908 @end itemize
20909
20910 @noindent
20911 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20912 directory, on both the Alpha and I64 OpenVMS platforms.
20913
20914 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20915 in the
20916 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20917 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20918 @code{Xt}, and @code{X_Lib}
20919 causing the default X/Motif sharable image libraries to be linked in. This
20920 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20921 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20922
20923 It may be necessary to edit these options files to update or correct the
20924 library names if, for example, the newer X/Motif bindings from
20925 @file{ADA$EXAMPLES}
20926 had been (previous to installing GNAT) copied and renamed to supersede the
20927 default @file{ADA$PREDEFINED} versions.
20928
20929 @menu
20930 * Shared Libraries and Options Files::
20931 * Interfaces to C::
20932 @end menu
20933
20934 @node Shared Libraries and Options Files
20935 @subsection Shared Libraries and Options Files
20936
20937 @noindent
20938 When using the HP Ada
20939 predefined X and Motif bindings, the linking with their sharable images is
20940 done automatically by @command{GNAT LINK}.
20941 When using other X and Motif bindings, you need
20942 to add the corresponding sharable images to the command line for
20943 @code{GNAT LINK}. When linking with shared libraries, or with
20944 @file{.OPT} files, you must
20945 also add them to the command line for @command{GNAT LINK}.
20946
20947 A shared library to be used with GNAT is built in the same way as other
20948 libraries under VMS. The VMS Link command can be used in standard fashion.
20949
20950 @node Interfaces to C
20951 @subsection Interfaces to C
20952
20953 @noindent
20954 HP Ada
20955 provides the following Ada types and operations:
20956
20957 @itemize @bullet
20958 @item C types package (@code{C_TYPES})
20959
20960 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20961
20962 @item Other_types (@code{SHORT_INT})
20963 @end itemize
20964
20965 @noindent
20966 Interfacing to C with GNAT, you can use the above approach
20967 described for HP Ada or the facilities of Annex B of
20968 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20969 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20970 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20971
20972 The @option{-gnatF} qualifier forces default and explicit
20973 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20974 to be uppercased for compatibility with the default behavior
20975 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20976
20977 @node Main Program Definition
20978 @section Main Program Definition
20979
20980 @noindent
20981 The following section discusses differences in the
20982 definition of main programs on HP Ada and GNAT.
20983 On HP Ada, main programs are defined to meet the
20984 following conditions:
20985 @itemize @bullet
20986 @item  Procedure with no formal parameters (returns @code{0} upon
20987 normal completion)
20988
20989 @item  Procedure with no formal parameters (returns @code{42} when
20990 an unhandled exception is raised)
20991
20992 @item  Function with no formal parameters whose returned value
20993 is of a discrete type
20994
20995 @item  Procedure with one @code{out} formal of a discrete type for
20996 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20997
20998 @end itemize
20999
21000 @noindent
21001 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21002 a main function or main procedure returns a discrete
21003 value whose size is less than 64 bits (32 on VAX systems),
21004 the value is zero- or sign-extended as appropriate.
21005 On GNAT, main programs are defined as follows:
21006 @itemize @bullet
21007 @item  Must be a non-generic, parameterless subprogram that
21008 is either a procedure or function returning an Ada
21009 @code{STANDARD.INTEGER} (the predefined type)
21010
21011 @item  Cannot be a generic subprogram or an instantiation of a
21012 generic subprogram
21013 @end itemize
21014
21015 @node Implementation-Defined Attributes
21016 @section Implementation-Defined Attributes
21017
21018 @noindent
21019 GNAT provides all HP Ada implementation-defined
21020 attributes.
21021
21022 @node Compiler and Run-Time Interfacing
21023 @section Compiler and Run-Time Interfacing
21024
21025 @noindent
21026 HP Ada provides the following qualifiers to pass options to the linker
21027 (ACS LINK):
21028 @itemize @bullet
21029 @item  @option{/WAIT} and @option{/SUBMIT}
21030
21031 @item  @option{/COMMAND}
21032
21033 @item  @option{/@r{[}NO@r{]}MAP}
21034
21035 @item  @option{/OUTPUT=@var{file-spec}}
21036
21037 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21038 @end itemize
21039
21040 @noindent
21041 To pass options to the linker, GNAT provides the following
21042 switches:
21043
21044 @itemize @bullet
21045 @item   @option{/EXECUTABLE=@var{exec-name}}
21046
21047 @item   @option{/VERBOSE}
21048
21049 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21050 @end itemize
21051
21052 @noindent
21053 For more information on these switches, see
21054 @ref{Switches for gnatlink}.
21055 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21056 to control optimization. HP Ada also supplies the
21057 following pragmas:
21058 @itemize @bullet
21059 @item  @code{OPTIMIZE}
21060
21061 @item  @code{INLINE}
21062
21063 @item  @code{INLINE_GENERIC}
21064
21065 @item  @code{SUPPRESS_ALL}
21066
21067 @item  @code{PASSIVE}
21068 @end itemize
21069
21070 @noindent
21071 In GNAT, optimization is controlled strictly by command
21072 line parameters, as described in the corresponding section of this guide.
21073 The HP pragmas for control of optimization are
21074 recognized but ignored.
21075
21076 Note that in GNAT, the default is optimization off, whereas in HP Ada
21077 the default is that optimization is turned on.
21078
21079 @node Program Compilation and Library Management
21080 @section Program Compilation and Library Management
21081
21082 @noindent
21083 HP Ada and GNAT provide a comparable set of commands to
21084 build programs. HP Ada also provides a program library,
21085 which is a concept that does not exist on GNAT. Instead,
21086 GNAT provides directories of sources that are compiled as
21087 needed.
21088
21089 The following table summarizes
21090 the HP Ada commands and provides
21091 equivalent GNAT commands. In this table, some GNAT
21092 equivalents reflect the fact that GNAT does not use the
21093 concept of a program library. Instead, it uses a model
21094 in which collections of source and object files are used
21095 in a manner consistent with other languages like C and
21096 Fortran. Therefore, standard system file commands are used
21097 to manipulate these elements. Those GNAT commands are marked with
21098 an asterisk.
21099 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21100
21101 @need 1500
21102 @multitable @columnfractions .35 .65
21103
21104 @item @emph{HP Ada Command}
21105 @tab @emph{GNAT Equivalent / Description}
21106
21107 @item @command{ADA}
21108 @tab @command{GNAT COMPILE}@*
21109 Invokes the compiler to compile one or more Ada source files.
21110
21111 @item @command{ACS ATTACH}@*
21112 @tab [No equivalent]@*
21113 Switches control of terminal from current process running the program
21114 library manager.
21115
21116 @item @command{ACS CHECK}
21117 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21118 Forms the execution closure of one
21119 or more compiled units and checks completeness and currency.
21120
21121 @item @command{ACS COMPILE}
21122 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21123 Forms the execution closure of one or
21124 more specified units, checks completeness and currency,
21125 identifies units that have revised source files, compiles same,
21126 and recompiles units that are or will become obsolete.
21127 Also completes incomplete generic instantiations.
21128
21129 @item @command{ACS COPY FOREIGN}
21130 @tab Copy (*)@*
21131 Copies a foreign object file into the program library as a
21132 library unit body.
21133
21134 @item @command{ACS COPY UNIT}
21135 @tab Copy (*)@*
21136 Copies a compiled unit from one program library to another.
21137
21138 @item @command{ACS CREATE LIBRARY}
21139 @tab Create /directory (*)@*
21140 Creates a program library.
21141
21142 @item @command{ACS CREATE SUBLIBRARY}
21143 @tab Create /directory (*)@*
21144 Creates a program sublibrary.
21145
21146 @item @command{ACS DELETE LIBRARY}
21147 @tab @*
21148 Deletes a program library and its contents.
21149
21150 @item @command{ACS DELETE SUBLIBRARY}
21151 @tab @*
21152 Deletes a program sublibrary and its contents.
21153
21154 @item @command{ACS DELETE UNIT}
21155 @tab Delete file (*)@*
21156 On OpenVMS systems, deletes one or more compiled units from
21157 the current program library.
21158
21159 @item @command{ACS DIRECTORY}
21160 @tab Directory (*)@*
21161 On OpenVMS systems, lists units contained in the current
21162 program library.
21163
21164 @item @command{ACS ENTER FOREIGN}
21165 @tab Copy (*)@*
21166 Allows the import of a foreign body as an Ada library
21167 spec and enters a reference to a pointer.
21168
21169 @item @command{ACS ENTER UNIT}
21170 @tab Copy (*)@*
21171 Enters a reference (pointer) from the current program library to
21172 a unit compiled into another program library.
21173
21174 @item @command{ACS EXIT}
21175 @tab [No equivalent]@*
21176 Exits from the program library manager.
21177
21178 @item @command{ACS EXPORT}
21179 @tab Copy (*)@*
21180 Creates an object file that contains system-specific object code
21181 for one or more units. With GNAT, object files can simply be copied
21182 into the desired directory.
21183
21184 @item @command{ACS EXTRACT SOURCE}
21185 @tab Copy (*)@*
21186 Allows access to the copied source file for each Ada compilation unit
21187
21188 @item @command{ACS HELP}
21189 @tab @command{HELP GNAT}@*
21190 Provides online help.
21191
21192 @item @command{ACS LINK}
21193 @tab @command{GNAT LINK}@*
21194 Links an object file containing Ada units into an executable file.
21195
21196 @item @command{ACS LOAD}
21197 @tab Copy (*)@*
21198 Loads (partially compiles) Ada units into the program library.
21199 Allows loading a program from a collection of files into a library
21200 without knowing the relationship among units.
21201
21202 @item @command{ACS MERGE}
21203 @tab Copy (*)@*
21204 Merges into the current program library, one or more units from
21205 another library where they were modified.
21206
21207 @item @command{ACS RECOMPILE}
21208 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21209 Recompiles from   external or copied source files any obsolete
21210 unit in the closure. Also, completes any incomplete generic
21211 instantiations.
21212
21213 @item @command{ACS REENTER}
21214 @tab @command{GNAT MAKE}@*
21215 Reenters current references to units compiled after last entered
21216 with the @command{ACS ENTER UNIT} command.
21217
21218 @item @command{ACS SET LIBRARY}
21219 @tab Set default (*)@*
21220 Defines a program library to be the compilation context as well
21221 as the target library for compiler output and commands in general.
21222
21223 @item @command{ACS SET PRAGMA}
21224 @tab Edit @file{gnat.adc} (*)@*
21225 Redefines specified  values of the library characteristics
21226 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21227 and @code{Float_Representation}.
21228
21229 @item @command{ACS SET SOURCE}
21230 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21231 Defines the source file search list for the @command{ACS COMPILE} command.
21232
21233 @item @command{ACS SHOW LIBRARY}
21234 @tab Directory (*)@*
21235 Lists information about one or more program libraries.
21236
21237 @item @command{ACS SHOW PROGRAM}
21238 @tab [No equivalent]@*
21239 Lists information about the execution closure of one or
21240 more units in the program library.
21241
21242 @item @command{ACS SHOW SOURCE}
21243 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21244 Shows the source file search used when compiling units.
21245
21246 @item @command{ACS SHOW VERSION}
21247 @tab Compile with @option{VERBOSE} option
21248 Displays the version number of the compiler and program library
21249 manager used.
21250
21251 @item @command{ACS SPAWN}
21252 @tab [No equivalent]@*
21253 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21254 command).
21255
21256 @item @command{ACS VERIFY}
21257 @tab [No equivalent]@*
21258 Performs a series of consistency checks on a program library to
21259 determine whether the library structure and library files are in
21260 valid form.
21261 @end multitable
21262
21263 @noindent
21264
21265 @node Input-Output
21266 @section Input-Output
21267
21268 @noindent
21269 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21270 Management Services (RMS) to perform operations on
21271 external files.
21272
21273 @noindent
21274 HP Ada and GNAT predefine an identical set of input-
21275 output packages. To make the use of the
21276 generic @code{TEXT_IO} operations more convenient, HP Ada
21277 provides predefined library packages that instantiate the
21278 integer and floating-point operations for the predefined
21279 integer and floating-point types as shown in the following table.
21280
21281 @multitable @columnfractions .45 .55
21282 @item @emph{Package Name} @tab Instantiation
21283
21284 @item @code{INTEGER_TEXT_IO}
21285 @tab @code{INTEGER_IO(INTEGER)}
21286
21287 @item @code{SHORT_INTEGER_TEXT_IO}
21288 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21289
21290 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21291 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21292
21293 @item @code{FLOAT_TEXT_IO}
21294 @tab @code{FLOAT_IO(FLOAT)}
21295
21296 @item @code{LONG_FLOAT_TEXT_IO}
21297 @tab @code{FLOAT_IO(LONG_FLOAT)}
21298 @end multitable
21299
21300 @noindent
21301 The HP Ada predefined packages and their operations
21302 are implemented using OpenVMS Alpha files and input-output
21303 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21304 Familiarity with the following is recommended:
21305 @itemize @bullet
21306 @item  RMS file organizations and access methods
21307
21308 @item  OpenVMS file specifications and directories
21309
21310 @item  OpenVMS File Definition Language (FDL)
21311 @end itemize
21312
21313 @noindent
21314 GNAT provides I/O facilities that are completely
21315 compatible with HP Ada. The distribution includes the
21316 standard HP Ada versions of all I/O packages, operating
21317 in a manner compatible with HP Ada. In particular, the
21318 following packages are by default the HP Ada (Ada 83)
21319 versions of these packages rather than the renamings
21320 suggested in Annex J of the Ada Reference Manual:
21321 @itemize @bullet
21322 @item  @code{TEXT_IO}
21323
21324 @item  @code{SEQUENTIAL_IO}
21325
21326 @item  @code{DIRECT_IO}
21327 @end itemize
21328
21329 @noindent
21330 The use of the standard child package syntax (for
21331 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21332 packages.
21333 GNAT provides HP-compatible predefined instantiations
21334 of the @code{TEXT_IO} packages, and also
21335 provides the standard predefined instantiations required
21336 by the @cite{Ada Reference Manual}.
21337
21338 For further information on how GNAT interfaces to the file
21339 system or how I/O is implemented in programs written in
21340 mixed languages, see @ref{Implementation of the Standard I/O,,,
21341 gnat_rm, GNAT Reference Manual}.
21342 This chapter covers the following:
21343 @itemize @bullet
21344 @item  Standard I/O packages
21345
21346 @item  @code{FORM} strings
21347
21348 @item  @code{ADA.DIRECT_IO}
21349
21350 @item  @code{ADA.SEQUENTIAL_IO}
21351
21352 @item  @code{ADA.TEXT_IO}
21353
21354 @item  Stream pointer positioning
21355
21356 @item  Reading and writing non-regular files
21357
21358 @item  @code{GET_IMMEDIATE}
21359
21360 @item  Treating @code{TEXT_IO} files as streams
21361
21362 @item  Shared files
21363
21364 @item  Open modes
21365 @end itemize
21366
21367 @node Implementation Limits
21368 @section Implementation Limits
21369
21370 @noindent
21371 The following table lists implementation limits for HP Ada
21372 and GNAT systems.
21373 @multitable @columnfractions .60 .20 .20
21374 @sp 1
21375 @item  @emph{Compilation Parameter}
21376 @tab   @emph{HP Ada}
21377 @tab   @emph{GNAT}
21378 @sp 1
21379
21380 @item  In a subprogram or entry  declaration, maximum number of
21381 formal parameters that are of an unconstrained record type
21382 @tab   32
21383 @tab   No set limit
21384 @sp 1
21385
21386 @item  Maximum identifier length (number of characters)
21387 @tab   255
21388 @tab   32766
21389 @sp 1
21390
21391 @item  Maximum number of characters in a source line
21392 @tab   255
21393 @tab   32766
21394 @sp 1
21395
21396 @item  Maximum collection size   (number of bytes)
21397 @tab   2**31-1
21398 @tab   2**31-1
21399 @sp 1
21400
21401 @item  Maximum number of discriminants for a record type
21402 @tab   245
21403 @tab   No set limit
21404 @sp 1
21405
21406 @item  Maximum number of formal parameters in an entry or
21407 subprogram declaration
21408 @tab   246
21409 @tab    No set limit
21410 @sp 1
21411
21412 @item  Maximum number of dimensions in an array type
21413 @tab   255
21414 @tab   No set limit
21415 @sp 1
21416
21417 @item  Maximum number of library  units and subunits in a compilation.
21418 @tab   4095
21419 @tab   No set limit
21420 @sp 1
21421
21422 @item  Maximum number of library units and subunits in an execution.
21423 @tab   16383
21424 @tab   No set limit
21425 @sp 1
21426
21427 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21428 or @code{PSECT_OBJECT}
21429 @tab   32757
21430 @tab   No set limit
21431 @sp 1
21432
21433 @item  Maximum number of enumeration literals in an enumeration type
21434 definition
21435 @tab   65535
21436 @tab   No set limit
21437 @sp 1
21438
21439 @item  Maximum number of lines in a source file
21440 @tab   65534
21441 @tab   No set limit
21442 @sp 1
21443
21444 @item  Maximum number of bits in any object
21445 @tab   2**31-1
21446 @tab   2**31-1
21447 @sp 1
21448
21449 @item  Maximum size of the static portion of a stack frame (approximate)
21450 @tab   2**31-1
21451 @tab   2**31-1
21452 @end multitable
21453
21454 @node Tools and Utilities
21455 @section Tools and Utilities
21456
21457 @noindent
21458 The following table lists some of the OpenVMS development tools
21459 available for HP Ada, and the corresponding tools for
21460 use with @value{EDITION} on Alpha and I64 platforms.
21461 Aside from the debugger, all the OpenVMS tools identified are part
21462 of the DECset package.
21463
21464 @iftex
21465 @c Specify table in TeX since Texinfo does a poor job
21466 @tex
21467 \smallskip
21468 \smallskip
21469 \settabs\+Language-Sensitive Editor\quad
21470    &Product with HP Ada\quad
21471    &\cr
21472 \+\it Tool
21473    &\it Product with HP Ada
21474    & \it Product with GNAT Pro\cr
21475 \smallskip
21476 \+Code Management System
21477    &HP CMS
21478    & HP CMS\cr
21479 \smallskip
21480 \+Language-Sensitive Editor
21481    &HP LSE
21482    & emacs or HP LSE (Alpha)\cr
21483 \+
21484    &
21485    & HP LSE (I64)\cr
21486 \smallskip
21487 \+Debugger
21488    &OpenVMS Debug
21489    & gdb (Alpha),\cr
21490 \+
21491    &
21492    & OpenVMS Debug (I64)\cr
21493 \smallskip
21494 \+Source Code Analyzer /
21495    &HP SCA
21496    & GNAT XREF\cr
21497 \+Cross Referencer
21498    &
21499    &\cr
21500 \smallskip
21501 \+Test Manager
21502    &HP Digital Test
21503    & HP DTM\cr
21504 \+
21505    &Manager (DTM)
21506    &\cr
21507 \smallskip
21508 \+Performance and
21509    & HP PCA
21510    & HP PCA\cr
21511 \+Coverage Analyzer
21512    &
21513    &\cr
21514 \smallskip
21515 \+Module Management
21516    & HP MMS
21517    & Not applicable\cr
21518 \+ System
21519    &
21520    &\cr
21521 \smallskip
21522 \smallskip
21523 @end tex
21524 @end iftex
21525
21526 @ifnottex
21527 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21528 @c the TeX version above for the printed version
21529 @flushleft
21530 @c @multitable @columnfractions .3 .4 .4
21531 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21532 @item @i{Tool}
21533 @tab @i{Tool with HP Ada}
21534 @tab @i{Tool with @value{EDITION}}
21535 @item Code Management@*System
21536 @tab HP CMS
21537 @tab HP CMS
21538 @item Language-Sensitive@*Editor
21539 @tab HP LSE
21540 @tab emacs or HP LSE (Alpha)
21541 @item
21542 @tab
21543 @tab HP LSE (I64)
21544 @item Debugger
21545 @tab OpenVMS Debug
21546 @tab gdb (Alpha),
21547 @item
21548 @tab
21549 @tab OpenVMS Debug (I64)
21550 @item Source Code Analyzer /@*Cross Referencer
21551 @tab HP SCA
21552 @tab GNAT XREF
21553 @item Test Manager
21554 @tab HP Digital Test@*Manager (DTM)
21555 @tab HP DTM
21556 @item Performance and@*Coverage Analyzer
21557 @tab HP PCA
21558 @tab HP PCA
21559 @item Module Management@*System
21560 @tab HP MMS
21561 @tab Not applicable
21562 @end multitable
21563 @end flushleft
21564 @end ifnottex
21565
21566 @end ifset
21567
21568 @c **************************************
21569 @node Platform-Specific Information for the Run-Time Libraries
21570 @appendix Platform-Specific Information for the Run-Time Libraries
21571 @cindex Tasking and threads libraries
21572 @cindex Threads libraries and tasking
21573 @cindex Run-time libraries (platform-specific information)
21574
21575 @noindent
21576 The GNAT run-time implementation may vary with respect to both the
21577 underlying threads library and the exception handling scheme.
21578 For threads support, one or more of the following are supplied:
21579 @itemize @bullet
21580 @item @b{native threads library}, a binding to the thread package from
21581 the underlying operating system
21582
21583 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21584 POSIX thread package
21585 @end itemize
21586
21587 @noindent
21588 For exception handling, either or both of two models are supplied:
21589 @itemize @bullet
21590 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21591 Most programs should experience a substantial speed improvement by
21592 being compiled with a ZCX run-time.
21593 This is especially true for
21594 tasking applications or applications with many exception handlers.}
21595 @cindex Zero-Cost Exceptions
21596 @cindex ZCX (Zero-Cost Exceptions)
21597 which uses binder-generated tables that
21598 are interrogated at run time to locate a handler
21599
21600 @item @b{setjmp / longjmp} (``SJLJ''),
21601 @cindex setjmp/longjmp Exception Model
21602 @cindex SJLJ (setjmp/longjmp Exception Model)
21603 which uses dynamically-set data to establish
21604 the set of handlers
21605 @end itemize
21606
21607 @noindent
21608 This appendix summarizes which combinations of threads and exception support
21609 are supplied on various GNAT platforms.
21610 It then shows how to select a particular library either
21611 permanently or temporarily,
21612 explains the properties of (and tradeoffs among) the various threads
21613 libraries, and provides some additional
21614 information about several specific platforms.
21615
21616 @menu
21617 * Summary of Run-Time Configurations::
21618 * Specifying a Run-Time Library::
21619 * Choosing the Scheduling Policy::
21620 * Solaris-Specific Considerations::
21621 * Linux-Specific Considerations::
21622 * AIX-Specific Considerations::
21623 * Irix-Specific Considerations::
21624 * RTX-Specific Considerations::
21625 * HP-UX-Specific Considerations::
21626 @end menu
21627
21628 @node Summary of Run-Time Configurations
21629 @section Summary of Run-Time Configurations
21630
21631 @multitable @columnfractions .30 .70
21632 @item @b{alpha-openvms}
21633 @item @code{@ @ }@i{rts-native (default)}
21634 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21635 @item @code{@ @ @ @ }Exceptions @tab ZCX
21636 @*
21637 @item @b{alpha-tru64}
21638 @item @code{@ @ }@i{rts-native (default)}
21639 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21640 @item @code{@ @ @ @ }Exceptions @tab ZCX
21641 @*
21642 @item @code{@ @ }@i{rts-sjlj}
21643 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21644 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21645 @*
21646 @item @b{ia64-hp_linux}
21647 @item @code{@ @ }@i{rts-native (default)}
21648 @item @code{@ @ @ @ }Tasking    @tab pthread library
21649 @item @code{@ @ @ @ }Exceptions @tab ZCX
21650 @*
21651 @item @b{ia64-hpux}
21652 @item @code{@ @ }@i{rts-native (default)}
21653 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21654 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21655 @*
21656 @item @b{ia64-openvms}
21657 @item @code{@ @ }@i{rts-native (default)}
21658 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21659 @item @code{@ @ @ @ }Exceptions @tab ZCX
21660 @*
21661 @item @b{ia64-sgi_linux}
21662 @item @code{@ @ }@i{rts-native (default)}
21663 @item @code{@ @ @ @ }Tasking    @tab pthread library
21664 @item @code{@ @ @ @ }Exceptions @tab ZCX
21665 @*
21666 @item @b{mips-irix}
21667 @item @code{@ @ }@i{rts-native (default)}
21668 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21669 @item @code{@ @ @ @ }Exceptions @tab ZCX
21670 @*
21671 @item @b{pa-hpux}
21672 @item @code{@ @ }@i{rts-native (default)}
21673 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21674 @item @code{@ @ @ @ }Exceptions @tab ZCX
21675 @*
21676 @item @code{@ @ }@i{rts-sjlj}
21677 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21678 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21679 @*
21680 @item @b{ppc-aix}
21681 @item @code{@ @ }@i{rts-native (default)}
21682 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21683 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21684 @*
21685 @item @b{ppc-darwin}
21686 @item @code{@ @ }@i{rts-native (default)}
21687 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21688 @item @code{@ @ @ @ }Exceptions @tab ZCX
21689 @*
21690 @item @b{sparc-solaris}  @tab
21691 @item @code{@ @ }@i{rts-native (default)}
21692 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21693 @item @code{@ @ @ @ }Exceptions @tab ZCX
21694 @*
21695 @item @code{@ @ }@i{rts-pthread}
21696 @item @code{@ @ @ @ }Tasking    @tab pthread library
21697 @item @code{@ @ @ @ }Exceptions @tab ZCX
21698 @*
21699 @item @code{@ @ }@i{rts-sjlj}
21700 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21701 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21702 @*
21703 @item @b{sparc64-solaris}  @tab
21704 @item @code{@ @ }@i{rts-native (default)}
21705 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21706 @item @code{@ @ @ @ }Exceptions @tab ZCX
21707 @*
21708 @item @b{x86-linux}
21709 @item @code{@ @ }@i{rts-native (default)}
21710 @item @code{@ @ @ @ }Tasking    @tab pthread library
21711 @item @code{@ @ @ @ }Exceptions @tab ZCX
21712 @*
21713 @item @code{@ @ }@i{rts-sjlj}
21714 @item @code{@ @ @ @ }Tasking    @tab pthread library
21715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21716 @*
21717 @item @b{x86-lynx}
21718 @item @code{@ @ }@i{rts-native (default)}
21719 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21721 @*
21722 @item @b{x86-solaris}
21723 @item @code{@ @ }@i{rts-native (default)}
21724 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21725 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21726 @*
21727 @item @b{x86-windows}
21728 @item @code{@ @ }@i{rts-native (default)}
21729 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21730 @item @code{@ @ @ @ }Exceptions @tab ZCX
21731 @*
21732 @item @code{@ @ }@i{rts-sjlj (default)}
21733 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21734 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21735 @*
21736 @item @b{x86-windows-rtx}
21737 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21738 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21739 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21740 @*
21741 @item @code{@ @ }@i{rts-rtx-w32}
21742 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21743 @item @code{@ @ @ @ }Exceptions @tab ZCX
21744 @*
21745 @item @b{x86_64-linux}
21746 @item @code{@ @ }@i{rts-native (default)}
21747 @item @code{@ @ @ @ }Tasking    @tab pthread library
21748 @item @code{@ @ @ @ }Exceptions @tab ZCX
21749 @*
21750 @item @code{@ @ }@i{rts-sjlj}
21751 @item @code{@ @ @ @ }Tasking    @tab pthread library
21752 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21753 @*
21754 @end multitable
21755
21756 @node Specifying a Run-Time Library
21757 @section Specifying a Run-Time Library
21758
21759 @noindent
21760 The @file{adainclude} subdirectory containing the sources of the GNAT
21761 run-time library, and the @file{adalib} subdirectory containing the
21762 @file{ALI} files and the static and/or shared GNAT library, are located
21763 in the gcc target-dependent area:
21764
21765 @smallexample
21766 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21767 @end smallexample
21768
21769 @noindent
21770 As indicated above, on some platforms several run-time libraries are supplied.
21771 These libraries are installed in the target dependent area and
21772 contain a complete source and binary subdirectory. The detailed description
21773 below explains the differences between the different libraries in terms of
21774 their thread support.
21775
21776 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21777 This default run time is selected by the means of soft links.
21778 For example on x86-linux:
21779
21780 @smallexample
21781 @group
21782  $(target-dir)
21783      |
21784      +--- adainclude----------+
21785      |                        |
21786      +--- adalib-----------+  |
21787      |                     |  |
21788      +--- rts-native       |  |
21789      |    |                |  |
21790      |    +--- adainclude <---+
21791      |    |                |
21792      |    +--- adalib <----+
21793      |
21794      +--- rts-sjlj
21795           |
21796           +--- adainclude
21797           |
21798           +--- adalib
21799 @end group
21800 @end smallexample
21801
21802 @noindent
21803 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21804 these soft links can be modified with the following commands:
21805
21806 @smallexample
21807 $ cd $target
21808 $ rm -f adainclude adalib
21809 $ ln -s rts-sjlj/adainclude adainclude
21810 $ ln -s rts-sjlj/adalib adalib
21811 @end smallexample
21812
21813 @noindent
21814 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21815 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21816 @file{$target/ada_object_path}.
21817
21818 Selecting another run-time library temporarily can be
21819 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21820 @cindex @option{--RTS} option
21821
21822 @node Choosing the Scheduling Policy
21823 @section Choosing the Scheduling Policy
21824
21825 @noindent
21826 When using a POSIX threads implementation, you have a choice of several
21827 scheduling policies: @code{SCHED_FIFO},
21828 @cindex @code{SCHED_FIFO} scheduling policy
21829 @code{SCHED_RR}
21830 @cindex @code{SCHED_RR} scheduling policy
21831 and @code{SCHED_OTHER}.
21832 @cindex @code{SCHED_OTHER} scheduling policy
21833 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21834 or @code{SCHED_RR} requires special (e.g., root) privileges.
21835
21836 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21837 @code{SCHED_FIFO},
21838 @cindex @code{SCHED_FIFO} scheduling policy
21839 you can use one of the following:
21840
21841 @itemize @bullet
21842 @item
21843 @code{pragma Time_Slice (0.0)}
21844 @cindex pragma Time_Slice
21845 @item
21846 the corresponding binder option @option{-T0}
21847 @cindex @option{-T0} option
21848 @item
21849 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21850 @cindex pragma Task_Dispatching_Policy
21851 @end itemize
21852
21853 @noindent
21854 To specify @code{SCHED_RR},
21855 @cindex @code{SCHED_RR} scheduling policy
21856 you should use @code{pragma Time_Slice} with a
21857 value greater than @code{0.0}, or else use the corresponding @option{-T}
21858 binder option.
21859
21860 @node Solaris-Specific Considerations
21861 @section Solaris-Specific Considerations
21862 @cindex Solaris Sparc threads libraries
21863
21864 @noindent
21865 This section addresses some topics related to the various threads libraries
21866 on Sparc Solaris.
21867
21868 @menu
21869 * Solaris Threads Issues::
21870 @end menu
21871
21872 @node Solaris Threads Issues
21873 @subsection Solaris Threads Issues
21874
21875 @noindent
21876 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21877 library based on POSIX threads --- @emph{rts-pthread}.
21878 @cindex rts-pthread threads library
21879 This run-time library has the advantage of being mostly shared across all
21880 POSIX-compliant thread implementations, and it also provides under
21881 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21882 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21883 and @code{PTHREAD_PRIO_PROTECT}
21884 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21885 semantics that can be selected using the predefined pragma
21886 @code{Locking_Policy}
21887 @cindex pragma Locking_Policy (under rts-pthread)
21888 with respectively
21889 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21890 @cindex @code{Inheritance_Locking} (under rts-pthread)
21891 @cindex @code{Ceiling_Locking} (under rts-pthread)
21892
21893 As explained above, the native run-time library is based on the Solaris thread
21894 library (@code{libthread}) and is the default library.
21895
21896 When the Solaris threads library is used (this is the default), programs
21897 compiled with GNAT can automatically take advantage of
21898 and can thus execute on multiple processors.
21899 The user can alternatively specify a processor on which the program should run
21900 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21901 is made by
21902 setting the environment variable @env{GNAT_PROCESSOR}
21903 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21904 to one of the following:
21905
21906 @table @code
21907 @item -2
21908 Use the default configuration (run the program on all
21909 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21910 unset
21911
21912 @item -1
21913 Let the run-time implementation choose one processor and run the program on
21914 that processor
21915
21916 @item 0 .. Last_Proc
21917 Run the program on the specified processor.
21918 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21919 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21920 @end table
21921
21922 @node Linux-Specific Considerations
21923 @section Linux-Specific Considerations
21924 @cindex Linux threads libraries
21925
21926 @noindent
21927 On GNU/Linux without NPTL support (usually system with GNU C Library
21928 older than 2.3), the signal model is not POSIX compliant, which means
21929 that to send a signal to the process, you need to send the signal to all
21930 threads, e.g.@: by using @code{killpg()}.
21931
21932 @node AIX-Specific Considerations
21933 @section AIX-Specific Considerations
21934 @cindex AIX resolver library
21935
21936 @noindent
21937 On AIX, the resolver library initializes some internal structure on
21938 the first call to @code{get*by*} functions, which are used to implement
21939 @code{GNAT.Sockets.Get_Host_By_Name} and
21940 @code{GNAT.Sockets.Get_Host_By_Address}.
21941 If such initialization occurs within an Ada task, and the stack size for
21942 the task is the default size, a stack overflow may occur.
21943
21944 To avoid this overflow, the user should either ensure that the first call
21945 to @code{GNAT.Sockets.Get_Host_By_Name} or
21946 @code{GNAT.Sockets.Get_Host_By_Addrss}
21947 occurs in the environment task, or use @code{pragma Storage_Size} to
21948 specify a sufficiently large size for the stack of the task that contains
21949 this call.
21950
21951 @node Irix-Specific Considerations
21952 @section Irix-Specific Considerations
21953 @cindex Irix libraries
21954
21955 @noindent
21956 The GCC support libraries coming with the Irix compiler have moved to
21957 their canonical place with respect to the general Irix ABI related
21958 conventions. Running applications built with the default shared GNAT
21959 run-time now requires the LD_LIBRARY_PATH environment variable to
21960 include this location. A possible way to achieve this is to issue the
21961 following command line on a bash prompt:
21962
21963 @smallexample
21964 @group
21965 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21966 @end group
21967 @end smallexample
21968
21969 @node RTX-Specific Considerations
21970 @section RTX-Specific Considerations
21971 @cindex RTX libraries
21972
21973 @noindent
21974 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21975 API. Applications can be built to work in two different modes:
21976
21977 @itemize @bullet
21978 @item
21979 Windows executables that run in Ring 3 to utilize memory protection
21980 (@emph{rts-rtx-w32}).
21981
21982 @item
21983 Real-time subsystem (RTSS) executables that run in Ring 0, where
21984 performance can be optimized with RTSS applications taking precedent
21985 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21986 the Microsoft linker to handle RTSS libraries.
21987
21988 @end itemize
21989
21990 @node HP-UX-Specific Considerations
21991 @section HP-UX-Specific Considerations
21992 @cindex HP-UX Scheduling
21993
21994 @noindent
21995 On HP-UX, appropriate privileges are required to change the scheduling
21996 parameters of a task. The calling process must have appropriate
21997 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21998 successfully change the scheduling parameters.
21999
22000 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22001 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22002 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22003
22004 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22005 one of the following:
22006
22007 @itemize @bullet
22008 @item
22009 @code{pragma Time_Slice (0.0)}
22010 @cindex pragma Time_Slice
22011 @item
22012 the corresponding binder option @option{-T0}
22013 @cindex @option{-T0} option
22014 @item
22015 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22016 @cindex pragma Task_Dispatching_Policy
22017 @end itemize
22018
22019 @noindent
22020 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22021 you should use @code{pragma Time_Slice} with a
22022 value greater than @code{0.0}, or use the corresponding @option{-T}
22023 binder option, or set the @code{pragma Task_Dispatching_Policy
22024 (Round_Robin_Within_Priorities)}.
22025
22026 @c *******************************
22027 @node Example of Binder Output File
22028 @appendix Example of Binder Output File
22029
22030 @noindent
22031 This Appendix displays the source code for @command{gnatbind}'s output
22032 file generated for a simple ``Hello World'' program.
22033 Comments have been added for clarification purposes.
22034
22035 @smallexample @c adanocomment
22036 @iftex
22037 @leftskip=0cm
22038 @end iftex
22039 --  The package is called Ada_Main unless this name is actually used
22040 --  as a unit name in the partition, in which case some other unique
22041 --  name is used.
22042
22043 with System;
22044 package ada_main is
22045
22046    Elab_Final_Code : Integer;
22047    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22048
22049    --  The main program saves the parameters (argument count,
22050    --  argument values, environment pointer) in global variables
22051    --  for later access by other units including
22052    --  Ada.Command_Line.
22053
22054    gnat_argc : Integer;
22055    gnat_argv : System.Address;
22056    gnat_envp : System.Address;
22057
22058    --  The actual variables are stored in a library routine. This
22059    --  is useful for some shared library situations, where there
22060    --  are problems if variables are not in the library.
22061
22062    pragma Import (C, gnat_argc);
22063    pragma Import (C, gnat_argv);
22064    pragma Import (C, gnat_envp);
22065
22066    --  The exit status is similarly an external location
22067
22068    gnat_exit_status : Integer;
22069    pragma Import (C, gnat_exit_status);
22070
22071    GNAT_Version : constant String :=
22072                     "GNAT Version: 6.0.0w (20061115)";
22073    pragma Export (C, GNAT_Version, "__gnat_version");
22074
22075    --  This is the generated adafinal routine that performs
22076    --  finalization at the end of execution. In the case where
22077    --  Ada is the main program, this main program makes a call
22078    --  to adafinal at program termination.
22079
22080    procedure adafinal;
22081    pragma Export (C, adafinal, "adafinal");
22082
22083    --  This is the generated adainit routine that performs
22084    --  initialization at the start of execution. In the case
22085    --  where Ada is the main program, this main program makes
22086    --  a call to adainit at program startup.
22087
22088    procedure adainit;
22089    pragma Export (C, adainit, "adainit");
22090
22091    --  This routine is called at the start of execution. It is
22092    --  a dummy routine that is used by the debugger to breakpoint
22093    --  at the start of execution.
22094
22095    procedure Break_Start;
22096    pragma Import (C, Break_Start, "__gnat_break_start");
22097
22098    --  This is the actual generated main program (it would be
22099    --  suppressed if the no main program switch were used). As
22100    --  required by standard system conventions, this program has
22101    --  the external name main.
22102
22103    function main
22104      (argc : Integer;
22105       argv : System.Address;
22106       envp : System.Address)
22107       return Integer;
22108    pragma Export (C, main, "main");
22109
22110    --  The following set of constants give the version
22111    --  identification values for every unit in the bound
22112    --  partition. This identification is computed from all
22113    --  dependent semantic units, and corresponds to the
22114    --  string that would be returned by use of the
22115    --  Body_Version or Version attributes.
22116
22117    type Version_32 is mod 2 ** 32;
22118    u00001 : constant Version_32 := 16#7880BEB3#;
22119    u00002 : constant Version_32 := 16#0D24CBD0#;
22120    u00003 : constant Version_32 := 16#3283DBEB#;
22121    u00004 : constant Version_32 := 16#2359F9ED#;
22122    u00005 : constant Version_32 := 16#664FB847#;
22123    u00006 : constant Version_32 := 16#68E803DF#;
22124    u00007 : constant Version_32 := 16#5572E604#;
22125    u00008 : constant Version_32 := 16#46B173D8#;
22126    u00009 : constant Version_32 := 16#156A40CF#;
22127    u00010 : constant Version_32 := 16#033DABE0#;
22128    u00011 : constant Version_32 := 16#6AB38FEA#;
22129    u00012 : constant Version_32 := 16#22B6217D#;
22130    u00013 : constant Version_32 := 16#68A22947#;
22131    u00014 : constant Version_32 := 16#18CC4A56#;
22132    u00015 : constant Version_32 := 16#08258E1B#;
22133    u00016 : constant Version_32 := 16#367D5222#;
22134    u00017 : constant Version_32 := 16#20C9ECA4#;
22135    u00018 : constant Version_32 := 16#50D32CB6#;
22136    u00019 : constant Version_32 := 16#39A8BB77#;
22137    u00020 : constant Version_32 := 16#5CF8FA2B#;
22138    u00021 : constant Version_32 := 16#2F1EB794#;
22139    u00022 : constant Version_32 := 16#31AB6444#;
22140    u00023 : constant Version_32 := 16#1574B6E9#;
22141    u00024 : constant Version_32 := 16#5109C189#;
22142    u00025 : constant Version_32 := 16#56D770CD#;
22143    u00026 : constant Version_32 := 16#02F9DE3D#;
22144    u00027 : constant Version_32 := 16#08AB6B2C#;
22145    u00028 : constant Version_32 := 16#3FA37670#;
22146    u00029 : constant Version_32 := 16#476457A0#;
22147    u00030 : constant Version_32 := 16#731E1B6E#;
22148    u00031 : constant Version_32 := 16#23C2E789#;
22149    u00032 : constant Version_32 := 16#0F1BD6A1#;
22150    u00033 : constant Version_32 := 16#7C25DE96#;
22151    u00034 : constant Version_32 := 16#39ADFFA2#;
22152    u00035 : constant Version_32 := 16#571DE3E7#;
22153    u00036 : constant Version_32 := 16#5EB646AB#;
22154    u00037 : constant Version_32 := 16#4249379B#;
22155    u00038 : constant Version_32 := 16#0357E00A#;
22156    u00039 : constant Version_32 := 16#3784FB72#;
22157    u00040 : constant Version_32 := 16#2E723019#;
22158    u00041 : constant Version_32 := 16#623358EA#;
22159    u00042 : constant Version_32 := 16#107F9465#;
22160    u00043 : constant Version_32 := 16#6843F68A#;
22161    u00044 : constant Version_32 := 16#63305874#;
22162    u00045 : constant Version_32 := 16#31E56CE1#;
22163    u00046 : constant Version_32 := 16#02917970#;
22164    u00047 : constant Version_32 := 16#6CCBA70E#;
22165    u00048 : constant Version_32 := 16#41CD4204#;
22166    u00049 : constant Version_32 := 16#572E3F58#;
22167    u00050 : constant Version_32 := 16#20729FF5#;
22168    u00051 : constant Version_32 := 16#1D4F93E8#;
22169    u00052 : constant Version_32 := 16#30B2EC3D#;
22170    u00053 : constant Version_32 := 16#34054F96#;
22171    u00054 : constant Version_32 := 16#5A199860#;
22172    u00055 : constant Version_32 := 16#0E7F912B#;
22173    u00056 : constant Version_32 := 16#5760634A#;
22174    u00057 : constant Version_32 := 16#5D851835#;
22175
22176    --  The following Export pragmas export the version numbers
22177    --  with symbolic names ending in B (for body) or S
22178    --  (for spec) so that they can be located in a link. The
22179    --  information provided here is sufficient to track down
22180    --  the exact versions of units used in a given build.
22181
22182    pragma Export (C, u00001, "helloB");
22183    pragma Export (C, u00002, "system__standard_libraryB");
22184    pragma Export (C, u00003, "system__standard_libraryS");
22185    pragma Export (C, u00004, "adaS");
22186    pragma Export (C, u00005, "ada__text_ioB");
22187    pragma Export (C, u00006, "ada__text_ioS");
22188    pragma Export (C, u00007, "ada__exceptionsB");
22189    pragma Export (C, u00008, "ada__exceptionsS");
22190    pragma Export (C, u00009, "gnatS");
22191    pragma Export (C, u00010, "gnat__heap_sort_aB");
22192    pragma Export (C, u00011, "gnat__heap_sort_aS");
22193    pragma Export (C, u00012, "systemS");
22194    pragma Export (C, u00013, "system__exception_tableB");
22195    pragma Export (C, u00014, "system__exception_tableS");
22196    pragma Export (C, u00015, "gnat__htableB");
22197    pragma Export (C, u00016, "gnat__htableS");
22198    pragma Export (C, u00017, "system__exceptionsS");
22199    pragma Export (C, u00018, "system__machine_state_operationsB");
22200    pragma Export (C, u00019, "system__machine_state_operationsS");
22201    pragma Export (C, u00020, "system__machine_codeS");
22202    pragma Export (C, u00021, "system__storage_elementsB");
22203    pragma Export (C, u00022, "system__storage_elementsS");
22204    pragma Export (C, u00023, "system__secondary_stackB");
22205    pragma Export (C, u00024, "system__secondary_stackS");
22206    pragma Export (C, u00025, "system__parametersB");
22207    pragma Export (C, u00026, "system__parametersS");
22208    pragma Export (C, u00027, "system__soft_linksB");
22209    pragma Export (C, u00028, "system__soft_linksS");
22210    pragma Export (C, u00029, "system__stack_checkingB");
22211    pragma Export (C, u00030, "system__stack_checkingS");
22212    pragma Export (C, u00031, "system__tracebackB");
22213    pragma Export (C, u00032, "system__tracebackS");
22214    pragma Export (C, u00033, "ada__streamsS");
22215    pragma Export (C, u00034, "ada__tagsB");
22216    pragma Export (C, u00035, "ada__tagsS");
22217    pragma Export (C, u00036, "system__string_opsB");
22218    pragma Export (C, u00037, "system__string_opsS");
22219    pragma Export (C, u00038, "interfacesS");
22220    pragma Export (C, u00039, "interfaces__c_streamsB");
22221    pragma Export (C, u00040, "interfaces__c_streamsS");
22222    pragma Export (C, u00041, "system__file_ioB");
22223    pragma Export (C, u00042, "system__file_ioS");
22224    pragma Export (C, u00043, "ada__finalizationB");
22225    pragma Export (C, u00044, "ada__finalizationS");
22226    pragma Export (C, u00045, "system__finalization_rootB");
22227    pragma Export (C, u00046, "system__finalization_rootS");
22228    pragma Export (C, u00047, "system__finalization_implementationB");
22229    pragma Export (C, u00048, "system__finalization_implementationS");
22230    pragma Export (C, u00049, "system__string_ops_concat_3B");
22231    pragma Export (C, u00050, "system__string_ops_concat_3S");
22232    pragma Export (C, u00051, "system__stream_attributesB");
22233    pragma Export (C, u00052, "system__stream_attributesS");
22234    pragma Export (C, u00053, "ada__io_exceptionsS");
22235    pragma Export (C, u00054, "system__unsigned_typesS");
22236    pragma Export (C, u00055, "system__file_control_blockS");
22237    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22238    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22239
22240    -- BEGIN ELABORATION ORDER
22241    -- ada (spec)
22242    -- gnat (spec)
22243    -- gnat.heap_sort_a (spec)
22244    -- gnat.heap_sort_a (body)
22245    -- gnat.htable (spec)
22246    -- gnat.htable (body)
22247    -- interfaces (spec)
22248    -- system (spec)
22249    -- system.machine_code (spec)
22250    -- system.parameters (spec)
22251    -- system.parameters (body)
22252    -- interfaces.c_streams (spec)
22253    -- interfaces.c_streams (body)
22254    -- system.standard_library (spec)
22255    -- ada.exceptions (spec)
22256    -- system.exception_table (spec)
22257    -- system.exception_table (body)
22258    -- ada.io_exceptions (spec)
22259    -- system.exceptions (spec)
22260    -- system.storage_elements (spec)
22261    -- system.storage_elements (body)
22262    -- system.machine_state_operations (spec)
22263    -- system.machine_state_operations (body)
22264    -- system.secondary_stack (spec)
22265    -- system.stack_checking (spec)
22266    -- system.soft_links (spec)
22267    -- system.soft_links (body)
22268    -- system.stack_checking (body)
22269    -- system.secondary_stack (body)
22270    -- system.standard_library (body)
22271    -- system.string_ops (spec)
22272    -- system.string_ops (body)
22273    -- ada.tags (spec)
22274    -- ada.tags (body)
22275    -- ada.streams (spec)
22276    -- system.finalization_root (spec)
22277    -- system.finalization_root (body)
22278    -- system.string_ops_concat_3 (spec)
22279    -- system.string_ops_concat_3 (body)
22280    -- system.traceback (spec)
22281    -- system.traceback (body)
22282    -- ada.exceptions (body)
22283    -- system.unsigned_types (spec)
22284    -- system.stream_attributes (spec)
22285    -- system.stream_attributes (body)
22286    -- system.finalization_implementation (spec)
22287    -- system.finalization_implementation (body)
22288    -- ada.finalization (spec)
22289    -- ada.finalization (body)
22290    -- ada.finalization.list_controller (spec)
22291    -- ada.finalization.list_controller (body)
22292    -- system.file_control_block (spec)
22293    -- system.file_io (spec)
22294    -- system.file_io (body)
22295    -- ada.text_io (spec)
22296    -- ada.text_io (body)
22297    -- hello (body)
22298    -- END ELABORATION ORDER
22299
22300 end ada_main;
22301
22302 --  The following source file name pragmas allow the generated file
22303 --  names to be unique for different main programs. They are needed
22304 --  since the package name will always be Ada_Main.
22305
22306 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22307 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22308
22309 --  Generated package body for Ada_Main starts here
22310
22311 package body ada_main is
22312
22313    --  The actual finalization is performed by calling the
22314    --  library routine in System.Standard_Library.Adafinal
22315
22316    procedure Do_Finalize;
22317    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22318
22319    -------------
22320    -- adainit --
22321    -------------
22322
22323 @findex adainit
22324    procedure adainit is
22325
22326       --  These booleans are set to True once the associated unit has
22327       --  been elaborated. It is also used to avoid elaborating the
22328       --  same unit twice.
22329
22330       E040 : Boolean;
22331       pragma Import (Ada, E040, "interfaces__c_streams_E");
22332
22333       E008 : Boolean;
22334       pragma Import (Ada, E008, "ada__exceptions_E");
22335
22336       E014 : Boolean;
22337       pragma Import (Ada, E014, "system__exception_table_E");
22338
22339       E053 : Boolean;
22340       pragma Import (Ada, E053, "ada__io_exceptions_E");
22341
22342       E017 : Boolean;
22343       pragma Import (Ada, E017, "system__exceptions_E");
22344
22345       E024 : Boolean;
22346       pragma Import (Ada, E024, "system__secondary_stack_E");
22347
22348       E030 : Boolean;
22349       pragma Import (Ada, E030, "system__stack_checking_E");
22350
22351       E028 : Boolean;
22352       pragma Import (Ada, E028, "system__soft_links_E");
22353
22354       E035 : Boolean;
22355       pragma Import (Ada, E035, "ada__tags_E");
22356
22357       E033 : Boolean;
22358       pragma Import (Ada, E033, "ada__streams_E");
22359
22360       E046 : Boolean;
22361       pragma Import (Ada, E046, "system__finalization_root_E");
22362
22363       E048 : Boolean;
22364       pragma Import (Ada, E048, "system__finalization_implementation_E");
22365
22366       E044 : Boolean;
22367       pragma Import (Ada, E044, "ada__finalization_E");
22368
22369       E057 : Boolean;
22370       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22371
22372       E055 : Boolean;
22373       pragma Import (Ada, E055, "system__file_control_block_E");
22374
22375       E042 : Boolean;
22376       pragma Import (Ada, E042, "system__file_io_E");
22377
22378       E006 : Boolean;
22379       pragma Import (Ada, E006, "ada__text_io_E");
22380
22381       --  Set_Globals is a library routine that stores away the
22382       --  value of the indicated set of global values in global
22383       --  variables within the library.
22384
22385       procedure Set_Globals
22386         (Main_Priority            : Integer;
22387          Time_Slice_Value         : Integer;
22388          WC_Encoding              : Character;
22389          Locking_Policy           : Character;
22390          Queuing_Policy           : Character;
22391          Task_Dispatching_Policy  : Character;
22392          Adafinal                 : System.Address;
22393          Unreserve_All_Interrupts : Integer;
22394          Exception_Tracebacks     : Integer);
22395 @findex __gnat_set_globals
22396       pragma Import (C, Set_Globals, "__gnat_set_globals");
22397
22398       --  SDP_Table_Build is a library routine used to build the
22399       --  exception tables. See unit Ada.Exceptions in files
22400       --  a-except.ads/adb for full details of how zero cost
22401       --  exception handling works. This procedure, the call to
22402       --  it, and the two following tables are all omitted if the
22403       --  build is in longjmp/setjmp exception mode.
22404
22405 @findex SDP_Table_Build
22406 @findex Zero Cost Exceptions
22407       procedure SDP_Table_Build
22408         (SDP_Addresses   : System.Address;
22409          SDP_Count       : Natural;
22410          Elab_Addresses  : System.Address;
22411          Elab_Addr_Count : Natural);
22412       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22413
22414       --  Table of Unit_Exception_Table addresses. Used for zero
22415       --  cost exception handling to build the top level table.
22416
22417       ST : aliased constant array (1 .. 23) of System.Address := (
22418         Hello'UET_Address,
22419         Ada.Text_Io'UET_Address,
22420         Ada.Exceptions'UET_Address,
22421         Gnat.Heap_Sort_A'UET_Address,
22422         System.Exception_Table'UET_Address,
22423         System.Machine_State_Operations'UET_Address,
22424         System.Secondary_Stack'UET_Address,
22425         System.Parameters'UET_Address,
22426         System.Soft_Links'UET_Address,
22427         System.Stack_Checking'UET_Address,
22428         System.Traceback'UET_Address,
22429         Ada.Streams'UET_Address,
22430         Ada.Tags'UET_Address,
22431         System.String_Ops'UET_Address,
22432         Interfaces.C_Streams'UET_Address,
22433         System.File_Io'UET_Address,
22434         Ada.Finalization'UET_Address,
22435         System.Finalization_Root'UET_Address,
22436         System.Finalization_Implementation'UET_Address,
22437         System.String_Ops_Concat_3'UET_Address,
22438         System.Stream_Attributes'UET_Address,
22439         System.File_Control_Block'UET_Address,
22440         Ada.Finalization.List_Controller'UET_Address);
22441
22442       --  Table of addresses of elaboration routines. Used for
22443       --  zero cost exception handling to make sure these
22444       --  addresses are included in the top level procedure
22445       --  address table.
22446
22447       EA : aliased constant array (1 .. 23) of System.Address := (
22448         adainit'Code_Address,
22449         Do_Finalize'Code_Address,
22450         Ada.Exceptions'Elab_Spec'Address,
22451         System.Exceptions'Elab_Spec'Address,
22452         Interfaces.C_Streams'Elab_Spec'Address,
22453         System.Exception_Table'Elab_Body'Address,
22454         Ada.Io_Exceptions'Elab_Spec'Address,
22455         System.Stack_Checking'Elab_Spec'Address,
22456         System.Soft_Links'Elab_Body'Address,
22457         System.Secondary_Stack'Elab_Body'Address,
22458         Ada.Tags'Elab_Spec'Address,
22459         Ada.Tags'Elab_Body'Address,
22460         Ada.Streams'Elab_Spec'Address,
22461         System.Finalization_Root'Elab_Spec'Address,
22462         Ada.Exceptions'Elab_Body'Address,
22463         System.Finalization_Implementation'Elab_Spec'Address,
22464         System.Finalization_Implementation'Elab_Body'Address,
22465         Ada.Finalization'Elab_Spec'Address,
22466         Ada.Finalization.List_Controller'Elab_Spec'Address,
22467         System.File_Control_Block'Elab_Spec'Address,
22468         System.File_Io'Elab_Body'Address,
22469         Ada.Text_Io'Elab_Spec'Address,
22470         Ada.Text_Io'Elab_Body'Address);
22471
22472    --  Start of processing for adainit
22473
22474    begin
22475
22476       --  Call SDP_Table_Build to build the top level procedure
22477       --  table for zero cost exception handling (omitted in
22478       --  longjmp/setjmp mode).
22479
22480       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22481
22482       --  Call Set_Globals to record various information for
22483       --  this partition.  The values are derived by the binder
22484       --  from information stored in the ali files by the compiler.
22485
22486 @findex __gnat_set_globals
22487       Set_Globals
22488         (Main_Priority            => -1,
22489          --  Priority of main program, -1 if no pragma Priority used
22490
22491          Time_Slice_Value         => -1,
22492          --  Time slice from Time_Slice pragma, -1 if none used
22493
22494          WC_Encoding              => 'b',
22495          --  Wide_Character encoding used, default is brackets
22496
22497          Locking_Policy           => ' ',
22498          --  Locking_Policy used, default of space means not
22499          --  specified, otherwise it is the first character of
22500          --  the policy name.
22501
22502          Queuing_Policy           => ' ',
22503          --  Queuing_Policy used, default of space means not
22504          --  specified, otherwise it is the first character of
22505          --  the policy name.
22506
22507          Task_Dispatching_Policy  => ' ',
22508          --  Task_Dispatching_Policy used, default of space means
22509          --  not specified, otherwise first character of the
22510          --  policy name.
22511
22512          Adafinal                 => System.Null_Address,
22513          --  Address of Adafinal routine, not used anymore
22514
22515          Unreserve_All_Interrupts => 0,
22516          --  Set true if pragma Unreserve_All_Interrupts was used
22517
22518          Exception_Tracebacks     => 0);
22519          --  Indicates if exception tracebacks are enabled
22520
22521       Elab_Final_Code := 1;
22522
22523       --  Now we have the elaboration calls for all units in the partition.
22524       --  The Elab_Spec and Elab_Body attributes generate references to the
22525       --  implicit elaboration procedures generated by the compiler for
22526       --  each unit that requires elaboration.
22527
22528       if not E040 then
22529          Interfaces.C_Streams'Elab_Spec;
22530       end if;
22531       E040 := True;
22532       if not E008 then
22533          Ada.Exceptions'Elab_Spec;
22534       end if;
22535       if not E014 then
22536          System.Exception_Table'Elab_Body;
22537          E014 := True;
22538       end if;
22539       if not E053 then
22540          Ada.Io_Exceptions'Elab_Spec;
22541          E053 := True;
22542       end if;
22543       if not E017 then
22544          System.Exceptions'Elab_Spec;
22545          E017 := True;
22546       end if;
22547       if not E030 then
22548          System.Stack_Checking'Elab_Spec;
22549       end if;
22550       if not E028 then
22551          System.Soft_Links'Elab_Body;
22552          E028 := True;
22553       end if;
22554       E030 := True;
22555       if not E024 then
22556          System.Secondary_Stack'Elab_Body;
22557          E024 := True;
22558       end if;
22559       if not E035 then
22560          Ada.Tags'Elab_Spec;
22561       end if;
22562       if not E035 then
22563          Ada.Tags'Elab_Body;
22564          E035 := True;
22565       end if;
22566       if not E033 then
22567          Ada.Streams'Elab_Spec;
22568          E033 := True;
22569       end if;
22570       if not E046 then
22571          System.Finalization_Root'Elab_Spec;
22572       end if;
22573       E046 := True;
22574       if not E008 then
22575          Ada.Exceptions'Elab_Body;
22576          E008 := True;
22577       end if;
22578       if not E048 then
22579          System.Finalization_Implementation'Elab_Spec;
22580       end if;
22581       if not E048 then
22582          System.Finalization_Implementation'Elab_Body;
22583          E048 := True;
22584       end if;
22585       if not E044 then
22586          Ada.Finalization'Elab_Spec;
22587       end if;
22588       E044 := True;
22589       if not E057 then
22590          Ada.Finalization.List_Controller'Elab_Spec;
22591       end if;
22592       E057 := True;
22593       if not E055 then
22594          System.File_Control_Block'Elab_Spec;
22595          E055 := True;
22596       end if;
22597       if not E042 then
22598          System.File_Io'Elab_Body;
22599          E042 := True;
22600       end if;
22601       if not E006 then
22602          Ada.Text_Io'Elab_Spec;
22603       end if;
22604       if not E006 then
22605          Ada.Text_Io'Elab_Body;
22606          E006 := True;
22607       end if;
22608
22609       Elab_Final_Code := 0;
22610    end adainit;
22611
22612    --------------
22613    -- adafinal --
22614    --------------
22615
22616 @findex adafinal
22617    procedure adafinal is
22618    begin
22619       Do_Finalize;
22620    end adafinal;
22621
22622    ----------
22623    -- main --
22624    ----------
22625
22626    --  main is actually a function, as in the ANSI C standard,
22627    --  defined to return the exit status. The three parameters
22628    --  are the argument count, argument values and environment
22629    --  pointer.
22630
22631 @findex Main Program
22632    function main
22633      (argc : Integer;
22634       argv : System.Address;
22635       envp : System.Address)
22636       return Integer
22637    is
22638       --  The initialize routine performs low level system
22639       --  initialization using a standard library routine which
22640       --  sets up signal handling and performs any other
22641       --  required setup. The routine can be found in file
22642       --  a-init.c.
22643
22644 @findex __gnat_initialize
22645       procedure initialize;
22646       pragma Import (C, initialize, "__gnat_initialize");
22647
22648       --  The finalize routine performs low level system
22649       --  finalization using a standard library routine. The
22650       --  routine is found in file a-final.c and in the standard
22651       --  distribution is a dummy routine that does nothing, so
22652       --  really this is a hook for special user finalization.
22653
22654 @findex __gnat_finalize
22655       procedure finalize;
22656       pragma Import (C, finalize, "__gnat_finalize");
22657
22658       --  We get to the main program of the partition by using
22659       --  pragma Import because if we try to with the unit and
22660       --  call it Ada style, then not only do we waste time
22661       --  recompiling it, but also, we don't really know the right
22662       --  switches (e.g.@: identifier character set) to be used
22663       --  to compile it.
22664
22665       procedure Ada_Main_Program;
22666       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22667
22668    --  Start of processing for main
22669
22670    begin
22671       --  Save global variables
22672
22673       gnat_argc := argc;
22674       gnat_argv := argv;
22675       gnat_envp := envp;
22676
22677       --  Call low level system initialization
22678
22679       Initialize;
22680
22681       --  Call our generated Ada initialization routine
22682
22683       adainit;
22684
22685       --  This is the point at which we want the debugger to get
22686       --  control
22687
22688       Break_Start;
22689
22690       --  Now we call the main program of the partition
22691
22692       Ada_Main_Program;
22693
22694       --  Perform Ada finalization
22695
22696       adafinal;
22697
22698       --  Perform low level system finalization
22699
22700       Finalize;
22701
22702       --  Return the proper exit status
22703       return (gnat_exit_status);
22704    end;
22705
22706 --  This section is entirely comments, so it has no effect on the
22707 --  compilation of the Ada_Main package. It provides the list of
22708 --  object files and linker options, as well as some standard
22709 --  libraries needed for the link. The gnatlink utility parses
22710 --  this b~hello.adb file to read these comment lines to generate
22711 --  the appropriate command line arguments for the call to the
22712 --  system linker. The BEGIN/END lines are used for sentinels for
22713 --  this parsing operation.
22714
22715 --  The exact file names will of course depend on the environment,
22716 --  host/target and location of files on the host system.
22717
22718 @findex Object file list
22719 -- BEGIN Object file/option list
22720    --   ./hello.o
22721    --   -L./
22722    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22723    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22724 -- END Object file/option list
22725
22726 end ada_main;
22727 @end smallexample
22728
22729 @noindent
22730 The Ada code in the above example is exactly what is generated by the
22731 binder. We have added comments to more clearly indicate the function
22732 of each part of the generated @code{Ada_Main} package.
22733
22734 The code is standard Ada in all respects, and can be processed by any
22735 tools that handle Ada. In particular, it is possible to use the debugger
22736 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22737 suppose that for reasons that you do not understand, your program is crashing
22738 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22739 you can place a breakpoint on the call:
22740
22741 @smallexample @c ada
22742 Ada.Text_Io'Elab_Body;
22743 @end smallexample
22744
22745 @noindent
22746 and trace the elaboration routine for this package to find out where
22747 the problem might be (more usually of course you would be debugging
22748 elaboration code in your own application).
22749
22750 @node Elaboration Order Handling in GNAT
22751 @appendix Elaboration Order Handling in GNAT
22752 @cindex Order of elaboration
22753 @cindex Elaboration control
22754
22755 @menu
22756 * Elaboration Code::
22757 * Checking the Elaboration Order::
22758 * Controlling the Elaboration Order::
22759 * Controlling Elaboration in GNAT - Internal Calls::
22760 * Controlling Elaboration in GNAT - External Calls::
22761 * Default Behavior in GNAT - Ensuring Safety::
22762 * Treatment of Pragma Elaborate::
22763 * Elaboration Issues for Library Tasks::
22764 * Mixing Elaboration Models::
22765 * What to Do If the Default Elaboration Behavior Fails::
22766 * Elaboration for Access-to-Subprogram Values::
22767 * Summary of Procedures for Elaboration Control::
22768 * Other Elaboration Order Considerations::
22769 @end menu
22770
22771 @noindent
22772 This chapter describes the handling of elaboration code in Ada and
22773 in GNAT, and discusses how the order of elaboration of program units can
22774 be controlled in GNAT, either automatically or with explicit programming
22775 features.
22776
22777 @node Elaboration Code
22778 @section Elaboration Code
22779
22780 @noindent
22781 Ada provides rather general mechanisms for executing code at elaboration
22782 time, that is to say before the main program starts executing. Such code arises
22783 in three contexts:
22784
22785 @table @asis
22786 @item Initializers for variables.
22787 Variables declared at the library level, in package specs or bodies, can
22788 require initialization that is performed at elaboration time, as in:
22789 @smallexample @c ada
22790 @cartouche
22791 Sqrt_Half : Float := Sqrt (0.5);
22792 @end cartouche
22793 @end smallexample
22794
22795 @item Package initialization code
22796 Code in a @code{BEGIN-END} section at the outer level of a package body is
22797 executed as part of the package body elaboration code.
22798
22799 @item Library level task allocators
22800 Tasks that are declared using task allocators at the library level
22801 start executing immediately and hence can execute at elaboration time.
22802 @end table
22803
22804 @noindent
22805 Subprogram calls are possible in any of these contexts, which means that
22806 any arbitrary part of the program may be executed as part of the elaboration
22807 code. It is even possible to write a program which does all its work at
22808 elaboration time, with a null main program, although stylistically this
22809 would usually be considered an inappropriate way to structure
22810 a program.
22811
22812 An important concern arises in the context of elaboration code:
22813 we have to be sure that it is executed in an appropriate order. What we
22814 have is a series of elaboration code sections, potentially one section
22815 for each unit in the program. It is important that these execute
22816 in the correct order. Correctness here means that, taking the above
22817 example of the declaration of @code{Sqrt_Half},
22818 if some other piece of
22819 elaboration code references @code{Sqrt_Half},
22820 then it must run after the
22821 section of elaboration code that contains the declaration of
22822 @code{Sqrt_Half}.
22823
22824 There would never be any order of elaboration problem if we made a rule
22825 that whenever you @code{with} a unit, you must elaborate both the spec and body
22826 of that unit before elaborating the unit doing the @code{with}'ing:
22827
22828 @smallexample @c ada
22829 @group
22830 @cartouche
22831 with Unit_1;
22832 package Unit_2 is @dots{}
22833 @end cartouche
22834 @end group
22835 @end smallexample
22836
22837 @noindent
22838 would require that both the body and spec of @code{Unit_1} be elaborated
22839 before the spec of @code{Unit_2}. However, a rule like that would be far too
22840 restrictive. In particular, it would make it impossible to have routines
22841 in separate packages that were mutually recursive.
22842
22843 You might think that a clever enough compiler could look at the actual
22844 elaboration code and determine an appropriate correct order of elaboration,
22845 but in the general case, this is not possible. Consider the following
22846 example.
22847
22848 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22849 that references
22850 the variable @code{Sqrt_1}, which is declared in the elaboration code
22851 of the body of @code{Unit_1}:
22852
22853 @smallexample @c ada
22854 @cartouche
22855 Sqrt_1 : Float := Sqrt (0.1);
22856 @end cartouche
22857 @end smallexample
22858
22859 @noindent
22860 The elaboration code of the body of @code{Unit_1} also contains:
22861
22862 @smallexample @c ada
22863 @group
22864 @cartouche
22865 if expression_1 = 1 then
22866    Q := Unit_2.Func_2;
22867 end if;
22868 @end cartouche
22869 @end group
22870 @end smallexample
22871
22872 @noindent
22873 @code{Unit_2} is exactly parallel,
22874 it has a procedure @code{Func_2} that references
22875 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22876 the body @code{Unit_2}:
22877
22878 @smallexample @c ada
22879 @cartouche
22880 Sqrt_2 : Float := Sqrt (0.1);
22881 @end cartouche
22882 @end smallexample
22883
22884 @noindent
22885 The elaboration code of the body of @code{Unit_2} also contains:
22886
22887 @smallexample @c ada
22888 @group
22889 @cartouche
22890 if expression_2 = 2 then
22891    Q := Unit_1.Func_1;
22892 end if;
22893 @end cartouche
22894 @end group
22895 @end smallexample
22896
22897 @noindent
22898 Now the question is, which of the following orders of elaboration is
22899 acceptable:
22900
22901 @smallexample
22902 @group
22903 Spec of Unit_1
22904 Spec of Unit_2
22905 Body of Unit_1
22906 Body of Unit_2
22907 @end group
22908 @end smallexample
22909
22910 @noindent
22911 or
22912
22913 @smallexample
22914 @group
22915 Spec of Unit_2
22916 Spec of Unit_1
22917 Body of Unit_2
22918 Body of Unit_1
22919 @end group
22920 @end smallexample
22921
22922 @noindent
22923 If you carefully analyze the flow here, you will see that you cannot tell
22924 at compile time the answer to this question.
22925 If @code{expression_1} is not equal to 1,
22926 and @code{expression_2} is not equal to 2,
22927 then either order is acceptable, because neither of the function calls is
22928 executed. If both tests evaluate to true, then neither order is acceptable
22929 and in fact there is no correct order.
22930
22931 If one of the two expressions is true, and the other is false, then one
22932 of the above orders is correct, and the other is incorrect. For example,
22933 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22934 then the call to @code{Func_1}
22935 will occur, but not the call to @code{Func_2.}
22936 This means that it is essential
22937 to elaborate the body of @code{Unit_1} before
22938 the body of @code{Unit_2}, so the first
22939 order of elaboration is correct and the second is wrong.
22940
22941 By making @code{expression_1} and @code{expression_2}
22942 depend on input data, or perhaps
22943 the time of day, we can make it impossible for the compiler or binder
22944 to figure out which of these expressions will be true, and hence it
22945 is impossible to guarantee a safe order of elaboration at run time.
22946
22947 @node Checking the Elaboration Order
22948 @section Checking the Elaboration Order
22949
22950 @noindent
22951 In some languages that involve the same kind of elaboration problems,
22952 e.g.@: Java and C++, the programmer is expected to worry about these
22953 ordering problems himself, and it is common to
22954 write a program in which an incorrect elaboration order  gives
22955 surprising results, because it references variables before they
22956 are initialized.
22957 Ada is designed to be a safe language, and a programmer-beware approach is
22958 clearly not sufficient. Consequently, the language provides three lines
22959 of defense:
22960
22961 @table @asis
22962 @item Standard rules
22963 Some standard rules restrict the possible choice of elaboration
22964 order. In particular, if you @code{with} a unit, then its spec is always
22965 elaborated before the unit doing the @code{with}. Similarly, a parent
22966 spec is always elaborated before the child spec, and finally
22967 a spec is always elaborated before its corresponding body.
22968
22969 @item Dynamic elaboration checks
22970 @cindex Elaboration checks
22971 @cindex Checks, elaboration
22972 Dynamic checks are made at run time, so that if some entity is accessed
22973 before it is elaborated (typically  by means of a subprogram call)
22974 then the exception (@code{Program_Error}) is raised.
22975
22976 @item Elaboration control
22977 Facilities are provided for the programmer to specify the desired order
22978 of elaboration.
22979 @end table
22980
22981 Let's look at these facilities in more detail. First, the rules for
22982 dynamic checking. One possible rule would be simply to say that the
22983 exception is raised if you access a variable which has not yet been
22984 elaborated. The trouble with this approach is that it could require
22985 expensive checks on every variable reference. Instead Ada has two
22986 rules which are a little more restrictive, but easier to check, and
22987 easier to state:
22988
22989 @table @asis
22990 @item Restrictions on calls
22991 A subprogram can only be called at elaboration time if its body
22992 has been elaborated. The rules for elaboration given above guarantee
22993 that the spec of the subprogram has been elaborated before the
22994 call, but not the body. If this rule is violated, then the
22995 exception @code{Program_Error} is raised.
22996
22997 @item Restrictions on instantiations
22998 A generic unit can only be instantiated if the body of the generic
22999 unit has been elaborated. Again, the rules for elaboration given above
23000 guarantee that the spec of the generic unit has been elaborated
23001 before the instantiation, but not the body. If this rule is
23002 violated, then the exception @code{Program_Error} is raised.
23003 @end table
23004
23005 @noindent
23006 The idea is that if the body has been elaborated, then any variables
23007 it references must have been elaborated; by checking for the body being
23008 elaborated we guarantee that none of its references causes any
23009 trouble. As we noted above, this is a little too restrictive, because a
23010 subprogram that has no non-local references in its body may in fact be safe
23011 to call. However, it really would be unsafe to rely on this, because
23012 it would mean that the caller was aware of details of the implementation
23013 in the body. This goes against the basic tenets of Ada.
23014
23015 A plausible implementation can be described as follows.
23016 A Boolean variable is associated with each subprogram
23017 and each generic unit. This variable is initialized to False, and is set to
23018 True at the point body is elaborated. Every call or instantiation checks the
23019 variable, and raises @code{Program_Error} if the variable is False.
23020
23021 Note that one might think that it would be good enough to have one Boolean
23022 variable for each package, but that would not deal with cases of trying
23023 to call a body in the same package as the call
23024 that has not been elaborated yet.
23025 Of course a compiler may be able to do enough analysis to optimize away
23026 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23027 does such optimizations, but still the easiest conceptual model is to
23028 think of there being one variable per subprogram.
23029
23030 @node Controlling the Elaboration Order
23031 @section Controlling the Elaboration Order
23032
23033 @noindent
23034 In the previous section we discussed the rules in Ada which ensure
23035 that @code{Program_Error} is raised if an incorrect elaboration order is
23036 chosen. This prevents erroneous executions, but we need mechanisms to
23037 specify a correct execution and avoid the exception altogether.
23038 To achieve this, Ada provides a number of features for controlling
23039 the order of elaboration. We discuss these features in this section.
23040
23041 First, there are several ways of indicating to the compiler that a given
23042 unit has no elaboration problems:
23043
23044 @table @asis
23045 @item packages that do not require a body
23046 A library package that does not require a body does not permit
23047 a body (this rule was introduced in Ada 95).
23048 Thus if we have a such a package, as in:
23049
23050 @smallexample @c ada
23051 @group
23052 @cartouche
23053 package Definitions is
23054    generic
23055       type m is new integer;
23056    package Subp is
23057       type a is array (1 .. 10) of m;
23058       type b is array (1 .. 20) of m;
23059    end Subp;
23060 end Definitions;
23061 @end cartouche
23062 @end group
23063 @end smallexample
23064
23065 @noindent
23066 A package that @code{with}'s @code{Definitions} may safely instantiate
23067 @code{Definitions.Subp} because the compiler can determine that there
23068 definitely is no package body to worry about in this case
23069
23070 @item pragma Pure
23071 @cindex pragma Pure
23072 @findex Pure
23073 Places sufficient restrictions on a unit to guarantee that
23074 no call to any subprogram in the unit can result in an
23075 elaboration problem. This means that the compiler does not need
23076 to worry about the point of elaboration of such units, and in
23077 particular, does not need to check any calls to any subprograms
23078 in this unit.
23079
23080 @item pragma Preelaborate
23081 @findex Preelaborate
23082 @cindex pragma Preelaborate
23083 This pragma places slightly less stringent restrictions on a unit than
23084 does pragma Pure,
23085 but these restrictions are still sufficient to ensure that there
23086 are no elaboration problems with any calls to the unit.
23087
23088 @item pragma Elaborate_Body
23089 @findex Elaborate_Body
23090 @cindex pragma Elaborate_Body
23091 This pragma requires that the body of a unit be elaborated immediately
23092 after its spec. Suppose a unit @code{A} has such a pragma,
23093 and unit @code{B} does
23094 a @code{with} of unit @code{A}. Recall that the standard rules require
23095 the spec of unit @code{A}
23096 to be elaborated before the @code{with}'ing unit; given the pragma in
23097 @code{A}, we also know that the body of @code{A}
23098 will be elaborated before @code{B}, so
23099 that calls to @code{A} are safe and do not need a check.
23100 @end table
23101
23102 @noindent
23103 Note that,
23104 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23105 the use of
23106 @code{Elaborate_Body} does not guarantee that the program is
23107 free of elaboration problems, because it may not be possible
23108 to satisfy the requested elaboration order.
23109 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23110 If a programmer
23111 marks @code{Unit_1} as @code{Elaborate_Body},
23112 and not @code{Unit_2,} then the order of
23113 elaboration will be:
23114
23115 @smallexample
23116 @group
23117 Spec of Unit_2
23118 Spec of Unit_1
23119 Body of Unit_1
23120 Body of Unit_2
23121 @end group
23122 @end smallexample
23123
23124 @noindent
23125 Now that means that the call to @code{Func_1} in @code{Unit_2}
23126 need not be checked,
23127 it must be safe. But the call to @code{Func_2} in
23128 @code{Unit_1} may still fail if
23129 @code{Expression_1} is equal to 1,
23130 and the programmer must still take
23131 responsibility for this not being the case.
23132
23133 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23134 eliminated, except for calls entirely within a body, which are
23135 in any case fully under programmer control. However, using the pragma
23136 everywhere is not always possible.
23137 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23138 we marked both of them as having pragma @code{Elaborate_Body}, then
23139 clearly there would be no possible elaboration order.
23140
23141 The above pragmas allow a server to guarantee safe use by clients, and
23142 clearly this is the preferable approach. Consequently a good rule
23143 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23144 and if this is not possible,
23145 mark them as @code{Elaborate_Body} if possible.
23146 As we have seen, there are situations where neither of these
23147 three pragmas can be used.
23148 So we also provide methods for clients to control the
23149 order of elaboration of the servers on which they depend:
23150
23151 @table @asis
23152 @item pragma Elaborate (unit)
23153 @findex Elaborate
23154 @cindex pragma Elaborate
23155 This pragma is placed in the context clause, after a @code{with} clause,
23156 and it requires that the body of the named unit be elaborated before
23157 the unit in which the pragma occurs. The idea is to use this pragma
23158 if the current unit calls at elaboration time, directly or indirectly,
23159 some subprogram in the named unit.
23160
23161 @item pragma Elaborate_All (unit)
23162 @findex Elaborate_All
23163 @cindex pragma Elaborate_All
23164 This is a stronger version of the Elaborate pragma. Consider the
23165 following example:
23166
23167 @smallexample
23168 Unit A @code{with}'s unit B and calls B.Func in elab code
23169 Unit B @code{with}'s unit C, and B.Func calls C.Func
23170 @end smallexample
23171
23172 @noindent
23173 Now if we put a pragma @code{Elaborate (B)}
23174 in unit @code{A}, this ensures that the
23175 body of @code{B} is elaborated before the call, but not the
23176 body of @code{C}, so
23177 the call to @code{C.Func} could still cause @code{Program_Error} to
23178 be raised.
23179
23180 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23181 not only that the body of the named unit be elaborated before the
23182 unit doing the @code{with}, but also the bodies of all units that the
23183 named unit uses, following @code{with} links transitively. For example,
23184 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23185 then it requires
23186 not only that the body of @code{B} be elaborated before @code{A},
23187 but also the
23188 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23189 @end table
23190
23191 @noindent
23192 We are now in a position to give a usage rule in Ada for avoiding
23193 elaboration problems, at least if dynamic dispatching and access to
23194 subprogram values are not used. We will handle these cases separately
23195 later.
23196
23197 The rule is simple. If a unit has elaboration code that can directly or
23198 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23199 a generic package in a @code{with}'ed unit,
23200 then if the @code{with}'ed unit does not have
23201 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23202 a pragma @code{Elaborate_All}
23203 for the @code{with}'ed unit. By following this rule a client is
23204 assured that calls can be made without risk of an exception.
23205
23206 For generic subprogram instantiations, the rule can be relaxed to
23207 require only a pragma @code{Elaborate} since elaborating the body
23208 of a subprogram cannot cause any transitive elaboration (we are
23209 not calling the subprogram in this case, just elaborating its
23210 declaration).
23211
23212 If this rule is not followed, then a program may be in one of four
23213 states:
23214
23215 @table @asis
23216 @item No order exists
23217 No order of elaboration exists which follows the rules, taking into
23218 account any @code{Elaborate}, @code{Elaborate_All},
23219 or @code{Elaborate_Body} pragmas. In
23220 this case, an Ada compiler must diagnose the situation at bind
23221 time, and refuse to build an executable program.
23222
23223 @item One or more orders exist, all incorrect
23224 One or more acceptable elaboration orders exist, and all of them
23225 generate an elaboration order problem. In this case, the binder
23226 can build an executable program, but @code{Program_Error} will be raised
23227 when the program is run.
23228
23229 @item Several orders exist, some right, some incorrect
23230 One or more acceptable elaboration orders exists, and some of them
23231 work, and some do not. The programmer has not controlled
23232 the order of elaboration, so the binder may or may not pick one of
23233 the correct orders, and the program may or may not raise an
23234 exception when it is run. This is the worst case, because it means
23235 that the program may fail when moved to another compiler, or even
23236 another version of the same compiler.
23237
23238 @item One or more orders exists, all correct
23239 One ore more acceptable elaboration orders exist, and all of them
23240 work. In this case the program runs successfully. This state of
23241 affairs can be guaranteed by following the rule we gave above, but
23242 may be true even if the rule is not followed.
23243 @end table
23244
23245 @noindent
23246 Note that one additional advantage of following our rules on the use
23247 of @code{Elaborate} and @code{Elaborate_All}
23248 is that the program continues to stay in the ideal (all orders OK) state
23249 even if maintenance
23250 changes some bodies of some units. Conversely, if a program that does
23251 not follow this rule happens to be safe at some point, this state of affairs
23252 may deteriorate silently as a result of maintenance changes.
23253
23254 You may have noticed that the above discussion did not mention
23255 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23256 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23257 code in the body makes calls to some other unit, so it is still necessary
23258 to use @code{Elaborate_All} on such units.
23259
23260 @node Controlling Elaboration in GNAT - Internal Calls
23261 @section Controlling Elaboration in GNAT - Internal Calls
23262
23263 @noindent
23264 In the case of internal calls, i.e., calls within a single package, the
23265 programmer has full control over the order of elaboration, and it is up
23266 to the programmer to elaborate declarations in an appropriate order. For
23267 example writing:
23268
23269 @smallexample @c ada
23270 @group
23271 @cartouche
23272 function One return Float;
23273
23274 Q : Float := One;
23275
23276 function One return Float is
23277 begin
23278      return 1.0;
23279 end One;
23280 @end cartouche
23281 @end group
23282 @end smallexample
23283
23284 @noindent
23285 will obviously raise @code{Program_Error} at run time, because function
23286 One will be called before its body is elaborated. In this case GNAT will
23287 generate a warning that the call will raise @code{Program_Error}:
23288
23289 @smallexample
23290 @group
23291 @cartouche
23292  1. procedure y is
23293  2.    function One return Float;
23294  3.
23295  4.    Q : Float := One;
23296                     |
23297     >>> warning: cannot call "One" before body is elaborated
23298     >>> warning: Program_Error will be raised at run time
23299
23300  5.
23301  6.    function One return Float is
23302  7.    begin
23303  8.         return 1.0;
23304  9.    end One;
23305 10.
23306 11. begin
23307 12.    null;
23308 13. end;
23309 @end cartouche
23310 @end group
23311 @end smallexample
23312
23313 @noindent
23314 Note that in this particular case, it is likely that the call is safe, because
23315 the function @code{One} does not access any global variables.
23316 Nevertheless in Ada, we do not want the validity of the check to depend on
23317 the contents of the body (think about the separate compilation case), so this
23318 is still wrong, as we discussed in the previous sections.
23319
23320 The error is easily corrected by rearranging the declarations so that the
23321 body of @code{One} appears before the declaration containing the call
23322 (note that in Ada 95 and Ada 2005,
23323 declarations can appear in any order, so there is no restriction that
23324 would prevent this reordering, and if we write:
23325
23326 @smallexample @c ada
23327 @group
23328 @cartouche
23329 function One return Float;
23330
23331 function One return Float is
23332 begin
23333      return 1.0;
23334 end One;
23335
23336 Q : Float := One;
23337 @end cartouche
23338 @end group
23339 @end smallexample
23340
23341 @noindent
23342 then all is well, no warning is generated, and no
23343 @code{Program_Error} exception
23344 will be raised.
23345 Things are more complicated when a chain of subprograms is executed:
23346
23347 @smallexample @c ada
23348 @group
23349 @cartouche
23350 function A return Integer;
23351 function B return Integer;
23352 function C return Integer;
23353
23354 function B return Integer is begin return A; end;
23355 function C return Integer is begin return B; end;
23356
23357 X : Integer := C;
23358
23359 function A return Integer is begin return 1; end;
23360 @end cartouche
23361 @end group
23362 @end smallexample
23363
23364 @noindent
23365 Now the call to @code{C}
23366 at elaboration time in the declaration of @code{X} is correct, because
23367 the body of @code{C} is already elaborated,
23368 and the call to @code{B} within the body of
23369 @code{C} is correct, but the call
23370 to @code{A} within the body of @code{B} is incorrect, because the body
23371 of @code{A} has not been elaborated, so @code{Program_Error}
23372 will be raised on the call to @code{A}.
23373 In this case GNAT will generate a
23374 warning that @code{Program_Error} may be
23375 raised at the point of the call. Let's look at the warning:
23376
23377 @smallexample
23378 @group
23379 @cartouche
23380  1. procedure x is
23381  2.    function A return Integer;
23382  3.    function B return Integer;
23383  4.    function C return Integer;
23384  5.
23385  6.    function B return Integer is begin return A; end;
23386                                                     |
23387     >>> warning: call to "A" before body is elaborated may
23388                  raise Program_Error
23389     >>> warning: "B" called at line 7
23390     >>> warning: "C" called at line 9
23391
23392  7.    function C return Integer is begin return B; end;
23393  8.
23394  9.    X : Integer := C;
23395 10.
23396 11.    function A return Integer is begin return 1; end;
23397 12.
23398 13. begin
23399 14.    null;
23400 15. end;
23401 @end cartouche
23402 @end group
23403 @end smallexample
23404
23405 @noindent
23406 Note that the message here says ``may raise'', instead of the direct case,
23407 where the message says ``will be raised''. That's because whether
23408 @code{A} is
23409 actually called depends in general on run-time flow of control.
23410 For example, if the body of @code{B} said
23411
23412 @smallexample @c ada
23413 @group
23414 @cartouche
23415 function B return Integer is
23416 begin
23417    if some-condition-depending-on-input-data then
23418       return A;
23419    else
23420       return 1;
23421    end if;
23422 end B;
23423 @end cartouche
23424 @end group
23425 @end smallexample
23426
23427 @noindent
23428 then we could not know until run time whether the incorrect call to A would
23429 actually occur, so @code{Program_Error} might
23430 or might not be raised. It is possible for a compiler to
23431 do a better job of analyzing bodies, to
23432 determine whether or not @code{Program_Error}
23433 might be raised, but it certainly
23434 couldn't do a perfect job (that would require solving the halting problem
23435 and is provably impossible), and because this is a warning anyway, it does
23436 not seem worth the effort to do the analysis. Cases in which it
23437 would be relevant are rare.
23438
23439 In practice, warnings of either of the forms given
23440 above will usually correspond to
23441 real errors, and should be examined carefully and eliminated.
23442 In the rare case where a warning is bogus, it can be suppressed by any of
23443 the following methods:
23444
23445 @itemize @bullet
23446 @item
23447 Compile with the @option{-gnatws} switch set
23448
23449 @item
23450 Suppress @code{Elaboration_Check} for the called subprogram
23451
23452 @item
23453 Use pragma @code{Warnings_Off} to turn warnings off for the call
23454 @end itemize
23455
23456 @noindent
23457 For the internal elaboration check case,
23458 GNAT by default generates the
23459 necessary run-time checks to ensure
23460 that @code{Program_Error} is raised if any
23461 call fails an elaboration check. Of course this can only happen if a
23462 warning has been issued as described above. The use of pragma
23463 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23464 some of these checks, meaning that it may be possible (but is not
23465 guaranteed) for a program to be able to call a subprogram whose body
23466 is not yet elaborated, without raising a @code{Program_Error} exception.
23467
23468 @node Controlling Elaboration in GNAT - External Calls
23469 @section Controlling Elaboration in GNAT - External Calls
23470
23471 @noindent
23472 The previous section discussed the case in which the execution of a
23473 particular thread of elaboration code occurred entirely within a
23474 single unit. This is the easy case to handle, because a programmer
23475 has direct and total control over the order of elaboration, and
23476 furthermore, checks need only be generated in cases which are rare
23477 and which the compiler can easily detect.
23478 The situation is more complex when separate compilation is taken into account.
23479 Consider the following:
23480
23481 @smallexample @c ada
23482 @cartouche
23483 @group
23484 package Math is
23485    function Sqrt (Arg : Float) return Float;
23486 end Math;
23487
23488 package body Math is
23489    function Sqrt (Arg : Float) return Float is
23490    begin
23491          @dots{}
23492    end Sqrt;
23493 end Math;
23494 @end group
23495 @group
23496 with Math;
23497 package Stuff is
23498    X : Float := Math.Sqrt (0.5);
23499 end Stuff;
23500
23501 with Stuff;
23502 procedure Main is
23503 begin
23504    @dots{}
23505 end Main;
23506 @end group
23507 @end cartouche
23508 @end smallexample
23509
23510 @noindent
23511 where @code{Main} is the main program. When this program is executed, the
23512 elaboration code must first be executed, and one of the jobs of the
23513 binder is to determine the order in which the units of a program are
23514 to be elaborated. In this case we have four units: the spec and body
23515 of @code{Math},
23516 the spec of @code{Stuff} and the body of @code{Main}).
23517 In what order should the four separate sections of elaboration code
23518 be executed?
23519
23520 There are some restrictions in the order of elaboration that the binder
23521 can choose. In particular, if unit U has a @code{with}
23522 for a package @code{X}, then you
23523 are assured that the spec of @code{X}
23524 is elaborated before U , but you are
23525 not assured that the body of @code{X}
23526 is elaborated before U.
23527 This means that in the above case, the binder is allowed to choose the
23528 order:
23529
23530 @smallexample
23531 spec of Math
23532 spec of Stuff
23533 body of Math
23534 body of Main
23535 @end smallexample
23536
23537 @noindent
23538 but that's not good, because now the call to @code{Math.Sqrt}
23539 that happens during
23540 the elaboration of the @code{Stuff}
23541 spec happens before the body of @code{Math.Sqrt} is
23542 elaborated, and hence causes @code{Program_Error} exception to be raised.
23543 At first glance, one might say that the binder is misbehaving, because
23544 obviously you want to elaborate the body of something you @code{with}
23545 first, but
23546 that is not a general rule that can be followed in all cases. Consider
23547
23548 @smallexample @c ada
23549 @group
23550 @cartouche
23551 package X is @dots{}
23552
23553 package Y is @dots{}
23554
23555 with X;
23556 package body Y is @dots{}
23557
23558 with Y;
23559 package body X is @dots{}
23560 @end cartouche
23561 @end group
23562 @end smallexample
23563
23564 @noindent
23565 This is a common arrangement, and, apart from the order of elaboration
23566 problems that might arise in connection with elaboration code, this works fine.
23567 A rule that says that you must first elaborate the body of anything you
23568 @code{with} cannot work in this case:
23569 the body of @code{X} @code{with}'s @code{Y},
23570 which means you would have to
23571 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23572 which means
23573 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23574 loop that cannot be broken.
23575
23576 It is true that the binder can in many cases guess an order of elaboration
23577 that is unlikely to cause a @code{Program_Error}
23578 exception to be raised, and it tries to do so (in the
23579 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23580 by default
23581 elaborate the body of @code{Math} right after its spec, so all will be well).
23582
23583 However, a program that blindly relies on the binder to be helpful can
23584 get into trouble, as we discussed in the previous sections, so
23585 GNAT
23586 provides a number of facilities for assisting the programmer in
23587 developing programs that are robust with respect to elaboration order.
23588
23589 @node Default Behavior in GNAT - Ensuring Safety
23590 @section Default Behavior in GNAT - Ensuring Safety
23591
23592 @noindent
23593 The default behavior in GNAT ensures elaboration safety. In its
23594 default mode GNAT implements the
23595 rule we previously described as the right approach. Let's restate it:
23596
23597 @itemize
23598 @item
23599 @emph{If a unit has elaboration code that can directly or indirectly make a
23600 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23601 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23602 does not have pragma @code{Pure} or
23603 @code{Preelaborate}, then the client should have an
23604 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23605
23606 @emph{In the case of instantiating a generic subprogram, it is always
23607 sufficient to have only an @code{Elaborate} pragma for the
23608 @code{with}'ed unit.}
23609 @end itemize
23610
23611 @noindent
23612 By following this rule a client is assured that calls and instantiations
23613 can be made without risk of an exception.
23614
23615 In this mode GNAT traces all calls that are potentially made from
23616 elaboration code, and puts in any missing implicit @code{Elaborate}
23617 and @code{Elaborate_All} pragmas.
23618 The advantage of this approach is that no elaboration problems
23619 are possible if the binder can find an elaboration order that is
23620 consistent with these implicit @code{Elaborate} and
23621 @code{Elaborate_All} pragmas. The
23622 disadvantage of this approach is that no such order may exist.
23623
23624 If the binder does not generate any diagnostics, then it means that it has
23625 found an elaboration order that is guaranteed to be safe. However, the binder
23626 may still be relying on implicitly generated @code{Elaborate} and
23627 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23628 guaranteed.
23629
23630 If it is important to guarantee portability, then the compilations should
23631 use the
23632 @option{-gnatwl}
23633 (warn on elaboration problems) switch. This will cause warning messages
23634 to be generated indicating the missing @code{Elaborate} and
23635 @code{Elaborate_All} pragmas.
23636 Consider the following source program:
23637
23638 @smallexample @c ada
23639 @group
23640 @cartouche
23641 with k;
23642 package j is
23643   m : integer := k.r;
23644 end;
23645 @end cartouche
23646 @end group
23647 @end smallexample
23648
23649 @noindent
23650 where it is clear that there
23651 should be a pragma @code{Elaborate_All}
23652 for unit @code{k}. An implicit pragma will be generated, and it is
23653 likely that the binder will be able to honor it. However, if you want
23654 to port this program to some other Ada compiler than GNAT.
23655 it is safer to include the pragma explicitly in the source. If this
23656 unit is compiled with the
23657 @option{-gnatwl}
23658 switch, then the compiler outputs a warning:
23659
23660 @smallexample
23661 @group
23662 @cartouche
23663 1. with k;
23664 2. package j is
23665 3.   m : integer := k.r;
23666                      |
23667    >>> warning: call to "r" may raise Program_Error
23668    >>> warning: missing pragma Elaborate_All for "k"
23669
23670 4. end;
23671 @end cartouche
23672 @end group
23673 @end smallexample
23674
23675 @noindent
23676 and these warnings can be used as a guide for supplying manually
23677 the missing pragmas. It is usually a bad idea to use this warning
23678 option during development. That's because it will warn you when
23679 you need to put in a pragma, but cannot warn you when it is time
23680 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23681 unnecessary dependencies and even false circularities.
23682
23683 This default mode is more restrictive than the Ada Reference
23684 Manual, and it is possible to construct programs which will compile
23685 using the dynamic model described there, but will run into a
23686 circularity using the safer static model we have described.
23687
23688 Of course any Ada compiler must be able to operate in a mode
23689 consistent with the requirements of the Ada Reference Manual,
23690 and in particular must have the capability of implementing the
23691 standard dynamic model of elaboration with run-time checks.
23692
23693 In GNAT, this standard mode can be achieved either by the use of
23694 the @option{-gnatE} switch on the compiler (@command{gcc} or
23695 @command{gnatmake}) command, or by the use of the configuration pragma:
23696
23697 @smallexample @c ada
23698 pragma Elaboration_Checks (DYNAMIC);
23699 @end smallexample
23700
23701 @noindent
23702 Either approach will cause the unit affected to be compiled using the
23703 standard dynamic run-time elaboration checks described in the Ada
23704 Reference Manual. The static model is generally preferable, since it
23705 is clearly safer to rely on compile and link time checks rather than
23706 run-time checks. However, in the case of legacy code, it may be
23707 difficult to meet the requirements of the static model. This
23708 issue is further discussed in
23709 @ref{What to Do If the Default Elaboration Behavior Fails}.
23710
23711 Note that the static model provides a strict subset of the allowed
23712 behavior and programs of the Ada Reference Manual, so if you do
23713 adhere to the static model and no circularities exist,
23714 then you are assured that your program will
23715 work using the dynamic model, providing that you remove any
23716 pragma Elaborate statements from the source.
23717
23718 @node Treatment of Pragma Elaborate
23719 @section Treatment of Pragma Elaborate
23720 @cindex Pragma Elaborate
23721
23722 @noindent
23723 The use of @code{pragma Elaborate}
23724 should generally be avoided in Ada 95 and Ada 2005 programs,
23725 since there is no guarantee that transitive calls
23726 will be properly handled. Indeed at one point, this pragma was placed
23727 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23728
23729 Now that's a bit restrictive. In practice, the case in which
23730 @code{pragma Elaborate} is useful is when the caller knows that there
23731 are no transitive calls, or that the called unit contains all necessary
23732 transitive @code{pragma Elaborate} statements, and legacy code often
23733 contains such uses.
23734
23735 Strictly speaking the static mode in GNAT should ignore such pragmas,
23736 since there is no assurance at compile time that the necessary safety
23737 conditions are met. In practice, this would cause GNAT to be incompatible
23738 with correctly written Ada 83 code that had all necessary
23739 @code{pragma Elaborate} statements in place. Consequently, we made the
23740 decision that GNAT in its default mode will believe that if it encounters
23741 a @code{pragma Elaborate} then the programmer knows what they are doing,
23742 and it will trust that no elaboration errors can occur.
23743
23744 The result of this decision is two-fold. First to be safe using the
23745 static mode, you should remove all @code{pragma Elaborate} statements.
23746 Second, when fixing circularities in existing code, you can selectively
23747 use @code{pragma Elaborate} statements to convince the static mode of
23748 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23749 statement.
23750
23751 When using the static mode with @option{-gnatwl}, any use of
23752 @code{pragma Elaborate} will generate a warning about possible
23753 problems.
23754
23755 @node Elaboration Issues for Library Tasks
23756 @section Elaboration Issues for Library Tasks
23757 @cindex Library tasks, elaboration issues
23758 @cindex Elaboration of library tasks
23759
23760 @noindent
23761 In this section we examine special elaboration issues that arise for
23762 programs that declare library level tasks.
23763
23764 Generally the model of execution of an Ada program is that all units are
23765 elaborated, and then execution of the program starts. However, the
23766 declaration of library tasks definitely does not fit this model. The
23767 reason for this is that library tasks start as soon as they are declared
23768 (more precisely, as soon as the statement part of the enclosing package
23769 body is reached), that is to say before elaboration
23770 of the program is complete. This means that if such a task calls a
23771 subprogram, or an entry in another task, the callee may or may not be
23772 elaborated yet, and in the standard
23773 Reference Manual model of dynamic elaboration checks, you can even
23774 get timing dependent Program_Error exceptions, since there can be
23775 a race between the elaboration code and the task code.
23776
23777 The static model of elaboration in GNAT seeks to avoid all such
23778 dynamic behavior, by being conservative, and the conservative
23779 approach in this particular case is to assume that all the code
23780 in a task body is potentially executed at elaboration time if
23781 a task is declared at the library level.
23782
23783 This can definitely result in unexpected circularities. Consider
23784 the following example
23785
23786 @smallexample @c ada
23787 package Decls is
23788   task Lib_Task is
23789      entry Start;
23790   end Lib_Task;
23791
23792   type My_Int is new Integer;
23793
23794   function Ident (M : My_Int) return My_Int;
23795 end Decls;
23796
23797 with Utils;
23798 package body Decls is
23799   task body Lib_Task is
23800   begin
23801      accept Start;
23802      Utils.Put_Val (2);
23803   end Lib_Task;
23804
23805   function Ident (M : My_Int) return My_Int is
23806   begin
23807      return M;
23808   end Ident;
23809 end Decls;
23810
23811 with Decls;
23812 package Utils is
23813   procedure Put_Val (Arg : Decls.My_Int);
23814 end Utils;
23815
23816 with Text_IO;
23817 package body Utils is
23818   procedure Put_Val (Arg : Decls.My_Int) is
23819   begin
23820      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23821   end Put_Val;
23822 end Utils;
23823
23824 with Decls;
23825 procedure Main is
23826 begin
23827    Decls.Lib_Task.Start;
23828 end;
23829 @end smallexample
23830
23831 @noindent
23832 If the above example is compiled in the default static elaboration
23833 mode, then a circularity occurs. The circularity comes from the call
23834 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23835 this call occurs in elaboration code, we need an implicit pragma
23836 @code{Elaborate_All} for @code{Utils}. This means that not only must
23837 the spec and body of @code{Utils} be elaborated before the body
23838 of @code{Decls}, but also the spec and body of any unit that is
23839 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23840 the body of @code{Decls}. This is the transitive implication of
23841 pragma @code{Elaborate_All} and it makes sense, because in general
23842 the body of @code{Put_Val} might have a call to something in a
23843 @code{with'ed} unit.
23844
23845 In this case, the body of Utils (actually its spec) @code{with's}
23846 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23847 must be elaborated before itself, in case there is a call from the
23848 body of @code{Utils}.
23849
23850 Here is the exact chain of events we are worrying about:
23851
23852 @enumerate
23853 @item
23854 In the body of @code{Decls} a call is made from within the body of a library
23855 task to a subprogram in the package @code{Utils}. Since this call may
23856 occur at elaboration time (given that the task is activated at elaboration
23857 time), we have to assume the worst, i.e., that the
23858 call does happen at elaboration time.
23859
23860 @item
23861 This means that the body and spec of @code{Util} must be elaborated before
23862 the body of @code{Decls} so that this call does not cause an access before
23863 elaboration.
23864
23865 @item
23866 Within the body of @code{Util}, specifically within the body of
23867 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23868 by this package.
23869
23870 @item
23871 One such @code{with}'ed package is package @code{Decls}, so there
23872 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23873 In fact there is such a call in this example, but we would have to
23874 assume that there was such a call even if it were not there, since
23875 we are not supposed to write the body of @code{Decls} knowing what
23876 is in the body of @code{Utils}; certainly in the case of the
23877 static elaboration model, the compiler does not know what is in
23878 other bodies and must assume the worst.
23879
23880 @item
23881 This means that the spec and body of @code{Decls} must also be
23882 elaborated before we elaborate the unit containing the call, but
23883 that unit is @code{Decls}! This means that the body of @code{Decls}
23884 must be elaborated before itself, and that's a circularity.
23885 @end enumerate
23886
23887 @noindent
23888 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23889 the body of @code{Decls} you will get a true Ada Reference Manual
23890 circularity that makes the program illegal.
23891
23892 In practice, we have found that problems with the static model of
23893 elaboration in existing code often arise from library tasks, so
23894 we must address this particular situation.
23895
23896 Note that if we compile and run the program above, using the dynamic model of
23897 elaboration (that is to say use the @option{-gnatE} switch),
23898 then it compiles, binds,
23899 links, and runs, printing the expected result of 2. Therefore in some sense
23900 the circularity here is only apparent, and we need to capture
23901 the properties of this program that  distinguish it from other library-level
23902 tasks that have real elaboration problems.
23903
23904 We have four possible answers to this question:
23905
23906 @itemize @bullet
23907
23908 @item
23909 Use the dynamic model of elaboration.
23910
23911 If we use the @option{-gnatE} switch, then as noted above, the program works.
23912 Why is this? If we examine the task body, it is apparent that the task cannot
23913 proceed past the
23914 @code{accept} statement until after elaboration has been completed, because
23915 the corresponding entry call comes from the main program, not earlier.
23916 This is why the dynamic model works here. But that's really giving
23917 up on a precise analysis, and we prefer to take this approach only if we cannot
23918 solve the
23919 problem in any other manner. So let us examine two ways to reorganize
23920 the program to avoid the potential elaboration problem.
23921
23922 @item
23923 Split library tasks into separate packages.
23924
23925 Write separate packages, so that library tasks are isolated from
23926 other declarations as much as possible. Let us look at a variation on
23927 the above program.
23928
23929 @smallexample @c ada
23930 package Decls1 is
23931   task Lib_Task is
23932      entry Start;
23933   end Lib_Task;
23934 end Decls1;
23935
23936 with Utils;
23937 package body Decls1 is
23938   task body Lib_Task is
23939   begin
23940      accept Start;
23941      Utils.Put_Val (2);
23942   end Lib_Task;
23943 end Decls1;
23944
23945 package Decls2 is
23946   type My_Int is new Integer;
23947   function Ident (M : My_Int) return My_Int;
23948 end Decls2;
23949
23950 with Utils;
23951 package body Decls2 is
23952   function Ident (M : My_Int) return My_Int is
23953   begin
23954      return M;
23955   end Ident;
23956 end Decls2;
23957
23958 with Decls2;
23959 package Utils is
23960   procedure Put_Val (Arg : Decls2.My_Int);
23961 end Utils;
23962
23963 with Text_IO;
23964 package body Utils is
23965   procedure Put_Val (Arg : Decls2.My_Int) is
23966   begin
23967      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23968   end Put_Val;
23969 end Utils;
23970
23971 with Decls1;
23972 procedure Main is
23973 begin
23974    Decls1.Lib_Task.Start;
23975 end;
23976 @end smallexample
23977
23978 @noindent
23979 All we have done is to split @code{Decls} into two packages, one
23980 containing the library task, and one containing everything else. Now
23981 there is no cycle, and the program compiles, binds, links and executes
23982 using the default static model of elaboration.
23983
23984 @item
23985 Declare separate task types.
23986
23987 A significant part of the problem arises because of the use of the
23988 single task declaration form. This means that the elaboration of
23989 the task type, and the elaboration of the task itself (i.e.@: the
23990 creation of the task) happen at the same time. A good rule
23991 of style in Ada is to always create explicit task types. By
23992 following the additional step of placing task objects in separate
23993 packages from the task type declaration, many elaboration problems
23994 are avoided. Here is another modified example of the example program:
23995
23996 @smallexample @c ada
23997 package Decls is
23998   task type Lib_Task_Type is
23999      entry Start;
24000   end Lib_Task_Type;
24001
24002   type My_Int is new Integer;
24003
24004   function Ident (M : My_Int) return My_Int;
24005 end Decls;
24006
24007 with Utils;
24008 package body Decls is
24009   task body Lib_Task_Type is
24010   begin
24011      accept Start;
24012      Utils.Put_Val (2);
24013   end Lib_Task_Type;
24014
24015   function Ident (M : My_Int) return My_Int is
24016   begin
24017      return M;
24018   end Ident;
24019 end Decls;
24020
24021 with Decls;
24022 package Utils is
24023   procedure Put_Val (Arg : Decls.My_Int);
24024 end Utils;
24025
24026 with Text_IO;
24027 package body Utils is
24028   procedure Put_Val (Arg : Decls.My_Int) is
24029   begin
24030      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24031   end Put_Val;
24032 end Utils;
24033
24034 with Decls;
24035 package Declst is
24036    Lib_Task : Decls.Lib_Task_Type;
24037 end Declst;
24038
24039 with Declst;
24040 procedure Main is
24041 begin
24042    Declst.Lib_Task.Start;
24043 end;
24044 @end smallexample
24045
24046 @noindent
24047 What we have done here is to replace the @code{task} declaration in
24048 package @code{Decls} with a @code{task type} declaration. Then we
24049 introduce a separate package @code{Declst} to contain the actual
24050 task object. This separates the elaboration issues for
24051 the @code{task type}
24052 declaration, which causes no trouble, from the elaboration issues
24053 of the task object, which is also unproblematic, since it is now independent
24054 of the elaboration of  @code{Utils}.
24055 This separation of concerns also corresponds to
24056 a generally sound engineering principle of separating declarations
24057 from instances. This version of the program also compiles, binds, links,
24058 and executes, generating the expected output.
24059
24060 @item
24061 Use No_Entry_Calls_In_Elaboration_Code restriction.
24062 @cindex No_Entry_Calls_In_Elaboration_Code
24063
24064 The previous two approaches described how a program can be restructured
24065 to avoid the special problems caused by library task bodies. in practice,
24066 however, such restructuring may be difficult to apply to existing legacy code,
24067 so we must consider solutions that do not require massive rewriting.
24068
24069 Let us consider more carefully why our original sample program works
24070 under the dynamic model of elaboration. The reason is that the code
24071 in the task body blocks immediately on the @code{accept}
24072 statement. Now of course there is nothing to prohibit elaboration
24073 code from making entry calls (for example from another library level task),
24074 so we cannot tell in isolation that
24075 the task will not execute the accept statement  during elaboration.
24076
24077 However, in practice it is very unusual to see elaboration code
24078 make any entry calls, and the pattern of tasks starting
24079 at elaboration time and then immediately blocking on @code{accept} or
24080 @code{select} statements is very common. What this means is that
24081 the compiler is being too pessimistic when it analyzes the
24082 whole package body as though it might be executed at elaboration
24083 time.
24084
24085 If we know that the elaboration code contains no entry calls, (a very safe
24086 assumption most of the time, that could almost be made the default
24087 behavior), then we can compile all units of the program under control
24088 of the following configuration pragma:
24089
24090 @smallexample
24091 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24092 @end smallexample
24093
24094 @noindent
24095 This pragma can be placed in the @file{gnat.adc} file in the usual
24096 manner. If we take our original unmodified program and compile it
24097 in the presence of a @file{gnat.adc} containing the above pragma,
24098 then once again, we can compile, bind, link, and execute, obtaining
24099 the expected result. In the presence of this pragma, the compiler does
24100 not trace calls in a task body, that appear after the first @code{accept}
24101 or @code{select} statement, and therefore does not report a potential
24102 circularity in the original program.
24103
24104 The compiler will check to the extent it can that the above
24105 restriction is not violated, but it is not always possible to do a
24106 complete check at compile time, so it is important to use this
24107 pragma only if the stated restriction is in fact met, that is to say
24108 no task receives an entry call before elaboration of all units is completed.
24109
24110 @end itemize
24111
24112 @node Mixing Elaboration Models
24113 @section Mixing Elaboration Models
24114 @noindent
24115 So far, we have assumed that the entire program is either compiled
24116 using the dynamic model or static model, ensuring consistency. It
24117 is possible to mix the two models, but rules have to be followed
24118 if this mixing is done to ensure that elaboration checks are not
24119 omitted.
24120
24121 The basic rule is that @emph{a unit compiled with the static model cannot
24122 be @code{with'ed} by a unit compiled with the dynamic model}. The
24123 reason for this is that in the static model, a unit assumes that
24124 its clients guarantee to use (the equivalent of) pragma
24125 @code{Elaborate_All} so that no elaboration checks are required
24126 in inner subprograms, and this assumption is violated if the
24127 client is compiled with dynamic checks.
24128
24129 The precise rule is as follows. A unit that is compiled with dynamic
24130 checks can only @code{with} a unit that meets at least one of the
24131 following criteria:
24132
24133 @itemize @bullet
24134
24135 @item
24136 The @code{with'ed} unit is itself compiled with dynamic elaboration
24137 checks (that is with the @option{-gnatE} switch.
24138
24139 @item
24140 The @code{with'ed} unit is an internal GNAT implementation unit from
24141 the System, Interfaces, Ada, or GNAT hierarchies.
24142
24143 @item
24144 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24145
24146 @item
24147 The @code{with'ing} unit (that is the client) has an explicit pragma
24148 @code{Elaborate_All} for the @code{with'ed} unit.
24149
24150 @end itemize
24151
24152 @noindent
24153 If this rule is violated, that is if a unit with dynamic elaboration
24154 checks @code{with's} a unit that does not meet one of the above four
24155 criteria, then the binder (@code{gnatbind}) will issue a warning
24156 similar to that in the following example:
24157
24158 @smallexample
24159 warning: "x.ads" has dynamic elaboration checks and with's
24160 warning:   "y.ads" which has static elaboration checks
24161 @end smallexample
24162
24163 @noindent
24164 These warnings indicate that the rule has been violated, and that as a result
24165 elaboration checks may be missed in the resulting executable file.
24166 This warning may be suppressed using the @option{-ws} binder switch
24167 in the usual manner.
24168
24169 One useful application of this mixing rule is in the case of a subsystem
24170 which does not itself @code{with} units from the remainder of the
24171 application. In this case, the entire subsystem can be compiled with
24172 dynamic checks to resolve a circularity in the subsystem, while
24173 allowing the main application that uses this subsystem to be compiled
24174 using the more reliable default static model.
24175
24176 @node What to Do If the Default Elaboration Behavior Fails
24177 @section What to Do If the Default Elaboration Behavior Fails
24178
24179 @noindent
24180 If the binder cannot find an acceptable order, it outputs detailed
24181 diagnostics. For example:
24182 @smallexample
24183 @group
24184 @iftex
24185 @leftskip=0cm
24186 @end iftex
24187 error: elaboration circularity detected
24188 info:   "proc (body)" must be elaborated before "pack (body)"
24189 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24190 info:     recompile "pack (body)" with -gnatwl
24191 info:                             for full details
24192 info:       "proc (body)"
24193 info:         is needed by its spec:
24194 info:       "proc (spec)"
24195 info:         which is withed by:
24196 info:       "pack (body)"
24197 info:  "pack (body)" must be elaborated before "proc (body)"
24198 info:     reason: pragma Elaborate in unit "proc (body)"
24199 @end group
24200
24201 @end smallexample
24202
24203 @noindent
24204 In this case we have a cycle that the binder cannot break. On the one
24205 hand, there is an explicit pragma Elaborate in @code{proc} for
24206 @code{pack}. This means that the body of @code{pack} must be elaborated
24207 before the body of @code{proc}. On the other hand, there is elaboration
24208 code in @code{pack} that calls a subprogram in @code{proc}. This means
24209 that for maximum safety, there should really be a pragma
24210 Elaborate_All in @code{pack} for @code{proc} which would require that
24211 the body of @code{proc} be elaborated before the body of
24212 @code{pack}. Clearly both requirements cannot be satisfied.
24213 Faced with a circularity of this kind, you have three different options.
24214
24215 @table @asis
24216 @item Fix the program
24217 The most desirable option from the point of view of long-term maintenance
24218 is to rearrange the program so that the elaboration problems are avoided.
24219 One useful technique is to place the elaboration code into separate
24220 child packages. Another is to move some of the initialization code to
24221 explicitly called subprograms, where the program controls the order
24222 of initialization explicitly. Although this is the most desirable option,
24223 it may be impractical and involve too much modification, especially in
24224 the case of complex legacy code.
24225
24226 @item Perform dynamic checks
24227 If the compilations are done using the
24228 @option{-gnatE}
24229 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24230 manner. Dynamic checks are generated for all calls that could possibly result
24231 in raising an exception. With this switch, the compiler does not generate
24232 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24233 exactly as specified in the @cite{Ada Reference Manual}.
24234 The binder will generate
24235 an executable program that may or may not raise @code{Program_Error}, and then
24236 it is the programmer's job to ensure that it does not raise an exception. Note
24237 that it is important to compile all units with the switch, it cannot be used
24238 selectively.
24239
24240 @item Suppress checks
24241 The drawback of dynamic checks is that they generate a
24242 significant overhead at run time, both in space and time. If you
24243 are absolutely sure that your program cannot raise any elaboration
24244 exceptions, and you still want to use the dynamic elaboration model,
24245 then you can use the configuration pragma
24246 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24247 example this pragma could be placed in the @file{gnat.adc} file.
24248
24249 @item Suppress checks selectively
24250 When you know that certain calls or instantiations in elaboration code cannot
24251 possibly lead to an elaboration error, and the binder nevertheless complains
24252 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24253 elaboration circularities, it is possible to remove those warnings locally and
24254 obtain a program that will bind. Clearly this can be unsafe, and it is the
24255 responsibility of the programmer to make sure that the resulting program has no
24256 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24257 used with different granularity to suppress warnings and break elaboration
24258 circularities:
24259
24260 @itemize @bullet
24261 @item
24262 Place the pragma that names the called subprogram in the declarative part
24263 that contains the call.
24264
24265 @item
24266 Place the pragma in the declarative part, without naming an entity. This
24267 disables warnings on all calls in the corresponding  declarative region.
24268
24269 @item
24270 Place the pragma in the package spec that declares the called subprogram,
24271 and name the subprogram. This disables warnings on all elaboration calls to
24272 that subprogram.
24273
24274 @item
24275 Place the pragma in the package spec that declares the called subprogram,
24276 without naming any entity. This disables warnings on all elaboration calls to
24277 all subprograms declared in this spec.
24278
24279 @item Use Pragma Elaborate
24280 As previously described in section @xref{Treatment of Pragma Elaborate},
24281 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24282 that no elaboration checks are required on calls to the designated unit.
24283 There may be cases in which the caller knows that no transitive calls
24284 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24285 case where @code{pragma Elaborate_All} would cause a circularity.
24286 @end itemize
24287
24288 @noindent
24289 These five cases are listed in order of decreasing safety, and therefore
24290 require increasing programmer care in their application. Consider the
24291 following program:
24292
24293 @smallexample @c adanocomment
24294 package Pack1 is
24295   function F1 return Integer;
24296   X1 : Integer;
24297 end Pack1;
24298
24299 package Pack2 is
24300   function F2 return Integer;
24301   function Pure (x : integer) return integer;
24302   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24303   --  pragma Suppress (Elaboration_Check);              -- (4)
24304 end Pack2;
24305
24306 with Pack2;
24307 package body Pack1 is
24308   function F1 return Integer is
24309   begin
24310     return 100;
24311   end F1;
24312   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24313 begin
24314   declare
24315     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24316     --  pragma Suppress(Elaboration_Check);             -- (2)
24317   begin
24318     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24319   end;
24320 end Pack1;
24321
24322 with Pack1;
24323 package body Pack2 is
24324   function F2 return Integer is
24325   begin
24326      return Pack1.F1;
24327   end F2;
24328   function Pure (x : integer) return integer is
24329   begin
24330      return x ** 3 - 3 * x;
24331   end;
24332 end Pack2;
24333
24334 with Pack1, Ada.Text_IO;
24335 procedure Proc3 is
24336 begin
24337   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24338 end Proc3;
24339 @end smallexample
24340 In the absence of any pragmas, an attempt to bind this program produces
24341 the following diagnostics:
24342 @smallexample
24343 @group
24344 @iftex
24345 @leftskip=.5cm
24346 @end iftex
24347 error: elaboration circularity detected
24348 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24349 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24350 info:       recompile "pack1 (body)" with -gnatwl for full details
24351 info:          "pack1 (body)"
24352 info:             must be elaborated along with its spec:
24353 info:          "pack1 (spec)"
24354 info:             which is withed by:
24355 info:          "pack2 (body)"
24356 info:             which must be elaborated along with its spec:
24357 info:          "pack2 (spec)"
24358 info:             which is withed by:
24359 info:          "pack1 (body)"
24360 @end group
24361 @end smallexample
24362 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24363 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24364 F2 is safe, even though F2 calls F1, because the call appears after the
24365 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24366 remove the warning on the call. It is also possible to use pragma (2)
24367 because there are no other potentially unsafe calls in the block.
24368
24369 @noindent
24370 The call to @code{Pure} is safe because this function does not depend on the
24371 state of @code{Pack2}. Therefore any call to this function is safe, and it
24372 is correct to place pragma (3) in the corresponding package spec.
24373
24374 @noindent
24375 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24376 warnings on all calls to functions declared therein. Note that this is not
24377 necessarily safe, and requires more detailed examination of the subprogram
24378 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24379 be already elaborated.
24380 @end table
24381
24382 @noindent
24383 It is hard to generalize on which of these four approaches should be
24384 taken. Obviously if it is possible to fix the program so that the default
24385 treatment works, this is preferable, but this may not always be practical.
24386 It is certainly simple enough to use
24387 @option{-gnatE}
24388 but the danger in this case is that, even if the GNAT binder
24389 finds a correct elaboration order, it may not always do so,
24390 and certainly a binder from another Ada compiler might not. A
24391 combination of testing and analysis (for which the warnings generated
24392 with the
24393 @option{-gnatwl}
24394 switch can be useful) must be used to ensure that the program is free
24395 of errors. One switch that is useful in this testing is the
24396 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24397 switch for
24398 @code{gnatbind}.
24399 Normally the binder tries to find an order that has the best chance
24400 of avoiding elaboration problems. However, if this switch is used, the binder
24401 plays a devil's advocate role, and tries to choose the order that
24402 has the best chance of failing. If your program works even with this
24403 switch, then it has a better chance of being error free, but this is still
24404 not a guarantee.
24405
24406 For an example of this approach in action, consider the C-tests (executable
24407 tests) from the ACVC suite. If these are compiled and run with the default
24408 treatment, then all but one of them succeed without generating any error
24409 diagnostics from the binder. However, there is one test that fails, and
24410 this is not surprising, because the whole point of this test is to ensure
24411 that the compiler can handle cases where it is impossible to determine
24412 a correct order statically, and it checks that an exception is indeed
24413 raised at run time.
24414
24415 This one test must be compiled and run using the
24416 @option{-gnatE}
24417 switch, and then it passes. Alternatively, the entire suite can
24418 be run using this switch. It is never wrong to run with the dynamic
24419 elaboration switch if your code is correct, and we assume that the
24420 C-tests are indeed correct (it is less efficient, but efficiency is
24421 not a factor in running the ACVC tests.)
24422
24423 @node Elaboration for Access-to-Subprogram Values
24424 @section Elaboration for Access-to-Subprogram Values
24425 @cindex Access-to-subprogram
24426
24427 @noindent
24428 Access-to-subprogram types (introduced in Ada 95) complicate
24429 the handling of elaboration. The trouble is that it becomes
24430 impossible to tell at compile time which procedure
24431 is being called. This means that it is not possible for the binder
24432 to analyze the elaboration requirements in this case.
24433
24434 If at the point at which the access value is created
24435 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24436 the body of the subprogram is
24437 known to have been elaborated, then the access value is safe, and its use
24438 does not require a check. This may be achieved by appropriate arrangement
24439 of the order of declarations if the subprogram is in the current unit,
24440 or, if the subprogram is in another unit, by using pragma
24441 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24442 on the referenced unit.
24443
24444 If the referenced body is not known to have been elaborated at the point
24445 the access value is created, then any use of the access value must do a
24446 dynamic check, and this dynamic check will fail and raise a
24447 @code{Program_Error} exception if the body has not been elaborated yet.
24448 GNAT will generate the necessary checks, and in addition, if the
24449 @option{-gnatwl}
24450 switch is set, will generate warnings that such checks are required.
24451
24452 The use of dynamic dispatching for tagged types similarly generates
24453 a requirement for dynamic checks, and premature calls to any primitive
24454 operation of a tagged type before the body of the operation has been
24455 elaborated, will result in the raising of @code{Program_Error}.
24456
24457 @node Summary of Procedures for Elaboration Control
24458 @section Summary of Procedures for Elaboration Control
24459 @cindex Elaboration control
24460
24461 @noindent
24462 First, compile your program with the default options, using none of
24463 the special elaboration control switches. If the binder successfully
24464 binds your program, then you can be confident that, apart from issues
24465 raised by the use of access-to-subprogram types and dynamic dispatching,
24466 the program is free of elaboration errors. If it is important that the
24467 program be portable, then use the
24468 @option{-gnatwl}
24469 switch to generate warnings about missing @code{Elaborate} or
24470 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24471
24472 If the program fails to bind using the default static elaboration
24473 handling, then you can fix the program to eliminate the binder
24474 message, or recompile the entire program with the
24475 @option{-gnatE} switch to generate dynamic elaboration checks,
24476 and, if you are sure there really are no elaboration problems,
24477 use a global pragma @code{Suppress (Elaboration_Check)}.
24478
24479 @node Other Elaboration Order Considerations
24480 @section Other Elaboration Order Considerations
24481 @noindent
24482 This section has been entirely concerned with the issue of finding a valid
24483 elaboration order, as defined by the Ada Reference Manual. In a case
24484 where several elaboration orders are valid, the task is to find one
24485 of the possible valid elaboration orders (and the static model in GNAT
24486 will ensure that this is achieved).
24487
24488 The purpose of the elaboration rules in the Ada Reference Manual is to
24489 make sure that no entity is accessed before it has been elaborated. For
24490 a subprogram, this means that the spec and body must have been elaborated
24491 before the subprogram is called. For an object, this means that the object
24492 must have been elaborated before its value is read or written. A violation
24493 of either of these two requirements is an access before elaboration order,
24494 and this section has been all about avoiding such errors.
24495
24496 In the case where more than one order of elaboration is possible, in the
24497 sense that access before elaboration errors are avoided, then any one of
24498 the orders is ``correct'' in the sense that it meets the requirements of
24499 the Ada Reference Manual, and no such error occurs.
24500
24501 However, it may be the case for a given program, that there are
24502 constraints on the order of elaboration that come not from consideration
24503 of avoiding elaboration errors, but rather from extra-lingual logic
24504 requirements. Consider this example:
24505
24506 @smallexample @c ada
24507 with Init_Constants;
24508 package Constants is
24509    X : Integer := 0;
24510    Y : Integer := 0;
24511 end Constants;
24512
24513 package Init_Constants is
24514    procedure P; -- require a body
24515 end Init_Constants;
24516
24517 with Constants;
24518 package body Init_Constants is
24519    procedure P is begin null; end;
24520 begin
24521    Constants.X := 3;
24522    Constants.Y := 4;
24523 end Init_Constants;
24524
24525 with Constants;
24526 package Calc is
24527    Z : Integer := Constants.X + Constants.Y;
24528 end Calc;
24529
24530 with Calc;
24531 with Text_IO; use Text_IO;
24532 procedure Main is
24533 begin
24534    Put_Line (Calc.Z'Img);
24535 end Main;
24536 @end smallexample
24537
24538 @noindent
24539 In this example, there is more than one valid order of elaboration. For
24540 example both the following are correct orders:
24541
24542 @smallexample
24543 Init_Constants spec
24544 Constants spec
24545 Calc spec
24546 Init_Constants body
24547 Main body
24548
24549   and
24550
24551 Init_Constants spec
24552 Init_Constants body
24553 Constants spec
24554 Calc spec
24555 Main body
24556 @end smallexample
24557
24558 @noindent
24559 There is no language rule to prefer one or the other, both are correct
24560 from an order of elaboration point of view. But the programmatic effects
24561 of the two orders are very different. In the first, the elaboration routine
24562 of @code{Calc} initializes @code{Z} to zero, and then the main program
24563 runs with this value of zero. But in the second order, the elaboration
24564 routine of @code{Calc} runs after the body of Init_Constants has set
24565 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24566 runs.
24567
24568 One could perhaps by applying pretty clever non-artificial intelligence
24569 to the situation guess that it is more likely that the second order of
24570 elaboration is the one desired, but there is no formal linguistic reason
24571 to prefer one over the other. In fact in this particular case, GNAT will
24572 prefer the second order, because of the rule that bodies are elaborated
24573 as soon as possible, but it's just luck that this is what was wanted
24574 (if indeed the second order was preferred).
24575
24576 If the program cares about the order of elaboration routines in a case like
24577 this, it is important to specify the order required. In this particular
24578 case, that could have been achieved by adding to the spec of Calc:
24579
24580 @smallexample @c ada
24581 pragma Elaborate_All (Constants);
24582 @end smallexample
24583
24584 @noindent
24585 which requires that the body (if any) and spec of @code{Constants},
24586 as well as the body and spec of any unit @code{with}'ed by
24587 @code{Constants} be elaborated before @code{Calc} is elaborated.
24588
24589 Clearly no automatic method can always guess which alternative you require,
24590 and if you are working with legacy code that had constraints of this kind
24591 which were not properly specified by adding @code{Elaborate} or
24592 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24593 compilers can choose different orders.
24594
24595 However, GNAT does attempt to diagnose the common situation where there
24596 are uninitialized variables in the visible part of a package spec, and the
24597 corresponding package body has an elaboration block that directly or
24598 indirectly initialized one or more of these variables. This is the situation
24599 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24600 a warning that suggests this addition if it detects this situation.
24601
24602 The @code{gnatbind}
24603 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24604 out problems. This switch causes bodies to be elaborated as late as possible
24605 instead of as early as possible. In the example above, it would have forced
24606 the choice of the first elaboration order. If you get different results
24607 when using this switch, and particularly if one set of results is right,
24608 and one is wrong as far as you are concerned, it shows that you have some
24609 missing @code{Elaborate} pragmas. For the example above, we have the
24610 following output:
24611
24612 @smallexample
24613 gnatmake -f -q main
24614 main
24615  7
24616 gnatmake -f -q main -bargs -p
24617 main
24618  0
24619 @end smallexample
24620
24621 @noindent
24622 It is of course quite unlikely that both these results are correct, so
24623 it is up to you in a case like this to investigate the source of the
24624 difference, by looking at the two elaboration orders that are chosen,
24625 and figuring out which is correct, and then adding the necessary
24626 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24627
24628
24629
24630 @c *******************************
24631 @node Conditional Compilation
24632 @appendix Conditional Compilation
24633 @c *******************************
24634 @cindex Conditional compilation
24635
24636 @noindent
24637 It is often necessary to arrange for a single source program
24638 to serve multiple purposes, where it is compiled in different
24639 ways to achieve these different goals. Some examples of the
24640 need for this feature are
24641
24642 @itemize @bullet
24643 @item  Adapting a program to a different hardware environment
24644 @item  Adapting a program to a different target architecture
24645 @item  Turning debugging features on and off
24646 @item  Arranging for a program to compile with different compilers
24647 @end itemize
24648
24649 @noindent
24650 In C, or C++, the typical approach would be to use the preprocessor
24651 that is defined as part of the language. The Ada language does not
24652 contain such a feature. This is not an oversight, but rather a very
24653 deliberate design decision, based on the experience that overuse of
24654 the preprocessing features in C and C++ can result in programs that
24655 are extremely difficult to maintain. For example, if we have ten
24656 switches that can be on or off, this means that there are a thousand
24657 separate programs, any one of which might not even be syntactically
24658 correct, and even if syntactically correct, the resulting program
24659 might not work correctly. Testing all combinations can quickly become
24660 impossible.
24661
24662 Nevertheless, the need to tailor programs certainly exists, and in
24663 this Appendix we will discuss how this can
24664 be achieved using Ada in general, and GNAT in particular.
24665
24666 @menu
24667 * Use of Boolean Constants::
24668 * Debugging - A Special Case::
24669 * Conditionalizing Declarations::
24670 * Use of Alternative Implementations::
24671 * Preprocessing::
24672 @end menu
24673
24674 @node Use of Boolean Constants
24675 @section Use of Boolean Constants
24676
24677 @noindent
24678 In the case where the difference is simply which code
24679 sequence is executed, the cleanest solution is to use Boolean
24680 constants to control which code is executed.
24681
24682 @smallexample @c ada
24683 @group
24684 FP_Initialize_Required : constant Boolean := True;
24685 @dots{}
24686 if FP_Initialize_Required then
24687 @dots{}
24688 end if;
24689 @end group
24690 @end smallexample
24691
24692 @noindent
24693 Not only will the code inside the @code{if} statement not be executed if
24694 the constant Boolean is @code{False}, but it will also be completely
24695 deleted from the program.
24696 However, the code is only deleted after the @code{if} statement
24697 has been checked for syntactic and semantic correctness.
24698 (In contrast, with preprocessors the code is deleted before the
24699 compiler ever gets to see it, so it is not checked until the switch
24700 is turned on.)
24701 @cindex Preprocessors (contrasted with conditional compilation)
24702
24703 Typically the Boolean constants will be in a separate package,
24704 something like:
24705
24706 @smallexample @c ada
24707 @group
24708 package Config is
24709    FP_Initialize_Required : constant Boolean := True;
24710    Reset_Available        : constant Boolean := False;
24711    @dots{}
24712 end Config;
24713 @end group
24714 @end smallexample
24715
24716 @noindent
24717 The @code{Config} package exists in multiple forms for the various targets,
24718 with an appropriate script selecting the version of @code{Config} needed.
24719 Then any other unit requiring conditional compilation can do a @code{with}
24720 of @code{Config} to make the constants visible.
24721
24722
24723 @node Debugging - A Special Case
24724 @section Debugging - A Special Case
24725
24726 @noindent
24727 A common use of conditional code is to execute statements (for example
24728 dynamic checks, or output of intermediate results) under control of a
24729 debug switch, so that the debugging behavior can be turned on and off.
24730 This can be done using a Boolean constant to control whether the code
24731 is active:
24732
24733 @smallexample @c ada
24734 @group
24735 if Debugging then
24736    Put_Line ("got to the first stage!");
24737 end if;
24738 @end group
24739 @end smallexample
24740
24741 @noindent
24742 or
24743
24744 @smallexample @c ada
24745 @group
24746 if Debugging and then Temperature > 999.0 then
24747    raise Temperature_Crazy;
24748 end if;
24749 @end group
24750 @end smallexample
24751
24752 @noindent
24753 Since this is a common case, there are special features to deal with
24754 this in a convenient manner. For the case of tests, Ada 2005 has added
24755 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24756 @cindex pragma @code{Assert}
24757 on the @code{Assert} pragma that has always been available in GNAT, so this
24758 feature may be used with GNAT even if you are not using Ada 2005 features.
24759 The use of pragma @code{Assert} is described in
24760 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24761 example, the last test could be written:
24762
24763 @smallexample @c ada
24764 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24765 @end smallexample
24766
24767 @noindent
24768 or simply
24769
24770 @smallexample @c ada
24771 pragma Assert (Temperature <= 999.0);
24772 @end smallexample
24773
24774 @noindent
24775 In both cases, if assertions are active and the temperature is excessive,
24776 the exception @code{Assert_Failure} will be raised, with the given string in
24777 the first case or a string indicating the location of the pragma in the second
24778 case used as the exception message.
24779
24780 You can turn assertions on and off by using the @code{Assertion_Policy}
24781 pragma.
24782 @cindex pragma @code{Assertion_Policy}
24783 This is an Ada 2005 pragma which is implemented in all modes by
24784 GNAT, but only in the latest versions of GNAT which include Ada 2005
24785 capability. Alternatively, you can use the @option{-gnata} switch
24786 @cindex @option{-gnata} switch
24787 to enable assertions from the command line (this is recognized by all versions
24788 of GNAT).
24789
24790 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24791 @code{Debug} can be used:
24792 @cindex pragma @code{Debug}
24793
24794 @smallexample @c ada
24795 pragma Debug (Put_Line ("got to the first stage!"));
24796 @end smallexample
24797
24798 @noindent
24799 If debug pragmas are enabled, the argument, which must be of the form of
24800 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24801 Only one call can be present, but of course a special debugging procedure
24802 containing any code you like can be included in the program and then
24803 called in a pragma @code{Debug} argument as needed.
24804
24805 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24806 construct is that pragma @code{Debug} can appear in declarative contexts,
24807 such as at the very beginning of a procedure, before local declarations have
24808 been elaborated.
24809
24810 Debug pragmas are enabled using either the @option{-gnata} switch that also
24811 controls assertions, or with a separate Debug_Policy pragma.
24812 @cindex pragma @code{Debug_Policy}
24813 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24814 in Ada 95 and Ada 83 programs as well), and is analogous to
24815 pragma @code{Assertion_Policy} to control assertions.
24816
24817 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24818 and thus they can appear in @file{gnat.adc} if you are not using a
24819 project file, or in the file designated to contain configuration pragmas
24820 in a project file.
24821 They then apply to all subsequent compilations. In practice the use of
24822 the @option{-gnata} switch is often the most convenient method of controlling
24823 the status of these pragmas.
24824
24825 Note that a pragma is not a statement, so in contexts where a statement
24826 sequence is required, you can't just write a pragma on its own. You have
24827 to add a @code{null} statement.
24828
24829 @smallexample @c ada
24830 @group
24831 if @dots{} then
24832    @dots{} -- some statements
24833 else
24834    pragma Assert (Num_Cases < 10);
24835    null;
24836 end if;
24837 @end group
24838 @end smallexample
24839
24840
24841 @node Conditionalizing Declarations
24842 @section Conditionalizing Declarations
24843
24844 @noindent
24845 In some cases, it may be necessary to conditionalize declarations to meet
24846 different requirements. For example we might want a bit string whose length
24847 is set to meet some hardware message requirement.
24848
24849 In some cases, it may be possible to do this using declare blocks controlled
24850 by conditional constants:
24851
24852 @smallexample @c ada
24853 @group
24854 if Small_Machine then
24855    declare
24856       X : Bit_String (1 .. 10);
24857    begin
24858       @dots{}
24859    end;
24860 else
24861    declare
24862       X : Large_Bit_String (1 .. 1000);
24863    begin
24864       @dots{}
24865    end;
24866 end if;
24867 @end group
24868 @end smallexample
24869
24870 @noindent
24871 Note that in this approach, both declarations are analyzed by the
24872 compiler so this can only be used where both declarations are legal,
24873 even though one of them will not be used.
24874
24875 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
24876 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24877 that are parameterized by these constants. For example
24878
24879 @smallexample @c ada
24880 @group
24881 for Rec use
24882   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24883 end record;
24884 @end group
24885 @end smallexample
24886
24887 @noindent
24888 If @code{Bits_Per_Word} is set to 32, this generates either
24889
24890 @smallexample @c ada
24891 @group
24892 for Rec use
24893   Field1 at 0 range 0 .. 32;
24894 end record;
24895 @end group
24896 @end smallexample
24897
24898 @noindent
24899 for the big endian case, or
24900
24901 @smallexample @c ada
24902 @group
24903 for Rec use record
24904   Field1 at 0 range 10 .. 32;
24905 end record;
24906 @end group
24907 @end smallexample
24908
24909 @noindent
24910 for the little endian case. Since a powerful subset of Ada expression
24911 notation is usable for creating static constants, clever use of this
24912 feature can often solve quite difficult problems in conditionalizing
24913 compilation (note incidentally that in Ada 95, the little endian
24914 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24915 need to define this one yourself).
24916
24917
24918 @node Use of Alternative Implementations
24919 @section Use of Alternative Implementations
24920
24921 @noindent
24922 In some cases, none of the approaches described above are adequate. This
24923 can occur for example if the set of declarations required is radically
24924 different for two different configurations.
24925
24926 In this situation, the official Ada way of dealing with conditionalizing
24927 such code is to write separate units for the different cases. As long as
24928 this does not result in excessive duplication of code, this can be done
24929 without creating maintenance problems. The approach is to share common
24930 code as far as possible, and then isolate the code and declarations
24931 that are different. Subunits are often a convenient method for breaking
24932 out a piece of a unit that is to be conditionalized, with separate files
24933 for different versions of the subunit for different targets, where the
24934 build script selects the right one to give to the compiler.
24935 @cindex Subunits (and conditional compilation)
24936
24937 As an example, consider a situation where a new feature in Ada 2005
24938 allows something to be done in a really nice way. But your code must be able
24939 to compile with an Ada 95 compiler. Conceptually you want to say:
24940
24941 @smallexample @c ada
24942 @group
24943 if Ada_2005 then
24944    @dots{} neat Ada 2005 code
24945 else
24946    @dots{} not quite as neat Ada 95 code
24947 end if;
24948 @end group
24949 @end smallexample
24950
24951 @noindent
24952 where @code{Ada_2005} is a Boolean constant.
24953
24954 But this won't work when @code{Ada_2005} is set to @code{False},
24955 since the @code{then} clause will be illegal for an Ada 95 compiler.
24956 (Recall that although such unreachable code would eventually be deleted
24957 by the compiler, it still needs to be legal.  If it uses features
24958 introduced in Ada 2005, it will be illegal in Ada 95.)
24959
24960 So instead we write
24961
24962 @smallexample @c ada
24963 procedure Insert is separate;
24964 @end smallexample
24965
24966 @noindent
24967 Then we have two files for the subunit @code{Insert}, with the two sets of
24968 code.
24969 If the package containing this is called @code{File_Queries}, then we might
24970 have two files
24971
24972 @itemize @bullet
24973 @item    @file{file_queries-insert-2005.adb}
24974 @item    @file{file_queries-insert-95.adb}
24975 @end itemize
24976
24977 @noindent
24978 and the build script renames the appropriate file to
24979
24980 @smallexample
24981 file_queries-insert.adb
24982 @end smallexample
24983
24984 @noindent
24985 and then carries out the compilation.
24986
24987 This can also be done with project files' naming schemes. For example:
24988
24989 @smallexample @c project
24990 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24991 @end smallexample
24992
24993 @noindent
24994 Note also that with project files it is desirable to use a different extension
24995 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24996 conflict may arise through another commonly used feature: to declare as part
24997 of the project a set of directories containing all the sources obeying the
24998 default naming scheme.
24999
25000 The use of alternative units is certainly feasible in all situations,
25001 and for example the Ada part of the GNAT run-time is conditionalized
25002 based on the target architecture using this approach. As a specific example,
25003 consider the implementation of the AST feature in VMS. There is one
25004 spec:
25005
25006 @smallexample
25007 s-asthan.ads
25008 @end smallexample
25009
25010 @noindent
25011 which is the same for all architectures, and three bodies:
25012
25013 @table @file
25014 @item    s-asthan.adb
25015 used for all non-VMS operating systems
25016 @item    s-asthan-vms-alpha.adb
25017 used for VMS on the Alpha
25018 @item    s-asthan-vms-ia64.adb
25019 used for VMS on the ia64
25020 @end table
25021
25022 @noindent
25023 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25024 this operating system feature is not available, and the two remaining
25025 versions interface with the corresponding versions of VMS to provide
25026 VMS-compatible AST handling. The GNAT build script knows the architecture
25027 and operating system, and automatically selects the right version,
25028 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25029
25030 Another style for arranging alternative implementations is through Ada's
25031 access-to-subprogram facility.
25032 In case some functionality is to be conditionally included,
25033 you can declare an access-to-procedure variable @code{Ref} that is initialized
25034 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25035 when appropriate.
25036 In some library package, set @code{Ref} to @code{Proc'Access} for some
25037 procedure @code{Proc} that performs the relevant processing.
25038 The initialization only occurs if the library package is included in the
25039 program.
25040 The same idea can also be implemented using tagged types and dispatching
25041 calls.
25042
25043
25044 @node Preprocessing
25045 @section Preprocessing
25046 @cindex Preprocessing
25047
25048 @noindent
25049 Although it is quite possible to conditionalize code without the use of
25050 C-style preprocessing, as described earlier in this section, it is
25051 nevertheless convenient in some cases to use the C approach. Moreover,
25052 older Ada compilers have often provided some preprocessing capability,
25053 so legacy code may depend on this approach, even though it is not
25054 standard.
25055
25056 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25057 extent on the various preprocessors that have been used
25058 with legacy code on other compilers, to enable easier transition).
25059
25060 The preprocessor may be used in two separate modes. It can be used quite
25061 separately from the compiler, to generate a separate output source file
25062 that is then fed to the compiler as a separate step. This is the
25063 @code{gnatprep} utility, whose use is fully described in
25064 @ref{Preprocessing Using gnatprep}.
25065 @cindex @code{gnatprep}
25066
25067 The preprocessing language allows such constructs as
25068
25069 @smallexample
25070 @group
25071 #if DEBUG or PRIORITY > 4 then
25072    bunch of declarations
25073 #else
25074    completely different bunch of declarations
25075 #end if;
25076 @end group
25077 @end smallexample
25078
25079 @noindent
25080 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25081 defined either on the command line or in a separate file.
25082
25083 The other way of running the preprocessor is even closer to the C style and
25084 often more convenient. In this approach the preprocessing is integrated into
25085 the compilation process. The compiler is fed the preprocessor input which
25086 includes @code{#if} lines etc, and then the compiler carries out the
25087 preprocessing internally and processes the resulting output.
25088 For more details on this approach, see @ref{Integrated Preprocessing}.
25089
25090
25091 @c *******************************
25092 @node Inline Assembler
25093 @appendix Inline Assembler
25094 @c *******************************
25095
25096 @noindent
25097 If you need to write low-level software that interacts directly
25098 with the hardware, Ada provides two ways to incorporate assembly
25099 language code into your program.  First, you can import and invoke
25100 external routines written in assembly language, an Ada feature fully
25101 supported by GNAT@.  However, for small sections of code it may be simpler
25102 or more efficient to include assembly language statements directly
25103 in your Ada source program, using the facilities of the implementation-defined
25104 package @code{System.Machine_Code}, which incorporates the gcc
25105 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25106 including the following:
25107
25108 @itemize @bullet
25109 @item No need to use non-Ada tools
25110 @item Consistent interface over different targets
25111 @item Automatic usage of the proper calling conventions
25112 @item Access to Ada constants and variables
25113 @item Definition of intrinsic routines
25114 @item Possibility of inlining a subprogram comprising assembler code
25115 @item Code optimizer can take Inline Assembler code into account
25116 @end itemize
25117
25118 This chapter presents a series of examples to show you how to use
25119 the Inline Assembler.  Although it focuses on the Intel x86,
25120 the general approach applies also to other processors.
25121 It is assumed that you are familiar with Ada
25122 and with assembly language programming.
25123
25124 @menu
25125 * Basic Assembler Syntax::
25126 * A Simple Example of Inline Assembler::
25127 * Output Variables in Inline Assembler::
25128 * Input Variables in Inline Assembler::
25129 * Inlining Inline Assembler Code::
25130 * Other Asm Functionality::
25131 @end menu
25132
25133 @c ---------------------------------------------------------------------------
25134 @node Basic Assembler Syntax
25135 @section Basic Assembler Syntax
25136
25137 @noindent
25138 The assembler used by GNAT and gcc is based not on the Intel assembly
25139 language, but rather on a language that descends from the AT&T Unix
25140 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25141 The following table summarizes the main features of @emph{as} syntax
25142 and points out the differences from the Intel conventions.
25143 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25144 pre-processor) documentation for further information.
25145
25146 @table @asis
25147 @item Register names
25148 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25149 @*
25150 Intel: No extra punctuation; for example @code{eax}
25151
25152 @item Immediate operand
25153 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25154 @*
25155 Intel: No extra punctuation; for example @code{4}
25156
25157 @item Address
25158 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25159 @*
25160 Intel: No extra punctuation; for example @code{loc}
25161
25162 @item Memory contents
25163 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25164 @*
25165 Intel: Square brackets; for example @code{[loc]}
25166
25167 @item Register contents
25168 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25169 @*
25170 Intel: Square brackets; for example @code{[eax]}
25171
25172 @item Hexadecimal numbers
25173 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25174 @*
25175 Intel: Trailing ``h''; for example @code{A0h}
25176
25177 @item Operand size
25178 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25179 a 16-bit word
25180 @*
25181 Intel: Implicit, deduced by assembler; for example @code{mov}
25182
25183 @item Instruction repetition
25184 gcc / @emph{as}: Split into two lines; for example
25185 @*
25186 @code{rep}
25187 @*
25188 @code{stosl}
25189 @*
25190 Intel: Keep on one line; for example @code{rep stosl}
25191
25192 @item Order of operands
25193 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25194 @*
25195 Intel: Destination first; for example @code{mov eax, 4}
25196 @end table
25197
25198 @c ---------------------------------------------------------------------------
25199 @node A Simple Example of Inline Assembler
25200 @section A Simple Example of Inline Assembler
25201
25202 @noindent
25203 The following example will generate a single assembly language statement,
25204 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25205 the example will be useful in illustrating the basics of
25206 the Inline Assembler facility.
25207
25208 @smallexample @c ada
25209 @group
25210 with System.Machine_Code; use System.Machine_Code;
25211 procedure Nothing is
25212 begin
25213    Asm ("nop");
25214 end Nothing;
25215 @end group
25216 @end smallexample
25217
25218 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25219 here it takes one parameter, a @emph{template string} that must be a static
25220 expression and that will form the generated instruction.
25221 @code{Asm} may be regarded as a compile-time procedure that parses
25222 the template string and additional parameters (none here),
25223 from which it generates a sequence of assembly language instructions.
25224
25225 The examples in this chapter will illustrate several of the forms
25226 for invoking @code{Asm}; a complete specification of the syntax
25227 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25228 Manual}.
25229
25230 Under the standard GNAT conventions, the @code{Nothing} procedure
25231 should be in a file named @file{nothing.adb}.
25232 You can build the executable in the usual way:
25233 @smallexample
25234 gnatmake nothing
25235 @end smallexample
25236 However, the interesting aspect of this example is not its run-time behavior
25237 but rather the generated assembly code.
25238 To see this output, invoke the compiler as follows:
25239 @smallexample
25240    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25241 @end smallexample
25242 where the options are:
25243
25244 @table @code
25245 @item -c
25246 compile only (no bind or link)
25247 @item -S
25248 generate assembler listing
25249 @item -fomit-frame-pointer
25250 do not set up separate stack frames
25251 @item -gnatp
25252 do not add runtime checks
25253 @end table
25254
25255 This gives a human-readable assembler version of the code. The resulting
25256 file will have the same name as the Ada source file, but with a @code{.s}
25257 extension. In our example, the file @file{nothing.s} has the following
25258 contents:
25259
25260 @smallexample
25261 @group
25262 .file "nothing.adb"
25263 gcc2_compiled.:
25264 ___gnu_compiled_ada:
25265 .text
25266    .align 4
25267 .globl __ada_nothing
25268 __ada_nothing:
25269 #APP
25270    nop
25271 #NO_APP
25272    jmp L1
25273    .align 2,0x90
25274 L1:
25275    ret
25276 @end group
25277 @end smallexample
25278
25279 The assembly code you included is clearly indicated by
25280 the compiler, between the @code{#APP} and @code{#NO_APP}
25281 delimiters. The character before the 'APP' and 'NOAPP'
25282 can differ on different targets. For example, GNU/Linux uses '#APP' while
25283 on NT you will see '/APP'.
25284
25285 If you make a mistake in your assembler code (such as using the
25286 wrong size modifier, or using a wrong operand for the instruction) GNAT
25287 will report this error in a temporary file, which will be deleted when
25288 the compilation is finished.  Generating an assembler file will help
25289 in such cases, since you can assemble this file separately using the
25290 @emph{as} assembler that comes with gcc.
25291
25292 Assembling the file using the command
25293
25294 @smallexample
25295 as @file{nothing.s}
25296 @end smallexample
25297 @noindent
25298 will give you error messages whose lines correspond to the assembler
25299 input file, so you can easily find and correct any mistakes you made.
25300 If there are no errors, @emph{as} will generate an object file
25301 @file{nothing.out}.
25302
25303 @c ---------------------------------------------------------------------------
25304 @node Output Variables in Inline Assembler
25305 @section Output Variables in Inline Assembler
25306
25307 @noindent
25308 The examples in this section, showing how to access the processor flags,
25309 illustrate how to specify the destination operands for assembly language
25310 statements.
25311
25312 @smallexample @c ada
25313 @group
25314 with Interfaces; use Interfaces;
25315 with Ada.Text_IO; use Ada.Text_IO;
25316 with System.Machine_Code; use System.Machine_Code;
25317 procedure Get_Flags is
25318    Flags : Unsigned_32;
25319    use ASCII;
25320 begin
25321    Asm ("pushfl"          & LF & HT & -- push flags on stack
25322         "popl %%eax"      & LF & HT & -- load eax with flags
25323         "movl %%eax, %0",             -- store flags in variable
25324         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25325    Put_Line ("Flags register:" & Flags'Img);
25326 end Get_Flags;
25327 @end group
25328 @end smallexample
25329
25330 In order to have a nicely aligned assembly listing, we have separated
25331 multiple assembler statements in the Asm template string with linefeed
25332 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25333 The resulting section of the assembly output file is:
25334
25335 @smallexample
25336 @group
25337 #APP
25338    pushfl
25339    popl %eax
25340    movl %eax, -40(%ebp)
25341 #NO_APP
25342 @end group
25343 @end smallexample
25344
25345 It would have been legal to write the Asm invocation as:
25346
25347 @smallexample
25348 Asm ("pushfl popl %%eax movl %%eax, %0")
25349 @end smallexample
25350
25351 but in the generated assembler file, this would come out as:
25352
25353 @smallexample
25354 #APP
25355    pushfl popl %eax movl %eax, -40(%ebp)
25356 #NO_APP
25357 @end smallexample
25358
25359 which is not so convenient for the human reader.
25360
25361 We use Ada comments
25362 at the end of each line to explain what the assembler instructions
25363 actually do.  This is a useful convention.
25364
25365 When writing Inline Assembler instructions, you need to precede each register
25366 and variable name with a percent sign.  Since the assembler already requires
25367 a percent sign at the beginning of a register name, you need two consecutive
25368 percent signs for such names in the Asm template string, thus @code{%%eax}.
25369 In the generated assembly code, one of the percent signs will be stripped off.
25370
25371 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25372 variables: operands you later define using @code{Input} or @code{Output}
25373 parameters to @code{Asm}.
25374 An output variable is illustrated in
25375 the third statement in the Asm template string:
25376 @smallexample
25377 movl %%eax, %0
25378 @end smallexample
25379 The intent is to store the contents of the eax register in a variable that can
25380 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25381 necessarily work, since the compiler might optimize by using a register
25382 to hold Flags, and the expansion of the @code{movl} instruction would not be
25383 aware of this optimization.  The solution is not to store the result directly
25384 but rather to advise the compiler to choose the correct operand form;
25385 that is the purpose of the @code{%0} output variable.
25386
25387 Information about the output variable is supplied in the @code{Outputs}
25388 parameter to @code{Asm}:
25389 @smallexample
25390 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25391 @end smallexample
25392
25393 The output is defined by the @code{Asm_Output} attribute of the target type;
25394 the general format is
25395 @smallexample
25396 Type'Asm_Output (constraint_string, variable_name)
25397 @end smallexample
25398
25399 The constraint string directs the compiler how
25400 to store/access the associated variable.  In the example
25401 @smallexample
25402 Unsigned_32'Asm_Output ("=m", Flags);
25403 @end smallexample
25404 the @code{"m"} (memory) constraint tells the compiler that the variable
25405 @code{Flags} should be stored in a memory variable, thus preventing
25406 the optimizer from keeping it in a register.  In contrast,
25407 @smallexample
25408 Unsigned_32'Asm_Output ("=r", Flags);
25409 @end smallexample
25410 uses the @code{"r"} (register) constraint, telling the compiler to
25411 store the variable in a register.
25412
25413 If the constraint is preceded by the equal character (@strong{=}), it tells
25414 the compiler that the variable will be used to store data into it.
25415
25416 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25417 allowing the optimizer to choose whatever it deems best.
25418
25419 There are a fairly large number of constraints, but the ones that are
25420 most useful (for the Intel x86 processor) are the following:
25421
25422 @table @code
25423 @item =
25424 output constraint
25425 @item g
25426 global (i.e.@: can be stored anywhere)
25427 @item m
25428 in memory
25429 @item I
25430 a constant
25431 @item a
25432 use eax
25433 @item b
25434 use ebx
25435 @item c
25436 use ecx
25437 @item d
25438 use edx
25439 @item S
25440 use esi
25441 @item D
25442 use edi
25443 @item r
25444 use one of eax, ebx, ecx or edx
25445 @item q
25446 use one of eax, ebx, ecx, edx, esi or edi
25447 @end table
25448
25449 The full set of constraints is described in the gcc and @emph{as}
25450 documentation; note that it is possible to combine certain constraints
25451 in one constraint string.
25452
25453 You specify the association of an output variable with an assembler operand
25454 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25455 integer.  Thus in
25456 @smallexample @c ada
25457 @group
25458 Asm ("pushfl"          & LF & HT & -- push flags on stack
25459      "popl %%eax"      & LF & HT & -- load eax with flags
25460      "movl %%eax, %0",             -- store flags in variable
25461      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25462 @end group
25463 @end smallexample
25464 @noindent
25465 @code{%0} will be replaced in the expanded code by the appropriate operand,
25466 whatever
25467 the compiler decided for the @code{Flags} variable.
25468
25469 In general, you may have any number of output variables:
25470 @itemize @bullet
25471 @item
25472 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25473 @item
25474 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25475 of @code{Asm_Output} attributes
25476 @end itemize
25477
25478 For example:
25479 @smallexample @c ada
25480 @group
25481 Asm ("movl %%eax, %0" & LF & HT &
25482      "movl %%ebx, %1" & LF & HT &
25483      "movl %%ecx, %2",
25484      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25485                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25486                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25487 @end group
25488 @end smallexample
25489 @noindent
25490 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25491 in the Ada program.
25492
25493 As a variation on the @code{Get_Flags} example, we can use the constraints
25494 string to direct the compiler to store the eax register into the @code{Flags}
25495 variable, instead of including the store instruction explicitly in the
25496 @code{Asm} template string:
25497
25498 @smallexample @c ada
25499 @group
25500 with Interfaces; use Interfaces;
25501 with Ada.Text_IO; use Ada.Text_IO;
25502 with System.Machine_Code; use System.Machine_Code;
25503 procedure Get_Flags_2 is
25504    Flags : Unsigned_32;
25505    use ASCII;
25506 begin
25507    Asm ("pushfl"      & LF & HT & -- push flags on stack
25508         "popl %%eax",             -- save flags in eax
25509         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25510    Put_Line ("Flags register:" & Flags'Img);
25511 end Get_Flags_2;
25512 @end group
25513 @end smallexample
25514
25515 @noindent
25516 The @code{"a"} constraint tells the compiler that the @code{Flags}
25517 variable will come from the eax register. Here is the resulting code:
25518
25519 @smallexample
25520 @group
25521 #APP
25522    pushfl
25523    popl %eax
25524 #NO_APP
25525    movl %eax,-40(%ebp)
25526 @end group
25527 @end smallexample
25528
25529 @noindent
25530 The compiler generated the store of eax into Flags after
25531 expanding the assembler code.
25532
25533 Actually, there was no need to pop the flags into the eax register;
25534 more simply, we could just pop the flags directly into the program variable:
25535
25536 @smallexample @c ada
25537 @group
25538 with Interfaces; use Interfaces;
25539 with Ada.Text_IO; use Ada.Text_IO;
25540 with System.Machine_Code; use System.Machine_Code;
25541 procedure Get_Flags_3 is
25542    Flags : Unsigned_32;
25543    use ASCII;
25544 begin
25545    Asm ("pushfl"  & LF & HT & -- push flags on stack
25546         "pop %0",             -- save flags in Flags
25547         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25548    Put_Line ("Flags register:" & Flags'Img);
25549 end Get_Flags_3;
25550 @end group
25551 @end smallexample
25552
25553 @c ---------------------------------------------------------------------------
25554 @node Input Variables in Inline Assembler
25555 @section Input Variables in Inline Assembler
25556
25557 @noindent
25558 The example in this section illustrates how to specify the source operands
25559 for assembly language statements.
25560 The program simply increments its input value by 1:
25561
25562 @smallexample @c ada
25563 @group
25564 with Interfaces; use Interfaces;
25565 with Ada.Text_IO; use Ada.Text_IO;
25566 with System.Machine_Code; use System.Machine_Code;
25567 procedure Increment is
25568
25569    function Incr (Value : Unsigned_32) return Unsigned_32 is
25570       Result : Unsigned_32;
25571    begin
25572       Asm ("incl %0",
25573            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25574            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25575       return Result;
25576    end Incr;
25577
25578    Value : Unsigned_32;
25579
25580 begin
25581    Value := 5;
25582    Put_Line ("Value before is" & Value'Img);
25583    Value := Incr (Value);
25584    Put_Line ("Value after is" & Value'Img);
25585 end Increment;
25586 @end group
25587 @end smallexample
25588
25589 The @code{Outputs} parameter to @code{Asm} specifies
25590 that the result will be in the eax register and that it is to be stored
25591 in the @code{Result} variable.
25592
25593 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25594 but with an @code{Asm_Input} attribute.
25595 The @code{"="} constraint, indicating an output value, is not present.
25596
25597 You can have multiple input variables, in the same way that you can have more
25598 than one output variable.
25599
25600 The parameter count (%0, %1) etc, now starts at the first input
25601 statement, and continues with the output statements.
25602 When both parameters use the same variable, the
25603 compiler will treat them as the same %n operand, which is the case here.
25604
25605 Just as the @code{Outputs} parameter causes the register to be stored into the
25606 target variable after execution of the assembler statements, so does the
25607 @code{Inputs} parameter cause its variable to be loaded into the register
25608 before execution of the assembler statements.
25609
25610 Thus the effect of the @code{Asm} invocation is:
25611 @enumerate
25612 @item load the 32-bit value of @code{Value} into eax
25613 @item execute the @code{incl %eax} instruction
25614 @item store the contents of eax into the @code{Result} variable
25615 @end enumerate
25616
25617 The resulting assembler file (with @option{-O2} optimization) contains:
25618 @smallexample
25619 @group
25620 _increment__incr.1:
25621    subl $4,%esp
25622    movl 8(%esp),%eax
25623 #APP
25624    incl %eax
25625 #NO_APP
25626    movl %eax,%edx
25627    movl %ecx,(%esp)
25628    addl $4,%esp
25629    ret
25630 @end group
25631 @end smallexample
25632
25633 @c ---------------------------------------------------------------------------
25634 @node Inlining Inline Assembler Code
25635 @section Inlining Inline Assembler Code
25636
25637 @noindent
25638 For a short subprogram such as the @code{Incr} function in the previous
25639 section, the overhead of the call and return (creating / deleting the stack
25640 frame) can be significant, compared to the amount of code in the subprogram
25641 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25642 which directs the compiler to expand invocations of the subprogram at the
25643 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25644 Here is the resulting program:
25645
25646 @smallexample @c ada
25647 @group
25648 with Interfaces; use Interfaces;
25649 with Ada.Text_IO; use Ada.Text_IO;
25650 with System.Machine_Code; use System.Machine_Code;
25651 procedure Increment_2 is
25652
25653    function Incr (Value : Unsigned_32) return Unsigned_32 is
25654       Result : Unsigned_32;
25655    begin
25656       Asm ("incl %0",
25657            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25658            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25659       return Result;
25660    end Incr;
25661    pragma Inline (Increment);
25662
25663    Value : Unsigned_32;
25664
25665 begin
25666    Value := 5;
25667    Put_Line ("Value before is" & Value'Img);
25668    Value := Increment (Value);
25669    Put_Line ("Value after is" & Value'Img);
25670 end Increment_2;
25671 @end group
25672 @end smallexample
25673
25674 Compile the program with both optimization (@option{-O2}) and inlining
25675 (@option{-gnatn}) enabled.
25676
25677 The @code{Incr} function is still compiled as usual, but at the
25678 point in @code{Increment} where our function used to be called:
25679
25680 @smallexample
25681 @group
25682 pushl %edi
25683 call _increment__incr.1
25684 @end group
25685 @end smallexample
25686
25687 @noindent
25688 the code for the function body directly appears:
25689
25690 @smallexample
25691 @group
25692 movl %esi,%eax
25693 #APP
25694    incl %eax
25695 #NO_APP
25696    movl %eax,%edx
25697 @end group
25698 @end smallexample
25699
25700 @noindent
25701 thus saving the overhead of stack frame setup and an out-of-line call.
25702
25703 @c ---------------------------------------------------------------------------
25704 @node Other Asm Functionality
25705 @section Other @code{Asm} Functionality
25706
25707 @noindent
25708 This section describes two important parameters to the @code{Asm}
25709 procedure: @code{Clobber}, which identifies register usage;
25710 and @code{Volatile}, which inhibits unwanted optimizations.
25711
25712 @menu
25713 * The Clobber Parameter::
25714 * The Volatile Parameter::
25715 @end menu
25716
25717 @c ---------------------------------------------------------------------------
25718 @node The Clobber Parameter
25719 @subsection The @code{Clobber} Parameter
25720
25721 @noindent
25722 One of the dangers of intermixing assembly language and a compiled language
25723 such as Ada is that the compiler needs to be aware of which registers are
25724 being used by the assembly code.  In some cases, such as the earlier examples,
25725 the constraint string is sufficient to indicate register usage (e.g.,
25726 @code{"a"} for
25727 the eax register).  But more generally, the compiler needs an explicit
25728 identification of the registers that are used by the Inline Assembly
25729 statements.
25730
25731 Using a register that the compiler doesn't know about
25732 could be a side effect of an instruction (like @code{mull}
25733 storing its result in both eax and edx).
25734 It can also arise from explicit register usage in your
25735 assembly code; for example:
25736 @smallexample
25737 @group
25738 Asm ("movl %0, %%ebx" & LF & HT &
25739      "movl %%ebx, %1",
25740      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25741      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25742 @end group
25743 @end smallexample
25744 @noindent
25745 where the compiler (since it does not analyze the @code{Asm} template string)
25746 does not know you are using the ebx register.
25747
25748 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25749 to identify the registers that will be used by your assembly code:
25750
25751 @smallexample
25752 @group
25753 Asm ("movl %0, %%ebx" & LF & HT &
25754      "movl %%ebx, %1",
25755      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25756      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25757      Clobber => "ebx");
25758 @end group
25759 @end smallexample
25760
25761 The Clobber parameter is a static string expression specifying the
25762 register(s) you are using.  Note that register names are @emph{not} prefixed
25763 by a percent sign. Also, if more than one register is used then their names
25764 are separated by commas; e.g., @code{"eax, ebx"}
25765
25766 The @code{Clobber} parameter has several additional uses:
25767 @enumerate
25768 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25769 @item Use ``register'' name @code{memory} if you changed a memory location
25770 @end enumerate
25771
25772 @c ---------------------------------------------------------------------------
25773 @node The Volatile Parameter
25774 @subsection The @code{Volatile} Parameter
25775 @cindex Volatile parameter
25776
25777 @noindent
25778 Compiler optimizations in the presence of Inline Assembler may sometimes have
25779 unwanted effects.  For example, when an @code{Asm} invocation with an input
25780 variable is inside a loop, the compiler might move the loading of the input
25781 variable outside the loop, regarding it as a one-time initialization.
25782
25783 If this effect is not desired, you can disable such optimizations by setting
25784 the @code{Volatile} parameter to @code{True}; for example:
25785
25786 @smallexample @c ada
25787 @group
25788 Asm ("movl %0, %%ebx" & LF & HT &
25789      "movl %%ebx, %1",
25790      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25791      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25792      Clobber  => "ebx",
25793      Volatile => True);
25794 @end group
25795 @end smallexample
25796
25797 By default, @code{Volatile} is set to @code{False} unless there is no
25798 @code{Outputs} parameter.
25799
25800 Although setting @code{Volatile} to @code{True} prevents unwanted
25801 optimizations, it will also disable other optimizations that might be
25802 important for efficiency. In general, you should set @code{Volatile}
25803 to @code{True} only if the compiler's optimizations have created
25804 problems.
25805 @c END OF INLINE ASSEMBLER CHAPTER
25806 @c ===============================
25807
25808 @c ***********************************
25809 @c * Compatibility and Porting Guide *
25810 @c ***********************************
25811 @node Compatibility and Porting Guide
25812 @appendix Compatibility and Porting Guide
25813
25814 @noindent
25815 This chapter describes the compatibility issues that may arise between
25816 GNAT and other Ada compilation systems (including those for Ada 83),
25817 and shows how GNAT can expedite porting
25818 applications developed in other Ada environments.
25819
25820 @menu
25821 * Compatibility with Ada 83::
25822 * Compatibility between Ada 95 and Ada 2005::
25823 * Implementation-dependent characteristics::
25824 * Compatibility with Other Ada Systems::
25825 * Representation Clauses::
25826 @ifclear vms
25827 @c Brief section is only in non-VMS version
25828 @c Full chapter is in VMS version
25829 * Compatibility with HP Ada 83::
25830 @end ifclear
25831 @ifset vms
25832 * Transitioning to 64-Bit GNAT for OpenVMS::
25833 @end ifset
25834 @end menu
25835
25836 @node Compatibility with Ada 83
25837 @section Compatibility with Ada 83
25838 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25839
25840 @noindent
25841 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25842 particular, the design intention was that the difficulties associated
25843 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25844 that occur when moving from one Ada 83 system to another.
25845
25846 However, there are a number of points at which there are minor
25847 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25848 full details of these issues,
25849 and should be consulted for a complete treatment.
25850 In practice the
25851 following subsections treat the most likely issues to be encountered.
25852
25853 @menu
25854 * Legal Ada 83 programs that are illegal in Ada 95::
25855 * More deterministic semantics::
25856 * Changed semantics::
25857 * Other language compatibility issues::
25858 @end menu
25859
25860 @node Legal Ada 83 programs that are illegal in Ada 95
25861 @subsection Legal Ada 83 programs that are illegal in Ada 95
25862
25863 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25864 Ada 95 and thus also in Ada 2005:
25865
25866 @table @emph
25867 @item Character literals
25868 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25869 @code{Wide_Character} as a new predefined character type, some uses of
25870 character literals that were legal in Ada 83 are illegal in Ada 95.
25871 For example:
25872 @smallexample @c ada
25873    for Char in 'A' .. 'Z' loop @dots{} end loop;
25874 @end smallexample
25875
25876 @noindent
25877 The problem is that @code{'A'} and @code{'Z'} could be from either
25878 @code{Character} or @code{Wide_Character}.  The simplest correction
25879 is to make the type explicit; e.g.:
25880 @smallexample @c ada
25881    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25882 @end smallexample
25883
25884 @item New reserved words
25885 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25886 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25887 Existing Ada 83 code using any of these identifiers must be edited to
25888 use some alternative name.
25889
25890 @item Freezing rules
25891 The rules in Ada 95 are slightly different with regard to the point at
25892 which entities are frozen, and representation pragmas and clauses are
25893 not permitted past the freeze point.  This shows up most typically in
25894 the form of an error message complaining that a representation item
25895 appears too late, and the appropriate corrective action is to move
25896 the item nearer to the declaration of the entity to which it refers.
25897
25898 A particular case is that representation pragmas
25899 @ifset vms
25900 (including the
25901 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25902 @end ifset
25903 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25904 declaration must be introduced to which the pragma can be applied.
25905
25906 @item Optional bodies for library packages
25907 In Ada 83, a package that did not require a package body was nevertheless
25908 allowed to have one.  This lead to certain surprises in compiling large
25909 systems (situations in which the body could be unexpectedly ignored by the
25910 binder).  In Ada 95, if a package does not require a body then it is not
25911 permitted to have a body.  To fix this problem, simply remove a redundant
25912 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25913 into the spec that makes the body required.  One approach is to add a private
25914 part to the package declaration (if necessary), and define a parameterless
25915 procedure called @code{Requires_Body}, which must then be given a dummy
25916 procedure body in the package body, which then becomes required.
25917 Another approach (assuming that this does not introduce elaboration
25918 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25919 since one effect of this pragma is to require the presence of a package body.
25920
25921 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25922 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25923 @code{Constraint_Error}.
25924 This means that it is illegal to have separate exception handlers for
25925 the two exceptions.  The fix is simply to remove the handler for the
25926 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25927 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25928
25929 @item Indefinite subtypes in generics
25930 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25931 as the actual for a generic formal private type, but then the instantiation
25932 would be illegal if there were any instances of declarations of variables
25933 of this type in the generic body.  In Ada 95, to avoid this clear violation
25934 of the methodological principle known as the ``contract model'',
25935 the generic declaration explicitly indicates whether
25936 or not such instantiations are permitted.  If a generic formal parameter
25937 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25938 type name, then it can be instantiated with indefinite types, but no
25939 stand-alone variables can be declared of this type.  Any attempt to declare
25940 such a variable will result in an illegality at the time the generic is
25941 declared.  If the @code{(<>)} notation is not used, then it is illegal
25942 to instantiate the generic with an indefinite type.
25943 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25944 It will show up as a compile time error, and
25945 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25946 @end table
25947
25948 @node More deterministic semantics
25949 @subsection More deterministic semantics
25950
25951 @table @emph
25952 @item Conversions
25953 Conversions from real types to integer types round away from 0.  In Ada 83
25954 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25955 implementation freedom was intended to support unbiased rounding in
25956 statistical applications, but in practice it interfered with portability.
25957 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25958 is required.  Numeric code may be affected by this change in semantics.
25959 Note, though, that this issue is no worse than already existed in Ada 83
25960 when porting code from one vendor to another.
25961
25962 @item Tasking
25963 The Real-Time Annex introduces a set of policies that define the behavior of
25964 features that were implementation dependent in Ada 83, such as the order in
25965 which open select branches are executed.
25966 @end table
25967
25968 @node Changed semantics
25969 @subsection Changed semantics
25970
25971 @noindent
25972 The worst kind of incompatibility is one where a program that is legal in
25973 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25974 possible in Ada 83.  Fortunately this is extremely rare, but the one
25975 situation that you should be alert to is the change in the predefined type
25976 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25977
25978 @table @emph
25979 @item Range of type @code{Character}
25980 The range of @code{Standard.Character} is now the full 256 characters
25981 of Latin-1, whereas in most Ada 83 implementations it was restricted
25982 to 128 characters. Although some of the effects of
25983 this change will be manifest in compile-time rejection of legal
25984 Ada 83 programs it is possible for a working Ada 83 program to have
25985 a different effect in Ada 95, one that was not permitted in Ada 83.
25986 As an example, the expression
25987 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25988 delivers @code{255} as its value.
25989 In general, you should look at the logic of any
25990 character-processing Ada 83 program and see whether it needs to be adapted
25991 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25992 character handling package that may be relevant if code needs to be adapted
25993 to account for the additional Latin-1 elements.
25994 The desirable fix is to
25995 modify the program to accommodate the full character set, but in some cases
25996 it may be convenient to define a subtype or derived type of Character that
25997 covers only the restricted range.
25998 @cindex Latin-1
25999 @end table
26000
26001 @node Other language compatibility issues
26002 @subsection Other language compatibility issues
26003
26004 @table @emph
26005 @item @option{-gnat83} switch
26006 All implementations of GNAT provide a switch that causes GNAT to operate
26007 in Ada 83 mode.  In this mode, some but not all compatibility problems
26008 of the type described above are handled automatically.  For example, the
26009 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26010 as identifiers as in Ada 83.
26011 However,
26012 in practice, it is usually advisable to make the necessary modifications
26013 to the program to remove the need for using this switch.
26014 See @ref{Compiling Different Versions of Ada}.
26015
26016 @item Support for removed Ada 83 pragmas and attributes
26017 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26018 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26019 compilers are allowed, but not required, to implement these missing
26020 elements.  In contrast with some other compilers, GNAT implements all
26021 such pragmas and attributes, eliminating this compatibility concern.  These
26022 include @code{pragma Interface} and the floating point type attributes
26023 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26024 @end table
26025
26026
26027 @node Compatibility between Ada 95 and Ada 2005
26028 @section Compatibility between Ada 95 and Ada 2005
26029 @cindex Compatibility between Ada 95 and Ada 2005
26030
26031 @noindent
26032 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26033 a number of incompatibilities. Several are enumerated below;
26034 for a complete description please see the
26035 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26036 @cite{Rationale for Ada 2005}.
26037
26038 @table @emph
26039 @item New reserved words.
26040 The words @code{interface}, @code{overriding} and @code{synchronized} are
26041 reserved in Ada 2005.
26042 A pre-Ada 2005 program that uses any of these as an identifier will be
26043 illegal.
26044
26045 @item New declarations in predefined packages.
26046 A number of packages in the predefined environment contain new declarations:
26047 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26048 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26049 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26050 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26051 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26052 If an Ada 95 program does a @code{with} and @code{use} of any of these
26053 packages, the new declarations may cause name clashes.
26054
26055 @item Access parameters.
26056 A nondispatching subprogram with an access parameter cannot be renamed
26057 as a dispatching operation.  This was permitted in Ada 95.
26058
26059 @item Access types, discriminants, and constraints.
26060 Rule changes in this area have led to some incompatibilities; for example,
26061 constrained subtypes of some access types are not permitted in Ada 2005.
26062
26063 @item Aggregates for limited types.
26064 The allowance of aggregates for limited types in Ada 2005 raises the
26065 possibility of ambiguities in legal Ada 95 programs, since additional types
26066 now need to be considered in expression resolution.
26067
26068 @item Fixed-point multiplication and division.
26069 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26070 were legal in Ada 95 and invoked the predefined versions of these operations,
26071 are now ambiguous.
26072 The ambiguity may be resolved either by applying a type conversion to the
26073 expression, or by explicitly invoking the operation from package
26074 @code{Standard}.
26075
26076 @item Return-by-reference types.
26077 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26078 can declare a function returning a value from an anonymous access type.
26079 @end table
26080
26081
26082 @node Implementation-dependent characteristics
26083 @section Implementation-dependent characteristics
26084 @noindent
26085 Although the Ada language defines the semantics of each construct as
26086 precisely as practical, in some situations (for example for reasons of
26087 efficiency, or where the effect is heavily dependent on the host or target
26088 platform) the implementation is allowed some freedom.  In porting Ada 83
26089 code to GNAT, you need to be aware of whether / how the existing code
26090 exercised such implementation dependencies.  Such characteristics fall into
26091 several categories, and GNAT offers specific support in assisting the
26092 transition from certain Ada 83 compilers.
26093
26094 @menu
26095 * Implementation-defined pragmas::
26096 * Implementation-defined attributes::
26097 * Libraries::
26098 * Elaboration order::
26099 * Target-specific aspects::
26100 @end menu
26101
26102 @node Implementation-defined pragmas
26103 @subsection Implementation-defined pragmas
26104
26105 @noindent
26106 Ada compilers are allowed to supplement the language-defined pragmas, and
26107 these are a potential source of non-portability.  All GNAT-defined pragmas
26108 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26109 Reference Manual}, and these include several that are specifically
26110 intended to correspond to other vendors' Ada 83 pragmas.
26111 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26112 For compatibility with HP Ada 83, GNAT supplies the pragmas
26113 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26114 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26115 and @code{Volatile}.
26116 Other relevant pragmas include @code{External} and @code{Link_With}.
26117 Some vendor-specific
26118 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26119 recognized, thus
26120 avoiding compiler rejection of units that contain such pragmas; they are not
26121 relevant in a GNAT context and hence are not otherwise implemented.
26122
26123 @node Implementation-defined attributes
26124 @subsection Implementation-defined attributes
26125
26126 Analogous to pragmas, the set of attributes may be extended by an
26127 implementation.  All GNAT-defined attributes are described in
26128 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26129 Manual}, and these include several that are specifically intended
26130 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26131 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26132 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26133 @code{Type_Class}.
26134
26135 @node Libraries
26136 @subsection Libraries
26137 @noindent
26138 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26139 code uses vendor-specific libraries then there are several ways to manage
26140 this in Ada 95 or Ada 2005:
26141 @enumerate
26142 @item
26143 If the source code for the libraries (specs and bodies) are
26144 available, then the libraries can be migrated in the same way as the
26145 application.
26146 @item
26147 If the source code for the specs but not the bodies are
26148 available, then you can reimplement the bodies.
26149 @item
26150 Some features introduced by Ada 95 obviate the need for library support.  For
26151 example most Ada 83 vendors supplied a package for unsigned integers.  The
26152 Ada 95 modular type feature is the preferred way to handle this need, so
26153 instead of migrating or reimplementing the unsigned integer package it may
26154 be preferable to retrofit the application using modular types.
26155 @end enumerate
26156
26157 @node Elaboration order
26158 @subsection Elaboration order
26159 @noindent
26160 The implementation can choose any elaboration order consistent with the unit
26161 dependency relationship.  This freedom means that some orders can result in
26162 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26163 to invoke a subprogram its body has been elaborated, or to instantiate a
26164 generic before the generic body has been elaborated.  By default GNAT
26165 attempts to choose a safe order (one that will not encounter access before
26166 elaboration problems) by implicitly inserting @code{Elaborate} or
26167 @code{Elaborate_All} pragmas where
26168 needed.  However, this can lead to the creation of elaboration circularities
26169 and a resulting rejection of the program by gnatbind.  This issue is
26170 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26171 In brief, there are several
26172 ways to deal with this situation:
26173
26174 @itemize @bullet
26175 @item
26176 Modify the program to eliminate the circularities, e.g.@: by moving
26177 elaboration-time code into explicitly-invoked procedures
26178 @item
26179 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26180 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26181 @code{Elaborate_All}
26182 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26183 (by selectively suppressing elaboration checks via pragma
26184 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26185 @end itemize
26186
26187 @node Target-specific aspects
26188 @subsection Target-specific aspects
26189 @noindent
26190 Low-level applications need to deal with machine addresses, data
26191 representations, interfacing with assembler code, and similar issues.  If
26192 such an Ada 83 application is being ported to different target hardware (for
26193 example where the byte endianness has changed) then you will need to
26194 carefully examine the program logic; the porting effort will heavily depend
26195 on the robustness of the original design.  Moreover, Ada 95 (and thus
26196 Ada 2005) are sometimes
26197 incompatible with typical Ada 83 compiler practices regarding implicit
26198 packing, the meaning of the Size attribute, and the size of access values.
26199 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26200
26201 @node Compatibility with Other Ada Systems
26202 @section Compatibility with Other Ada Systems
26203
26204 @noindent
26205 If programs avoid the use of implementation dependent and
26206 implementation defined features, as documented in the @cite{Ada
26207 Reference Manual}, there should be a high degree of portability between
26208 GNAT and other Ada systems.  The following are specific items which
26209 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26210 compilers, but do not affect porting code to GNAT@.
26211 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26212 the following issues may or may not arise for Ada 2005 programs
26213 when other compilers appear.)
26214
26215 @table @emph
26216 @item Ada 83 Pragmas and Attributes
26217 Ada 95 compilers are allowed, but not required, to implement the missing
26218 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26219 GNAT implements all such pragmas and attributes, eliminating this as
26220 a compatibility concern, but some other Ada 95 compilers reject these
26221 pragmas and attributes.
26222
26223 @item Specialized Needs Annexes
26224 GNAT implements the full set of special needs annexes.  At the
26225 current time, it is the only Ada 95 compiler to do so.  This means that
26226 programs making use of these features may not be portable to other Ada
26227 95 compilation systems.
26228
26229 @item Representation Clauses
26230 Some other Ada 95 compilers implement only the minimal set of
26231 representation clauses required by the Ada 95 reference manual.  GNAT goes
26232 far beyond this minimal set, as described in the next section.
26233 @end table
26234
26235 @node Representation Clauses
26236 @section Representation Clauses
26237
26238 @noindent
26239 The Ada 83 reference manual was quite vague in describing both the minimal
26240 required implementation of representation clauses, and also their precise
26241 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26242 minimal set of capabilities required is still quite limited.
26243
26244 GNAT implements the full required set of capabilities in
26245 Ada 95 and Ada 2005, but also goes much further, and in particular
26246 an effort has been made to be compatible with existing Ada 83 usage to the
26247 greatest extent possible.
26248
26249 A few cases exist in which Ada 83 compiler behavior is incompatible with
26250 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26251 intentional or accidental dependence on specific implementation dependent
26252 characteristics of these Ada 83 compilers.  The following is a list of
26253 the cases most likely to arise in existing Ada 83 code.
26254
26255 @table @emph
26256 @item Implicit Packing
26257 Some Ada 83 compilers allowed a Size specification to cause implicit
26258 packing of an array or record.  This could cause expensive implicit
26259 conversions for change of representation in the presence of derived
26260 types, and the Ada design intends to avoid this possibility.
26261 Subsequent AI's were issued to make it clear that such implicit
26262 change of representation in response to a Size clause is inadvisable,
26263 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26264 Reference Manuals as implementation advice that is followed by GNAT@.
26265 The problem will show up as an error
26266 message rejecting the size clause.  The fix is simply to provide
26267 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26268 a Component_Size clause.
26269
26270 @item Meaning of Size Attribute
26271 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26272 the minimal number of bits required to hold values of the type.  For example,
26273 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26274 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26275 some 32 in this situation.  This problem will usually show up as a compile
26276 time error, but not always.  It is a good idea to check all uses of the
26277 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26278 Object_Size can provide a useful way of duplicating the behavior of
26279 some Ada 83 compiler systems.
26280
26281 @item Size of Access Types
26282 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26283 and that therefore it will be the same size as a System.Address value.  This
26284 assumption is true for GNAT in most cases with one exception.  For the case of
26285 a pointer to an unconstrained array type (where the bounds may vary from one
26286 value of the access type to another), the default is to use a ``fat pointer'',
26287 which is represented as two separate pointers, one to the bounds, and one to
26288 the array.  This representation has a number of advantages, including improved
26289 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26290 code which makes the assumption that, for example, pointers fit in 32 bits on
26291 a machine with 32-bit addressing.
26292
26293 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26294 access types in this case (where the designated type is an unconstrained array
26295 type).  These thin pointers are indeed the same size as a System.Address value.
26296 To specify a thin pointer, use a size clause for the type, for example:
26297
26298 @smallexample @c ada
26299 type X is access all String;
26300 for X'Size use Standard'Address_Size;
26301 @end smallexample
26302
26303 @noindent
26304 which will cause the type X to be represented using a single pointer.
26305 When using this representation, the bounds are right behind the array.
26306 This representation is slightly less efficient, and does not allow quite
26307 such flexibility in the use of foreign pointers or in using the
26308 Unrestricted_Access attribute to create pointers to non-aliased objects.
26309 But for any standard portable use of the access type it will work in
26310 a functionally correct manner and allow porting of existing code.
26311 Note that another way of forcing a thin pointer representation
26312 is to use a component size clause for the element size in an array,
26313 or a record representation clause for an access field in a record.
26314 @end table
26315
26316 @ifclear vms
26317 @c This brief section is only in the non-VMS version
26318 @c The complete chapter on HP Ada is in the VMS version
26319 @node Compatibility with HP Ada 83
26320 @section Compatibility with HP Ada 83
26321
26322 @noindent
26323 The VMS version of GNAT fully implements all the pragmas and attributes
26324 provided by HP Ada 83, as well as providing the standard HP Ada 83
26325 libraries, including Starlet.  In addition, data layouts and parameter
26326 passing conventions are highly compatible.  This means that porting
26327 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26328 most other porting efforts.  The following are some of the most
26329 significant differences between GNAT and HP Ada 83.
26330
26331 @table @emph
26332 @item Default floating-point representation
26333 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26334 it is VMS format.  GNAT does implement the necessary pragmas
26335 (Long_Float, Float_Representation) for changing this default.
26336
26337 @item System
26338 The package System in GNAT exactly corresponds to the definition in the
26339 Ada 95 reference manual, which means that it excludes many of the
26340 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26341 that contains the additional definitions, and a special pragma,
26342 Extend_System allows this package to be treated transparently as an
26343 extension of package System.
26344
26345 @item To_Address
26346 The definitions provided by Aux_DEC are exactly compatible with those
26347 in the HP Ada 83 version of System, with one exception.
26348 HP Ada provides the following declarations:
26349
26350 @smallexample @c ada
26351 TO_ADDRESS (INTEGER)
26352 TO_ADDRESS (UNSIGNED_LONGWORD)
26353 TO_ADDRESS (@i{universal_integer})
26354 @end smallexample
26355
26356 @noindent
26357 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26358 an extension to Ada 83 not strictly compatible with the reference manual.
26359 In GNAT, we are constrained to be exactly compatible with the standard,
26360 and this means we cannot provide this capability.  In HP Ada 83, the
26361 point of this definition is to deal with a call like:
26362
26363 @smallexample @c ada
26364 TO_ADDRESS (16#12777#);
26365 @end smallexample
26366
26367 @noindent
26368 Normally, according to the Ada 83 standard, one would expect this to be
26369 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26370 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26371 definition using @i{universal_integer} takes precedence.
26372
26373 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26374 is not possible to be 100% compatible.  Since there are many programs using
26375 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26376 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26377 declarations provided in the GNAT version of AUX_Dec are:
26378
26379 @smallexample @c ada
26380 function To_Address (X : Integer) return Address;
26381 pragma Pure_Function (To_Address);
26382
26383 function To_Address_Long (X : Unsigned_Longword)
26384  return Address;
26385 pragma Pure_Function (To_Address_Long);
26386 @end smallexample
26387
26388 @noindent
26389 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26390 change the name to TO_ADDRESS_LONG@.
26391
26392 @item Task_Id values
26393 The Task_Id values assigned will be different in the two systems, and GNAT
26394 does not provide a specified value for the Task_Id of the environment task,
26395 which in GNAT is treated like any other declared task.
26396 @end table
26397
26398 @noindent
26399 For full details on these and other less significant compatibility issues,
26400 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26401 Overview and Comparison on HP Platforms}.
26402
26403 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26404 attributes are recognized, although only a subset of them can sensibly
26405 be implemented.  The description of pragmas in @ref{Implementation
26406 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26407 indicates whether or not they are applicable to non-VMS systems.
26408 @end ifclear
26409
26410 @ifset vms
26411 @node Transitioning to 64-Bit GNAT for OpenVMS
26412 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26413
26414 @noindent
26415 This section is meant to assist users of pre-2006 @value{EDITION}
26416 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26417 the version of the GNAT technology supplied in 2006 and later for
26418 OpenVMS on both Alpha and I64.
26419
26420 @menu
26421 * Introduction to transitioning::
26422 * Migration of 32 bit code::
26423 * Taking advantage of 64 bit addressing::
26424 * Technical details::
26425 @end menu
26426
26427 @node Introduction to transitioning
26428 @subsection Introduction
26429
26430 @noindent
26431 64-bit @value{EDITION} for Open VMS has been designed to meet
26432 three main goals:
26433
26434 @enumerate
26435 @item
26436 Providing a full conforming implementation of Ada 95 and Ada 2005
26437
26438 @item
26439 Allowing maximum backward compatibility, thus easing migration of existing
26440 Ada source code
26441
26442 @item
26443 Supplying a path for exploiting the full 64-bit address range
26444 @end enumerate
26445
26446 @noindent
26447 Ada's strong typing semantics has made it
26448 impractical to have different 32-bit and 64-bit modes. As soon as
26449 one object could possibly be outside the 32-bit address space, this
26450 would make it necessary for the @code{System.Address} type to be 64 bits.
26451 In particular, this would cause inconsistencies if 32-bit code is
26452 called from 64-bit code that raises an exception.
26453
26454 This issue has been resolved by always using 64-bit addressing
26455 at the system level, but allowing for automatic conversions between
26456 32-bit and 64-bit addresses where required. Thus users who
26457 do not currently require 64-bit addressing capabilities, can
26458 recompile their code with only minimal changes (and indeed
26459 if the code is written in portable Ada, with no assumptions about
26460 the size of the @code{Address} type, then no changes at all are necessary).
26461 At the same time,
26462 this approach provides a simple, gradual upgrade path to future
26463 use of larger memories than available for 32-bit systems.
26464 Also, newly written applications or libraries will by default
26465 be fully compatible with future systems exploiting 64-bit
26466 addressing capabilities.
26467
26468 @ref{Migration of 32 bit code}, will focus on porting applications
26469 that do not require more than 2 GB of
26470 addressable memory. This code will be referred to as
26471 @emph{32-bit code}.
26472 For applications intending to exploit the full 64-bit address space,
26473 @ref{Taking advantage of 64 bit addressing},
26474 will consider further changes that may be required.
26475 Such code will be referred to below as @emph{64-bit code}.
26476
26477 @node Migration of 32 bit code
26478 @subsection Migration of 32-bit code
26479
26480 @menu
26481 * Address types::
26482 * Access types::
26483 * Unchecked conversions::
26484 * Predefined constants::
26485 * Interfacing with C::
26486 * Experience with source compatibility::
26487 @end menu
26488
26489 @node Address types
26490 @subsubsection Address types
26491
26492 @noindent
26493 To solve the problem of mixing 64-bit and 32-bit addressing,
26494 while maintaining maximum backward compatibility, the following
26495 approach has been taken:
26496
26497 @itemize @bullet
26498 @item
26499 @code{System.Address} always has a size of 64 bits
26500
26501 @item
26502 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26503 @end itemize
26504
26505 @noindent
26506 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26507 a @code{Short_Address}
26508 may be used where an @code{Address} is required, and vice versa, without
26509 needing explicit type conversions.
26510 By virtue of the Open VMS parameter passing conventions,
26511 even imported
26512 and exported subprograms that have 32-bit address parameters are
26513 compatible with those that have 64-bit address parameters.
26514 (See @ref{Making code 64 bit clean} for details.)
26515
26516 The areas that may need attention are those where record types have
26517 been defined that contain components of the type @code{System.Address}, and
26518 where objects of this type are passed to code expecting a record layout with
26519 32-bit addresses.
26520
26521 Different compilers on different platforms cannot be
26522 expected to represent the same type in the same way,
26523 since alignment constraints
26524 and other system-dependent properties affect the compiler's decision.
26525 For that reason, Ada code
26526 generally uses representation clauses to specify the expected
26527 layout where required.
26528
26529 If such a representation clause uses 32 bits for a component having
26530 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26531 will detect that error and produce a specific diagnostic message.
26532 The developer should then determine whether the representation
26533 should be 64 bits or not and make either of two changes:
26534 change the size to 64 bits and leave the type as @code{System.Address}, or
26535 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26536 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26537 required in any code setting or accessing the field; the compiler will
26538 automatically perform any needed conversions between address
26539 formats.
26540
26541 @node Access types
26542 @subsubsection Access types
26543
26544 @noindent
26545 By default, objects designated by access values are always
26546 allocated in the 32-bit
26547 address space. Thus legacy code will never contain
26548 any objects that are not addressable with 32-bit addresses, and
26549 the compiler will never raise exceptions as result of mixing
26550 32-bit and 64-bit addresses.
26551
26552 However, the access values themselves are represented in 64 bits, for optimum
26553 performance and future compatibility with 64-bit code. As was
26554 the case with @code{System.Address}, the compiler will give an error message
26555 if an object or record component has a representation clause that
26556 requires the access value to fit in 32 bits. In such a situation,
26557 an explicit size clause for the access type, specifying 32 bits,
26558 will have the desired effect.
26559
26560 General access types (declared with @code{access all}) can never be
26561 32 bits, as values of such types must be able to refer to any object
26562 of the  designated type,
26563 including objects residing outside the 32-bit address range.
26564 Existing Ada 83 code will not contain such type definitions,
26565 however, since general access types were introduced in Ada 95.
26566
26567 @node Unchecked conversions
26568 @subsubsection Unchecked conversions
26569
26570 @noindent
26571 In the case of an @code{Unchecked_Conversion} where the source type is a
26572 64-bit access type or the type @code{System.Address}, and the target
26573 type is a 32-bit type, the compiler will generate a warning.
26574 Even though the generated code will still perform the required
26575 conversions, it is highly recommended in these cases to use
26576 respectively a 32-bit access type or @code{System.Short_Address}
26577 as the source type.
26578
26579 @node Predefined constants
26580 @subsubsection Predefined constants
26581
26582 @noindent
26583 The following table shows the correspondence between pre-2006 versions of
26584 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26585 (``New''):
26586
26587 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26588 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26589 @item   @code{System.Word_Size}          @tab 32      @tab 64
26590 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26591 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26592 @item   @code{System.Address_Size}       @tab 32      @tab 64
26593 @end multitable
26594
26595 @noindent
26596 If you need to refer to the specific
26597 memory size of a 32-bit implementation, instead of the
26598 actual memory size, use @code{System.Short_Memory_Size}
26599 rather than @code{System.Memory_Size}.
26600 Similarly, references to @code{System.Address_Size} may need
26601 to be replaced by @code{System.Short_Address'Size}.
26602 The program @command{gnatfind} may be useful for locating
26603 references to the above constants, so that you can verify that they
26604 are still correct.
26605
26606 @node Interfacing with C
26607 @subsubsection Interfacing with C
26608
26609 @noindent
26610 In order to minimize the impact of the transition to 64-bit addresses on
26611 legacy programs, some fundamental types in the @code{Interfaces.C}
26612 package hierarchy continue to be represented in 32 bits.
26613 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26614 This eases integration with the default HP C layout choices, for example
26615 as found in the system routines in @code{DECC$SHR.EXE}.
26616 Because of this implementation choice, the type fully compatible with
26617 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26618 Depending on the context the compiler will issue a
26619 warning or an error when type @code{Address} is used, alerting the user to a
26620 potential problem. Otherwise 32-bit programs that use
26621 @code{Interfaces.C} should normally not require code modifications
26622
26623 The other issue arising with C interfacing concerns pragma @code{Convention}.
26624 For VMS 64-bit systems, there is an issue of the appropriate default size
26625 of C convention pointers in the absence of an explicit size clause. The HP
26626 C compiler can choose either 32 or 64 bits depending on compiler options.
26627 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26628 clause is given. This proves a better choice for porting 32-bit legacy
26629 applications. In order to have a 64-bit representation, it is necessary to
26630 specify a size representation clause. For example:
26631
26632 @smallexample @c ada
26633 type int_star is access Interfaces.C.int;
26634 pragma Convention(C, int_star);
26635 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26636 @end smallexample
26637
26638 @node Experience with source compatibility
26639 @subsubsection Experience with source compatibility
26640
26641 @noindent
26642 The Security Server and STARLET on I64 provide an interesting ``test case''
26643 for source compatibility issues, since it is in such system code
26644 where assumptions about @code{Address} size might be expected to occur.
26645 Indeed, there were a small number of occasions in the Security Server
26646 file @file{jibdef.ads}
26647 where a representation clause for a record type specified
26648 32 bits for a component of type @code{Address}.
26649 All of these errors were detected by the compiler.
26650 The repair was obvious and immediate; to simply replace @code{Address} by
26651 @code{Short_Address}.
26652
26653 In the case of STARLET, there were several record types that should
26654 have had representation clauses but did not.  In these record types
26655 there was an implicit assumption that an @code{Address} value occupied
26656 32 bits.
26657 These compiled without error, but their usage resulted in run-time error
26658 returns from STARLET system calls.
26659 Future GNAT technology enhancements may include a tool that detects and flags
26660 these sorts of potential source code porting problems.
26661
26662 @c ****************************************
26663 @node Taking advantage of 64 bit addressing
26664 @subsection Taking advantage of 64-bit addressing
26665
26666 @menu
26667 * Making code 64 bit clean::
26668 * Allocating memory from the 64 bit storage pool::
26669 * Restrictions on use of 64 bit objects::
26670 * Using 64 bit storage pools by default::
26671 * General access types::
26672 * STARLET and other predefined libraries::
26673 @end menu
26674
26675 @node Making code 64 bit clean
26676 @subsubsection Making code 64-bit clean
26677
26678 @noindent
26679 In order to prevent problems that may occur when (parts of) a
26680 system start using memory outside the 32-bit address range,
26681 we recommend some additional guidelines:
26682
26683 @itemize @bullet
26684 @item
26685 For imported subprograms that take parameters of the
26686 type @code{System.Address}, ensure that these subprograms can
26687 indeed handle 64-bit addresses. If not, or when in doubt,
26688 change the subprogram declaration to specify
26689 @code{System.Short_Address} instead.
26690
26691 @item
26692 Resolve all warnings related to size mismatches in
26693 unchecked conversions. Failing to do so causes
26694 erroneous execution if the source object is outside
26695 the 32-bit address space.
26696
26697 @item
26698 (optional) Explicitly use the 32-bit storage pool
26699 for access types used in a 32-bit context, or use
26700 generic access types where possible
26701 (@pxref{Restrictions on use of 64 bit objects}).
26702 @end itemize
26703
26704 @noindent
26705 If these rules are followed, the compiler will automatically insert
26706 any necessary checks to ensure that no addresses or access values
26707 passed to 32-bit code ever refer to objects outside the 32-bit
26708 address range.
26709 Any attempt to do this will raise @code{Constraint_Error}.
26710
26711 @node Allocating memory from the 64 bit storage pool
26712 @subsubsection Allocating memory from the 64-bit storage pool
26713
26714 @noindent
26715 For any access type @code{T} that potentially requires memory allocations
26716 beyond the 32-bit address space,
26717 use the following representation clause:
26718
26719 @smallexample @c ada
26720    for T'Storage_Pool use System.Pool_64;
26721 @end smallexample
26722
26723 @node Restrictions on use of 64 bit objects
26724 @subsubsection Restrictions on use of 64-bit objects
26725
26726 @noindent
26727 Taking the address of an object allocated from a 64-bit storage pool,
26728 and then passing this address to a subprogram expecting
26729 @code{System.Short_Address},
26730 or assigning it to a variable of type @code{Short_Address}, will cause
26731 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26732 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26733 no exception is raised and execution
26734 will become erroneous.
26735
26736 @node Using 64 bit storage pools by default
26737 @subsubsection Using 64-bit storage pools by default
26738
26739 @noindent
26740 In some cases it may be desirable to have the compiler allocate
26741 from 64-bit storage pools by default. This may be the case for
26742 libraries that are 64-bit clean, but may be used in both 32-bit
26743 and 64-bit contexts. For these cases the following configuration
26744 pragma may be specified:
26745
26746 @smallexample @c ada
26747   pragma Pool_64_Default;
26748 @end smallexample
26749
26750 @noindent
26751 Any code compiled in the context of this pragma will by default
26752 use the @code{System.Pool_64} storage pool. This default may be overridden
26753 for a specific access type @code{T} by the representation clause:
26754
26755 @smallexample @c ada
26756    for T'Storage_Pool use System.Pool_32;
26757 @end smallexample
26758
26759 @noindent
26760 Any object whose address may be passed to a subprogram with a
26761 @code{Short_Address} argument, or assigned to a variable of type
26762 @code{Short_Address}, needs to be allocated from this pool.
26763
26764 @node General access types
26765 @subsubsection General access types
26766
26767 @noindent
26768 Objects designated by access values from a
26769 general access type (declared with @code{access all}) are never allocated
26770 from a 64-bit storage pool. Code that uses general access types will
26771 accept objects allocated in either 32-bit or 64-bit address spaces,
26772 but never allocate objects outside the 32-bit address space.
26773 Using general access types ensures maximum compatibility with both
26774 32-bit and 64-bit code.
26775
26776 @node STARLET and other predefined libraries
26777 @subsubsection STARLET and other predefined libraries
26778
26779 @noindent
26780 All code that comes as part of GNAT is 64-bit clean, but the
26781 restrictions given in @ref{Restrictions on use of 64 bit objects},
26782 still apply. Look at the package
26783 specs to see in which contexts objects allocated
26784 in 64-bit address space are acceptable.
26785
26786 @node Technical details
26787 @subsection Technical details
26788
26789 @noindent
26790 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26791 Ada standard with respect to the type of @code{System.Address}. Previous
26792 versions of GNAT Pro have defined this type as private and implemented it as a
26793 modular type.
26794
26795 In order to allow defining @code{System.Short_Address} as a proper subtype,
26796 and to match the implicit sign extension in parameter passing,
26797 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26798 visible (i.e., non-private) integer type.
26799 Standard operations on the type, such as the binary operators ``+'', ``-'',
26800 etc., that take @code{Address} operands and return an @code{Address} result,
26801 have been hidden by declaring these
26802 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26803 ambiguities that would otherwise result from overloading.
26804 (Note that, although @code{Address} is a visible integer type,
26805 good programming practice dictates against exploiting the type's
26806 integer properties such as literals, since this will compromise
26807 code portability.)
26808
26809 Defining @code{Address} as a visible integer type helps achieve
26810 maximum compatibility for existing Ada code,
26811 without sacrificing the capabilities of the 64-bit architecture.
26812 @end ifset
26813
26814 @c ************************************************
26815 @ifset unw
26816 @node Microsoft Windows Topics
26817 @appendix Microsoft Windows Topics
26818 @cindex Windows NT
26819 @cindex Windows 95
26820 @cindex Windows 98
26821
26822 @noindent
26823 This chapter describes topics that are specific to the Microsoft Windows
26824 platforms (NT, 2000, and XP Professional).
26825
26826 @menu
26827 * Using GNAT on Windows::
26828 * Using a network installation of GNAT::
26829 * CONSOLE and WINDOWS subsystems::
26830 * Temporary Files::
26831 * Mixed-Language Programming on Windows::
26832 * Windows Calling Conventions::
26833 * Introduction to Dynamic Link Libraries (DLLs)::
26834 * Using DLLs with GNAT::
26835 * Building DLLs with GNAT::
26836 * Building DLLs with GNAT Project files::
26837 * Building DLLs with gnatdll::
26838 * GNAT and Windows Resources::
26839 * Debugging a DLL::
26840 * Setting Stack Size from gnatlink::
26841 * Setting Heap Size from gnatlink::
26842 @end menu
26843
26844 @node Using GNAT on Windows
26845 @section Using GNAT on Windows
26846
26847 @noindent
26848 One of the strengths of the GNAT technology is that its tool set
26849 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26850 @code{gdb} debugger, etc.) is used in the same way regardless of the
26851 platform.
26852
26853 On Windows this tool set is complemented by a number of Microsoft-specific
26854 tools that have been provided to facilitate interoperability with Windows
26855 when this is required. With these tools:
26856
26857 @itemize @bullet
26858
26859 @item
26860 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26861 subsystems.
26862
26863 @item
26864 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26865 relocatable and non-relocatable DLLs are supported).
26866
26867 @item
26868 You can build Ada DLLs for use in other applications. These applications
26869 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26870 relocatable and non-relocatable Ada DLLs are supported.
26871
26872 @item
26873 You can include Windows resources in your Ada application.
26874
26875 @item
26876 You can use or create COM/DCOM objects.
26877 @end itemize
26878
26879 @noindent
26880 Immediately below are listed all known general GNAT-for-Windows restrictions.
26881 Other restrictions about specific features like Windows Resources and DLLs
26882 are listed in separate sections below.
26883
26884 @itemize @bullet
26885
26886 @item
26887 It is not possible to use @code{GetLastError} and @code{SetLastError}
26888 when tasking, protected records, or exceptions are used. In these
26889 cases, in order to implement Ada semantics, the GNAT run-time system
26890 calls certain Win32 routines that set the last error variable to 0 upon
26891 success. It should be possible to use @code{GetLastError} and
26892 @code{SetLastError} when tasking, protected record, and exception
26893 features are not used, but it is not guaranteed to work.
26894
26895 @item
26896 It is not possible to link against Microsoft libraries except for
26897 import libraries. The library must be built to be compatible with
26898 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26899 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26900 not be compatible with the GNAT runtime. Even if the library is
26901 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26902
26903 @item
26904 When the compilation environment is located on FAT32 drives, users may
26905 experience recompilations of the source files that have not changed if
26906 Daylight Saving Time (DST) state has changed since the last time files
26907 were compiled. NTFS drives do not have this problem.
26908
26909 @item
26910 No components of the GNAT toolset use any entries in the Windows
26911 registry. The only entries that can be created are file associations and
26912 PATH settings, provided the user has chosen to create them at installation
26913 time, as well as some minimal book-keeping information needed to correctly
26914 uninstall or integrate different GNAT products.
26915 @end itemize
26916
26917 @node Using a network installation of GNAT
26918 @section Using a network installation of GNAT
26919
26920 @noindent
26921 Make sure the system on which GNAT is installed is accessible from the
26922 current machine, i.e., the install location is shared over the network.
26923 Shared resources are accessed on Windows by means of UNC paths, which
26924 have the format @code{\\server\sharename\path}
26925
26926 In order to use such a network installation, simply add the UNC path of the
26927 @file{bin} directory of your GNAT installation in front of your PATH. For
26928 example, if GNAT is installed in @file{\GNAT} directory of a share location
26929 called @file{c-drive} on a machine @file{LOKI}, the following command will
26930 make it available:
26931
26932 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26933
26934 Be aware that every compilation using the network installation results in the
26935 transfer of large amounts of data across the network and will likely cause
26936 serious performance penalty.
26937
26938 @node CONSOLE and WINDOWS subsystems
26939 @section CONSOLE and WINDOWS subsystems
26940 @cindex CONSOLE Subsystem
26941 @cindex WINDOWS Subsystem
26942 @cindex -mwindows
26943
26944 @noindent
26945 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26946 (which is the default subsystem) will always create a console when
26947 launching the application. This is not something desirable when the
26948 application has a Windows GUI. To get rid of this console the
26949 application must be using the @code{WINDOWS} subsystem. To do so
26950 the @option{-mwindows} linker option must be specified.
26951
26952 @smallexample
26953 $ gnatmake winprog -largs -mwindows
26954 @end smallexample
26955
26956 @node Temporary Files
26957 @section Temporary Files
26958 @cindex Temporary files
26959
26960 @noindent
26961 It is possible to control where temporary files gets created by setting
26962 the @env{TMP} environment variable. The file will be created:
26963
26964 @itemize
26965 @item Under the directory pointed to by the @env{TMP} environment variable if
26966 this directory exists.
26967
26968 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26969 set (or not pointing to a directory) and if this directory exists.
26970
26971 @item Under the current working directory otherwise.
26972 @end itemize
26973
26974 @noindent
26975 This allows you to determine exactly where the temporary
26976 file will be created. This is particularly useful in networked
26977 environments where you may not have write access to some
26978 directories.
26979
26980 @node Mixed-Language Programming on Windows
26981 @section Mixed-Language Programming on Windows
26982
26983 @noindent
26984 Developing pure Ada applications on Windows is no different than on
26985 other GNAT-supported platforms. However, when developing or porting an
26986 application that contains a mix of Ada and C/C++, the choice of your
26987 Windows C/C++ development environment conditions your overall
26988 interoperability strategy.
26989
26990 If you use @command{gcc} to compile the non-Ada part of your application,
26991 there are no Windows-specific restrictions that affect the overall
26992 interoperability with your Ada code. If you plan to use
26993 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
26994 the following limitations:
26995
26996 @itemize @bullet
26997 @item
26998 You cannot link your Ada code with an object or library generated with
26999 Microsoft tools if these use the @code{.tls} section (Thread Local
27000 Storage section) since the GNAT linker does not yet support this section.
27001
27002 @item
27003 You cannot link your Ada code with an object or library generated with
27004 Microsoft tools if these use I/O routines other than those provided in
27005 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27006 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27007 libraries can cause a conflict with @code{msvcrt.dll} services. For
27008 instance Visual C++ I/O stream routines conflict with those in
27009 @code{msvcrt.dll}.
27010 @end itemize
27011
27012 @noindent
27013 If you do want to use the Microsoft tools for your non-Ada code and hit one
27014 of the above limitations, you have two choices:
27015
27016 @enumerate
27017 @item
27018 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27019 application. In this case, use the Microsoft or whatever environment to
27020 build the DLL and use GNAT to build your executable
27021 (@pxref{Using DLLs with GNAT}).
27022
27023 @item
27024 Or you can encapsulate your Ada code in a DLL to be linked with the
27025 other part of your application. In this case, use GNAT to build the DLL
27026 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27027 environment to build your executable.
27028 @end enumerate
27029
27030 @node Windows Calling Conventions
27031 @section Windows Calling Conventions
27032 @findex Stdcall
27033 @findex APIENTRY
27034
27035 @menu
27036 * C Calling Convention::
27037 * Stdcall Calling Convention::
27038 * Win32 Calling Convention::
27039 * DLL Calling Convention::
27040 @end menu
27041
27042 @noindent
27043 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27044 (callee), there are several ways to push @code{G}'s parameters on the
27045 stack and there are several possible scenarios to clean up the stack
27046 upon @code{G}'s return. A calling convention is an agreed upon software
27047 protocol whereby the responsibilities between the caller (@code{F}) and
27048 the callee (@code{G}) are clearly defined. Several calling conventions
27049 are available for Windows:
27050
27051 @itemize @bullet
27052 @item
27053 @code{C} (Microsoft defined)
27054
27055 @item
27056 @code{Stdcall} (Microsoft defined)
27057
27058 @item
27059 @code{Win32} (GNAT specific)
27060
27061 @item
27062 @code{DLL} (GNAT specific)
27063 @end itemize
27064
27065 @node C Calling Convention
27066 @subsection @code{C} Calling Convention
27067
27068 @noindent
27069 This is the default calling convention used when interfacing to C/C++
27070 routines compiled with either @command{gcc} or Microsoft Visual C++.
27071
27072 In the @code{C} calling convention subprogram parameters are pushed on the
27073 stack by the caller from right to left. The caller itself is in charge of
27074 cleaning up the stack after the call. In addition, the name of a routine
27075 with @code{C} calling convention is mangled by adding a leading underscore.
27076
27077 The name to use on the Ada side when importing (or exporting) a routine
27078 with @code{C} calling convention is the name of the routine. For
27079 instance the C function:
27080
27081 @smallexample
27082 int get_val (long);
27083 @end smallexample
27084
27085 @noindent
27086 should be imported from Ada as follows:
27087
27088 @smallexample @c ada
27089 @group
27090 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27091 pragma Import (C, Get_Val, External_Name => "get_val");
27092 @end group
27093 @end smallexample
27094
27095 @noindent
27096 Note that in this particular case the @code{External_Name} parameter could
27097 have been omitted since, when missing, this parameter is taken to be the
27098 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27099 is missing, as in the above example, this parameter is set to be the
27100 @code{External_Name} with a leading underscore.
27101
27102 When importing a variable defined in C, you should always use the @code{C}
27103 calling convention unless the object containing the variable is part of a
27104 DLL (in which case you should use the @code{Stdcall} calling
27105 convention, @pxref{Stdcall Calling Convention}).
27106
27107 @node Stdcall Calling Convention
27108 @subsection @code{Stdcall} Calling Convention
27109
27110 @noindent
27111 This convention, which was the calling convention used for Pascal
27112 programs, is used by Microsoft for all the routines in the Win32 API for
27113 efficiency reasons. It must be used to import any routine for which this
27114 convention was specified.
27115
27116 In the @code{Stdcall} calling convention subprogram parameters are pushed
27117 on the stack by the caller from right to left. The callee (and not the
27118 caller) is in charge of cleaning the stack on routine exit. In addition,
27119 the name of a routine with @code{Stdcall} calling convention is mangled by
27120 adding a leading underscore (as for the @code{C} calling convention) and a
27121 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27122 bytes) of the parameters passed to the routine.
27123
27124 The name to use on the Ada side when importing a C routine with a
27125 @code{Stdcall} calling convention is the name of the C routine. The leading
27126 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27127 the compiler. For instance the Win32 function:
27128
27129 @smallexample
27130 @b{APIENTRY} int get_val (long);
27131 @end smallexample
27132
27133 @noindent
27134 should be imported from Ada as follows:
27135
27136 @smallexample @c ada
27137 @group
27138 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27139 pragma Import (Stdcall, Get_Val);
27140 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27141 @end group
27142 @end smallexample
27143
27144 @noindent
27145 As for the @code{C} calling convention, when the @code{External_Name}
27146 parameter is missing, it is taken to be the name of the Ada entity in lower
27147 case. If instead of writing the above import pragma you write:
27148
27149 @smallexample @c ada
27150 @group
27151 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27152 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27153 @end group
27154 @end smallexample
27155
27156 @noindent
27157 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27158 of specifying the @code{External_Name} parameter you specify the
27159 @code{Link_Name} as in the following example:
27160
27161 @smallexample @c ada
27162 @group
27163 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27164 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27165 @end group
27166 @end smallexample
27167
27168 @noindent
27169 then the imported routine is @code{retrieve_val}, that is, there is no
27170 decoration at all. No leading underscore and no Stdcall suffix
27171 @code{@@}@code{@var{nn}}.
27172
27173 @noindent
27174 This is especially important as in some special cases a DLL's entry
27175 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27176 name generated for a call has it.
27177
27178 @noindent
27179 It is also possible to import variables defined in a DLL by using an
27180 import pragma for a variable. As an example, if a DLL contains a
27181 variable defined as:
27182
27183 @smallexample
27184 int my_var;
27185 @end smallexample
27186
27187 @noindent
27188 then, to access this variable from Ada you should write:
27189
27190 @smallexample @c ada
27191 @group
27192 My_Var : Interfaces.C.int;
27193 pragma Import (Stdcall, My_Var);
27194 @end group
27195 @end smallexample
27196
27197 @noindent
27198 Note that to ease building cross-platform bindings this convention
27199 will be handled as a @code{C} calling convention on non-Windows platforms.
27200
27201 @node Win32 Calling Convention
27202 @subsection @code{Win32} Calling Convention
27203
27204 @noindent
27205 This convention, which is GNAT-specific is fully equivalent to the
27206 @code{Stdcall} calling convention described above.
27207
27208 @node DLL Calling Convention
27209 @subsection @code{DLL} Calling Convention
27210
27211 @noindent
27212 This convention, which is GNAT-specific is fully equivalent to the
27213 @code{Stdcall} calling convention described above.
27214
27215 @node Introduction to Dynamic Link Libraries (DLLs)
27216 @section Introduction to Dynamic Link Libraries (DLLs)
27217 @findex DLL
27218
27219 @noindent
27220 A Dynamically Linked Library (DLL) is a library that can be shared by
27221 several applications running under Windows. A DLL can contain any number of
27222 routines and variables.
27223
27224 One advantage of DLLs is that you can change and enhance them without
27225 forcing all the applications that depend on them to be relinked or
27226 recompiled. However, you should be aware than all calls to DLL routines are
27227 slower since, as you will understand below, such calls are indirect.
27228
27229 To illustrate the remainder of this section, suppose that an application
27230 wants to use the services of a DLL @file{API.dll}. To use the services
27231 provided by @file{API.dll} you must statically link against the DLL or
27232 an import library which contains a jump table with an entry for each
27233 routine and variable exported by the DLL. In the Microsoft world this
27234 import library is called @file{API.lib}. When using GNAT this import
27235 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27236 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27237
27238 After you have linked your application with the DLL or the import library
27239 and you run your application, here is what happens:
27240
27241 @enumerate
27242 @item
27243 Your application is loaded into memory.
27244
27245 @item
27246 The DLL @file{API.dll} is mapped into the address space of your
27247 application. This means that:
27248
27249 @itemize @bullet
27250 @item
27251 The DLL will use the stack of the calling thread.
27252
27253 @item
27254 The DLL will use the virtual address space of the calling process.
27255
27256 @item
27257 The DLL will allocate memory from the virtual address space of the calling
27258 process.
27259
27260 @item
27261 Handles (pointers) can be safely exchanged between routines in the DLL
27262 routines and routines in the application using the DLL.
27263 @end itemize
27264
27265 @item
27266 The entries in the jump table (from the import library @file{libAPI.dll.a}
27267 or @file{API.lib} or automatically created when linking against a DLL)
27268 which is part of your application are initialized with the addresses
27269 of the routines and variables in @file{API.dll}.
27270
27271 @item
27272 If present in @file{API.dll}, routines @code{DllMain} or
27273 @code{DllMainCRTStartup} are invoked. These routines typically contain
27274 the initialization code needed for the well-being of the routines and
27275 variables exported by the DLL.
27276 @end enumerate
27277
27278 @noindent
27279 There is an additional point which is worth mentioning. In the Windows
27280 world there are two kind of DLLs: relocatable and non-relocatable
27281 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27282 in the target application address space. If the addresses of two
27283 non-relocatable DLLs overlap and these happen to be used by the same
27284 application, a conflict will occur and the application will run
27285 incorrectly. Hence, when possible, it is always preferable to use and
27286 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27287 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27288 User's Guide) removes the debugging symbols from the DLL but the DLL can
27289 still be relocated.
27290
27291 As a side note, an interesting difference between Microsoft DLLs and
27292 Unix shared libraries, is the fact that on most Unix systems all public
27293 routines are exported by default in a Unix shared library, while under
27294 Windows it is possible (but not required) to list exported routines in
27295 a definition file (@pxref{The Definition File}).
27296
27297 @node Using DLLs with GNAT
27298 @section Using DLLs with GNAT
27299
27300 @menu
27301 * Creating an Ada Spec for the DLL Services::
27302 * Creating an Import Library::
27303 @end menu
27304
27305 @noindent
27306 To use the services of a DLL, say @file{API.dll}, in your Ada application
27307 you must have:
27308
27309 @enumerate
27310 @item
27311 The Ada spec for the routines and/or variables you want to access in
27312 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27313 header files provided with the DLL.
27314
27315 @item
27316 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27317 mentioned an import library is a statically linked library containing the
27318 import table which will be filled at load time to point to the actual
27319 @file{API.dll} routines. Sometimes you don't have an import library for the
27320 DLL you want to use. The following sections will explain how to build
27321 one. Note that this is optional.
27322
27323 @item
27324 The actual DLL, @file{API.dll}.
27325 @end enumerate
27326
27327 @noindent
27328 Once you have all the above, to compile an Ada application that uses the
27329 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27330 you simply issue the command
27331
27332 @smallexample
27333 $ gnatmake my_ada_app -largs -lAPI
27334 @end smallexample
27335
27336 @noindent
27337 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27338 tells the GNAT linker to look first for a library named @file{API.lib}
27339 (Microsoft-style name) and if not found for a libraries named
27340 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
27341 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27342 contains the following pragma
27343
27344 @smallexample @c ada
27345 pragma Linker_Options ("-lAPI");
27346 @end smallexample
27347
27348 @noindent
27349 you do not have to add @option{-largs -lAPI} at the end of the
27350 @command{gnatmake} command.
27351
27352 If any one of the items above is missing you will have to create it
27353 yourself. The following sections explain how to do so using as an
27354 example a fictitious DLL called @file{API.dll}.
27355
27356 @node Creating an Ada Spec for the DLL Services
27357 @subsection Creating an Ada Spec for the DLL Services
27358
27359 @noindent
27360 A DLL typically comes with a C/C++ header file which provides the
27361 definitions of the routines and variables exported by the DLL. The Ada
27362 equivalent of this header file is a package spec that contains definitions
27363 for the imported entities. If the DLL you intend to use does not come with
27364 an Ada spec you have to generate one such spec yourself. For example if
27365 the header file of @file{API.dll} is a file @file{api.h} containing the
27366 following two definitions:
27367
27368 @smallexample
27369 @group
27370 @cartouche
27371 int some_var;
27372 int get (char *);
27373 @end cartouche
27374 @end group
27375 @end smallexample
27376
27377 @noindent
27378 then the equivalent Ada spec could be:
27379
27380 @smallexample @c ada
27381 @group
27382 @cartouche
27383 with Interfaces.C.Strings;
27384 package API is
27385    use Interfaces;
27386
27387    Some_Var : C.int;
27388    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27389
27390 private
27391    pragma Import (C, Get);
27392    pragma Import (DLL, Some_Var);
27393 end API;
27394 @end cartouche
27395 @end group
27396 @end smallexample
27397
27398 @noindent
27399 Note that a variable is
27400 @strong{always imported with a Stdcall convention}. A function
27401 can have @code{C} or @code{Stdcall} convention.
27402 (@pxref{Windows Calling Conventions}).
27403
27404 @node Creating an Import Library
27405 @subsection Creating an Import Library
27406 @cindex Import library
27407
27408 @menu
27409 * The Definition File::
27410 * GNAT-Style Import Library::
27411 * Microsoft-Style Import Library::
27412 @end menu
27413
27414 @noindent
27415 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27416 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27417 with @file{API.dll} you can skip this section. You can also skip this
27418 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27419 as in this case it is possible to link directly against the
27420 DLL. Otherwise read on.
27421
27422 @node The Definition File
27423 @subsubsection The Definition File
27424 @cindex Definition file
27425 @findex .def
27426
27427 @noindent
27428 As previously mentioned, and unlike Unix systems, the list of symbols
27429 that are exported from a DLL must be provided explicitly in Windows.
27430 The main goal of a definition file is precisely that: list the symbols
27431 exported by a DLL. A definition file (usually a file with a @code{.def}
27432 suffix) has the following structure:
27433
27434 @smallexample
27435 @group
27436 @cartouche
27437 @r{[}LIBRARY @var{name}@r{]}
27438 @r{[}DESCRIPTION @var{string}@r{]}
27439 EXPORTS
27440    @var{symbol1}
27441    @var{symbol2}
27442    @dots{}
27443 @end cartouche
27444 @end group
27445 @end smallexample
27446
27447 @table @code
27448 @item LIBRARY @var{name}
27449 This section, which is optional, gives the name of the DLL.
27450
27451 @item DESCRIPTION @var{string}
27452 This section, which is optional, gives a description string that will be
27453 embedded in the import library.
27454
27455 @item EXPORTS
27456 This section gives the list of exported symbols (procedures, functions or
27457 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27458 section of @file{API.def} looks like:
27459
27460 @smallexample
27461 @group
27462 @cartouche
27463 EXPORTS
27464    some_var
27465    get
27466 @end cartouche
27467 @end group
27468 @end smallexample
27469 @end table
27470
27471 @noindent
27472 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27473 (@pxref{Windows Calling Conventions}) for a Stdcall
27474 calling convention function in the exported symbols list.
27475
27476 @noindent
27477 There can actually be other sections in a definition file, but these
27478 sections are not relevant to the discussion at hand.
27479
27480 @node GNAT-Style Import Library
27481 @subsubsection GNAT-Style Import Library
27482
27483 @noindent
27484 To create a static import library from @file{API.dll} with the GNAT tools
27485 you should proceed as follows:
27486
27487 @enumerate
27488 @item
27489 Create the definition file @file{API.def} (@pxref{The Definition File}).
27490 For that use the @code{dll2def} tool as follows:
27491
27492 @smallexample
27493 $ dll2def API.dll > API.def
27494 @end smallexample
27495
27496 @noindent
27497 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27498 to standard output the list of entry points in the DLL. Note that if
27499 some routines in the DLL have the @code{Stdcall} convention
27500 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27501 suffix then you'll have to edit @file{api.def} to add it, and specify
27502 @option{-k} to @command{gnatdll} when creating the import library.
27503
27504 @noindent
27505 Here are some hints to find the right @code{@@}@var{nn} suffix.
27506
27507 @enumerate
27508 @item
27509 If you have the Microsoft import library (.lib), it is possible to get
27510 the right symbols by using Microsoft @code{dumpbin} tool (see the
27511 corresponding Microsoft documentation for further details).
27512
27513 @smallexample
27514 $ dumpbin /exports api.lib
27515 @end smallexample
27516
27517 @item
27518 If you have a message about a missing symbol at link time the compiler
27519 tells you what symbol is expected. You just have to go back to the
27520 definition file and add the right suffix.
27521 @end enumerate
27522
27523 @item
27524 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27525 (@pxref{Using gnatdll}) as follows:
27526
27527 @smallexample
27528 $ gnatdll -e API.def -d API.dll
27529 @end smallexample
27530
27531 @noindent
27532 @code{gnatdll} takes as input a definition file @file{API.def} and the
27533 name of the DLL containing the services listed in the definition file
27534 @file{API.dll}. The name of the static import library generated is
27535 computed from the name of the definition file as follows: if the
27536 definition file name is @var{xyz}@code{.def}, the import library name will
27537 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27538 @option{-e} could have been removed because the name of the definition
27539 file (before the ``@code{.def}'' suffix) is the same as the name of the
27540 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27541 @end enumerate
27542
27543 @node Microsoft-Style Import Library
27544 @subsubsection Microsoft-Style Import Library
27545
27546 @noindent
27547 With GNAT you can either use a GNAT-style or Microsoft-style import
27548 library. A Microsoft import library is needed only if you plan to make an
27549 Ada DLL available to applications developed with Microsoft
27550 tools (@pxref{Mixed-Language Programming on Windows}).
27551
27552 To create a Microsoft-style import library for @file{API.dll} you
27553 should proceed as follows:
27554
27555 @enumerate
27556 @item
27557 Create the definition file @file{API.def} from the DLL. For this use either
27558 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27559 tool (see the corresponding Microsoft documentation for further details).
27560
27561 @item
27562 Build the actual import library using Microsoft's @code{lib} utility:
27563
27564 @smallexample
27565 $ lib -machine:IX86 -def:API.def -out:API.lib
27566 @end smallexample
27567
27568 @noindent
27569 If you use the above command the definition file @file{API.def} must
27570 contain a line giving the name of the DLL:
27571
27572 @smallexample
27573 LIBRARY      "API"
27574 @end smallexample
27575
27576 @noindent
27577 See the Microsoft documentation for further details about the usage of
27578 @code{lib}.
27579 @end enumerate
27580
27581 @node Building DLLs with GNAT
27582 @section Building DLLs with GNAT
27583 @cindex DLLs, building
27584
27585 @noindent
27586 This section explain how to build DLLs using the GNAT built-in DLL
27587 support. With the following procedure it is straight forward to build
27588 and use DLLs with GNAT.
27589
27590 @enumerate
27591
27592 @item building object files
27593
27594 The first step is to build all objects files that are to be included
27595 into the DLL. This is done by using the standard @command{gnatmake} tool.
27596
27597 @item building the DLL
27598
27599 To build the DLL you must use @command{gcc}'s @option{-shared}
27600 option. It is quite simple to use this method:
27601
27602 @smallexample
27603 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27604 @end smallexample
27605
27606 It is important to note that in this case all symbols found in the
27607 object files are automatically exported. It is possible to restrict
27608 the set of symbols to export by passing to @command{gcc} a definition
27609 file, @pxref{The Definition File}. For example:
27610
27611 @smallexample
27612 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27613 @end smallexample
27614
27615 If you use a definition file you must export the elaboration procedures
27616 for every package that required one. Elaboration procedures are named
27617 using the package name followed by "_E".
27618
27619 @item preparing DLL to be used
27620
27621 For the DLL to be used by client programs the bodies must be hidden
27622 from it and the .ali set with read-only attribute. This is very important
27623 otherwise GNAT will recompile all packages and will not actually use
27624 the code in the DLL. For example:
27625
27626 @smallexample
27627 $ mkdir apilib
27628 $ copy *.ads *.ali api.dll apilib
27629 $ attrib +R apilib\*.ali
27630 @end smallexample
27631
27632 @end enumerate
27633
27634 At this point it is possible to use the DLL by directly linking
27635 against it. Note that you must use the GNAT shared runtime when using
27636 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27637 option.
27638
27639 @smallexample
27640 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27641 @end smallexample
27642
27643 @node Building DLLs with GNAT Project files
27644 @section Building DLLs with GNAT Project files
27645 @cindex DLLs, building
27646
27647 @noindent
27648 There is nothing specific to Windows in the build process.
27649 @pxref{Library Projects}.
27650
27651 @noindent
27652 Due to a system limitation, it is not possible under Windows to create threads
27653 when inside the @code{DllMain} routine which is used for auto-initialization
27654 of shared libraries, so it is not possible to have library level tasks in SALs.
27655
27656 @node Building DLLs with gnatdll
27657 @section Building DLLs with gnatdll
27658 @cindex DLLs, building
27659
27660 @menu
27661 * Limitations When Using Ada DLLs from Ada::
27662 * Exporting Ada Entities::
27663 * Ada DLLs and Elaboration::
27664 * Ada DLLs and Finalization::
27665 * Creating a Spec for Ada DLLs::
27666 * Creating the Definition File::
27667 * Using gnatdll::
27668 @end menu
27669
27670 @noindent
27671 Note that it is preferred to use the built-in GNAT DLL support
27672 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27673 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27674
27675 This section explains how to build DLLs containing Ada code using
27676 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27677 remainder of this section.
27678
27679 The steps required to build an Ada DLL that is to be used by Ada as well as
27680 non-Ada applications are as follows:
27681
27682 @enumerate
27683 @item
27684 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27685 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27686 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27687 skip this step if you plan to use the Ada DLL only from Ada applications.
27688
27689 @item
27690 Your Ada code must export an initialization routine which calls the routine
27691 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27692 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27693 routine exported by the Ada DLL must be invoked by the clients of the DLL
27694 to initialize the DLL.
27695
27696 @item
27697 When useful, the DLL should also export a finalization routine which calls
27698 routine @code{adafinal} generated by @command{gnatbind} to perform the
27699 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27700 The finalization routine exported by the Ada DLL must be invoked by the
27701 clients of the DLL when the DLL services are no further needed.
27702
27703 @item
27704 You must provide a spec for the services exported by the Ada DLL in each
27705 of the programming languages to which you plan to make the DLL available.
27706
27707 @item
27708 You must provide a definition file listing the exported entities
27709 (@pxref{The Definition File}).
27710
27711 @item
27712 Finally you must use @code{gnatdll} to produce the DLL and the import
27713 library (@pxref{Using gnatdll}).
27714 @end enumerate
27715
27716 @noindent
27717 Note that a relocatable DLL stripped using the @code{strip}
27718 binutils tool will not be relocatable anymore. To build a DLL without
27719 debug information pass @code{-largs -s} to @code{gnatdll}. This
27720 restriction does not apply to a DLL built using a Library Project.
27721 @pxref{Library Projects}.
27722
27723 @node Limitations When Using Ada DLLs from Ada
27724 @subsection Limitations When Using Ada DLLs from Ada
27725
27726 @noindent
27727 When using Ada DLLs from Ada applications there is a limitation users
27728 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27729 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27730 each Ada DLL includes the services of the GNAT run time that are necessary
27731 to the Ada code inside the DLL. As a result, when an Ada program uses an
27732 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27733 one in the main program.
27734
27735 It is therefore not possible to exchange GNAT run-time objects between the
27736 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27737 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27738 types, etc.
27739
27740 It is completely safe to exchange plain elementary, array or record types,
27741 Windows object handles, etc.
27742
27743 @node Exporting Ada Entities
27744 @subsection Exporting Ada Entities
27745 @cindex Export table
27746
27747 @noindent
27748 Building a DLL is a way to encapsulate a set of services usable from any
27749 application. As a result, the Ada entities exported by a DLL should be
27750 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27751 any Ada name mangling. As an example here is an Ada package
27752 @code{API}, spec and body, exporting two procedures, a function, and a
27753 variable:
27754
27755 @smallexample @c ada
27756 @group
27757 @cartouche
27758 with Interfaces.C; use Interfaces;
27759 package API is
27760    Count : C.int := 0;
27761    function Factorial (Val : C.int) return C.int;
27762
27763    procedure Initialize_API;
27764    procedure Finalize_API;
27765    --  Initialization & Finalization routines. More in the next section.
27766 private
27767    pragma Export (C, Initialize_API);
27768    pragma Export (C, Finalize_API);
27769    pragma Export (C, Count);
27770    pragma Export (C, Factorial);
27771 end API;
27772 @end cartouche
27773 @end group
27774 @end smallexample
27775
27776 @smallexample @c ada
27777 @group
27778 @cartouche
27779 package body API is
27780    function Factorial (Val : C.int) return C.int is
27781       Fact : C.int := 1;
27782    begin
27783       Count := Count + 1;
27784       for K in 1 .. Val loop
27785          Fact := Fact * K;
27786       end loop;
27787       return Fact;
27788    end Factorial;
27789
27790    procedure Initialize_API is
27791       procedure Adainit;
27792       pragma Import (C, Adainit);
27793    begin
27794       Adainit;
27795    end Initialize_API;
27796
27797    procedure Finalize_API is
27798       procedure Adafinal;
27799       pragma Import (C, Adafinal);
27800    begin
27801       Adafinal;
27802    end Finalize_API;
27803 end API;
27804 @end cartouche
27805 @end group
27806 @end smallexample
27807
27808 @noindent
27809 If the Ada DLL you are building will only be used by Ada applications
27810 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27811 convention. As an example, the previous package could be written as
27812 follows:
27813
27814 @smallexample @c ada
27815 @group
27816 @cartouche
27817 package API is
27818    Count : Integer := 0;
27819    function Factorial (Val : Integer) return Integer;
27820
27821    procedure Initialize_API;
27822    procedure Finalize_API;
27823    --  Initialization and Finalization routines.
27824 end API;
27825 @end cartouche
27826 @end group
27827 @end smallexample
27828
27829 @smallexample @c ada
27830 @group
27831 @cartouche
27832 package body API is
27833    function Factorial (Val : Integer) return Integer is
27834       Fact : Integer := 1;
27835    begin
27836       Count := Count + 1;
27837       for K in 1 .. Val loop
27838          Fact := Fact * K;
27839       end loop;
27840       return Fact;
27841    end Factorial;
27842
27843    @dots{}
27844    --  The remainder of this package body is unchanged.
27845 end API;
27846 @end cartouche
27847 @end group
27848 @end smallexample
27849
27850 @noindent
27851 Note that if you do not export the Ada entities with a @code{C} or
27852 @code{Stdcall} convention you will have to provide the mangled Ada names
27853 in the definition file of the Ada DLL
27854 (@pxref{Creating the Definition File}).
27855
27856 @node Ada DLLs and Elaboration
27857 @subsection Ada DLLs and Elaboration
27858 @cindex DLLs and elaboration
27859
27860 @noindent
27861 The DLL that you are building contains your Ada code as well as all the
27862 routines in the Ada library that are needed by it. The first thing a
27863 user of your DLL must do is elaborate the Ada code
27864 (@pxref{Elaboration Order Handling in GNAT}).
27865
27866 To achieve this you must export an initialization routine
27867 (@code{Initialize_API} in the previous example), which must be invoked
27868 before using any of the DLL services. This elaboration routine must call
27869 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27870 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27871 @code{Initialize_Api} for an example. Note that the GNAT binder is
27872 automatically invoked during the DLL build process by the @code{gnatdll}
27873 tool (@pxref{Using gnatdll}).
27874
27875 When a DLL is loaded, Windows systematically invokes a routine called
27876 @code{DllMain}. It would therefore be possible to call @code{adainit}
27877 directly from @code{DllMain} without having to provide an explicit
27878 initialization routine. Unfortunately, it is not possible to call
27879 @code{adainit} from the @code{DllMain} if your program has library level
27880 tasks because access to the @code{DllMain} entry point is serialized by
27881 the system (that is, only a single thread can execute ``through'' it at a
27882 time), which means that the GNAT run time will deadlock waiting for the
27883 newly created task to complete its initialization.
27884
27885 @node Ada DLLs and Finalization
27886 @subsection Ada DLLs and Finalization
27887 @cindex DLLs and finalization
27888
27889 @noindent
27890 When the services of an Ada DLL are no longer needed, the client code should
27891 invoke the DLL finalization routine, if available. The DLL finalization
27892 routine is in charge of releasing all resources acquired by the DLL. In the
27893 case of the Ada code contained in the DLL, this is achieved by calling
27894 routine @code{adafinal} generated by the GNAT binder
27895 (@pxref{Binding with Non-Ada Main Programs}).
27896 See the body of @code{Finalize_Api} for an
27897 example. As already pointed out the GNAT binder is automatically invoked
27898 during the DLL build process by the @code{gnatdll} tool
27899 (@pxref{Using gnatdll}).
27900
27901 @node Creating a Spec for Ada DLLs
27902 @subsection Creating a Spec for Ada DLLs
27903
27904 @noindent
27905 To use the services exported by the Ada DLL from another programming
27906 language (e.g.@: C), you have to translate the specs of the exported Ada
27907 entities in that language. For instance in the case of @code{API.dll},
27908 the corresponding C header file could look like:
27909
27910 @smallexample
27911 @group
27912 @cartouche
27913 extern int *_imp__count;
27914 #define count (*_imp__count)
27915 int factorial (int);
27916 @end cartouche
27917 @end group
27918 @end smallexample
27919
27920 @noindent
27921 It is important to understand that when building an Ada DLL to be used by
27922 other Ada applications, you need two different specs for the packages
27923 contained in the DLL: one for building the DLL and the other for using
27924 the DLL. This is because the @code{DLL} calling convention is needed to
27925 use a variable defined in a DLL, but when building the DLL, the variable
27926 must have either the @code{Ada} or @code{C} calling convention. As an
27927 example consider a DLL comprising the following package @code{API}:
27928
27929 @smallexample @c ada
27930 @group
27931 @cartouche
27932 package API is
27933    Count : Integer := 0;
27934    @dots{}
27935    --  Remainder of the package omitted.
27936 end API;
27937 @end cartouche
27938 @end group
27939 @end smallexample
27940
27941 @noindent
27942 After producing a DLL containing package @code{API}, the spec that
27943 must be used to import @code{API.Count} from Ada code outside of the
27944 DLL is:
27945
27946 @smallexample @c ada
27947 @group
27948 @cartouche
27949 package API is
27950    Count : Integer;
27951    pragma Import (DLL, Count);
27952 end API;
27953 @end cartouche
27954 @end group
27955 @end smallexample
27956
27957 @node Creating the Definition File
27958 @subsection Creating the Definition File
27959
27960 @noindent
27961 The definition file is the last file needed to build the DLL. It lists
27962 the exported symbols. As an example, the definition file for a DLL
27963 containing only package @code{API} (where all the entities are exported
27964 with a @code{C} calling convention) is:
27965
27966 @smallexample
27967 @group
27968 @cartouche
27969 EXPORTS
27970     count
27971     factorial
27972     finalize_api
27973     initialize_api
27974 @end cartouche
27975 @end group
27976 @end smallexample
27977
27978 @noindent
27979 If the @code{C} calling convention is missing from package @code{API},
27980 then the definition file contains the mangled Ada names of the above
27981 entities, which in this case are:
27982
27983 @smallexample
27984 @group
27985 @cartouche
27986 EXPORTS
27987     api__count
27988     api__factorial
27989     api__finalize_api
27990     api__initialize_api
27991 @end cartouche
27992 @end group
27993 @end smallexample
27994
27995 @node Using gnatdll
27996 @subsection Using @code{gnatdll}
27997 @findex gnatdll
27998
27999 @menu
28000 * gnatdll Example::
28001 * gnatdll behind the Scenes::
28002 * Using dlltool::
28003 @end menu
28004
28005 @noindent
28006 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28007 and non-Ada sources that make up your DLL have been compiled.
28008 @code{gnatdll} is actually in charge of two distinct tasks: build the
28009 static import library for the DLL and the actual DLL. The form of the
28010 @code{gnatdll} command is
28011
28012 @smallexample
28013 @cartouche
28014 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28015 @c Expanding @ovar macro inline (explanation in macro def comments)
28016 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28017 @end cartouche
28018 @end smallexample
28019
28020 @noindent
28021 where @var{list-of-files} is a list of ALI and object files. The object
28022 file list must be the exact list of objects corresponding to the non-Ada
28023 sources whose services are to be included in the DLL. The ALI file list
28024 must be the exact list of ALI files for the corresponding Ada sources
28025 whose services are to be included in the DLL. If @var{list-of-files} is
28026 missing, only the static import library is generated.
28027
28028 @noindent
28029 You may specify any of the following switches to @code{gnatdll}:
28030
28031 @table @code
28032 @c @item -a@ovar{address}
28033 @c Expanding @ovar macro inline (explanation in macro def comments)
28034 @item -a@r{[}@var{address}@r{]}
28035 @cindex @option{-a} (@code{gnatdll})
28036 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28037 specified the default address @var{0x11000000} will be used. By default,
28038 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28039 advise the reader to build relocatable DLL.
28040
28041 @item -b @var{address}
28042 @cindex @option{-b} (@code{gnatdll})
28043 Set the relocatable DLL base address. By default the address is
28044 @code{0x11000000}.
28045
28046 @item -bargs @var{opts}
28047 @cindex @option{-bargs} (@code{gnatdll})
28048 Binder options. Pass @var{opts} to the binder.
28049
28050 @item -d @var{dllfile}
28051 @cindex @option{-d} (@code{gnatdll})
28052 @var{dllfile} is the name of the DLL. This switch must be present for
28053 @code{gnatdll} to do anything. The name of the generated import library is
28054 obtained algorithmically from @var{dllfile} as shown in the following
28055 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28056 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28057 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28058 as shown in the following example:
28059 if @var{dllfile} is @code{xyz.dll}, the definition
28060 file used is @code{xyz.def}.
28061
28062 @item -e @var{deffile}
28063 @cindex @option{-e} (@code{gnatdll})
28064 @var{deffile} is the name of the definition file.
28065
28066 @item -g
28067 @cindex @option{-g} (@code{gnatdll})
28068 Generate debugging information. This information is stored in the object
28069 file and copied from there to the final DLL file by the linker,
28070 where it can be read by the debugger. You must use the
28071 @option{-g} switch if you plan on using the debugger or the symbolic
28072 stack traceback.
28073
28074 @item -h
28075 @cindex @option{-h} (@code{gnatdll})
28076 Help mode. Displays @code{gnatdll} switch usage information.
28077
28078 @item -Idir
28079 @cindex @option{-I} (@code{gnatdll})
28080 Direct @code{gnatdll} to search the @var{dir} directory for source and
28081 object files needed to build the DLL.
28082 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28083
28084 @item -k
28085 @cindex @option{-k} (@code{gnatdll})
28086 Removes the @code{@@}@var{nn} suffix from the import library's exported
28087 names, but keeps them for the link names. You must specify this
28088 option if you want to use a @code{Stdcall} function in a DLL for which
28089 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28090 of the Windows NT DLL for example. This option has no effect when
28091 @option{-n} option is specified.
28092
28093 @item -l @var{file}
28094 @cindex @option{-l} (@code{gnatdll})
28095 The list of ALI and object files used to build the DLL are listed in
28096 @var{file}, instead of being given in the command line. Each line in
28097 @var{file} contains the name of an ALI or object file.
28098
28099 @item -n
28100 @cindex @option{-n} (@code{gnatdll})
28101 No Import. Do not create the import library.
28102
28103 @item -q
28104 @cindex @option{-q} (@code{gnatdll})
28105 Quiet mode. Do not display unnecessary messages.
28106
28107 @item -v
28108 @cindex @option{-v} (@code{gnatdll})
28109 Verbose mode. Display extra information.
28110
28111 @item -largs @var{opts}
28112 @cindex @option{-largs} (@code{gnatdll})
28113 Linker options. Pass @var{opts} to the linker.
28114 @end table
28115
28116 @node gnatdll Example
28117 @subsubsection @code{gnatdll} Example
28118
28119 @noindent
28120 As an example the command to build a relocatable DLL from @file{api.adb}
28121 once @file{api.adb} has been compiled and @file{api.def} created is
28122
28123 @smallexample
28124 $ gnatdll -d api.dll api.ali
28125 @end smallexample
28126
28127 @noindent
28128 The above command creates two files: @file{libapi.dll.a} (the import
28129 library) and @file{api.dll} (the actual DLL). If you want to create
28130 only the DLL, just type:
28131
28132 @smallexample
28133 $ gnatdll -d api.dll -n api.ali
28134 @end smallexample
28135
28136 @noindent
28137 Alternatively if you want to create just the import library, type:
28138
28139 @smallexample
28140 $ gnatdll -d api.dll
28141 @end smallexample
28142
28143 @node gnatdll behind the Scenes
28144 @subsubsection @code{gnatdll} behind the Scenes
28145
28146 @noindent
28147 This section details the steps involved in creating a DLL. @code{gnatdll}
28148 does these steps for you. Unless you are interested in understanding what
28149 goes on behind the scenes, you should skip this section.
28150
28151 We use the previous example of a DLL containing the Ada package @code{API},
28152 to illustrate the steps necessary to build a DLL. The starting point is a
28153 set of objects that will make up the DLL and the corresponding ALI
28154 files. In the case of this example this means that @file{api.o} and
28155 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28156 the following:
28157
28158 @enumerate
28159 @item
28160 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28161 the information necessary to generate relocation information for the
28162 DLL.
28163
28164 @smallexample
28165 @group
28166 $ gnatbind -n api
28167 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28168 @end group
28169 @end smallexample
28170
28171 @noindent
28172 In addition to the base file, the @command{gnatlink} command generates an
28173 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28174 asks @command{gnatlink} to generate the routines @code{DllMain} and
28175 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28176 is loaded into memory.
28177
28178 @item
28179 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28180 export table (@file{api.exp}). The export table contains the relocation
28181 information in a form which can be used during the final link to ensure
28182 that the Windows loader is able to place the DLL anywhere in memory.
28183
28184 @smallexample
28185 @group
28186 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28187           --output-exp api.exp
28188 @end group
28189 @end smallexample
28190
28191 @item
28192 @code{gnatdll} builds the base file using the new export table. Note that
28193 @command{gnatbind} must be called once again since the binder generated file
28194 has been deleted during the previous call to @command{gnatlink}.
28195
28196 @smallexample
28197 @group
28198 $ gnatbind -n api
28199 $ gnatlink api -o api.jnk api.exp -mdll
28200       -Wl,--base-file,api.base
28201 @end group
28202 @end smallexample
28203
28204 @item
28205 @code{gnatdll} builds the new export table using the new base file and
28206 generates the DLL import library @file{libAPI.dll.a}.
28207
28208 @smallexample
28209 @group
28210 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28211           --output-exp api.exp --output-lib libAPI.a
28212 @end group
28213 @end smallexample
28214
28215 @item
28216 Finally @code{gnatdll} builds the relocatable DLL using the final export
28217 table.
28218
28219 @smallexample
28220 @group
28221 $ gnatbind -n api
28222 $ gnatlink api api.exp -o api.dll -mdll
28223 @end group
28224 @end smallexample
28225 @end enumerate
28226
28227 @node Using dlltool
28228 @subsubsection Using @code{dlltool}
28229
28230 @noindent
28231 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28232 DLLs and static import libraries. This section summarizes the most
28233 common @code{dlltool} switches. The form of the @code{dlltool} command
28234 is
28235
28236 @smallexample
28237 @c $ dlltool @ovar{switches}
28238 @c Expanding @ovar macro inline (explanation in macro def comments)
28239 $ dlltool @r{[}@var{switches}@r{]}
28240 @end smallexample
28241
28242 @noindent
28243 @code{dlltool} switches include:
28244
28245 @table @option
28246 @item --base-file @var{basefile}
28247 @cindex @option{--base-file} (@command{dlltool})
28248 Read the base file @var{basefile} generated by the linker. This switch
28249 is used to create a relocatable DLL.
28250
28251 @item --def @var{deffile}
28252 @cindex @option{--def} (@command{dlltool})
28253 Read the definition file.
28254
28255 @item --dllname @var{name}
28256 @cindex @option{--dllname} (@command{dlltool})
28257 Gives the name of the DLL. This switch is used to embed the name of the
28258 DLL in the static import library generated by @code{dlltool} with switch
28259 @option{--output-lib}.
28260
28261 @item -k
28262 @cindex @option{-k} (@command{dlltool})
28263 Kill @code{@@}@var{nn} from exported names
28264 (@pxref{Windows Calling Conventions}
28265 for a discussion about @code{Stdcall}-style symbols.
28266
28267 @item --help
28268 @cindex @option{--help} (@command{dlltool})
28269 Prints the @code{dlltool} switches with a concise description.
28270
28271 @item --output-exp @var{exportfile}
28272 @cindex @option{--output-exp} (@command{dlltool})
28273 Generate an export file @var{exportfile}. The export file contains the
28274 export table (list of symbols in the DLL) and is used to create the DLL.
28275
28276 @item --output-lib @var{libfile}
28277 @cindex @option{--output-lib} (@command{dlltool})
28278 Generate a static import library @var{libfile}.
28279
28280 @item -v
28281 @cindex @option{-v} (@command{dlltool})
28282 Verbose mode.
28283
28284 @item --as @var{assembler-name}
28285 @cindex @option{--as} (@command{dlltool})
28286 Use @var{assembler-name} as the assembler. The default is @code{as}.
28287 @end table
28288
28289 @node GNAT and Windows Resources
28290 @section GNAT and Windows Resources
28291 @cindex Resources, windows
28292
28293 @menu
28294 * Building Resources::
28295 * Compiling Resources::
28296 * Using Resources::
28297 @end menu
28298
28299 @noindent
28300 Resources are an easy way to add Windows specific objects to your
28301 application. The objects that can be added as resources include:
28302
28303 @itemize @bullet
28304 @item
28305 menus
28306
28307 @item
28308 accelerators
28309
28310 @item
28311 dialog boxes
28312
28313 @item
28314 string tables
28315
28316 @item
28317 bitmaps
28318
28319 @item
28320 cursors
28321
28322 @item
28323 icons
28324
28325 @item
28326 fonts
28327 @end itemize
28328
28329 @noindent
28330 This section explains how to build, compile and use resources.
28331
28332 @node Building Resources
28333 @subsection Building Resources
28334 @cindex Resources, building
28335
28336 @noindent
28337 A resource file is an ASCII file. By convention resource files have an
28338 @file{.rc} extension.
28339 The easiest way to build a resource file is to use Microsoft tools
28340 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28341 @code{dlgedit.exe} to build dialogs.
28342 It is always possible to build an @file{.rc} file yourself by writing a
28343 resource script.
28344
28345 It is not our objective to explain how to write a resource file. A
28346 complete description of the resource script language can be found in the
28347 Microsoft documentation.
28348
28349 @node Compiling Resources
28350 @subsection Compiling Resources
28351 @findex rc
28352 @findex windres
28353 @cindex Resources, compiling
28354
28355 @noindent
28356 This section describes how to build a GNAT-compatible (COFF) object file
28357 containing the resources. This is done using the Resource Compiler
28358 @code{windres} as follows:
28359
28360 @smallexample
28361 $ windres -i myres.rc -o myres.o
28362 @end smallexample
28363
28364 @noindent
28365 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28366 file. You can specify an alternate preprocessor (usually named
28367 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28368 parameter. A list of all possible options may be obtained by entering
28369 the command @code{windres} @option{--help}.
28370
28371 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28372 to produce a @file{.res} file (binary resource file). See the
28373 corresponding Microsoft documentation for further details. In this case
28374 you need to use @code{windres} to translate the @file{.res} file to a
28375 GNAT-compatible object file as follows:
28376
28377 @smallexample
28378 $ windres -i myres.res -o myres.o
28379 @end smallexample
28380
28381 @node Using Resources
28382 @subsection Using Resources
28383 @cindex Resources, using
28384
28385 @noindent
28386 To include the resource file in your program just add the
28387 GNAT-compatible object file for the resource(s) to the linker
28388 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28389 option:
28390
28391 @smallexample
28392 $ gnatmake myprog -largs myres.o
28393 @end smallexample
28394
28395 @node Debugging a DLL
28396 @section Debugging a DLL
28397 @cindex DLL debugging
28398
28399 @menu
28400 * Program and DLL Both Built with GCC/GNAT::
28401 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28402 @end menu
28403
28404 @noindent
28405 Debugging a DLL is similar to debugging a standard program. But
28406 we have to deal with two different executable parts: the DLL and the
28407 program that uses it. We have the following four possibilities:
28408
28409 @enumerate 1
28410 @item
28411 The program and the DLL are built with @code{GCC/GNAT}.
28412 @item
28413 The program is built with foreign tools and the DLL is built with
28414 @code{GCC/GNAT}.
28415 @item
28416 The program is built with @code{GCC/GNAT} and the DLL is built with
28417 foreign tools.
28418 @item
28419 @end enumerate
28420
28421 @noindent
28422 In this section we address only cases one and two above.
28423 There is no point in trying to debug
28424 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28425 information in it. To do so you must use a debugger compatible with the
28426 tools suite used to build the DLL.
28427
28428 @node Program and DLL Both Built with GCC/GNAT
28429 @subsection Program and DLL Both Built with GCC/GNAT
28430
28431 @noindent
28432 This is the simplest case. Both the DLL and the program have @code{GDB}
28433 compatible debugging information. It is then possible to break anywhere in
28434 the process. Let's suppose here that the main procedure is named
28435 @code{ada_main} and that in the DLL there is an entry point named
28436 @code{ada_dll}.
28437
28438 @noindent
28439 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28440 program must have been built with the debugging information (see GNAT -g
28441 switch). Here are the step-by-step instructions for debugging it:
28442
28443 @enumerate 1
28444 @item Launch @code{GDB} on the main program.
28445
28446 @smallexample
28447 $ gdb -nw ada_main
28448 @end smallexample
28449
28450 @item Start the program and stop at the beginning of the main procedure
28451
28452 @smallexample
28453 (gdb) start
28454 @end smallexample
28455
28456 @noindent
28457 This step is required to be able to set a breakpoint inside the DLL. As long
28458 as the program is not run, the DLL is not loaded. This has the
28459 consequence that the DLL debugging information is also not loaded, so it is not
28460 possible to set a breakpoint in the DLL.
28461
28462 @item Set a breakpoint inside the DLL
28463
28464 @smallexample
28465 (gdb) break ada_dll
28466 (gdb) cont
28467 @end smallexample
28468
28469 @end enumerate
28470
28471 @noindent
28472 At this stage a breakpoint is set inside the DLL. From there on
28473 you can use the standard approach to debug the whole program
28474 (@pxref{Running and Debugging Ada Programs}).
28475
28476 @ignore
28477 @c This used to work, probably because the DLLs were non-relocatable
28478 @c keep this section around until the problem is sorted out.
28479
28480 To break on the @code{DllMain} routine it is not possible to follow
28481 the procedure above. At the time the program stop on @code{ada_main}
28482 the @code{DllMain} routine as already been called. Either you can use
28483 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28484
28485 @enumerate 1
28486 @item Launch @code{GDB} on the main program.
28487
28488 @smallexample
28489 $ gdb ada_main
28490 @end smallexample
28491
28492 @item Load DLL symbols
28493
28494 @smallexample
28495 (gdb) add-sym api.dll
28496 @end smallexample
28497
28498 @item Set a breakpoint inside the DLL
28499
28500 @smallexample
28501 (gdb) break ada_dll.adb:45
28502 @end smallexample
28503
28504 Note that at this point it is not possible to break using the routine symbol
28505 directly as the program is not yet running. The solution is to break
28506 on the proper line (break in @file{ada_dll.adb} line 45).
28507
28508 @item Start the program
28509
28510 @smallexample
28511 (gdb) run
28512 @end smallexample
28513
28514 @end enumerate
28515 @end ignore
28516
28517 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28518 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28519
28520 @menu
28521 * Debugging the DLL Directly::
28522 * Attaching to a Running Process::
28523 @end menu
28524
28525 @noindent
28526 In this case things are slightly more complex because it is not possible to
28527 start the main program and then break at the beginning to load the DLL and the
28528 associated DLL debugging information. It is not possible to break at the
28529 beginning of the program because there is no @code{GDB} debugging information,
28530 and therefore there is no direct way of getting initial control. This
28531 section addresses this issue by describing some methods that can be used
28532 to break somewhere in the DLL to debug it.
28533
28534 @noindent
28535 First suppose that the main procedure is named @code{main} (this is for
28536 example some C code built with Microsoft Visual C) and that there is a
28537 DLL named @code{test.dll} containing an Ada entry point named
28538 @code{ada_dll}.
28539
28540 @noindent
28541 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28542 been built with debugging information (see GNAT -g option).
28543
28544 @node Debugging the DLL Directly
28545 @subsubsection Debugging the DLL Directly
28546
28547 @enumerate 1
28548 @item
28549 Find out the executable starting address
28550
28551 @smallexample
28552 $ objdump --file-header main.exe
28553 @end smallexample
28554
28555 The starting address is reported on the last line. For example:
28556
28557 @smallexample
28558 main.exe:     file format pei-i386
28559 architecture: i386, flags 0x0000010a:
28560 EXEC_P, HAS_DEBUG, D_PAGED
28561 start address 0x00401010
28562 @end smallexample
28563
28564 @item
28565 Launch the debugger on the executable.
28566
28567 @smallexample
28568 $ gdb main.exe
28569 @end smallexample
28570
28571 @item
28572 Set a breakpoint at the starting address, and launch the program.
28573
28574 @smallexample
28575 $ (gdb) break *0x00401010
28576 $ (gdb) run
28577 @end smallexample
28578
28579 The program will stop at the given address.
28580
28581 @item
28582 Set a breakpoint on a DLL subroutine.
28583
28584 @smallexample
28585 (gdb) break ada_dll.adb:45
28586 @end smallexample
28587
28588 Or if you want to break using a symbol on the DLL, you need first to
28589 select the Ada language (language used by the DLL).
28590
28591 @smallexample
28592 (gdb) set language ada
28593 (gdb) break ada_dll
28594 @end smallexample
28595
28596 @item
28597 Continue the program.
28598
28599 @smallexample
28600 (gdb) cont
28601 @end smallexample
28602
28603 @noindent
28604 This will run the program until it reaches the breakpoint that has been
28605 set. From that point you can use the standard way to debug a program
28606 as described in (@pxref{Running and Debugging Ada Programs}).
28607
28608 @end enumerate
28609
28610 @noindent
28611 It is also possible to debug the DLL by attaching to a running process.
28612
28613 @node Attaching to a Running Process
28614 @subsubsection Attaching to a Running Process
28615 @cindex DLL debugging, attach to process
28616
28617 @noindent
28618 With @code{GDB} it is always possible to debug a running process by
28619 attaching to it. It is possible to debug a DLL this way. The limitation
28620 of this approach is that the DLL must run long enough to perform the
28621 attach operation. It may be useful for instance to insert a time wasting
28622 loop in the code of the DLL to meet this criterion.
28623
28624 @enumerate 1
28625
28626 @item Launch the main program @file{main.exe}.
28627
28628 @smallexample
28629 $ main
28630 @end smallexample
28631
28632 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28633 that the process PID for @file{main.exe} is 208.
28634
28635 @item Launch gdb.
28636
28637 @smallexample
28638 $ gdb
28639 @end smallexample
28640
28641 @item Attach to the running process to be debugged.
28642
28643 @smallexample
28644 (gdb) attach 208
28645 @end smallexample
28646
28647 @item Load the process debugging information.
28648
28649 @smallexample
28650 (gdb) symbol-file main.exe
28651 @end smallexample
28652
28653 @item Break somewhere in the DLL.
28654
28655 @smallexample
28656 (gdb) break ada_dll
28657 @end smallexample
28658
28659 @item Continue process execution.
28660
28661 @smallexample
28662 (gdb) cont
28663 @end smallexample
28664
28665 @end enumerate
28666
28667 @noindent
28668 This last step will resume the process execution, and stop at
28669 the breakpoint we have set. From there you can use the standard
28670 approach to debug a program as described in
28671 (@pxref{Running and Debugging Ada Programs}).
28672
28673 @node Setting Stack Size from gnatlink
28674 @section Setting Stack Size from @command{gnatlink}
28675
28676 @noindent
28677 It is possible to specify the program stack size at link time. On modern
28678 versions of Windows, starting with XP, this is mostly useful to set the size of
28679 the main stack (environment task). The other task stacks are set with pragma
28680 Storage_Size or with the @command{gnatbind -d} command.
28681
28682 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28683 reserve size of individual tasks, the link-time stack size applies to all
28684 tasks, and pragma Storage_Size has no effect.
28685 In particular, Stack Overflow checks are made against this
28686 link-time specified size.
28687
28688 This setting can be done with
28689 @command{gnatlink} using either:
28690
28691 @itemize @bullet
28692
28693 @item using @option{-Xlinker} linker option
28694
28695 @smallexample
28696 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28697 @end smallexample
28698
28699 This sets the stack reserve size to 0x10000 bytes and the stack commit
28700 size to 0x1000 bytes.
28701
28702 @item using @option{-Wl} linker option
28703
28704 @smallexample
28705 $ gnatlink hello -Wl,--stack=0x1000000
28706 @end smallexample
28707
28708 This sets the stack reserve size to 0x1000000 bytes. Note that with
28709 @option{-Wl} option it is not possible to set the stack commit size
28710 because the coma is a separator for this option.
28711
28712 @end itemize
28713
28714 @node Setting Heap Size from gnatlink
28715 @section Setting Heap Size from @command{gnatlink}
28716
28717 @noindent
28718 Under Windows systems, it is possible to specify the program heap size from
28719 @command{gnatlink} using either:
28720
28721 @itemize @bullet
28722
28723 @item using @option{-Xlinker} linker option
28724
28725 @smallexample
28726 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28727 @end smallexample
28728
28729 This sets the heap reserve size to 0x10000 bytes and the heap commit
28730 size to 0x1000 bytes.
28731
28732 @item using @option{-Wl} linker option
28733
28734 @smallexample
28735 $ gnatlink hello -Wl,--heap=0x1000000
28736 @end smallexample
28737
28738 This sets the heap reserve size to 0x1000000 bytes. Note that with
28739 @option{-Wl} option it is not possible to set the heap commit size
28740 because the coma is a separator for this option.
28741
28742 @end itemize
28743
28744 @end ifset
28745
28746 @c **********************************
28747 @c * GNU Free Documentation License *
28748 @c **********************************
28749 @include fdl.texi
28750 @c GNU Free Documentation License
28751
28752 @node Index,,GNU Free Documentation License, Top
28753 @unnumbered Index
28754
28755 @printindex cp
28756
28757 @contents
28758 @c Put table of contents at end, otherwise it precedes the "title page" in
28759 @c the .txt version
28760 @c Edit the pdf file to move the contents to the beginning, after the title
28761 @c page
28762
28763 @bye