OSDN Git Service

2011-12-02 Thomas Quinot <quinot@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           Copyright (C) 1992-2011, Free Software Foundation, Inc.          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 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Creating Unit Tests Using gnattest::
196 * Generating Ada Bindings for C and C++ headers::
197 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
199 @ifclear vms
200 * Code Coverage and Profiling::
201 @end ifclear
202 @ifset vms
203 * Compatibility with HP Ada::
204 @end ifset
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Conditional Compilation::
209 * Inline Assembler::
210 * Compatibility and Porting Guide::
211 @ifset unw
212 * Microsoft Windows Topics::
213 @end ifset
214 * GNU Free Documentation License::
215 * Index::
216
217  --- The Detailed Node Listing ---
218
219 About This Guide
220
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
224 * Conventions::
225
226 Getting Started with GNAT
227
228 * Running GNAT::
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
232 @ifset vms
233 * Editing with Emacs::
234 @end ifset
235 @ifclear vms
236 * Introduction to GPS::
237 @end ifclear
238
239 The GNAT Compilation Model
240
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
251 @ifclear vms
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
254 @end ifclear
255 * Comparison between GNAT and Conventional Ada Library Models::
256 @ifset vms
257 * Placement of temporary files::
258 @end ifset
259
260 Foreign Language Representation
261
262 * Latin-1::
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
265
266 Compiling Ada Programs With gcc
267
268 * Compiling Programs::
269 * Switches for gcc::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
272 * Examples::
273
274 Switches for gcc
275
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
280 * Style Checking::
281 * Run-Time Checks::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
293 @ifset vms
294 * Return Codes::
295 @end ifset
296
297 Binding Ada Programs With gnatbind
298
299 * Running gnatbind::
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
304
305 Switches for gnatbind
306
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
310 * Output Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
313
314 Linking Using gnatlink
315
316 * Running gnatlink::
317 * Switches for gnatlink::
318
319 The GNAT Make Program gnatmake
320
321 * Running gnatmake::
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
327
328 Improving Performance
329 * Performance Considerations::
330 * Text_IO Suggestions::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
333
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Vectorization of loops::
341 * Other Optimization Switches::
342 * Optimization and Strict Aliasing::
343 @ifset vms
344 * Coverage Analysis::
345 @end ifset
346
347 Reducing Size of Ada Executables with gnatelim
348 * About gnatelim::
349 * Running gnatelim::
350 * Processing Precompiled Libraries::
351 * Correcting the List of Eliminate Pragmas::
352 * Making Your Executables Smaller::
353 * Summary of the gnatelim Usage Cycle::
354
355 Reducing Size of Executables with unused subprogram/data elimination
356 * About unused subprogram/data elimination::
357 * Compilation options::
358
359 Renaming Files Using gnatchop
360
361 * Handling Files with Multiple Units::
362 * Operating gnatchop in Compilation Mode::
363 * Command Line for gnatchop::
364 * Switches for gnatchop::
365 * Examples of gnatchop Usage::
366
367 Configuration Pragmas
368
369 * Handling of Configuration Pragmas::
370 * The Configuration Pragmas Files::
371
372 Handling Arbitrary File Naming Conventions Using gnatname
373
374 * Arbitrary File Naming Conventions::
375 * Running gnatname::
376 * Switches for gnatname::
377 * Examples of gnatname Usage::
378
379 The Cross-Referencing Tools gnatxref and gnatfind
380
381 * Switches for gnatxref::
382 * Switches for gnatfind::
383 * Project Files for gnatxref and gnatfind::
384 * Regular Expressions in gnatfind and gnatxref::
385 * Examples of gnatxref Usage::
386 * Examples of gnatfind Usage::
387
388 The GNAT Pretty-Printer gnatpp
389
390 * Switches for gnatpp::
391 * Formatting Rules::
392
393 The GNAT Metrics Tool gnatmetric
394
395 * Switches for gnatmetric::
396
397 File Name Krunching Using gnatkr
398
399 * About gnatkr::
400 * Using gnatkr::
401 * Krunching Method::
402 * Examples of gnatkr Usage::
403
404 Preprocessing Using gnatprep
405 * Preprocessing Symbols::
406 * Using gnatprep::
407 * Switches for gnatprep::
408 * Form of Definitions File::
409 * Form of Input Text for gnatprep::
410
411 The GNAT Library Browser gnatls
412
413 * Running gnatls::
414 * Switches for gnatls::
415 * Examples of gnatls Usage::
416
417 Cleaning Up Using gnatclean
418
419 * Running gnatclean::
420 * Switches for gnatclean::
421 @c * Examples of gnatclean Usage::
422
423 @ifclear vms
424
425 GNAT and Libraries
426
427 * Introduction to Libraries in GNAT::
428 * General Ada Libraries::
429 * Stand-alone Ada Libraries::
430 * Rebuilding the GNAT Run-Time Library::
431
432 Using the GNU make Utility
433
434 * Using gnatmake in a Makefile::
435 * Automatically Creating a List of Directories::
436 * Generating the Command Line Switches::
437 * Overcoming Command Line Length Limits::
438 @end ifclear
439
440 Memory Management Issues
441
442 * Some Useful Memory Pools::
443 * The GNAT Debug Pool Facility::
444 @ifclear vms
445 * The gnatmem Tool::
446 @end ifclear
447
448 Stack Related Facilities
449
450 * Stack Overflow Checking::
451 * Static Stack Usage Analysis::
452 * Dynamic Stack Usage Analysis::
453
454 Some Useful Memory Pools
455
456 The GNAT Debug Pool Facility
457
458 @ifclear vms
459 The gnatmem Tool
460
461 * Running gnatmem::
462 * Switches for gnatmem::
463 * Example of gnatmem Usage::
464 @end ifclear
465
466 Verifying Properties Using gnatcheck
467
468 Sample Bodies Using gnatstub
469
470 * Running gnatstub::
471 * Switches for gnatstub::
472
473 Creating Unit Tests Using gnattest
474
475 * Running gnattest::
476 * Switches for gnattest::
477 * Project Attributes for gnattest::
478 * Simple Example::
479 * Setting Up and Tearing Down the Testing Environment::
480 * Regenerating Tests::
481 * Default Test Behavior::
482 * Testing Primitive Operations of Tagged Types::
483 * Testing Inheritance::
484 * Tagged Types Substitutability Testing::
485 * Testing with Contracts::
486 * Additional Tests::
487 * Current Limitations::
488
489 Other Utility Programs
490
491 * Using Other Utility Programs with GNAT::
492 * The External Symbol Naming Scheme of GNAT::
493 * Converting Ada Files to html with gnathtml::
494
495 @ifclear vms
496 Code Coverage and Profiling
497
498 * Code Coverage of Ada Programs using gcov::
499 * Profiling an Ada Program using gprof::
500 @end ifclear
501
502 Running and Debugging Ada Programs
503
504 * The GNAT Debugger GDB::
505 * Running GDB::
506 * Introduction to GDB Commands::
507 * Using Ada Expressions::
508 * Calling User-Defined Subprograms::
509 * Using the Next Command in a Function::
510 * Ada Exceptions::
511 * Ada Tasks::
512 * Debugging Generic Units::
513 * Remote Debugging using gdbserver::
514 * GNAT Abnormal Termination or Failure to Terminate::
515 * Naming Conventions for GNAT Source Files::
516 * Getting Internal Debugging Information::
517 * Stack Traceback::
518
519 @ifset vms
520 * LSE::
521 @end ifset
522
523 @ifset vms
524 Compatibility with HP Ada
525
526 * Ada Language Compatibility::
527 * Differences in the Definition of Package System::
528 * Language-Related Features::
529 * The Package STANDARD::
530 * The Package SYSTEM::
531 * Tasking and Task-Related Features::
532 * Pragmas and Pragma-Related Features::
533 * Library of Predefined Units::
534 * Bindings::
535 * Main Program Definition::
536 * Implementation-Defined Attributes::
537 * Compiler and Run-Time Interfacing::
538 * Program Compilation and Library Management::
539 * Input-Output::
540 * Implementation Limits::
541 * Tools and Utilities::
542
543 Language-Related Features
544
545 * Integer Types and Representations::
546 * Floating-Point Types and Representations::
547 * Pragmas Float_Representation and Long_Float::
548 * Fixed-Point Types and Representations::
549 * Record and Array Component Alignment::
550 * Address Clauses::
551 * Other Representation Clauses::
552
553 Tasking and Task-Related Features
554
555 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
556 * Assigning Task IDs::
557 * Task IDs and Delays::
558 * Task-Related Pragmas::
559 * Scheduling and Task Priority::
560 * The Task Stack::
561 * External Interrupts::
562
563 Pragmas and Pragma-Related Features
564
565 * Restrictions on the Pragma INLINE::
566 * Restrictions on the Pragma INTERFACE::
567 * Restrictions on the Pragma SYSTEM_NAME::
568
569 Library of Predefined Units
570
571 * Changes to DECLIB::
572
573 Bindings
574
575 * Shared Libraries and Options Files::
576 * Interfaces to C::
577 @end ifset
578
579 Platform-Specific Information for the Run-Time Libraries
580
581 * Summary of Run-Time Configurations::
582 * Specifying a Run-Time Library::
583 * Choosing the Scheduling Policy::
584 * Solaris-Specific Considerations::
585 * Linux-Specific Considerations::
586 * AIX-Specific Considerations::
587 * Irix-Specific Considerations::
588 * RTX-Specific Considerations::
589 * HP-UX-Specific Considerations::
590
591 Example of Binder Output File
592
593 Elaboration Order Handling in GNAT
594
595 * Elaboration Code::
596 * Checking the Elaboration Order::
597 * Controlling the Elaboration Order::
598 * Controlling Elaboration in GNAT - Internal Calls::
599 * Controlling Elaboration in GNAT - External Calls::
600 * Default Behavior in GNAT - Ensuring Safety::
601 * Treatment of Pragma Elaborate::
602 * Elaboration Issues for Library Tasks::
603 * Mixing Elaboration Models::
604 * What to Do If the Default Elaboration Behavior Fails::
605 * Elaboration for Access-to-Subprogram Values::
606 * Summary of Procedures for Elaboration Control::
607 * Other Elaboration Order Considerations::
608
609 Conditional Compilation
610 * Use of Boolean Constants::
611 * Debugging - A Special Case::
612 * Conditionalizing Declarations::
613 * Use of Alternative Implementations::
614 * Preprocessing::
615
616 Inline Assembler
617
618 * Basic Assembler Syntax::
619 * A Simple Example of Inline Assembler::
620 * Output Variables in Inline Assembler::
621 * Input Variables in Inline Assembler::
622 * Inlining Inline Assembler Code::
623 * Other Asm Functionality::
624
625 Compatibility and Porting Guide
626
627 * Compatibility with Ada 83::
628 * Compatibility between Ada 95 and Ada 2005::
629 * Implementation-dependent characteristics::
630 @ifclear vms
631 @c This brief section is only in the non-VMS version
632 @c The complete chapter on HP Ada issues is in the VMS version
633 * Compatibility with HP Ada 83::
634 @end ifclear
635 * Compatibility with Other Ada Systems::
636 * Representation Clauses::
637 @ifset vms
638 * Transitioning to 64-Bit GNAT for OpenVMS::
639 @end ifset
640
641 @ifset unw
642 Microsoft Windows Topics
643
644 * Using GNAT on Windows::
645 * CONSOLE and WINDOWS subsystems::
646 * Temporary Files::
647 * Mixed-Language Programming on Windows::
648 * Windows Calling Conventions::
649 * Introduction to Dynamic Link Libraries (DLLs)::
650 * Using DLLs with GNAT::
651 * Building DLLs with GNAT::
652 * GNAT and Windows Resources::
653 * Debugging a DLL::
654 * Setting Stack Size from gnatlink::
655 * Setting Heap Size from gnatlink::
656 @end ifset
657
658 * Index::
659 @end menu
660 @end ifnottex
661
662 @node About This Guide
663 @unnumbered About This Guide
664
665 @noindent
666 @ifset vms
667 This guide describes the use of @value{EDITION},
668 a compiler and software development toolset for the full Ada
669 programming language, implemented on OpenVMS for HP's Alpha and
670 Integrity server (I64) platforms.
671 @end ifset
672 @ifclear vms
673 This guide describes the use of @value{EDITION},
674 a compiler and software development
675 toolset for the full Ada programming language.
676 @end ifclear
677 It documents the features of the compiler and tools, and explains
678 how to use them to build Ada applications.
679
680 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
681 Ada 83 compatibility mode.
682 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
683 but you can override with a compiler switch
684 (@pxref{Compiling Different Versions of Ada})
685 to explicitly specify the language version.
686 Throughout this manual, references to ``Ada'' without a year suffix
687 apply to both the Ada 95 and Ada 2005 versions of the language.
688
689
690 @ifclear FSFEDITION
691 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
692 ``GNAT'' in the remainder of this document.
693 @end ifclear
694
695
696
697
698 @menu
699 * What This Guide Contains::
700 * What You Should Know before Reading This Guide::
701 * Related Information::
702 * Conventions::
703 @end menu
704
705 @node What This Guide Contains
706 @unnumberedsec What This Guide Contains
707
708 @noindent
709 This guide contains the following chapters:
710 @itemize @bullet
711
712 @item
713 @ref{Getting Started with GNAT}, describes how to get started compiling
714 and running Ada programs with the GNAT Ada programming environment.
715 @item
716 @ref{The GNAT Compilation Model}, describes the compilation model used
717 by GNAT.
718
719 @item
720 @ref{Compiling Using gcc}, describes how to compile
721 Ada programs with @command{gcc}, the Ada compiler.
722
723 @item
724 @ref{Binding Using gnatbind}, describes how to
725 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
726 utility.
727
728 @item
729 @ref{Linking Using gnatlink},
730 describes @command{gnatlink}, a
731 program that provides for linking using the GNAT run-time library to
732 construct a program. @command{gnatlink} can also incorporate foreign language
733 object units into the executable.
734
735 @item
736 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
737 utility that automatically determines the set of sources
738 needed by an Ada compilation unit, and executes the necessary compilations
739 binding and link.
740
741 @item
742 @ref{Improving Performance}, shows various techniques for making your
743 Ada program run faster or take less space.
744 It discusses the effect of the compiler's optimization switch and
745 also describes the @command{gnatelim} tool and unused subprogram/data
746 elimination.
747
748 @item
749 @ref{Renaming Files Using gnatchop}, describes
750 @code{gnatchop}, a utility that allows you to preprocess a file that
751 contains Ada source code, and split it into one or more new files, one
752 for each compilation unit.
753
754 @item
755 @ref{Configuration Pragmas}, describes the configuration pragmas
756 handled by GNAT.
757
758 @item
759 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
760 shows how to override the default GNAT file naming conventions,
761 either for an individual unit or globally.
762
763 @item
764 @ref{GNAT Project Manager}, describes how to use project files
765 to organize large projects.
766
767 @item
768 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
769 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
770 way to navigate through sources.
771
772 @item
773 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
774 version of an Ada source file with control over casing, indentation,
775 comment placement, and other elements of program presentation style.
776
777 @item
778 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
779 metrics for an Ada source file, such as the number of types and subprograms,
780 and assorted complexity measures.
781
782 @item
783 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
784 file name krunching utility, used to handle shortened
785 file names on operating systems with a limit on the length of names.
786
787 @item
788 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
789 preprocessor utility that allows a single source file to be used to
790 generate multiple or parameterized source files by means of macro
791 substitution.
792
793 @item
794 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
795 utility that displays information about compiled units, including dependences
796 on the corresponding sources files, and consistency of compilations.
797
798 @item
799 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
800 to delete files that are produced by the compiler, binder and linker.
801
802 @ifclear vms
803 @item
804 @ref{GNAT and Libraries}, describes the process of creating and using
805 Libraries with GNAT. It also describes how to recompile the GNAT run-time
806 library.
807
808 @item
809 @ref{Using the GNU make Utility}, describes some techniques for using
810 the GNAT toolset in Makefiles.
811 @end ifclear
812
813 @item
814 @ref{Memory Management Issues}, describes some useful predefined storage pools
815 and in particular the GNAT Debug Pool facility, which helps detect incorrect
816 memory references.
817 @ifclear vms
818 It also describes @command{gnatmem}, a utility that monitors dynamic
819 allocation and deallocation and helps detect ``memory leaks''.
820 @end ifclear
821
822 @item
823 @ref{Stack Related Facilities}, describes some useful tools associated with
824 stack checking and analysis.
825
826 @item
827 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
828 a utility that checks Ada code against a set of rules.
829
830 @item
831 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
832 a utility that generates empty but compilable bodies for library units.
833
834 @item
835 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
836 a utility that generates unit testing templates for library units.
837
838 @item
839 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
840 generate automatically Ada bindings from C and C++ headers.
841
842 @item
843 @ref{Other Utility Programs}, discusses several other GNAT utilities,
844 including @code{gnathtml}.
845
846 @ifclear vms
847 @item
848 @ref{Code Coverage and Profiling}, describes how to perform a structural
849 coverage and profile the execution of Ada programs.
850 @end ifclear
851
852 @item
853 @ref{Running and Debugging Ada Programs}, describes how to run and debug
854 Ada programs.
855
856 @ifset vms
857 @item
858 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
859 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
860 developed by Digital Equipment Corporation and currently supported by HP.}
861 for OpenVMS Alpha. This product was formerly known as DEC Ada,
862 @cindex DEC Ada
863 and for
864 historical compatibility reasons, the relevant libraries still use the
865 DEC prefix.
866 @end ifset
867
868 @item
869 @ref{Platform-Specific Information for the Run-Time Libraries},
870 describes the various run-time
871 libraries supported by GNAT on various platforms and explains how to
872 choose a particular library.
873
874 @item
875 @ref{Example of Binder Output File}, shows the source code for the binder
876 output file for a sample program.
877
878 @item
879 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
880 you deal with elaboration order issues.
881
882 @item
883 @ref{Conditional Compilation}, describes how to model conditional compilation,
884 both with Ada in general and with GNAT facilities in particular.
885
886 @item
887 @ref{Inline Assembler}, shows how to use the inline assembly facility
888 in an Ada program.
889
890 @item
891 @ref{Compatibility and Porting Guide}, contains sections on compatibility
892 of GNAT with other Ada development environments (including Ada 83 systems),
893 to assist in porting code from those environments.
894
895 @ifset unw
896 @item
897 @ref{Microsoft Windows Topics}, presents information relevant to the
898 Microsoft Windows platform.
899 @end ifset
900 @end itemize
901
902 @c *************************************************
903 @node What You Should Know before Reading This Guide
904 @c *************************************************
905 @unnumberedsec What You Should Know before Reading This Guide
906
907 @cindex Ada 95 Language Reference Manual
908 @cindex Ada 2005 Language Reference Manual
909 @noindent
910 This guide assumes a basic familiarity with the Ada 95 language, as
911 described in the International Standard ANSI/ISO/IEC-8652:1995, January
912 1995.
913 It does not require knowledge of the new features introduced by Ada 2005,
914 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
915 and Amendment 1).
916 Both reference manuals are included in the GNAT documentation
917 package.
918
919 @node Related Information
920 @unnumberedsec Related Information
921
922 @noindent
923 For further information about related tools, refer to the following
924 documents:
925
926 @itemize @bullet
927 @item
928 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
929 Reference Manual}, which contains all reference material for the GNAT
930 implementation of Ada.
931
932 @ifset unw
933 @item
934 @cite{Using the GNAT Programming Studio}, which describes the GPS
935 Integrated Development Environment.
936
937 @item
938 @cite{GNAT Programming Studio Tutorial}, which introduces the
939 main GPS features through examples.
940 @end ifset
941
942 @item
943 @cite{Ada 95 Reference Manual}, which contains reference
944 material for the Ada 95 programming language.
945
946 @item
947 @cite{Ada 2005 Reference Manual}, which contains reference
948 material for the Ada 2005 programming language.
949
950 @item
951 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
952 @ifset vms
953 in the GNU:[DOCS] directory,
954 @end ifset
955 for all details on the use of the GNU source-level debugger.
956
957 @item
958 @xref{Top,, The extensible self-documenting text editor, emacs,
959 GNU Emacs Manual},
960 @ifset vms
961 located in the GNU:[DOCS] directory if the EMACS kit is installed,
962 @end ifset
963 for full information on the extensible editor and programming
964 environment Emacs.
965
966 @end itemize
967
968 @c **************
969 @node Conventions
970 @unnumberedsec Conventions
971 @cindex Conventions
972 @cindex Typographical conventions
973
974 @noindent
975 Following are examples of the typographical and graphic conventions used
976 in this guide:
977
978 @itemize @bullet
979 @item
980 @code{Functions}, @command{utility program names}, @code{standard names},
981 and @code{classes}.
982
983 @item
984 @option{Option flags}
985
986 @item
987 @file{File names}, @samp{button names}, and @samp{field names}.
988
989 @item
990 @code{Variables}, @env{environment variables}, and @var{metasyntactic
991 variables}.
992
993 @item
994 @emph{Emphasis}.
995
996 @item
997 @r{[}optional information or parameters@r{]}
998
999 @item
1000 Examples are described by text
1001 @smallexample
1002 and then shown this way.
1003 @end smallexample
1004 @end itemize
1005
1006 @noindent
1007 Commands that are entered by the user are preceded in this manual by the
1008 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1009 uses this sequence as a prompt, then the commands will appear exactly as
1010 you see them in the manual. If your system uses some other prompt, then
1011 the command will appear with the @code{$} replaced by whatever prompt
1012 character you are using.
1013
1014 @ifset unw
1015 Full file names are shown with the ``@code{/}'' character
1016 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1017 If you are using GNAT on a Windows platform, please note that
1018 the ``@code{\}'' character should be used instead.
1019 @end ifset
1020
1021 @c ****************************
1022 @node Getting Started with GNAT
1023 @chapter Getting Started with GNAT
1024
1025 @noindent
1026 This chapter describes some simple ways of using GNAT to build
1027 executable Ada programs.
1028 @ifset unw
1029 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1030 show how to use the command line environment.
1031 @ref{Introduction to GPS}, provides a brief
1032 introduction to the GNAT Programming Studio, a visually-oriented
1033 Integrated Development Environment for GNAT.
1034 GPS offers a graphical ``look and feel'', support for development in
1035 other programming languages, comprehensive browsing features, and
1036 many other capabilities.
1037 For information on GPS please refer to
1038 @cite{Using the GNAT Programming Studio}.
1039 @end ifset
1040
1041 @menu
1042 * Running GNAT::
1043 * Running a Simple Ada Program::
1044 * Running a Program with Multiple Units::
1045 * Using the gnatmake Utility::
1046 @ifset vms
1047 * Editing with Emacs::
1048 @end ifset
1049 @ifclear vms
1050 * Introduction to GPS::
1051 @end ifclear
1052 @end menu
1053
1054 @node Running GNAT
1055 @section Running GNAT
1056
1057 @noindent
1058 Three steps are needed to create an executable file from an Ada source
1059 file:
1060
1061 @enumerate
1062 @item
1063 The source file(s) must be compiled.
1064 @item
1065 The file(s) must be bound using the GNAT binder.
1066 @item
1067 All appropriate object files must be linked to produce an executable.
1068 @end enumerate
1069
1070 @noindent
1071 All three steps are most commonly handled by using the @command{gnatmake}
1072 utility program that, given the name of the main program, automatically
1073 performs the necessary compilation, binding and linking steps.
1074
1075 @node Running a Simple Ada Program
1076 @section Running a Simple Ada Program
1077
1078 @noindent
1079 Any text editor may be used to prepare an Ada program.
1080 (If @code{Emacs} is
1081 used, the optional Ada mode may be helpful in laying out the program.)
1082 The
1083 program text is a normal text file. We will assume in our initial
1084 example that you have used your editor to prepare the following
1085 standard format text file:
1086
1087 @smallexample @c ada
1088 @cartouche
1089 with Ada.Text_IO; use Ada.Text_IO;
1090 procedure Hello is
1091 begin
1092    Put_Line ("Hello WORLD!");
1093 end Hello;
1094 @end cartouche
1095 @end smallexample
1096
1097 @noindent
1098 This file should be named @file{hello.adb}.
1099 With the normal default file naming conventions, GNAT requires
1100 that each file
1101 contain a single compilation unit whose file name is the
1102 unit name,
1103 with periods replaced by hyphens; the
1104 extension is @file{ads} for a
1105 spec and @file{adb} for a body.
1106 You can override this default file naming convention by use of the
1107 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1108 Alternatively, if you want to rename your files according to this default
1109 convention, which is probably more convenient if you will be using GNAT
1110 for all your compilations, then the @code{gnatchop} utility
1111 can be used to generate correctly-named source files
1112 (@pxref{Renaming Files Using gnatchop}).
1113
1114 You can compile the program using the following command (@code{$} is used
1115 as the command prompt in the examples in this document):
1116
1117 @smallexample
1118 $ gcc -c hello.adb
1119 @end smallexample
1120
1121 @noindent
1122 @command{gcc} is the command used to run the compiler. This compiler is
1123 capable of compiling programs in several languages, including Ada and
1124 C. It assumes that you have given it an Ada program if the file extension is
1125 either @file{.ads} or @file{.adb}, and it will then call
1126 the GNAT compiler to compile the specified file.
1127
1128 @ifclear vms
1129 The @option{-c} switch is required. It tells @command{gcc} to only do a
1130 compilation. (For C programs, @command{gcc} can also do linking, but this
1131 capability is not used directly for Ada programs, so the @option{-c}
1132 switch must always be present.)
1133 @end ifclear
1134
1135 This compile command generates a file
1136 @file{hello.o}, which is the object
1137 file corresponding to your Ada program. It also generates
1138 an ``Ada Library Information'' file @file{hello.ali},
1139 which contains additional information used to check
1140 that an Ada program is consistent.
1141 To build an executable file,
1142 use @code{gnatbind} to bind the program
1143 and @command{gnatlink} to link it. The
1144 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1145 @file{ALI} file, but the default extension of @file{.ali} can
1146 be omitted. This means that in the most common case, the argument
1147 is simply the name of the main program:
1148
1149 @smallexample
1150 $ gnatbind hello
1151 $ gnatlink hello
1152 @end smallexample
1153
1154 @noindent
1155 A simpler method of carrying out these steps is to use
1156 @command{gnatmake},
1157 a master program that invokes all the required
1158 compilation, binding and linking tools in the correct order. In particular,
1159 @command{gnatmake} automatically recompiles any sources that have been
1160 modified since they were last compiled, or sources that depend
1161 on such modified sources, so that ``version skew'' is avoided.
1162 @cindex Version skew (avoided by @command{gnatmake})
1163
1164 @smallexample
1165 $ gnatmake hello.adb
1166 @end smallexample
1167
1168 @noindent
1169 The result is an executable program called @file{hello}, which can be
1170 run by entering:
1171
1172 @smallexample
1173 $ ^hello^RUN HELLO^
1174 @end smallexample
1175
1176 @noindent
1177 assuming that the current directory is on the search path
1178 for executable programs.
1179
1180 @noindent
1181 and, if all has gone well, you will see
1182
1183 @smallexample
1184 Hello WORLD!
1185 @end smallexample
1186
1187 @noindent
1188 appear in response to this command.
1189
1190 @c ****************************************
1191 @node Running a Program with Multiple Units
1192 @section Running a Program with Multiple Units
1193
1194 @noindent
1195 Consider a slightly more complicated example that has three files: a
1196 main program, and the spec and body of a package:
1197
1198 @smallexample @c ada
1199 @cartouche
1200 @group
1201 package Greetings is
1202    procedure Hello;
1203    procedure Goodbye;
1204 end Greetings;
1205
1206 with Ada.Text_IO; use Ada.Text_IO;
1207 package body Greetings is
1208    procedure Hello is
1209    begin
1210       Put_Line ("Hello WORLD!");
1211    end Hello;
1212
1213    procedure Goodbye is
1214    begin
1215       Put_Line ("Goodbye WORLD!");
1216    end Goodbye;
1217 end Greetings;
1218 @end group
1219
1220 @group
1221 with Greetings;
1222 procedure Gmain is
1223 begin
1224    Greetings.Hello;
1225    Greetings.Goodbye;
1226 end Gmain;
1227 @end group
1228 @end cartouche
1229 @end smallexample
1230
1231 @noindent
1232 Following the one-unit-per-file rule, place this program in the
1233 following three separate files:
1234
1235 @table @file
1236 @item greetings.ads
1237 spec of package @code{Greetings}
1238
1239 @item greetings.adb
1240 body of package @code{Greetings}
1241
1242 @item gmain.adb
1243 body of main program
1244 @end table
1245
1246 @noindent
1247 To build an executable version of
1248 this program, we could use four separate steps to compile, bind, and link
1249 the program, as follows:
1250
1251 @smallexample
1252 $ gcc -c gmain.adb
1253 $ gcc -c greetings.adb
1254 $ gnatbind gmain
1255 $ gnatlink gmain
1256 @end smallexample
1257
1258 @noindent
1259 Note that there is no required order of compilation when using GNAT.
1260 In particular it is perfectly fine to compile the main program first.
1261 Also, it is not necessary to compile package specs in the case where
1262 there is an accompanying body; you only need to compile the body. If you want
1263 to submit these files to the compiler for semantic checking and not code
1264 generation, then use the
1265 @option{-gnatc} switch:
1266
1267 @smallexample
1268 $ gcc -c greetings.ads -gnatc
1269 @end smallexample
1270
1271 @noindent
1272 Although the compilation can be done in separate steps as in the
1273 above example, in practice it is almost always more convenient
1274 to use the @command{gnatmake} tool. All you need to know in this case
1275 is the name of the main program's source file. The effect of the above four
1276 commands can be achieved with a single one:
1277
1278 @smallexample
1279 $ gnatmake gmain.adb
1280 @end smallexample
1281
1282 @noindent
1283 In the next section we discuss the advantages of using @command{gnatmake} in
1284 more detail.
1285
1286 @c *****************************
1287 @node Using the gnatmake Utility
1288 @section Using the @command{gnatmake} Utility
1289
1290 @noindent
1291 If you work on a program by compiling single components at a time using
1292 @command{gcc}, you typically keep track of the units you modify. In order to
1293 build a consistent system, you compile not only these units, but also any
1294 units that depend on the units you have modified.
1295 For example, in the preceding case,
1296 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1297 you edit @file{greetings.ads}, you must recompile both
1298 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1299 units that depend on @file{greetings.ads}.
1300
1301 @code{gnatbind} will warn you if you forget one of these compilation
1302 steps, so that it is impossible to generate an inconsistent program as a
1303 result of forgetting to do a compilation. Nevertheless it is tedious and
1304 error-prone to keep track of dependencies among units.
1305 One approach to handle the dependency-bookkeeping is to use a
1306 makefile. However, makefiles present maintenance problems of their own:
1307 if the dependencies change as you change the program, you must make
1308 sure that the makefile is kept up-to-date manually, which is also an
1309 error-prone process.
1310
1311 The @command{gnatmake} utility takes care of these details automatically.
1312 Invoke it using either one of the following forms:
1313
1314 @smallexample
1315 $ gnatmake gmain.adb
1316 $ gnatmake ^gmain^GMAIN^
1317 @end smallexample
1318
1319 @noindent
1320 The argument is the name of the file containing the main program;
1321 you may omit the extension. @command{gnatmake}
1322 examines the environment, automatically recompiles any files that need
1323 recompiling, and binds and links the resulting set of object files,
1324 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1325 In a large program, it
1326 can be extremely helpful to use @command{gnatmake}, because working out by hand
1327 what needs to be recompiled can be difficult.
1328
1329 Note that @command{gnatmake}
1330 takes into account all the Ada rules that
1331 establish dependencies among units. These include dependencies that result
1332 from inlining subprogram bodies, and from
1333 generic instantiation. Unlike some other
1334 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1335 found by the compiler on a previous compilation, which may possibly
1336 be wrong when sources change. @command{gnatmake} determines the exact set of
1337 dependencies from scratch each time it is run.
1338
1339 @ifset vms
1340 @node Editing with Emacs
1341 @section Editing with Emacs
1342 @cindex Emacs
1343
1344 @noindent
1345 Emacs is an extensible self-documenting text editor that is available in a
1346 separate VMSINSTAL kit.
1347
1348 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1349 click on the Emacs Help menu and run the Emacs Tutorial.
1350 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1351 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1352
1353 Documentation on Emacs and other tools is available in Emacs under the
1354 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1355 use the middle mouse button to select a topic (e.g.@: Emacs).
1356
1357 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1358 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1359 get to the Emacs manual.
1360 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1361 prompt.
1362
1363 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1364 which is sufficiently extensible to provide for a complete programming
1365 environment and shell for the sophisticated user.
1366 @end ifset
1367
1368 @ifclear vms
1369 @node Introduction to GPS
1370 @section Introduction to GPS
1371 @cindex GPS (GNAT Programming Studio)
1372 @cindex GNAT Programming Studio (GPS)
1373 @noindent
1374 Although the command line interface (@command{gnatmake}, etc.) alone
1375 is sufficient, a graphical Interactive Development
1376 Environment can make it easier for you to compose, navigate, and debug
1377 programs.  This section describes the main features of GPS
1378 (``GNAT Programming Studio''), the GNAT graphical IDE.
1379 You will see how to use GPS to build and debug an executable, and
1380 you will also learn some of the basics of the GNAT ``project'' facility.
1381
1382 GPS enables you to do much more than is presented here;
1383 e.g., you can produce a call graph, interface to a third-party
1384 Version Control System, and inspect the generated assembly language
1385 for a program.
1386 Indeed, GPS also supports languages other than Ada.
1387 Such additional information, and an explanation of all of the GPS menu
1388 items. may be found in the on-line help, which includes
1389 a user's guide and a tutorial (these are also accessible from the GNAT
1390 startup menu).
1391
1392 @menu
1393 * Building a New Program with GPS::
1394 * Simple Debugging with GPS::
1395 @end menu
1396
1397 @node Building a New Program with GPS
1398 @subsection Building a New Program with GPS
1399 @noindent
1400 GPS invokes the GNAT compilation tools using information
1401 contained in a @emph{project} (also known as a @emph{project file}):
1402 a collection of properties such
1403 as source directories, identities of main subprograms, tool switches, etc.,
1404 and their associated values.
1405 See @ref{GNAT Project Manager} for details.
1406 In order to run GPS, you will need to either create a new project
1407 or else open an existing one.
1408
1409 This section will explain how you can use GPS to create a project,
1410 to associate Ada source files with a project, and to build and run
1411 programs.
1412
1413 @enumerate
1414 @item @emph{Creating a project}
1415
1416 Invoke GPS, either from the command line or the platform's IDE.
1417 After it starts, GPS will display a ``Welcome'' screen with three
1418 radio buttons:
1419
1420 @itemize @bullet
1421 @item
1422 @code{Start with default project in directory}
1423
1424 @item
1425 @code{Create new project with wizard}
1426
1427 @item
1428 @code{Open existing project}
1429 @end itemize
1430
1431 @noindent
1432 Select @code{Create new project with wizard} and press @code{OK}.
1433 A new window will appear.  In the text box labeled with
1434 @code{Enter the name of the project to create}, type @file{sample}
1435 as the project name.
1436 In the next box, browse to choose the directory in which you
1437 would like to create the project file.
1438 After selecting an appropriate directory, press @code{Forward}.
1439
1440 A window will appear with the title
1441 @code{Version Control System Configuration}.
1442 Simply press @code{Forward}.
1443
1444 A window will appear with the title
1445 @code{Please select the source directories for this project}.
1446 The directory that you specified for the project file will be selected
1447 by default as the one to use for sources; simply press @code{Forward}.
1448
1449 A window will appear with the title
1450 @code{Please select the build directory for this project}.
1451 The directory that you specified for the project file will be selected
1452 by default for object files and executables;
1453 simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the main units for this project}.
1457 You will supply this information later, after creating the source file.
1458 Simply press @code{Forward} for now.
1459
1460 A window will appear with the title
1461 @code{Please select the switches to build the project}.
1462 Press @code{Apply}.  This will create a project file named
1463 @file{sample.prj} in the directory that you had specified.
1464
1465 @item @emph{Creating and saving the source file}
1466
1467 After you create the new project, a GPS window will appear, which is
1468 partitioned into two main sections:
1469
1470 @itemize @bullet
1471 @item
1472 A @emph{Workspace area}, initially greyed out, which you will use for
1473 creating and editing source files
1474
1475 @item
1476 Directly below, a @emph{Messages area}, which initially displays a
1477 ``Welcome'' message.
1478 (If the Messages area is not visible, drag its border upward to expand it.)
1479 @end itemize
1480
1481 @noindent
1482 Select @code{File} on the menu bar, and then the @code{New} command.
1483 The Workspace area will become white, and you can now
1484 enter the source program explicitly.
1485 Type the following text
1486
1487 @smallexample @c ada
1488 @group
1489 with Ada.Text_IO; use Ada.Text_IO;
1490 procedure Hello is
1491 begin
1492   Put_Line("Hello from GPS!");
1493 end Hello;
1494 @end group
1495 @end smallexample
1496
1497 @noindent
1498 Select @code{File}, then @code{Save As}, and enter the source file name
1499 @file{hello.adb}.
1500 The file will be saved in the same directory you specified as the
1501 location of the default project file.
1502
1503 @item @emph{Updating the project file}
1504
1505 You need to add the new source file to the project.
1506 To do this, select
1507 the @code{Project} menu and then @code{Edit project properties}.
1508 Click the @code{Main files} tab on the left, and then the
1509 @code{Add} button.
1510 Choose @file{hello.adb} from the list, and press @code{Open}.
1511 The project settings window will reflect this action.
1512 Click @code{OK}.
1513
1514 @item @emph{Building and running the program}
1515
1516 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1517 and select @file{hello.adb}.
1518 The Messages window will display the resulting invocations of @command{gcc},
1519 @command{gnatbind}, and @command{gnatlink}
1520 (reflecting the default switch settings from the
1521 project file that you created) and then a ``successful compilation/build''
1522 message.
1523
1524 To run the program, choose the @code{Build} menu, then @code{Run}, and
1525 select @command{hello}.
1526 An @emph{Arguments Selection} window will appear.
1527 There are no command line arguments, so just click @code{OK}.
1528
1529 The Messages window will now display the program's output (the string
1530 @code{Hello from GPS}), and at the bottom of the GPS window a status
1531 update is displayed (@code{Run: hello}).
1532 Close the GPS window (or select @code{File}, then @code{Exit}) to
1533 terminate this GPS session.
1534 @end enumerate
1535
1536 @node Simple Debugging with GPS
1537 @subsection Simple Debugging with GPS
1538 @noindent
1539 This section illustrates basic debugging techniques (setting breakpoints,
1540 examining/modifying variables, single stepping).
1541
1542 @enumerate
1543 @item @emph{Opening a project}
1544
1545 Start GPS and select @code{Open existing project}; browse to
1546 specify the project file @file{sample.prj} that you had created in the
1547 earlier example.
1548
1549 @item @emph{Creating a source file}
1550
1551 Select @code{File}, then @code{New}, and type in the following program:
1552
1553 @smallexample @c ada
1554 @group
1555 with Ada.Text_IO; use Ada.Text_IO;
1556 procedure Example is
1557    Line : String (1..80);
1558    N    : Natural;
1559 begin
1560    Put_Line("Type a line of text at each prompt; an empty line to exit");
1561    loop
1562       Put(": ");
1563       Get_Line (Line, N);
1564       Put_Line (Line (1..N) );
1565       exit when N=0;
1566    end loop;
1567 end Example;
1568 @end group
1569 @end smallexample
1570
1571 @noindent
1572 Select @code{File}, then @code{Save as}, and enter the file name
1573 @file{example.adb}.
1574
1575 @item @emph{Updating the project file}
1576
1577 Add @code{Example} as a new main unit for the project:
1578 @enumerate a
1579 @item
1580 Select @code{Project}, then @code{Edit Project Properties}.
1581
1582 @item
1583 Select the @code{Main files} tab, click @code{Add}, then
1584 select the file @file{example.adb} from the list, and
1585 click @code{Open}.
1586 You will see the file name appear in the list of main units
1587
1588 @item
1589 Click @code{OK}
1590 @end enumerate
1591
1592 @item @emph{Building/running the executable}
1593
1594 To build the executable
1595 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1596
1597 Run the program to see its effect (in the Messages area).
1598 Each line that you enter is displayed; an empty line will
1599 cause the loop to exit and the program to terminate.
1600
1601 @item @emph{Debugging the program}
1602
1603 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1604 which are required for debugging, are on by default when you create
1605 a new project.
1606 Thus unless you intentionally remove these settings, you will be able
1607 to debug any program that you develop using GPS.
1608
1609 @enumerate a
1610 @item @emph{Initializing}
1611
1612 Select @code{Debug}, then @code{Initialize}, then @file{example}
1613
1614 @item @emph{Setting a breakpoint}
1615
1616 After performing the initialization step, you will observe a small
1617 icon to the right of each line number.
1618 This serves as a toggle for breakpoints; clicking the icon will
1619 set a breakpoint at the corresponding line (the icon will change to
1620 a red circle with an ``x''), and clicking it again
1621 will remove the breakpoint / reset the icon.
1622
1623 For purposes of this example, set a breakpoint at line 10 (the
1624 statement @code{Put_Line@ (Line@ (1..N));}
1625
1626 @item @emph{Starting program execution}
1627
1628 Select @code{Debug}, then @code{Run}.  When the
1629 @code{Program Arguments} window appears, click @code{OK}.
1630 A console window will appear; enter some line of text,
1631 e.g.@: @code{abcde}, at the prompt.
1632 The program will pause execution when it gets to the
1633 breakpoint, and the corresponding line is highlighted.
1634
1635 @item @emph{Examining a variable}
1636
1637 Move the mouse over one of the occurrences of the variable @code{N}.
1638 You will see the value (5) displayed, in ``tool tip'' fashion.
1639 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1640 You will see information about @code{N} appear in the @code{Debugger Data}
1641 pane, showing the value as 5.
1642
1643 @item @emph{Assigning a new value to a variable}
1644
1645 Right click on the @code{N} in the @code{Debugger Data} pane, and
1646 select @code{Set value of N}.
1647 When the input window appears, enter the value @code{4} and click
1648 @code{OK}.
1649 This value does not automatically appear in the @code{Debugger Data}
1650 pane; to see it, right click again on the @code{N} in the
1651 @code{Debugger Data} pane and select @code{Update value}.
1652 The new value, 4, will appear in red.
1653
1654 @item @emph{Single stepping}
1655
1656 Select @code{Debug}, then @code{Next}.
1657 This will cause the next statement to be executed, in this case the
1658 call of @code{Put_Line} with the string slice.
1659 Notice in the console window that the displayed string is simply
1660 @code{abcd} and not @code{abcde} which you had entered.
1661 This is because the upper bound of the slice is now 4 rather than 5.
1662
1663 @item @emph{Removing a breakpoint}
1664
1665 Toggle the breakpoint icon at line 10.
1666
1667 @item @emph{Resuming execution from a breakpoint}
1668
1669 Select @code{Debug}, then @code{Continue}.
1670 The program will reach the next iteration of the loop, and
1671 wait for input after displaying the prompt.
1672 This time, just hit the @kbd{Enter} key.
1673 The value of @code{N} will be 0, and the program will terminate.
1674 The console window will disappear.
1675 @end enumerate
1676 @end enumerate
1677 @end ifclear
1678
1679 @node The GNAT Compilation Model
1680 @chapter The GNAT Compilation Model
1681 @cindex GNAT compilation model
1682 @cindex Compilation model
1683
1684 @menu
1685 * Source Representation::
1686 * Foreign Language Representation::
1687 * File Naming Rules::
1688 * Using Other File Names::
1689 * Alternative File Naming Schemes::
1690 * Generating Object Files::
1691 * Source Dependencies::
1692 * The Ada Library Information Files::
1693 * Binding an Ada Program::
1694 * Mixed Language Programming::
1695 @ifclear vms
1696 * Building Mixed Ada & C++ Programs::
1697 * Comparison between GNAT and C/C++ Compilation Models::
1698 @end ifclear
1699 * Comparison between GNAT and Conventional Ada Library Models::
1700 @ifset vms
1701 * Placement of temporary files::
1702 @end ifset
1703 @end menu
1704
1705 @noindent
1706 This chapter describes the compilation model used by GNAT. Although
1707 similar to that used by other languages, such as C and C++, this model
1708 is substantially different from the traditional Ada compilation models,
1709 which are based on a library. The model is initially described without
1710 reference to the library-based model. If you have not previously used an
1711 Ada compiler, you need only read the first part of this chapter. The
1712 last section describes and discusses the differences between the GNAT
1713 model and the traditional Ada compiler models. If you have used other
1714 Ada compilers, this section will help you to understand those
1715 differences, and the advantages of the GNAT model.
1716
1717 @node Source Representation
1718 @section Source Representation
1719 @cindex Latin-1
1720
1721 @noindent
1722 Ada source programs are represented in standard text files, using
1723 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1724 7-bit ASCII set, plus additional characters used for
1725 representing foreign languages (@pxref{Foreign Language Representation}
1726 for support of non-USA character sets). The format effector characters
1727 are represented using their standard ASCII encodings, as follows:
1728
1729 @table @code
1730 @item VT
1731 @findex VT
1732 Vertical tab, @code{16#0B#}
1733
1734 @item HT
1735 @findex HT
1736 Horizontal tab, @code{16#09#}
1737
1738 @item CR
1739 @findex CR
1740 Carriage return, @code{16#0D#}
1741
1742 @item LF
1743 @findex LF
1744 Line feed, @code{16#0A#}
1745
1746 @item FF
1747 @findex FF
1748 Form feed, @code{16#0C#}
1749 @end table
1750
1751 @noindent
1752 Source files are in standard text file format. In addition, GNAT will
1753 recognize a wide variety of stream formats, in which the end of
1754 physical lines is marked by any of the following sequences:
1755 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1756 in accommodating files that are imported from other operating systems.
1757
1758 @cindex End of source file
1759 @cindex Source file, end
1760 @findex SUB
1761 The end of a source file is normally represented by the physical end of
1762 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1763 recognized as signalling the end of the source file. Again, this is
1764 provided for compatibility with other operating systems where this
1765 code is used to represent the end of file.
1766
1767 Each file contains a single Ada compilation unit, including any pragmas
1768 associated with the unit. For example, this means you must place a
1769 package declaration (a package @dfn{spec}) and the corresponding body in
1770 separate files. An Ada @dfn{compilation} (which is a sequence of
1771 compilation units) is represented using a sequence of files. Similarly,
1772 you will place each subunit or child unit in a separate file.
1773
1774 @node Foreign Language Representation
1775 @section Foreign Language Representation
1776
1777 @noindent
1778 GNAT supports the standard character sets defined in Ada as well as
1779 several other non-standard character sets for use in localized versions
1780 of the compiler (@pxref{Character Set Control}).
1781 @menu
1782 * Latin-1::
1783 * Other 8-Bit Codes::
1784 * Wide Character Encodings::
1785 @end menu
1786
1787 @node Latin-1
1788 @subsection Latin-1
1789 @cindex Latin-1
1790
1791 @noindent
1792 The basic character set is Latin-1. This character set is defined by ISO
1793 standard 8859, part 1. The lower half (character codes @code{16#00#}
1794 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1795 half is used to represent additional characters. These include extended letters
1796 used by European languages, such as French accents, the vowels with umlauts
1797 used in German, and the extra letter A-ring used in Swedish.
1798
1799 @findex Ada.Characters.Latin_1
1800 For a complete list of Latin-1 codes and their encodings, see the source
1801 file of library unit @code{Ada.Characters.Latin_1} in file
1802 @file{a-chlat1.ads}.
1803 You may use any of these extended characters freely in character or
1804 string literals. In addition, the extended characters that represent
1805 letters can be used in identifiers.
1806
1807 @node Other 8-Bit Codes
1808 @subsection Other 8-Bit Codes
1809
1810 @noindent
1811 GNAT also supports several other 8-bit coding schemes:
1812
1813 @table @asis
1814 @item ISO 8859-2 (Latin-2)
1815 @cindex Latin-2
1816 @cindex ISO 8859-2
1817 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1818 equivalence.
1819
1820 @item ISO 8859-3 (Latin-3)
1821 @cindex Latin-3
1822 @cindex ISO 8859-3
1823 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1824 equivalence.
1825
1826 @item ISO 8859-4 (Latin-4)
1827 @cindex Latin-4
1828 @cindex ISO 8859-4
1829 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-5 (Cyrillic)
1833 @cindex ISO 8859-5
1834 @cindex Cyrillic
1835 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1836 lowercase equivalence.
1837
1838 @item ISO 8859-15 (Latin-9)
1839 @cindex ISO 8859-15
1840 @cindex Latin-9
1841 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1842 lowercase equivalence
1843
1844 @item IBM PC (code page 437)
1845 @cindex code page 437
1846 This code page is the normal default for PCs in the U.S. It corresponds
1847 to the original IBM PC character set. This set has some, but not all, of
1848 the extended Latin-1 letters, but these letters do not have the same
1849 encoding as Latin-1. In this mode, these letters are allowed in
1850 identifiers with uppercase and lowercase equivalence.
1851
1852 @item IBM PC (code page 850)
1853 @cindex code page 850
1854 This code page is a modification of 437 extended to include all the
1855 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1856 mode, all these letters are allowed in identifiers with uppercase and
1857 lowercase equivalence.
1858
1859 @item Full Upper 8-bit
1860 Any character in the range 80-FF allowed in identifiers, and all are
1861 considered distinct. In other words, there are no uppercase and lowercase
1862 equivalences in this range. This is useful in conjunction with
1863 certain encoding schemes used for some foreign character sets (e.g.,
1864 the typical method of representing Chinese characters on the PC).
1865
1866 @item No Upper-Half
1867 No upper-half characters in the range 80-FF are allowed in identifiers.
1868 This gives Ada 83 compatibility for identifier names.
1869 @end table
1870
1871 @noindent
1872 For precise data on the encodings permitted, and the uppercase and lowercase
1873 equivalences that are recognized, see the file @file{csets.adb} in
1874 the GNAT compiler sources. You will need to obtain a full source release
1875 of GNAT to obtain this file.
1876
1877 @node Wide Character Encodings
1878 @subsection Wide Character Encodings
1879
1880 @noindent
1881 GNAT allows wide character codes to appear in character and string
1882 literals, and also optionally in identifiers, by means of the following
1883 possible encoding schemes:
1884
1885 @table @asis
1886
1887 @item Hex Coding
1888 In this encoding, a wide character is represented by the following five
1889 character sequence:
1890
1891 @smallexample
1892 ESC a b c d
1893 @end smallexample
1894
1895 @noindent
1896 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1897 characters (using uppercase letters) of the wide character code. For
1898 example, ESC A345 is used to represent the wide character with code
1899 @code{16#A345#}.
1900 This scheme is compatible with use of the full Wide_Character set.
1901
1902 @item Upper-Half Coding
1903 @cindex Upper-Half Coding
1904 The wide character with encoding @code{16#abcd#} where the upper bit is on
1905 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1906 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1907 character, but is not required to be in the upper half. This method can
1908 be also used for shift-JIS or EUC, where the internal coding matches the
1909 external coding.
1910
1911 @item Shift JIS Coding
1912 @cindex Shift JIS Coding
1913 A wide character is represented by a two-character sequence,
1914 @code{16#ab#} and
1915 @code{16#cd#}, with the restrictions described for upper-half encoding as
1916 described above. The internal character code is the corresponding JIS
1917 character according to the standard algorithm for Shift-JIS
1918 conversion. Only characters defined in the JIS code set table can be
1919 used with this encoding method.
1920
1921 @item EUC Coding
1922 @cindex EUC Coding
1923 A wide character is represented by a two-character sequence
1924 @code{16#ab#} and
1925 @code{16#cd#}, with both characters being in the upper half. The internal
1926 character code is the corresponding JIS character according to the EUC
1927 encoding algorithm. Only characters defined in the JIS code set table
1928 can be used with this encoding method.
1929
1930 @item UTF-8 Coding
1931 A wide character is represented using
1932 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1933 10646-1/Am.2. Depending on the character value, the representation
1934 is a one, two, or three byte sequence:
1935 @smallexample
1936 @iftex
1937 @leftskip=.7cm
1938 @end iftex
1939 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1940 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1941 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1942
1943 @end smallexample
1944
1945 @noindent
1946 where the @var{xxx} bits correspond to the left-padded bits of the
1947 16-bit character value. Note that all lower half ASCII characters
1948 are represented as ASCII bytes and all upper half characters and
1949 other wide characters are represented as sequences of upper-half
1950 (The full UTF-8 scheme allows for encoding 31-bit characters as
1951 6-byte sequences, but in this implementation, all UTF-8 sequences
1952 of four or more bytes length will be treated as illegal).
1953 @item Brackets Coding
1954 In this encoding, a wide character is represented by the following eight
1955 character sequence:
1956
1957 @smallexample
1958 [ " a b c d " ]
1959 @end smallexample
1960
1961 @noindent
1962 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1963 characters (using uppercase letters) of the wide character code. For
1964 example, [``A345''] is used to represent the wide character with code
1965 @code{16#A345#}. It is also possible (though not required) to use the
1966 Brackets coding for upper half characters. For example, the code
1967 @code{16#A3#} can be represented as @code{[``A3'']}.
1968
1969 This scheme is compatible with use of the full Wide_Character set,
1970 and is also the method used for wide character encoding in the standard
1971 ACVC (Ada Compiler Validation Capability) test suite distributions.
1972
1973 @end table
1974
1975 @noindent
1976 Note: Some of these coding schemes do not permit the full use of the
1977 Ada character set. For example, neither Shift JIS, nor EUC allow the
1978 use of the upper half of the Latin-1 set.
1979
1980 @node File Naming Rules
1981 @section File Naming Rules
1982
1983 @noindent
1984 The default file name is determined by the name of the unit that the
1985 file contains. The name is formed by taking the full expanded name of
1986 the unit and replacing the separating dots with hyphens and using
1987 ^lowercase^uppercase^ for all letters.
1988
1989 An exception arises if the file name generated by the above rules starts
1990 with one of the characters
1991 @ifset vms
1992 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1993 @end ifset
1994 @ifclear vms
1995 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1996 @end ifclear
1997 and the second character is a
1998 minus. In this case, the character ^tilde^dollar sign^ is used in place
1999 of the minus. The reason for this special rule is to avoid clashes with
2000 the standard names for child units of the packages System, Ada,
2001 Interfaces, and GNAT, which use the prefixes
2002 @ifset vms
2003 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2004 @end ifset
2005 @ifclear vms
2006 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2007 @end ifclear
2008 respectively.
2009
2010 The file extension is @file{.ads} for a spec and
2011 @file{.adb} for a body. The following list shows some
2012 examples of these rules.
2013
2014 @table @file
2015 @item main.ads
2016 Main (spec)
2017 @item main.adb
2018 Main (body)
2019 @item arith_functions.ads
2020 Arith_Functions (package spec)
2021 @item arith_functions.adb
2022 Arith_Functions (package body)
2023 @item func-spec.ads
2024 Func.Spec (child package spec)
2025 @item func-spec.adb
2026 Func.Spec (child package body)
2027 @item main-sub.adb
2028 Sub (subunit of Main)
2029 @item ^a~bad.adb^A$BAD.ADB^
2030 A.Bad (child package body)
2031 @end table
2032
2033 @noindent
2034 Following these rules can result in excessively long
2035 file names if corresponding
2036 unit names are long (for example, if child units or subunits are
2037 heavily nested). An option is available to shorten such long file names
2038 (called file name ``krunching''). This may be particularly useful when
2039 programs being developed with GNAT are to be used on operating systems
2040 with limited file name lengths. @xref{Using gnatkr}.
2041
2042 Of course, no file shortening algorithm can guarantee uniqueness over
2043 all possible unit names; if file name krunching is used, it is your
2044 responsibility to ensure no name clashes occur. Alternatively you
2045 can specify the exact file names that you want used, as described
2046 in the next section. Finally, if your Ada programs are migrating from a
2047 compiler with a different naming convention, you can use the gnatchop
2048 utility to produce source files that follow the GNAT naming conventions.
2049 (For details @pxref{Renaming Files Using gnatchop}.)
2050
2051 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2052 systems, case is not significant. So for example on @code{Windows XP}
2053 if the canonical name is @code{main-sub.adb}, you can use the file name
2054 @code{Main-Sub.adb} instead. However, case is significant for other
2055 operating systems, so for example, if you want to use other than
2056 canonically cased file names on a Unix system, you need to follow
2057 the procedures described in the next section.
2058
2059 @node Using Other File Names
2060 @section Using Other File Names
2061 @cindex File names
2062
2063 @noindent
2064 In the previous section, we have described the default rules used by
2065 GNAT to determine the file name in which a given unit resides. It is
2066 often convenient to follow these default rules, and if you follow them,
2067 the compiler knows without being explicitly told where to find all
2068 the files it needs.
2069
2070 However, in some cases, particularly when a program is imported from
2071 another Ada compiler environment, it may be more convenient for the
2072 programmer to specify which file names contain which units. GNAT allows
2073 arbitrary file names to be used by means of the Source_File_Name pragma.
2074 The form of this pragma is as shown in the following examples:
2075 @cindex Source_File_Name pragma
2076
2077 @smallexample @c ada
2078 @cartouche
2079 pragma Source_File_Name (My_Utilities.Stacks,
2080   Spec_File_Name => "myutilst_a.ada");
2081 pragma Source_File_name (My_Utilities.Stacks,
2082   Body_File_Name => "myutilst.ada");
2083 @end cartouche
2084 @end smallexample
2085
2086 @noindent
2087 As shown in this example, the first argument for the pragma is the unit
2088 name (in this example a child unit). The second argument has the form
2089 of a named association. The identifier
2090 indicates whether the file name is for a spec or a body;
2091 the file name itself is given by a string literal.
2092
2093 The source file name pragma is a configuration pragma, which means that
2094 normally it will be placed in the @file{gnat.adc}
2095 file used to hold configuration
2096 pragmas that apply to a complete compilation environment.
2097 For more details on how the @file{gnat.adc} file is created and used
2098 see @ref{Handling of Configuration Pragmas}.
2099 @cindex @file{gnat.adc}
2100
2101 @ifclear vms
2102 GNAT allows completely arbitrary file names to be specified using the
2103 source file name pragma. However, if the file name specified has an
2104 extension other than @file{.ads} or @file{.adb} it is necessary to use
2105 a special syntax when compiling the file. The name in this case must be
2106 preceded by the special sequence @option{-x} followed by a space and the name
2107 of the language, here @code{ada}, as in:
2108
2109 @smallexample
2110 $ gcc -c -x ada peculiar_file_name.sim
2111 @end smallexample
2112 @end ifclear
2113
2114 @noindent
2115 @command{gnatmake} handles non-standard file names in the usual manner (the
2116 non-standard file name for the main program is simply used as the
2117 argument to gnatmake). Note that if the extension is also non-standard,
2118 then it must be included in the @command{gnatmake} command, it may not
2119 be omitted.
2120
2121 @node Alternative File Naming Schemes
2122 @section Alternative File Naming Schemes
2123 @cindex File naming schemes, alternative
2124 @cindex File names
2125
2126 In the previous section, we described the use of the @code{Source_File_Name}
2127 pragma to allow arbitrary names to be assigned to individual source files.
2128 However, this approach requires one pragma for each file, and especially in
2129 large systems can result in very long @file{gnat.adc} files, and also create
2130 a maintenance problem.
2131
2132 GNAT also provides a facility for specifying systematic file naming schemes
2133 other than the standard default naming scheme previously described. An
2134 alternative scheme for naming is specified by the use of
2135 @code{Source_File_Name} pragmas having the following format:
2136 @cindex Source_File_Name pragma
2137
2138 @smallexample @c ada
2139 pragma Source_File_Name (
2140    Spec_File_Name  => FILE_NAME_PATTERN
2141  @r{[},Casing          => CASING_SPEC@r{]}
2142  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2143
2144 pragma Source_File_Name (
2145    Body_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    Subunit_File_Name  => FILE_NAME_PATTERN
2151  @r{[},Casing             => CASING_SPEC@r{]}
2152  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2153
2154 FILE_NAME_PATTERN ::= STRING_LITERAL
2155 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2156 @end smallexample
2157
2158 @noindent
2159 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2160 It contains a single asterisk character, and the unit name is substituted
2161 systematically for this asterisk. The optional parameter
2162 @code{Casing} indicates
2163 whether the unit name is to be all upper-case letters, all lower-case letters,
2164 or mixed-case. If no
2165 @code{Casing} parameter is used, then the default is all
2166 ^lower-case^upper-case^.
2167
2168 The optional @code{Dot_Replacement} string is used to replace any periods
2169 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2170 argument is used then separating dots appear unchanged in the resulting
2171 file name.
2172 Although the above syntax indicates that the
2173 @code{Casing} argument must appear
2174 before the @code{Dot_Replacement} argument, but it
2175 is also permissible to write these arguments in the opposite order.
2176
2177 As indicated, it is possible to specify different naming schemes for
2178 bodies, specs, and subunits. Quite often the rule for subunits is the
2179 same as the rule for bodies, in which case, there is no need to give
2180 a separate @code{Subunit_File_Name} rule, and in this case the
2181 @code{Body_File_name} rule is used for subunits as well.
2182
2183 The separate rule for subunits can also be used to implement the rather
2184 unusual case of a compilation environment (e.g.@: a single directory) which
2185 contains a subunit and a child unit with the same unit name. Although
2186 both units cannot appear in the same partition, the Ada Reference Manual
2187 allows (but does not require) the possibility of the two units coexisting
2188 in the same environment.
2189
2190 The file name translation works in the following steps:
2191
2192 @itemize @bullet
2193
2194 @item
2195 If there is a specific @code{Source_File_Name} pragma for the given unit,
2196 then this is always used, and any general pattern rules are ignored.
2197
2198 @item
2199 If there is a pattern type @code{Source_File_Name} pragma that applies to
2200 the unit, then the resulting file name will be used if the file exists. If
2201 more than one pattern matches, the latest one will be tried first, and the
2202 first attempt resulting in a reference to a file that exists will be used.
2203
2204 @item
2205 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2206 for which the corresponding file exists, then the standard GNAT default
2207 naming rules are used.
2208
2209 @end itemize
2210
2211 @noindent
2212 As an example of the use of this mechanism, consider a commonly used scheme
2213 in which file names are all lower case, with separating periods copied
2214 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2215 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2216 two pragmas appear:
2217
2218 @smallexample @c ada
2219 pragma Source_File_Name
2220   (Spec_File_Name => "*.1.ada");
2221 pragma Source_File_Name
2222   (Body_File_Name => "*.2.ada");
2223 @end smallexample
2224
2225 @noindent
2226 The default GNAT scheme is actually implemented by providing the following
2227 default pragmas internally:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2234 @end smallexample
2235
2236 @noindent
2237 Our final example implements a scheme typically used with one of the
2238 Ada 83 compilers, where the separator character for subunits was ``__''
2239 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2240 by adding @file{.ADA}, and subunits by
2241 adding @file{.SEP}. All file names were
2242 upper case. Child units were not present of course since this was an
2243 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2244 the same double underscore separator for child units.
2245
2246 @smallexample @c ada
2247 pragma Source_File_Name
2248   (Spec_File_Name => "*_.ADA",
2249    Dot_Replacement => "__",
2250    Casing = Uppercase);
2251 pragma Source_File_Name
2252   (Body_File_Name => "*.ADA",
2253    Dot_Replacement => "__",
2254    Casing = Uppercase);
2255 pragma Source_File_Name
2256   (Subunit_File_Name => "*.SEP",
2257    Dot_Replacement => "__",
2258    Casing = Uppercase);
2259 @end smallexample
2260
2261 @node Generating Object Files
2262 @section Generating Object Files
2263
2264 @noindent
2265 An Ada program consists of a set of source files, and the first step in
2266 compiling the program is to generate the corresponding object files.
2267 These are generated by compiling a subset of these source files.
2268 The files you need to compile are the following:
2269
2270 @itemize @bullet
2271 @item
2272 If a package spec has no body, compile the package spec to produce the
2273 object file for the package.
2274
2275 @item
2276 If a package has both a spec and a body, compile the body to produce the
2277 object file for the package. The source file for the package spec need
2278 not be compiled in this case because there is only one object file, which
2279 contains the code for both the spec and body of the package.
2280
2281 @item
2282 For a subprogram, compile the subprogram body to produce the object file
2283 for the subprogram. The spec, if one is present, is as usual in a
2284 separate file, and need not be compiled.
2285
2286 @item
2287 @cindex Subunits
2288 In the case of subunits, only compile the parent unit. A single object
2289 file is generated for the entire subunit tree, which includes all the
2290 subunits.
2291
2292 @item
2293 Compile child units independently of their parent units
2294 (though, of course, the spec of all the ancestor unit must be present in order
2295 to compile a child unit).
2296
2297 @item
2298 @cindex Generics
2299 Compile generic units in the same manner as any other units. The object
2300 files in this case are small dummy files that contain at most the
2301 flag used for elaboration checking. This is because GNAT always handles generic
2302 instantiation by means of macro expansion. However, it is still necessary to
2303 compile generic units, for dependency checking and elaboration purposes.
2304 @end itemize
2305
2306 @noindent
2307 The preceding rules describe the set of files that must be compiled to
2308 generate the object files for a program. Each object file has the same
2309 name as the corresponding source file, except that the extension is
2310 @file{.o} as usual.
2311
2312 You may wish to compile other files for the purpose of checking their
2313 syntactic and semantic correctness. For example, in the case where a
2314 package has a separate spec and body, you would not normally compile the
2315 spec. However, it is convenient in practice to compile the spec to make
2316 sure it is error-free before compiling clients of this spec, because such
2317 compilations will fail if there is an error in the spec.
2318
2319 GNAT provides an option for compiling such files purely for the
2320 purposes of checking correctness; such compilations are not required as
2321 part of the process of building a program. To compile a file in this
2322 checking mode, use the @option{-gnatc} switch.
2323
2324 @node Source Dependencies
2325 @section Source Dependencies
2326
2327 @noindent
2328 A given object file clearly depends on the source file which is compiled
2329 to produce it. Here we are using @dfn{depends} in the sense of a typical
2330 @code{make} utility; in other words, an object file depends on a source
2331 file if changes to the source file require the object file to be
2332 recompiled.
2333 In addition to this basic dependency, a given object may depend on
2334 additional source files as follows:
2335
2336 @itemize @bullet
2337 @item
2338 If a file being compiled @code{with}'s a unit @var{X}, the object file
2339 depends on the file containing the spec of unit @var{X}. This includes
2340 files that are @code{with}'ed implicitly either because they are parents
2341 of @code{with}'ed child units or they are run-time units required by the
2342 language constructs used in a particular unit.
2343
2344 @item
2345 If a file being compiled instantiates a library level generic unit, the
2346 object file depends on both the spec and body files for this generic
2347 unit.
2348
2349 @item
2350 If a file being compiled instantiates a generic unit defined within a
2351 package, the object file depends on the body file for the package as
2352 well as the spec file.
2353
2354 @item
2355 @findex Inline
2356 @cindex @option{-gnatn} switch
2357 If a file being compiled contains a call to a subprogram for which
2358 pragma @code{Inline} applies and inlining is activated with the
2359 @option{-gnatn} switch, the object file depends on the file containing the
2360 body of this subprogram as well as on the file containing the spec. Note
2361 that for inlining to actually occur as a result of the use of this switch,
2362 it is necessary to compile in optimizing mode.
2363
2364 @cindex @option{-gnatN} switch
2365 The use of @option{-gnatN} activates  inlining optimization
2366 that is performed by the front end of the compiler. This inlining does
2367 not require that the code generation be optimized. Like @option{-gnatn},
2368 the use of this switch generates additional dependencies.
2369
2370 When using a gcc-based back end (in practice this means using any version
2371 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2372 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2373 Historically front end inlining was more extensive than the gcc back end
2374 inlining, but that is no longer the case.
2375
2376 @item
2377 If an object file @file{O} depends on the proper body of a subunit through
2378 inlining or instantiation, it depends on the parent unit of the subunit.
2379 This means that any modification of the parent unit or one of its subunits
2380 affects the compilation of @file{O}.
2381
2382 @item
2383 The object file for a parent unit depends on all its subunit body files.
2384
2385 @item
2386 The previous two rules meant that for purposes of computing dependencies and
2387 recompilation, a body and all its subunits are treated as an indivisible whole.
2388
2389 @noindent
2390 These rules are applied transitively: if unit @code{A} @code{with}'s
2391 unit @code{B}, whose elaboration calls an inlined procedure in package
2392 @code{C}, the object file for unit @code{A} will depend on the body of
2393 @code{C}, in file @file{c.adb}.
2394
2395 The set of dependent files described by these rules includes all the
2396 files on which the unit is semantically dependent, as dictated by the
2397 Ada language standard. However, it is a superset of what the
2398 standard describes, because it includes generic, inline, and subunit
2399 dependencies.
2400
2401 An object file must be recreated by recompiling the corresponding source
2402 file if any of the source files on which it depends are modified. For
2403 example, if the @code{make} utility is used to control compilation,
2404 the rule for an Ada object file must mention all the source files on
2405 which the object file depends, according to the above definition.
2406 The determination of the necessary
2407 recompilations is done automatically when one uses @command{gnatmake}.
2408 @end itemize
2409
2410 @node The Ada Library Information Files
2411 @section The Ada Library Information Files
2412 @cindex Ada Library Information files
2413 @cindex @file{ALI} files
2414
2415 @noindent
2416 Each compilation actually generates two output files. The first of these
2417 is the normal object file that has a @file{.o} extension. The second is a
2418 text file containing full dependency information. It has the same
2419 name as the source file, but an @file{.ali} extension.
2420 This file is known as the Ada Library Information (@file{ALI}) file.
2421 The following information is contained in the @file{ALI} file.
2422
2423 @itemize @bullet
2424 @item
2425 Version information (indicates which version of GNAT was used to compile
2426 the unit(s) in question)
2427
2428 @item
2429 Main program information (including priority and time slice settings,
2430 as well as the wide character encoding used during compilation).
2431
2432 @item
2433 List of arguments used in the @command{gcc} command for the compilation
2434
2435 @item
2436 Attributes of the unit, including configuration pragmas used, an indication
2437 of whether the compilation was successful, exception model used etc.
2438
2439 @item
2440 A list of relevant restrictions applying to the unit (used for consistency)
2441 checking.
2442
2443 @item
2444 Categorization information (e.g.@: use of pragma @code{Pure}).
2445
2446 @item
2447 Information on all @code{with}'ed units, including presence of
2448 @code{Elaborate} or @code{Elaborate_All} pragmas.
2449
2450 @item
2451 Information from any @code{Linker_Options} pragmas used in the unit
2452
2453 @item
2454 Information on the use of @code{Body_Version} or @code{Version}
2455 attributes in the unit.
2456
2457 @item
2458 Dependency information. This is a list of files, together with
2459 time stamp and checksum information. These are files on which
2460 the unit depends in the sense that recompilation is required
2461 if any of these units are modified.
2462
2463 @item
2464 Cross-reference data. Contains information on all entities referenced
2465 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2466 provide cross-reference information.
2467
2468 @end itemize
2469
2470 @noindent
2471 For a full detailed description of the format of the @file{ALI} file,
2472 see the source of the body of unit @code{Lib.Writ}, contained in file
2473 @file{lib-writ.adb} in the GNAT compiler sources.
2474
2475 @node Binding an Ada Program
2476 @section Binding an Ada Program
2477
2478 @noindent
2479 When using languages such as C and C++, once the source files have been
2480 compiled the only remaining step in building an executable program
2481 is linking the object modules together. This means that it is possible to
2482 link an inconsistent version of a program, in which two units have
2483 included different versions of the same header.
2484
2485 The rules of Ada do not permit such an inconsistent program to be built.
2486 For example, if two clients have different versions of the same package,
2487 it is illegal to build a program containing these two clients.
2488 These rules are enforced by the GNAT binder, which also determines an
2489 elaboration order consistent with the Ada rules.
2490
2491 The GNAT binder is run after all the object files for a program have
2492 been created. It is given the name of the main program unit, and from
2493 this it determines the set of units required by the program, by reading the
2494 corresponding ALI files. It generates error messages if the program is
2495 inconsistent or if no valid order of elaboration exists.
2496
2497 If no errors are detected, the binder produces a main program, in Ada by
2498 default, that contains calls to the elaboration procedures of those
2499 compilation unit that require them, followed by
2500 a call to the main program. This Ada program is compiled to generate the
2501 object file for the main program. The name of
2502 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2503 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2504 main program unit.
2505
2506 Finally, the linker is used to build the resulting executable program,
2507 using the object from the main program from the bind step as well as the
2508 object files for the Ada units of the program.
2509
2510 @node Mixed Language Programming
2511 @section Mixed Language Programming
2512 @cindex Mixed Language Programming
2513
2514 @noindent
2515 This section describes how to develop a mixed-language program,
2516 specifically one that comprises units in both Ada and C.
2517
2518 @menu
2519 * Interfacing to C::
2520 * Calling Conventions::
2521 @end menu
2522
2523 @node Interfacing to C
2524 @subsection Interfacing to C
2525 @noindent
2526 Interfacing Ada with a foreign language such as C involves using
2527 compiler directives to import and/or export entity definitions in each
2528 language---using @code{extern} statements in C, for instance, and the
2529 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2530 A full treatment of these topics is provided in Appendix B, section 1
2531 of the Ada Reference Manual.
2532
2533 There are two ways to build a program using GNAT that contains some Ada
2534 sources and some foreign language sources, depending on whether or not
2535 the main subprogram is written in Ada.  Here is a source example with
2536 the main subprogram in Ada:
2537
2538 @smallexample
2539 /* file1.c */
2540 #include <stdio.h>
2541
2542 void print_num (int num)
2543 @{
2544   printf ("num is %d.\n", num);
2545   return;
2546 @}
2547
2548 /* file2.c */
2549
2550 /* num_from_Ada is declared in my_main.adb */
2551 extern int num_from_Ada;
2552
2553 int get_num (void)
2554 @{
2555   return num_from_Ada;
2556 @}
2557 @end smallexample
2558
2559 @smallexample @c ada
2560 --  my_main.adb
2561 procedure My_Main is
2562
2563    --  Declare then export an Integer entity called num_from_Ada
2564    My_Num : Integer := 10;
2565    pragma Export (C, My_Num, "num_from_Ada");
2566
2567    --  Declare an Ada function spec for Get_Num, then use
2568    --  C function get_num for the implementation.
2569    function Get_Num return Integer;
2570    pragma Import (C, Get_Num, "get_num");
2571
2572    --  Declare an Ada procedure spec for Print_Num, then use
2573    --  C function print_num for the implementation.
2574    procedure Print_Num (Num : Integer);
2575    pragma Import (C, Print_Num, "print_num");
2576
2577 begin
2578    Print_Num (Get_Num);
2579 end My_Main;
2580 @end smallexample
2581
2582 @enumerate
2583 @item
2584 To build this example, first compile the foreign language files to
2585 generate object files:
2586 @smallexample
2587 ^gcc -c file1.c^gcc -c FILE1.C^
2588 ^gcc -c file2.c^gcc -c FILE2.C^
2589 @end smallexample
2590
2591 @item
2592 Then, compile the Ada units to produce a set of object files and ALI
2593 files:
2594 @smallexample
2595 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2596 @end smallexample
2597
2598 @item
2599 Run the Ada binder on the Ada main program:
2600 @smallexample
2601 gnatbind my_main.ali
2602 @end smallexample
2603
2604 @item
2605 Link the Ada main program, the Ada objects and the other language
2606 objects:
2607 @smallexample
2608 gnatlink my_main.ali file1.o file2.o
2609 @end smallexample
2610 @end enumerate
2611
2612 The last three steps can be grouped in a single command:
2613 @smallexample
2614 gnatmake my_main.adb -largs file1.o file2.o
2615 @end smallexample
2616
2617 @cindex Binder output file
2618 @noindent
2619 If the main program is in a language other than Ada, then you may have
2620 more than one entry point into the Ada subsystem. You must use a special
2621 binder option to generate callable routines that initialize and
2622 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2623 Calls to the initialization and finalization routines must be inserted
2624 in the main program, or some other appropriate point in the code. The
2625 call to initialize the Ada units must occur before the first Ada
2626 subprogram is called, and the call to finalize the Ada units must occur
2627 after the last Ada subprogram returns. The binder will place the
2628 initialization and finalization subprograms into the
2629 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2630 sources.  To illustrate, we have the following example:
2631
2632 @smallexample
2633 /* main.c */
2634 extern void adainit (void);
2635 extern void adafinal (void);
2636 extern int add (int, int);
2637 extern int sub (int, int);
2638
2639 int main (int argc, char *argv[])
2640 @{
2641   int a = 21, b = 7;
2642
2643   adainit();
2644
2645   /* Should print "21 + 7 = 28" */
2646   printf ("%d + %d = %d\n", a, b, add (a, b));
2647   /* Should print "21 - 7 = 14" */
2648   printf ("%d - %d = %d\n", a, b, sub (a, b));
2649
2650   adafinal();
2651 @}
2652 @end smallexample
2653
2654 @smallexample @c ada
2655 --  unit1.ads
2656 package Unit1 is
2657    function Add (A, B : Integer) return Integer;
2658    pragma Export (C, Add, "add");
2659 end Unit1;
2660
2661 --  unit1.adb
2662 package body Unit1 is
2663    function Add (A, B : Integer) return Integer is
2664    begin
2665       return A + B;
2666    end Add;
2667 end Unit1;
2668
2669 --  unit2.ads
2670 package Unit2 is
2671    function Sub (A, B : Integer) return Integer;
2672    pragma Export (C, Sub, "sub");
2673 end Unit2;
2674
2675 --  unit2.adb
2676 package body Unit2 is
2677    function Sub (A, B : Integer) return Integer is
2678    begin
2679       return A - B;
2680    end Sub;
2681 end Unit2;
2682 @end smallexample
2683
2684 @enumerate
2685 @item
2686 The build procedure for this application is similar to the last
2687 example's.  First, compile the foreign language files to generate object
2688 files:
2689 @smallexample
2690 ^gcc -c main.c^gcc -c main.c^
2691 @end smallexample
2692
2693 @item
2694 Next, compile the Ada units to produce a set of object files and ALI
2695 files:
2696 @smallexample
2697 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2698 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2699 @end smallexample
2700
2701 @item
2702 Run the Ada binder on every generated ALI file.  Make sure to use the
2703 @option{-n} option to specify a foreign main program:
2704 @smallexample
2705 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2706 @end smallexample
2707
2708 @item
2709 Link the Ada main program, the Ada objects and the foreign language
2710 objects. You need only list the last ALI file here:
2711 @smallexample
2712 gnatlink unit2.ali main.o -o exec_file
2713 @end smallexample
2714
2715 This procedure yields a binary executable called @file{exec_file}.
2716 @end enumerate
2717
2718 @noindent
2719 Depending on the circumstances (for example when your non-Ada main object
2720 does not provide symbol @code{main}), you may also need to instruct the
2721 GNAT linker not to include the standard startup objects by passing the
2722 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2723
2724 @node Calling Conventions
2725 @subsection Calling Conventions
2726 @cindex Foreign Languages
2727 @cindex Calling Conventions
2728 GNAT follows standard calling sequence conventions and will thus interface
2729 to any other language that also follows these conventions. The following
2730 Convention identifiers are recognized by GNAT:
2731
2732 @table @code
2733 @cindex Interfacing to Ada
2734 @cindex Other Ada compilers
2735 @cindex Convention Ada
2736 @item Ada
2737 This indicates that the standard Ada calling sequence will be
2738 used and all Ada data items may be passed without any limitations in the
2739 case where GNAT is used to generate both the caller and callee. It is also
2740 possible to mix GNAT generated code and code generated by another Ada
2741 compiler. In this case, the data types should be restricted to simple
2742 cases, including primitive types. Whether complex data types can be passed
2743 depends on the situation. Probably it is safe to pass simple arrays, such
2744 as arrays of integers or floats. Records may or may not work, depending
2745 on whether both compilers lay them out identically. Complex structures
2746 involving variant records, access parameters, tasks, or protected types,
2747 are unlikely to be able to be passed.
2748
2749 Note that in the case of GNAT running
2750 on a platform that supports HP Ada 83, a higher degree of compatibility
2751 can be guaranteed, and in particular records are layed out in an identical
2752 manner in the two compilers. Note also that if output from two different
2753 compilers is mixed, the program is responsible for dealing with elaboration
2754 issues. Probably the safest approach is to write the main program in the
2755 version of Ada other than GNAT, so that it takes care of its own elaboration
2756 requirements, and then call the GNAT-generated adainit procedure to ensure
2757 elaboration of the GNAT components. Consult the documentation of the other
2758 Ada compiler for further details on elaboration.
2759
2760 However, it is not possible to mix the tasking run time of GNAT and
2761 HP Ada 83, All the tasking operations must either be entirely within
2762 GNAT compiled sections of the program, or entirely within HP Ada 83
2763 compiled sections of the program.
2764
2765 @cindex Interfacing to Assembly
2766 @cindex Convention Assembler
2767 @item Assembler
2768 Specifies assembler as the convention. In practice this has the
2769 same effect as convention Ada (but is not equivalent in the sense of being
2770 considered the same convention).
2771
2772 @cindex Convention Asm
2773 @findex Asm
2774 @item Asm
2775 Equivalent to Assembler.
2776
2777 @cindex Interfacing to COBOL
2778 @cindex Convention COBOL
2779 @findex COBOL
2780 @item COBOL
2781 Data will be passed according to the conventions described
2782 in section B.4 of the Ada Reference Manual.
2783
2784 @findex C
2785 @cindex Interfacing to C
2786 @cindex Convention C
2787 @item C
2788 Data will be passed according to the conventions described
2789 in section B.3 of the Ada Reference Manual.
2790
2791 A note on interfacing to a C ``varargs'' function:
2792 @findex C varargs function
2793 @cindex Interfacing to C varargs function
2794 @cindex varargs function interfaces
2795
2796 @itemize @bullet
2797 @item
2798 In C, @code{varargs} allows a function to take a variable number of
2799 arguments. There is no direct equivalent in this to Ada. One
2800 approach that can be used is to create a C wrapper for each
2801 different profile and then interface to this C wrapper. For
2802 example, to print an @code{int} value using @code{printf},
2803 create a C function @code{printfi} that takes two arguments, a
2804 pointer to a string and an int, and calls @code{printf}.
2805 Then in the Ada program, use pragma @code{Import} to
2806 interface to @code{printfi}.
2807
2808 @item
2809 It may work on some platforms to directly interface to
2810 a @code{varargs} function by providing a specific Ada profile
2811 for a particular call. However, this does not work on
2812 all platforms, since there is no guarantee that the
2813 calling sequence for a two argument normal C function
2814 is the same as for calling a @code{varargs} C function with
2815 the same two arguments.
2816 @end itemize
2817
2818 @cindex Convention Default
2819 @findex Default
2820 @item Default
2821 Equivalent to C.
2822
2823 @cindex Convention External
2824 @findex External
2825 @item External
2826 Equivalent to C.
2827
2828 @ifclear vms
2829 @findex C++
2830 @cindex Interfacing to C++
2831 @cindex Convention C++
2832 @item C_Plus_Plus (or CPP)
2833 This stands for C++. For most purposes this is identical to C.
2834 See the separate description of the specialized GNAT pragmas relating to
2835 C++ interfacing for further details.
2836 @end ifclear
2837
2838 @findex Fortran
2839 @cindex Interfacing to Fortran
2840 @cindex Convention Fortran
2841 @item Fortran
2842 Data will be passed according to the conventions described
2843 in section B.5 of the Ada Reference Manual.
2844
2845 @item Intrinsic
2846 This applies to an intrinsic operation, as defined in the Ada
2847 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2848 this means that the body of the subprogram is provided by the compiler itself,
2849 usually by means of an efficient code sequence, and that the user does not
2850 supply an explicit body for it. In an application program, the pragma may
2851 be applied to the following sets of names:
2852
2853 @itemize @bullet
2854 @item
2855 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2856 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2857 two formal parameters. The
2858 first one must be a signed integer type or a modular type with a binary
2859 modulus, and the second parameter must be of type Natural.
2860 The return type must be the same as the type of the first argument. The size
2861 of this type can only be 8, 16, 32, or 64.
2862
2863 @item
2864 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2865 The corresponding operator declaration must have parameters and result type
2866 that have the same root numeric type (for example, all three are long_float
2867 types). This simplifies the definition of operations that use type checking
2868 to perform dimensional checks:
2869
2870 @smallexample @c ada
2871 type Distance is new Long_Float;
2872 type Time     is new Long_Float;
2873 type Velocity is new Long_Float;
2874 function "/" (D : Distance; T : Time)
2875   return Velocity;
2876 pragma Import (Intrinsic, "/");
2877 @end smallexample
2878
2879 @noindent
2880 This common idiom is often programmed with a generic definition and an
2881 explicit body. The pragma makes it simpler to introduce such declarations.
2882 It incurs no overhead in compilation time or code size, because it is
2883 implemented as a single machine instruction.
2884
2885 @item
2886 General subprogram entities, to bind an Ada subprogram declaration to
2887 a compiler builtin by name with back-ends where such interfaces are
2888 available. A typical example is the set of ``__builtin'' functions
2889 exposed by the GCC back-end, as in the following example:
2890
2891 @smallexample @c ada
2892    function builtin_sqrt (F : Float) return Float;
2893    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2894 @end smallexample
2895
2896 Most of the GCC builtins are accessible this way, and as for other
2897 import conventions (e.g. C), it is the user's responsibility to ensure
2898 that the Ada subprogram profile matches the underlying builtin
2899 expectations.
2900 @end itemize
2901
2902 @noindent
2903
2904 @ifset unw
2905 @findex Stdcall
2906 @cindex Convention Stdcall
2907 @item Stdcall
2908 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2909 and specifies that the @code{Stdcall} calling sequence will be used,
2910 as defined by the NT API. Nevertheless, to ease building
2911 cross-platform bindings this convention will be handled as a @code{C} calling
2912 convention on non-Windows platforms.
2913
2914 @findex DLL
2915 @cindex Convention DLL
2916 @item DLL
2917 This is equivalent to @code{Stdcall}.
2918
2919 @findex Win32
2920 @cindex Convention Win32
2921 @item Win32
2922 This is equivalent to @code{Stdcall}.
2923 @end ifset
2924
2925 @findex Stubbed
2926 @cindex Convention Stubbed
2927 @item Stubbed
2928 This is a special convention that indicates that the compiler
2929 should provide a stub body that raises @code{Program_Error}.
2930 @end table
2931
2932 @noindent
2933 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2934 that can be used to parameterize conventions and allow additional synonyms
2935 to be specified. For example if you have legacy code in which the convention
2936 identifier Fortran77 was used for Fortran, you can use the configuration
2937 pragma:
2938
2939 @smallexample @c ada
2940 pragma Convention_Identifier (Fortran77, Fortran);
2941 @end smallexample
2942
2943 @noindent
2944 And from now on the identifier Fortran77 may be used as a convention
2945 identifier (for example in an @code{Import} pragma) with the same
2946 meaning as Fortran.
2947
2948 @ifclear vms
2949 @node Building Mixed Ada & C++ Programs
2950 @section Building Mixed Ada and C++ Programs
2951
2952 @noindent
2953 A programmer inexperienced with mixed-language development may find that
2954 building an application containing both Ada and C++ code can be a
2955 challenge.  This section gives a few
2956 hints that should make this task easier. The first section addresses
2957 the differences between interfacing with C and interfacing with C++.
2958 The second section
2959 looks into the delicate problem of linking the complete application from
2960 its Ada and C++ parts. The last section gives some hints on how the GNAT
2961 run-time library can be adapted in order to allow inter-language dispatching
2962 with a new C++ compiler.
2963
2964 @menu
2965 * Interfacing to C++::
2966 * Linking a Mixed C++ & Ada Program::
2967 * A Simple Example::
2968 * Interfacing with C++ constructors::
2969 * Interfacing with C++ at the Class Level::
2970 @end menu
2971
2972 @node Interfacing to C++
2973 @subsection Interfacing to C++
2974
2975 @noindent
2976 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2977 generating code that is compatible with the G++ Application Binary
2978 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2979
2980 @noindent
2981 Interfacing can be done at 3 levels: simple data, subprograms, and
2982 classes. In the first two cases, GNAT offers a specific @code{Convention
2983 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2984 Usually, C++ mangles the names of subprograms. To generate proper mangled
2985 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2986 This problem can also be addressed manually in two ways:
2987
2988 @itemize @bullet
2989 @item
2990 by modifying the C++ code in order to force a C convention using
2991 the @code{extern "C"} syntax.
2992
2993 @item
2994 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2995 Link_Name argument of the pragma import.
2996 @end itemize
2997
2998 @noindent
2999 Interfacing at the class level can be achieved by using the GNAT specific
3000 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3001 gnat_rm, GNAT Reference Manual}, for additional information.
3002
3003 @node Linking a Mixed C++ & Ada Program
3004 @subsection Linking a Mixed C++ & Ada Program
3005
3006 @noindent
3007 Usually the linker of the C++ development system must be used to link
3008 mixed applications because most C++ systems will resolve elaboration
3009 issues (such as calling constructors on global class instances)
3010 transparently during the link phase. GNAT has been adapted to ease the
3011 use of a foreign linker for the last phase. Three cases can be
3012 considered:
3013 @enumerate
3014
3015 @item
3016 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3017 The C++ linker can simply be called by using the C++ specific driver
3018 called @code{g++}.
3019
3020 Note that if the C++ code uses inline functions, you will need to
3021 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3022 order to provide an existing function implementation that the Ada code can
3023 link with.
3024
3025 @smallexample
3026 $ g++ -c -fkeep-inline-functions file1.C
3027 $ g++ -c -fkeep-inline-functions file2.C
3028 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3029 @end smallexample
3030
3031 @item
3032 Using GNAT and G++ from two different GCC installations: If both
3033 compilers are on the @env{PATH}, the previous method may be used. It is
3034 important to note that environment variables such as
3035 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3036 @env{GCC_ROOT} will affect both compilers
3037 at the same time and may make one of the two compilers operate
3038 improperly if set during invocation of the wrong compiler.  It is also
3039 very important that the linker uses the proper @file{libgcc.a} GCC
3040 library -- that is, the one from the C++ compiler installation. The
3041 implicit link command as suggested in the @command{gnatmake} command
3042 from the former example can be replaced by an explicit link command with
3043 the full-verbosity option in order to verify which library is used:
3044 @smallexample
3045 $ gnatbind ada_unit
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3047 @end smallexample
3048 If there is a problem due to interfering environment variables, it can
3049 be worked around by using an intermediate script. The following example
3050 shows the proper script to use when GNAT has not been installed at its
3051 default location and g++ has been installed at its default location:
3052
3053 @smallexample
3054 $ cat ./my_script
3055 #!/bin/sh
3056 unset BINUTILS_ROOT
3057 unset GCC_ROOT
3058 c++ $*
3059 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3060 @end smallexample
3061
3062 @item
3063 Using a non-GNU C++ compiler: The commands previously described can be
3064 used to insure that the C++ linker is used. Nonetheless, you need to add
3065 a few more parameters to the link command line, depending on the exception
3066 mechanism used.
3067
3068 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3069 to the libgcc libraries are required:
3070
3071 @smallexample
3072 $ cat ./my_script
3073 #!/bin/sh
3074 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3075 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3076 @end smallexample
3077
3078 Where CC is the name of the non-GNU C++ compiler.
3079
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3082 paths to more objects are required:
3083
3084 @smallexample
3085 $ cat ./my_script
3086 #!/bin/sh
3087 CC `gcc -print-file-name=crtbegin.o` $* \
3088 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3089 `gcc -print-file-name=crtend.o`
3090 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3091 @end smallexample
3092
3093 If the @code{zero cost} exception mechanism is used, and the platform
3094 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3095 Tru64 or AIX), the simple approach described above will not work and
3096 a pre-linking phase using GNAT will be necessary.
3097
3098 @end enumerate
3099
3100 Another alternative is to use the @command{gprbuild} multi-language builder
3101 which has a large knowledge base and knows how to link Ada and C++ code
3102 together automatically in most cases.
3103
3104 @node A Simple Example
3105 @subsection  A Simple Example
3106 @noindent
3107 The following example, provided as part of the GNAT examples, shows how
3108 to achieve procedural interfacing between Ada and C++ in both
3109 directions. The C++ class A has two methods. The first method is exported
3110 to Ada by the means of an extern C wrapper function. The second method
3111 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3112 a limited record with a layout comparable to the C++ class. The Ada
3113 subprogram, in turn, calls the C++ method. So, starting from the C++
3114 main program, the process passes back and forth between the two
3115 languages.
3116
3117 @noindent
3118 Here are the compilation commands:
3119 @smallexample
3120 $ gnatmake -c simple_cpp_interface
3121 $ g++ -c cpp_main.C
3122 $ g++ -c ex7.C
3123 $ gnatbind -n simple_cpp_interface
3124 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3125       -lstdc++ ex7.o cpp_main.o
3126 @end smallexample
3127
3128 @noindent
3129 Here are the corresponding sources:
3130 @smallexample
3131
3132 //cpp_main.C
3133
3134 #include "ex7.h"
3135
3136 extern "C" @{
3137   void adainit (void);
3138   void adafinal (void);
3139   void method1 (A *t);
3140 @}
3141
3142 void method1 (A *t)
3143 @{
3144   t->method1 ();
3145 @}
3146
3147 int main ()
3148 @{
3149   A obj;
3150   adainit ();
3151   obj.method2 (3030);
3152   adafinal ();
3153 @}
3154
3155 //ex7.h
3156
3157 class Origin @{
3158  public:
3159   int o_value;
3160 @};
3161 class A : public Origin @{
3162  public:
3163   void method1 (void);
3164   void method2 (int v);
3165   A();
3166   int   a_value;
3167 @};
3168
3169 //ex7.C
3170
3171 #include "ex7.h"
3172 #include <stdio.h>
3173
3174 extern "C" @{ void ada_method2 (A *t, int v);@}
3175
3176 void A::method1 (void)
3177 @{
3178   a_value = 2020;
3179   printf ("in A::method1, a_value = %d \n",a_value);
3180
3181 @}
3182
3183 void A::method2 (int v)
3184 @{
3185    ada_method2 (this, v);
3186    printf ("in A::method2, a_value = %d \n",a_value);
3187
3188 @}
3189
3190 A::A(void)
3191 @{
3192    a_value = 1010;
3193   printf ("in A::A, a_value = %d \n",a_value);
3194 @}
3195 @end smallexample
3196
3197 @smallexample @c ada
3198 -- Ada sources
3199 package body Simple_Cpp_Interface is
3200
3201    procedure Ada_Method2 (This : in out A; V : Integer) is
3202    begin
3203       Method1 (This);
3204       This.A_Value := V;
3205    end Ada_Method2;
3206
3207 end Simple_Cpp_Interface;
3208
3209 with System;
3210 package Simple_Cpp_Interface is
3211    type A is limited
3212       record
3213          Vptr    : System.Address;
3214          O_Value : Integer;
3215          A_Value : Integer;
3216       end record;
3217    pragma Convention (C, A);
3218
3219    procedure Method1 (This : in out A);
3220    pragma Import (C, Method1);
3221
3222    procedure Ada_Method2 (This : in out A; V : Integer);
3223    pragma Export (C, Ada_Method2);
3224
3225 end Simple_Cpp_Interface;
3226 @end smallexample
3227
3228 @node Interfacing with C++ constructors
3229 @subsection Interfacing with C++ constructors
3230 @noindent
3231
3232 In order to interface with C++ constructors GNAT provides the
3233 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3234 gnat_rm, GNAT Reference Manual}, for additional information).
3235 In this section we present some common uses of C++ constructors
3236 in mixed-languages programs in GNAT.
3237
3238 Let us assume that we need to interface with the following
3239 C++ class:
3240
3241 @smallexample
3242 @b{class} Root @{
3243 @b{public}:
3244   int  a_value;
3245   int  b_value;
3246   @b{virtual} int Get_Value ();
3247   Root();              // Default constructor
3248   Root(int v);         // 1st non-default constructor
3249   Root(int v, int w);  // 2nd non-default constructor
3250 @};
3251 @end smallexample
3252
3253 For this purpose we can write the following package spec (further
3254 information on how to build this spec is available in
3255 @ref{Interfacing with C++ at the Class Level} and
3256 @ref{Generating Ada Bindings for C and C++ headers}).
3257
3258 @smallexample @c ada
3259 with Interfaces.C; use Interfaces.C;
3260 package Pkg_Root is
3261   type Root is tagged limited record
3262      A_Value : int;
3263      B_Value : int;
3264   end record;
3265   pragma Import (CPP, Root);
3266
3267   function Get_Value (Obj : Root) return int;
3268   pragma Import (CPP, Get_Value);
3269
3270   function Constructor return Root;
3271   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3272
3273   function Constructor (v : Integer) return Root;
3274   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3275
3276   function Constructor (v, w : Integer) return Root;
3277   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3278 end Pkg_Root;
3279 @end smallexample
3280
3281 On the Ada side the constructor is represented by a function (whose
3282 name is arbitrary) that returns the classwide type corresponding to
3283 the imported C++ class. Although the constructor is described as a
3284 function, it is typically a procedure with an extra implicit argument
3285 (the object being initialized) at the implementation level. GNAT
3286 issues the appropriate call, whatever it is, to get the object
3287 properly initialized.
3288
3289 Constructors can only appear in the following contexts:
3290
3291 @itemize @bullet
3292 @item
3293 On the right side of an initialization of an object of type @var{T}.
3294 @item
3295 On the right side of an initialization of a record component of type @var{T}.
3296 @item
3297 In an Ada 2005 limited aggregate.
3298 @item
3299 In an Ada 2005 nested limited aggregate.
3300 @item
3301 In an Ada 2005 limited aggregate that initializes an object built in
3302 place by an extended return statement.
3303 @end itemize
3304
3305 @noindent
3306 In a declaration of an object whose type is a class imported from C++,
3307 either the default C++ constructor is implicitly called by GNAT, or
3308 else the required C++ constructor must be explicitly called in the
3309 expression that initializes the object. For example:
3310
3311 @smallexample @c ada
3312   Obj1 : Root;
3313   Obj2 : Root := Constructor;
3314   Obj3 : Root := Constructor (v => 10);
3315   Obj4 : Root := Constructor (30, 40);
3316 @end smallexample
3317
3318 The first two declarations are equivalent: in both cases the default C++
3319 constructor is invoked (in the former case the call to the constructor is
3320 implicit, and in the latter case the call is explicit in the object
3321 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3322 that takes an integer argument, and @code{Obj4} is initialized by the
3323 non-default C++ constructor that takes two integers.
3324
3325 Let us derive the imported C++ class in the Ada side. For example:
3326
3327 @smallexample @c ada
3328   type DT is new Root with record
3329      C_Value : Natural := 2009;
3330   end record;
3331 @end smallexample
3332
3333 In this case the components DT inherited from the C++ side must be
3334 initialized by a C++ constructor, and the additional Ada components
3335 of type DT are initialized by GNAT. The initialization of such an
3336 object is done either by default, or by means of a function returning
3337 an aggregate of type DT, or by means of an extension aggregate.
3338
3339 @smallexample @c ada
3340   Obj5 : DT;
3341   Obj6 : DT := Function_Returning_DT (50);
3342   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3343 @end smallexample
3344
3345 The declaration of @code{Obj5} invokes the default constructors: the
3346 C++ default constructor of the parent type takes care of the initialization
3347 of the components inherited from Root, and GNAT takes care of the default
3348 initialization of the additional Ada components of type DT (that is,
3349 @code{C_Value} is initialized to value 2009). The order of invocation of
3350 the constructors is consistent with the order of elaboration required by
3351 Ada and C++. That is, the constructor of the parent type is always called
3352 before the constructor of the derived type.
3353
3354 Let us now consider a record that has components whose type is imported
3355 from C++. For example:
3356
3357 @smallexample @c ada
3358   type Rec1 is limited record
3359      Data1 : Root := Constructor (10);
3360      Value : Natural := 1000;
3361   end record;
3362
3363   type Rec2 (D : Integer := 20) is limited record
3364      Rec   : Rec1;
3365      Data2 : Root := Constructor (D, 30);
3366   end record;
3367 @end smallexample
3368
3369 The initialization of an object of type @code{Rec2} will call the
3370 non-default C++ constructors specified for the imported components.
3371 For example:
3372
3373 @smallexample @c ada
3374   Obj8 : Rec2 (40);
3375 @end smallexample
3376
3377 Using Ada 2005 we can use limited aggregates to initialize an object
3378 invoking C++ constructors that differ from those specified in the type
3379 declarations. For example:
3380
3381 @smallexample @c ada
3382   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3383                           others => <>),
3384                   others => <>);
3385 @end smallexample
3386
3387 The above declaration uses an Ada 2005 limited aggregate to
3388 initialize @code{Obj9}, and the C++ constructor that has two integer
3389 arguments is invoked to initialize the @code{Data1} component instead
3390 of the constructor specified in the declaration of type @code{Rec1}. In
3391 Ada 2005 the box in the aggregate indicates that unspecified components
3392 are initialized using the expression (if any) available in the component
3393 declaration. That is, in this case discriminant @code{D} is initialized
3394 to value @code{20}, @code{Value} is initialized to value 1000, and the
3395 non-default C++ constructor that handles two integers takes care of
3396 initializing component @code{Data2} with values @code{20,30}.
3397
3398 In Ada 2005 we can use the extended return statement to build the Ada
3399 equivalent to C++ non-default constructors. For example:
3400
3401 @smallexample @c ada
3402   function Constructor (V : Integer) return Rec2 is
3403   begin
3404      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3405                                    others => <>),
3406                            others => <>) do
3407         --  Further actions required for construction of
3408         --  objects of type Rec2
3409         ...
3410      end record;
3411   end Constructor;
3412 @end smallexample
3413
3414 In this example the extended return statement construct is used to
3415 build in place the returned object whose components are initialized
3416 by means of a limited aggregate. Any further action associated with
3417 the constructor can be placed inside the construct.
3418
3419 @node Interfacing with C++ at the Class Level
3420 @subsection Interfacing with C++ at the Class Level
3421 @noindent
3422 In this section we demonstrate the GNAT features for interfacing with
3423 C++ by means of an example making use of Ada 2005 abstract interface
3424 types. This example consists of a classification of animals; classes
3425 have been used to model our main classification of animals, and
3426 interfaces provide support for the management of secondary
3427 classifications. We first demonstrate a case in which the types and
3428 constructors are defined on the C++ side and imported from the Ada
3429 side, and latter the reverse case.
3430
3431 The root of our derivation will be the @code{Animal} class, with a
3432 single private attribute (the @code{Age} of the animal) and two public
3433 primitives to set and get the value of this attribute.
3434
3435 @smallexample
3436 @b{class} Animal @{
3437  @b{public}:
3438    @b{virtual} void Set_Age (int New_Age);
3439    @b{virtual} int Age ();
3440  @b{private}:
3441    int Age_Count;
3442 @};
3443 @end smallexample
3444
3445 Abstract interface types are defined in C++ by means of classes with pure
3446 virtual functions and no data members. In our example we will use two
3447 interfaces that provide support for the common management of @code{Carnivore}
3448 and @code{Domestic} animals:
3449
3450 @smallexample
3451 @b{class} Carnivore @{
3452 @b{public}:
3453    @b{virtual} int Number_Of_Teeth () = 0;
3454 @};
3455
3456 @b{class} Domestic @{
3457 @b{public}:
3458    @b{virtual void} Set_Owner (char* Name) = 0;
3459 @};
3460 @end smallexample
3461
3462 Using these declarations, we can now say that a @code{Dog} is an animal that is
3463 both Carnivore and Domestic, that is:
3464
3465 @smallexample
3466 @b{class} Dog : Animal, Carnivore, Domestic @{
3467  @b{public}:
3468    @b{virtual} int  Number_Of_Teeth ();
3469    @b{virtual} void Set_Owner (char* Name);
3470
3471    Dog(); // Constructor
3472  @b{private}:
3473    int  Tooth_Count;
3474    char *Owner;
3475 @};
3476 @end smallexample
3477
3478 In the following examples we will assume that the previous declarations are
3479 located in a file named @code{animals.h}. The following package demonstrates
3480 how to import these C++ declarations from the Ada side:
3481
3482 @smallexample @c ada
3483 with Interfaces.C.Strings; use Interfaces.C.Strings;
3484 package Animals is
3485   type Carnivore is interface;
3486   pragma Convention (C_Plus_Plus, Carnivore);
3487   function Number_Of_Teeth (X : Carnivore)
3488      return Natural is abstract;
3489
3490   type Domestic is interface;
3491   pragma Convention (C_Plus_Plus, Set_Owner);
3492   procedure Set_Owner
3493     (X    : in out Domestic;
3494      Name : Chars_Ptr) is abstract;
3495
3496   type Animal is tagged record
3497     Age : Natural := 0;
3498   end record;
3499   pragma Import (C_Plus_Plus, Animal);
3500
3501   procedure Set_Age (X : in out Animal; Age : Integer);
3502   pragma Import (C_Plus_Plus, Set_Age);
3503
3504   function Age (X : Animal) return Integer;
3505   pragma Import (C_Plus_Plus, Age);
3506
3507   type Dog is new Animal and Carnivore and Domestic with record
3508     Tooth_Count : Natural;
3509     Owner       : String (1 .. 30);
3510   end record;
3511   pragma Import (C_Plus_Plus, Dog);
3512
3513   function Number_Of_Teeth (A : Dog) return Integer;
3514   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3515
3516   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3517   pragma Import (C_Plus_Plus, Set_Owner);
3518
3519   function New_Dog return Dog;
3520   pragma CPP_Constructor (New_Dog);
3521   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3522 end Animals;
3523 @end smallexample
3524
3525 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3526 interfacing with these C++ classes is easy. The only requirement is that all
3527 the primitives and components must be declared exactly in the same order in
3528 the two languages.
3529
3530 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3531 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3532 the arguments to the called primitives will be the same as for C++. For the
3533 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3534 to indicate that they have been defined on the C++ side; this is required
3535 because the dispatch table associated with these tagged types will be built
3536 in the C++ side and therefore will not contain the predefined Ada primitives
3537 which Ada would otherwise expect.
3538
3539 As the reader can see there is no need to indicate the C++ mangled names
3540 associated with each subprogram because it is assumed that all the calls to
3541 these primitives will be dispatching calls. The only exception is the
3542 constructor, which must be registered with the compiler by means of
3543 @code{pragma CPP_Constructor} and needs to provide its associated C++
3544 mangled name because the Ada compiler generates direct calls to it.
3545
3546 With the above packages we can now declare objects of type Dog on the Ada side
3547 and dispatch calls to the corresponding subprograms on the C++ side. We can
3548 also extend the tagged type Dog with further fields and primitives, and
3549 override some of its C++ primitives on the Ada side. For example, here we have
3550 a type derivation defined on the Ada side that inherits all the dispatching
3551 primitives of the ancestor from the C++ side.
3552
3553 @smallexample
3554 @b{with} Animals; @b{use} Animals;
3555 @b{package} Vaccinated_Animals @b{is}
3556   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3557   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3558 @b{end} Vaccinated_Animals;
3559 @end smallexample
3560
3561 It is important to note that, because of the ABI compatibility, the programmer
3562 does not need to add any further information to indicate either the object
3563 layout or the dispatch table entry associated with each dispatching operation.
3564
3565 Now let us define all the types and constructors on the Ada side and export
3566 them to C++, using the same hierarchy of our previous example:
3567
3568 @smallexample @c ada
3569 with Interfaces.C.Strings;
3570 use Interfaces.C.Strings;
3571 package Animals is
3572   type Carnivore is interface;
3573   pragma Convention (C_Plus_Plus, Carnivore);
3574   function Number_Of_Teeth (X : Carnivore)
3575      return Natural is abstract;
3576
3577   type Domestic is interface;
3578   pragma Convention (C_Plus_Plus, Set_Owner);
3579   procedure Set_Owner
3580     (X    : in out Domestic;
3581      Name : Chars_Ptr) is abstract;
3582
3583   type Animal is tagged record
3584     Age : Natural := 0;
3585   end record;
3586   pragma Convention (C_Plus_Plus, Animal);
3587
3588   procedure Set_Age (X : in out Animal; Age : Integer);
3589   pragma Export (C_Plus_Plus, Set_Age);
3590
3591   function Age (X : Animal) return Integer;
3592   pragma Export (C_Plus_Plus, Age);
3593
3594   type Dog is new Animal and Carnivore and Domestic with record
3595     Tooth_Count : Natural;
3596     Owner       : String (1 .. 30);
3597   end record;
3598   pragma Convention (C_Plus_Plus, Dog);
3599
3600   function Number_Of_Teeth (A : Dog) return Integer;
3601   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3602
3603   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3604   pragma Export (C_Plus_Plus, Set_Owner);
3605
3606   function New_Dog return Dog'Class;
3607   pragma Export (C_Plus_Plus, New_Dog);
3608 end Animals;
3609 @end smallexample
3610
3611 Compared with our previous example the only difference is the use of
3612 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3613 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3614 nothing else to be done; as explained above, the only requirement is that all
3615 the primitives and components are declared in exactly the same order.
3616
3617 For completeness, let us see a brief C++ main program that uses the
3618 declarations available in @code{animals.h} (presented in our first example) to
3619 import and use the declarations from the Ada side, properly initializing and
3620 finalizing the Ada run-time system along the way:
3621
3622 @smallexample
3623 @b{#include} "animals.h"
3624 @b{#include} <iostream>
3625 @b{using namespace} std;
3626
3627 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3628 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3629 void Check_Animal (Animal *obj)       @{@dots{}@}
3630 void Check_Dog (Dog *obj)             @{@dots{}@}
3631
3632 @b{extern} "C" @{
3633   void adainit (void);
3634   void adafinal (void);
3635   Dog* new_dog ();
3636 @}
3637
3638 void test ()
3639 @{
3640   Dog *obj = new_dog();  // Ada constructor
3641   Check_Carnivore (obj); // Check secondary DT
3642   Check_Domestic (obj);  // Check secondary DT
3643   Check_Animal (obj);    // Check primary DT
3644   Check_Dog (obj);       // Check primary DT
3645 @}
3646
3647 int main ()
3648 @{
3649   adainit ();  test();  adafinal ();
3650   return 0;
3651 @}
3652 @end smallexample
3653
3654 @node Comparison between GNAT and C/C++ Compilation Models
3655 @section Comparison between GNAT and C/C++ Compilation Models
3656
3657 @noindent
3658 The GNAT model of compilation is close to the C and C++ models. You can
3659 think of Ada specs as corresponding to header files in C. As in C, you
3660 don't need to compile specs; they are compiled when they are used. The
3661 Ada @code{with} is similar in effect to the @code{#include} of a C
3662 header.
3663
3664 One notable difference is that, in Ada, you may compile specs separately
3665 to check them for semantic and syntactic accuracy. This is not always
3666 possible with C headers because they are fragments of programs that have
3667 less specific syntactic or semantic rules.
3668
3669 The other major difference is the requirement for running the binder,
3670 which performs two important functions. First, it checks for
3671 consistency. In C or C++, the only defense against assembling
3672 inconsistent programs lies outside the compiler, in a makefile, for
3673 example. The binder satisfies the Ada requirement that it be impossible
3674 to construct an inconsistent program when the compiler is used in normal
3675 mode.
3676
3677 @cindex Elaboration order control
3678 The other important function of the binder is to deal with elaboration
3679 issues. There are also elaboration issues in C++ that are handled
3680 automatically. This automatic handling has the advantage of being
3681 simpler to use, but the C++ programmer has no control over elaboration.
3682 Where @code{gnatbind} might complain there was no valid order of
3683 elaboration, a C++ compiler would simply construct a program that
3684 malfunctioned at run time.
3685 @end ifclear
3686
3687 @node Comparison between GNAT and Conventional Ada Library Models
3688 @section Comparison between GNAT and Conventional Ada Library Models
3689
3690 @noindent
3691 This section is intended for Ada programmers who have
3692 used an Ada compiler implementing the traditional Ada library
3693 model, as described in the Ada Reference Manual.
3694
3695 @cindex GNAT library
3696 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3697 source files themselves acts as the library. Compiling Ada programs does
3698 not generate any centralized information, but rather an object file and
3699 a ALI file, which are of interest only to the binder and linker.
3700 In a traditional system, the compiler reads information not only from
3701 the source file being compiled, but also from the centralized library.
3702 This means that the effect of a compilation depends on what has been
3703 previously compiled. In particular:
3704
3705 @itemize @bullet
3706 @item
3707 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3708 to the version of the unit most recently compiled into the library.
3709
3710 @item
3711 Inlining is effective only if the necessary body has already been
3712 compiled into the library.
3713
3714 @item
3715 Compiling a unit may obsolete other units in the library.
3716 @end itemize
3717
3718 @noindent
3719 In GNAT, compiling one unit never affects the compilation of any other
3720 units because the compiler reads only source files. Only changes to source
3721 files can affect the results of a compilation. In particular:
3722
3723 @itemize @bullet
3724 @item
3725 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3726 to the source version of the unit that is currently accessible to the
3727 compiler.
3728
3729 @item
3730 @cindex Inlining
3731 Inlining requires the appropriate source files for the package or
3732 subprogram bodies to be available to the compiler. Inlining is always
3733 effective, independent of the order in which units are complied.
3734
3735 @item
3736 Compiling a unit never affects any other compilations. The editing of
3737 sources may cause previous compilations to be out of date if they
3738 depended on the source file being modified.
3739 @end itemize
3740
3741 @noindent
3742 The most important result of these differences is that order of compilation
3743 is never significant in GNAT. There is no situation in which one is
3744 required to do one compilation before another. What shows up as order of
3745 compilation requirements in the traditional Ada library becomes, in
3746 GNAT, simple source dependencies; in other words, there is only a set
3747 of rules saying what source files must be present when a file is
3748 compiled.
3749
3750 @ifset vms
3751 @node Placement of temporary files
3752 @section Placement of temporary files
3753 @cindex Temporary files (user control over placement)
3754
3755 @noindent
3756 GNAT creates temporary files in the directory designated by the environment
3757 variable @env{TMPDIR}.
3758 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3759 for detailed information on how environment variables are resolved.
3760 For most users the easiest way to make use of this feature is to simply
3761 define @env{TMPDIR} as a job level logical name).
3762 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3763 for compiler temporary files, then you can include something like the
3764 following command in your @file{LOGIN.COM} file:
3765
3766 @smallexample
3767 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3768 @end smallexample
3769
3770 @noindent
3771 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3772 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3773 designated by @env{TEMP}.
3774 If none of these environment variables are defined then GNAT uses the
3775 directory designated by the logical name @code{SYS$SCRATCH:}
3776 (by default the user's home directory). If all else fails
3777 GNAT uses the current directory for temporary files.
3778 @end ifset
3779
3780 @c *************************
3781 @node Compiling Using gcc
3782 @chapter Compiling Using @command{gcc}
3783
3784 @noindent
3785 This chapter discusses how to compile Ada programs using the @command{gcc}
3786 command. It also describes the set of switches
3787 that can be used to control the behavior of the compiler.
3788 @menu
3789 * Compiling Programs::
3790 * Switches for gcc::
3791 * Search Paths and the Run-Time Library (RTL)::
3792 * Order of Compilation Issues::
3793 * Examples::
3794 @end menu
3795
3796 @node Compiling Programs
3797 @section Compiling Programs
3798
3799 @noindent
3800 The first step in creating an executable program is to compile the units
3801 of the program using the @command{gcc} command. You must compile the
3802 following files:
3803
3804 @itemize @bullet
3805 @item
3806 the body file (@file{.adb}) for a library level subprogram or generic
3807 subprogram
3808
3809 @item
3810 the spec file (@file{.ads}) for a library level package or generic
3811 package that has no body
3812
3813 @item
3814 the body file (@file{.adb}) for a library level package
3815 or generic package that has a body
3816
3817 @end itemize
3818
3819 @noindent
3820 You need @emph{not} compile the following files
3821
3822 @itemize @bullet
3823
3824 @item
3825 the spec of a library unit which has a body
3826
3827 @item
3828 subunits
3829 @end itemize
3830
3831 @noindent
3832 because they are compiled as part of compiling related units. GNAT
3833 package specs
3834 when the corresponding body is compiled, and subunits when the parent is
3835 compiled.
3836
3837 @cindex cannot generate code
3838 If you attempt to compile any of these files, you will get one of the
3839 following error messages (where @var{fff} is the name of the file you
3840 compiled):
3841
3842 @smallexample
3843 cannot generate code for file @var{fff} (package spec)
3844 to check package spec, use -gnatc
3845
3846 cannot generate code for file @var{fff} (missing subunits)
3847 to check parent unit, use -gnatc
3848
3849 cannot generate code for file @var{fff} (subprogram spec)
3850 to check subprogram spec, use -gnatc
3851
3852 cannot generate code for file @var{fff} (subunit)
3853 to check subunit, use -gnatc
3854 @end smallexample
3855
3856 @noindent
3857 As indicated by the above error messages, if you want to submit
3858 one of these files to the compiler to check for correct semantics
3859 without generating code, then use the @option{-gnatc} switch.
3860
3861 The basic command for compiling a file containing an Ada unit is
3862
3863 @smallexample
3864 @c $ gcc -c @ovar{switches} @file{file name}
3865 @c Expanding @ovar macro inline (explanation in macro def comments)
3866 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3867 @end smallexample
3868
3869 @noindent
3870 where @var{file name} is the name of the Ada file (usually
3871 having an extension
3872 @file{.ads} for a spec or @file{.adb} for a body).
3873 @ifclear vms
3874 You specify the
3875 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3876 @end ifclear
3877 The result of a successful compilation is an object file, which has the
3878 same name as the source file but an extension of @file{.o} and an Ada
3879 Library Information (ALI) file, which also has the same name as the
3880 source file, but with @file{.ali} as the extension. GNAT creates these
3881 two output files in the current directory, but you may specify a source
3882 file in any directory using an absolute or relative path specification
3883 containing the directory information.
3884
3885 @findex gnat1
3886 @command{gcc} is actually a driver program that looks at the extensions of
3887 the file arguments and loads the appropriate compiler. For example, the
3888 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3889 These programs are in directories known to the driver program (in some
3890 configurations via environment variables you set), but need not be in
3891 your path. The @command{gcc} driver also calls the assembler and any other
3892 utilities needed to complete the generation of the required object
3893 files.
3894
3895 It is possible to supply several file names on the same @command{gcc}
3896 command. This causes @command{gcc} to call the appropriate compiler for
3897 each file. For example, the following command lists three separate
3898 files to be compiled:
3899
3900 @smallexample
3901 $ gcc -c x.adb y.adb z.c
3902 @end smallexample
3903
3904 @noindent
3905 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3906 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3907 The compiler generates three object files @file{x.o}, @file{y.o} and
3908 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3909 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3910 @ifclear vms
3911 except for
3912 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3913 @end ifclear
3914
3915 @node Switches for gcc
3916 @section Switches for @command{gcc}
3917
3918 @noindent
3919 The @command{gcc} command accepts switches that control the
3920 compilation process. These switches are fully described in this section.
3921 First we briefly list all the switches, in alphabetical order, then we
3922 describe the switches in more detail in functionally grouped sections.
3923
3924 More switches exist for GCC than those documented here, especially
3925 for specific targets. However, their use is not recommended as
3926 they may change code generation in ways that are incompatible with
3927 the Ada run-time library, or can cause inconsistencies between
3928 compilation units.
3929
3930 @menu
3931 * Output and Error Message Control::
3932 * Warning Message Control::
3933 * Debugging and Assertion Control::
3934 * Validity Checking::
3935 * Style Checking::
3936 * Run-Time Checks::
3937 * Using gcc for Syntax Checking::
3938 * Using gcc for Semantic Checking::
3939 * Compiling Different Versions of Ada::
3940 * Character Set Control::
3941 * File Naming Control::
3942 * Subprogram Inlining Control::
3943 * Auxiliary Output Control::
3944 * Debugging Control::
3945 * Exception Handling Control::
3946 * Units to Sources Mapping Files::
3947 * Integrated Preprocessing::
3948 * Code Generation Control::
3949 @ifset vms
3950 * Return Codes::
3951 @end ifset
3952 @end menu
3953
3954 @table @option
3955 @c !sort!
3956 @ifclear vms
3957 @cindex @option{-b} (@command{gcc})
3958 @item -b @var{target}
3959 Compile your program to run on @var{target}, which is the name of a
3960 system configuration. You must have a GNAT cross-compiler built if
3961 @var{target} is not the same as your host system.
3962
3963 @item -B@var{dir}
3964 @cindex @option{-B} (@command{gcc})
3965 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3966 from @var{dir} instead of the default location. Only use this switch
3967 when multiple versions of the GNAT compiler are available.
3968 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3969 GNU Compiler Collection (GCC)}, for further details. You would normally
3970 use the @option{-b} or @option{-V} switch instead.
3971
3972 @item -c
3973 @cindex @option{-c} (@command{gcc})
3974 Compile. Always use this switch when compiling Ada programs.
3975
3976 Note: for some other languages when using @command{gcc}, notably in
3977 the case of C and C++, it is possible to use
3978 use @command{gcc} without a @option{-c} switch to
3979 compile and link in one step. In the case of GNAT, you
3980 cannot use this approach, because the binder must be run
3981 and @command{gcc} cannot be used to run the GNAT binder.
3982 @end ifclear
3983
3984 @item -fno-inline
3985 @cindex @option{-fno-inline} (@command{gcc})
3986 Suppresses all inlining, even if other optimization or inlining
3987 switches are set.  This includes suppression of inlining that
3988 results from the use of the pragma @code{Inline_Always}.
3989 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3990 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3991 effect if this switch is present.
3992
3993 @item -fno-inline-functions
3994 @cindex @option{-fno-inline-functions} (@command{gcc})
3995 Suppresses automatic inlining of subprograms, which is enabled
3996 if @option{-O3} is used.
3997
3998 @item -fno-inline-small-functions
3999 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4000 Suppresses automatic inlining of small subprograms, which is enabled
4001 if @option{-O2} is used.
4002
4003 @item -fno-inline-functions-called-once
4004 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4005 Suppresses inlining of subprograms local to the unit and called once
4006 from within it, which is enabled if @option{-O1} is used.
4007
4008 @item -fno-ivopts
4009 @cindex @option{-fno-ivopts} (@command{gcc})
4010 Suppresses high-level loop induction variable optimizations, which are
4011 enabled if @option{-O1} is used. These optimizations are generally
4012 profitable but, for some specific cases of loops with numerous uses
4013 of the iteration variable that follow a common pattern, they may end
4014 up destroying the regularity that could be exploited at a lower level
4015 and thus producing inferior code.
4016
4017 @item -fno-strict-aliasing
4018 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4019 Causes the compiler to avoid assumptions regarding non-aliasing
4020 of objects of different types. See
4021 @ref{Optimization and Strict Aliasing} for details.
4022
4023 @item -fstack-check
4024 @cindex @option{-fstack-check} (@command{gcc})
4025 Activates stack checking.
4026 See @ref{Stack Overflow Checking} for details.
4027
4028 @item -fstack-usage
4029 @cindex @option{-fstack-usage} (@command{gcc})
4030 Makes the compiler output stack usage information for the program, on a
4031 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4032
4033 @item -fcallgraph-info@r{[}=su@r{]}
4034 @cindex @option{-fcallgraph-info} (@command{gcc})
4035 Makes the compiler output callgraph information for the program, on a
4036 per-file basis.  The information is generated in the VCG format.  It can
4037 be decorated with stack-usage per-node information.
4038
4039 @item ^-g^/DEBUG^
4040 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4041 Generate debugging information. This information is stored in the object
4042 file and copied from there to the final executable file by the linker,
4043 where it can be read by the debugger. You must use the
4044 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4045
4046 @item -gnat83
4047 @cindex @option{-gnat83} (@command{gcc})
4048 Enforce Ada 83 restrictions.
4049
4050 @item -gnat95
4051 @cindex @option{-gnat95} (@command{gcc})
4052 Enforce Ada 95 restrictions.
4053
4054 @item -gnat05
4055 @cindex @option{-gnat05} (@command{gcc})
4056 Allow full Ada 2005 features.
4057
4058 @item -gnat2005
4059 @cindex @option{-gnat2005} (@command{gcc})
4060 Allow full Ada 2005 features (same as @option{-gnat05})
4061
4062 @item -gnat12
4063 @cindex @option{-gnat12} (@command{gcc})
4064
4065 @item -gnat2012
4066 @cindex @option{-gnat2012} (@command{gcc})
4067 Allow full Ada 2012 features (same as @option{-gnat12})
4068
4069 @item -gnata
4070 @cindex @option{-gnata} (@command{gcc})
4071 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4072 activated. Note that these pragmas can also be controlled using the
4073 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4074 It also activates pragmas @code{Check}, @code{Precondition}, and
4075 @code{Postcondition}. Note that these pragmas can also be controlled
4076 using the configuration pragma @code{Check_Policy}.
4077
4078 @item -gnatA
4079 @cindex @option{-gnatA} (@command{gcc})
4080 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4081 it will be ignored.
4082
4083 @item -gnatb
4084 @cindex @option{-gnatb} (@command{gcc})
4085 Generate brief messages to @file{stderr} even if verbose mode set.
4086
4087 @item -gnatB
4088 @cindex @option{-gnatB} (@command{gcc})
4089 Assume no invalid (bad) values except for 'Valid attribute use
4090 (@pxref{Validity Checking}).
4091
4092 @item -gnatc
4093 @cindex @option{-gnatc} (@command{gcc})
4094 Check syntax and semantics only (no code generation attempted).
4095
4096 @item -gnatC
4097 @cindex @option{-gnatC} (@command{gcc})
4098 Generate CodePeer information (no code generation attempted).
4099 This switch will generate an intermediate representation suitable for
4100 use by CodePeer (@file{.scil} files). This switch is not compatible with
4101 code generation (it will, among other things, disable some switches such
4102 as -gnatn, and enable others such as -gnata).
4103
4104 @item -gnatd
4105 @cindex @option{-gnatd} (@command{gcc})
4106 Specify debug options for the compiler. The string of characters after
4107 the @option{-gnatd} specify the specific debug options. The possible
4108 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4109 compiler source file @file{debug.adb} for details of the implemented
4110 debug options. Certain debug options are relevant to applications
4111 programmers, and these are documented at appropriate points in this
4112 users guide.
4113
4114 @ifclear vms
4115 @item -gnatD
4116 @cindex @option{-gnatD[nn]} (@command{gcc})
4117 @end ifclear
4118 @ifset vms
4119 @item /XDEBUG /LXDEBUG=nnn
4120 @end ifset
4121 Create expanded source files for source level debugging. This switch
4122 also suppress generation of cross-reference information
4123 (see @option{-gnatx}).
4124
4125 @item -gnatec=@var{path}
4126 @cindex @option{-gnatec} (@command{gcc})
4127 Specify a configuration pragma file
4128 @ifclear vms
4129 (the equal sign is optional)
4130 @end ifclear
4131 (@pxref{The Configuration Pragmas Files}).
4132
4133 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4134 @cindex @option{-gnateD} (@command{gcc})
4135 Defines a symbol, associated with @var{value}, for preprocessing.
4136 (@pxref{Integrated Preprocessing}).
4137
4138 @item -gnateE
4139 @cindex @option{-gnateE} (@command{gcc})
4140 Generate extra information in exception messages. In particular, display
4141 extra column information and the value and range associated with index and
4142 range check failures, and extra column information for access checks.
4143 In cases where the compiler is able to determine at compile time that
4144 a check will fail, it gives a warning, and the extra information is not
4145 produced at run time.
4146
4147 @item -gnatef
4148 @cindex @option{-gnatef} (@command{gcc})
4149 Display full source path name in brief error messages.
4150
4151 @item -gnateG
4152 @cindex @option{-gnateG} (@command{gcc})
4153 Save result of preprocessing in a text file.
4154
4155 @item ^-gnateI^/MULTI_UNIT_INDEX=^@var{nnn}
4156 @cindex @option{-gnateI} (@command{gcc})
4157 Indicates that the source is a multi-unit source and that the index of the
4158 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4159 to be a valid index in the multi-unit source.
4160
4161 @item -gnatem=@var{path}
4162 @cindex @option{-gnatem} (@command{gcc})
4163 Specify a mapping file
4164 @ifclear vms
4165 (the equal sign is optional)
4166 @end ifclear
4167 (@pxref{Units to Sources Mapping Files}).
4168
4169 @item -gnatep=@var{file}
4170 @cindex @option{-gnatep} (@command{gcc})
4171 Specify a preprocessing data file
4172 @ifclear vms
4173 (the equal sign is optional)
4174 @end ifclear
4175 (@pxref{Integrated Preprocessing}).
4176
4177 @item -gnateP
4178 @cindex @option{-gnateP} (@command{gcc})
4179 Turn categorization dependency errors into warnings.
4180 Ada requires that units that WITH one another have compatible categories, for
4181 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4182 these errors become warnings (which can be ignored, or suppressed in the usual
4183 manner). This can be useful in some specialized circumstances such as the
4184 temporary use of special test software.
4185 @item -gnateS
4186 @cindex @option{-gnateS} (@command{gcc})
4187 Generate SCO (Source Coverage Obligation) information in the ALI
4188 file. This information is used by advanced coverage tools. See
4189 unit @file{SCOs} in the compiler sources for details in files
4190 @file{scos.ads} and @file{scos.adb}.
4191
4192 @item -gnatE
4193 @cindex @option{-gnatE} (@command{gcc})
4194 Full dynamic elaboration checks.
4195
4196 @item -gnatf
4197 @cindex @option{-gnatf} (@command{gcc})
4198 Full errors. Multiple errors per line, all undefined references, do not
4199 attempt to suppress cascaded errors.
4200
4201 @item -gnatF
4202 @cindex @option{-gnatF} (@command{gcc})
4203 Externals names are folded to all uppercase.
4204
4205 @item ^-gnatg^/GNAT_INTERNAL^
4206 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4207 Internal GNAT implementation mode. This should not be used for
4208 applications programs, it is intended only for use by the compiler
4209 and its run-time library. For documentation, see the GNAT sources.
4210 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4211 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4212 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4213 so that all standard warnings and all standard style options are turned on.
4214 All warnings and style messages are treated as errors.
4215
4216 @ifclear vms
4217 @item -gnatG=nn
4218 @cindex @option{-gnatG[nn]} (@command{gcc})
4219 @end ifclear
4220 @ifset vms
4221 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4222 @end ifset
4223 List generated expanded code in source form.
4224
4225 @item ^-gnath^/HELP^
4226 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4227 Output usage information. The output is written to @file{stdout}.
4228
4229 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4230 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4231 Identifier character set
4232 @ifclear vms
4233 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4234 @end ifclear
4235 For details of the possible selections for @var{c},
4236 see @ref{Character Set Control}.
4237
4238 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4239 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4240 Ignore representation clauses. When this switch is used,
4241 representation clauses are treated as comments. This is useful
4242 when initially porting code where you want to ignore rep clause
4243 problems, and also for compiling foreign code (particularly
4244 for use with ASIS). The representation clauses that are ignored
4245 are: enumeration_representation_clause, record_representation_clause,
4246 and attribute_definition_clause for the following attributes:
4247 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4248 Object_Size, Size, Small, Stream_Size, and Value_Size.
4249 Note that this option should be used only for compiling -- the
4250 code is likely to malfunction at run time.
4251
4252 @item -gnatjnn
4253 @cindex @option{-gnatjnn} (@command{gcc})
4254 Reformat error messages to fit on nn character lines
4255
4256 @item -gnatk=@var{n}
4257 @cindex @option{-gnatk} (@command{gcc})
4258 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4259
4260 @item -gnatl
4261 @cindex @option{-gnatl} (@command{gcc})
4262 Output full source listing with embedded error messages.
4263
4264 @item -gnatL
4265 @cindex @option{-gnatL} (@command{gcc})
4266 Used in conjunction with -gnatG or -gnatD to intersperse original
4267 source lines (as comment lines with line numbers) in the expanded
4268 source output.
4269
4270 @item -gnatm=@var{n}
4271 @cindex @option{-gnatm} (@command{gcc})
4272 Limit number of detected error or warning messages to @var{n}
4273 where @var{n} is in the range 1..999999. The default setting if
4274 no switch is given is 9999. If the number of warnings reaches this
4275 limit, then a message is output and further warnings are suppressed,
4276 but the compilation is continued. If the number of error messages
4277 reaches this limit, then a message is output and the compilation
4278 is abandoned. The equal sign here is optional. A value of zero
4279 means that no limit applies.
4280
4281 @item -gnatn
4282 @cindex @option{-gnatn} (@command{gcc})
4283 Activate inlining for subprograms for which
4284 pragma @code{Inline} is specified. This inlining is performed
4285 by the GCC back-end.
4286
4287 @item -gnatN
4288 @cindex @option{-gnatN} (@command{gcc})
4289 Activate front end inlining for subprograms for which
4290 pragma @code{Inline} is specified. This inlining is performed
4291 by the front end and will be visible in the
4292 @option{-gnatG} output.
4293
4294 When using a gcc-based back end (in practice this means using any version
4295 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4296 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4297 Historically front end inlining was more extensive than the gcc back end
4298 inlining, but that is no longer the case.
4299
4300 @item -gnato
4301 @cindex @option{-gnato} (@command{gcc})
4302 Enable numeric overflow checking (which is not normally enabled by
4303 default). Note that division by zero is a separate check that is not
4304 controlled by this switch (division by zero checking is on by default).
4305
4306 @item -gnatp
4307 @cindex @option{-gnatp} (@command{gcc})
4308 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4309 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4310
4311 @item -gnat-p
4312 @cindex @option{-gnat-p} (@command{gcc})
4313 Cancel effect of previous @option{-gnatp} switch.
4314
4315 @item -gnatP
4316 @cindex @option{-gnatP} (@command{gcc})
4317 Enable polling. This is required on some systems (notably Windows NT) to
4318 obtain asynchronous abort and asynchronous transfer of control capability.
4319 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4320 details.
4321
4322 @item -gnatq
4323 @cindex @option{-gnatq} (@command{gcc})
4324 Don't quit. Try semantics, even if parse errors.
4325
4326 @item -gnatQ
4327 @cindex @option{-gnatQ} (@command{gcc})
4328 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4329
4330 @item -gnatr
4331 @cindex @option{-gnatr} (@command{gcc})
4332 Treat pragma Restrictions as Restriction_Warnings.
4333
4334 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4335 @cindex @option{-gnatR} (@command{gcc})
4336 Output representation information for declared types and objects.
4337
4338 @item -gnats
4339 @cindex @option{-gnats} (@command{gcc})
4340 Syntax check only.
4341
4342 @item -gnatS
4343 @cindex @option{-gnatS} (@command{gcc})
4344 Print package Standard.
4345
4346 @item -gnatt
4347 @cindex @option{-gnatt} (@command{gcc})
4348 Generate tree output file.
4349
4350 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4351 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4352 All compiler tables start at @var{nnn} times usual starting size.
4353
4354 @item -gnatu
4355 @cindex @option{-gnatu} (@command{gcc})
4356 List units for this compilation.
4357
4358 @item -gnatU
4359 @cindex @option{-gnatU} (@command{gcc})
4360 Tag all error messages with the unique string ``error:''
4361
4362 @item -gnatv
4363 @cindex @option{-gnatv} (@command{gcc})
4364 Verbose mode. Full error output with source lines to @file{stdout}.
4365
4366 @item -gnatV
4367 @cindex @option{-gnatV} (@command{gcc})
4368 Control level of validity checking (@pxref{Validity Checking}).
4369
4370 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4371 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4372 Warning mode where
4373 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4374 the exact warnings that
4375 are enabled or disabled (@pxref{Warning Message Control}).
4376
4377 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4378 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4379 Wide character encoding method
4380 @ifclear vms
4381 (@var{e}=n/h/u/s/e/8).
4382 @end ifclear
4383 @ifset vms
4384 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4385 @end ifset
4386
4387 @item -gnatx
4388 @cindex @option{-gnatx} (@command{gcc})
4389 Suppress generation of cross-reference information.
4390
4391 @item -gnatX
4392 @cindex @option{-gnatX} (@command{gcc})
4393 Enable GNAT implementation extensions and latest Ada version.
4394
4395 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4396 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4397 Enable built-in style checks (@pxref{Style Checking}).
4398
4399 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4400 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4401 Distribution stub generation and compilation
4402 @ifclear vms
4403 (@var{m}=r/c for receiver/caller stubs).
4404 @end ifclear
4405 @ifset vms
4406 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4407 to be generated and compiled).
4408 @end ifset
4409
4410 @item ^-I^/SEARCH=^@var{dir}
4411 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4412 @cindex RTL
4413 Direct GNAT to search the @var{dir} directory for source files needed by
4414 the current compilation
4415 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4416
4417 @item ^-I-^/NOCURRENT_DIRECTORY^
4418 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4419 @cindex RTL
4420 Except for the source file named in the command line, do not look for source
4421 files in the directory containing the source file named in the command line
4422 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4423
4424 @ifclear vms
4425 @item -mbig-switch
4426 @cindex @option{-mbig-switch} (@command{gcc})
4427 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4428 This standard gcc switch causes the compiler to use larger offsets in its
4429 jump table representation for @code{case} statements.
4430 This may result in less efficient code, but is sometimes necessary
4431 (for example on HP-UX targets)
4432 @cindex HP-UX and @option{-mbig-switch} option
4433 in order to compile large and/or nested @code{case} statements.
4434
4435 @item -o @var{file}
4436 @cindex @option{-o} (@command{gcc})
4437 This switch is used in @command{gcc} to redirect the generated object file
4438 and its associated ALI file. Beware of this switch with GNAT, because it may
4439 cause the object file and ALI file to have different names which in turn
4440 may confuse the binder and the linker.
4441 @end ifclear
4442
4443 @item -nostdinc
4444 @cindex @option{-nostdinc} (@command{gcc})
4445 Inhibit the search of the default location for the GNAT Run Time
4446 Library (RTL) source files.
4447
4448 @item -nostdlib
4449 @cindex @option{-nostdlib} (@command{gcc})
4450 Inhibit the search of the default location for the GNAT Run Time
4451 Library (RTL) ALI files.
4452
4453 @ifclear vms
4454 @c @item -O@ovar{n}
4455 @c Expanding @ovar macro inline (explanation in macro def comments)
4456 @item -O@r{[}@var{n}@r{]}
4457 @cindex @option{-O} (@command{gcc})
4458 @var{n} controls the optimization level.
4459
4460 @table @asis
4461 @item n = 0
4462 No optimization, the default setting if no @option{-O} appears
4463
4464 @item n = 1
4465 Normal optimization, the default if you specify @option{-O} without
4466 an operand. A good compromise between code quality and compilation
4467 time.
4468
4469 @item n = 2
4470 Extensive optimization, may improve execution time, possibly at the cost of
4471 substantially increased compilation time.
4472
4473 @item n = 3
4474 Same as @option{-O2}, and also includes inline expansion for small subprograms
4475 in the same unit.
4476
4477 @item n = s
4478 Optimize space usage
4479 @end table
4480
4481 @noindent
4482 See also @ref{Optimization Levels}.
4483 @end ifclear
4484
4485 @ifset vms
4486 @item  /NOOPTIMIZE
4487 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4488 Equivalent to @option{/OPTIMIZE=NONE}.
4489 This is the default behavior in the absence of an @option{/OPTIMIZE}
4490 qualifier.
4491
4492 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4493 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4494 Selects the level of optimization for your program. The supported
4495 keywords are as follows:
4496 @table @code
4497 @item   ALL
4498 Perform most optimizations, including those that
4499 are expensive.
4500 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4501 without keyword options.
4502
4503 @item   NONE
4504 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4505
4506 @item SOME
4507 Perform some optimizations, but omit ones that are costly.
4508
4509 @item   DEVELOPMENT
4510 Same as @code{SOME}.
4511
4512 @item INLINING
4513 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4514 automatic inlining of small subprograms within a unit
4515
4516 @item   UNROLL_LOOPS
4517 Try to unroll loops. This keyword may be specified together with
4518 any keyword above other than @code{NONE}. Loop unrolling
4519 usually, but not always, improves the performance of programs.
4520
4521 @item SPACE
4522 Optimize space usage
4523 @end table
4524
4525 @noindent
4526 See also @ref{Optimization Levels}.
4527 @end ifset
4528
4529 @ifclear vms
4530 @item -pass-exit-codes
4531 @cindex @option{-pass-exit-codes} (@command{gcc})
4532 Catch exit codes from the compiler and use the most meaningful as
4533 exit status.
4534 @end ifclear
4535
4536 @item --RTS=@var{rts-path}
4537 @cindex @option{--RTS} (@command{gcc})
4538 Specifies the default location of the runtime library. Same meaning as the
4539 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4540
4541 @item ^-S^/ASM^
4542 @cindex @option{^-S^/ASM^} (@command{gcc})
4543 ^Used in place of @option{-c} to^Used to^
4544 cause the assembler source file to be
4545 generated, using @file{^.s^.S^} as the extension,
4546 instead of the object file.
4547 This may be useful if you need to examine the generated assembly code.
4548
4549 @item ^-fverbose-asm^/VERBOSE_ASM^
4550 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4551 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4552 to cause the generated assembly code file to be annotated with variable
4553 names, making it significantly easier to follow.
4554
4555 @item ^-v^/VERBOSE^
4556 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4557 Show commands generated by the @command{gcc} driver. Normally used only for
4558 debugging purposes or if you need to be sure what version of the
4559 compiler you are executing.
4560
4561 @ifclear vms
4562 @item -V @var{ver}
4563 @cindex @option{-V} (@command{gcc})
4564 Execute @var{ver} version of the compiler. This is the @command{gcc}
4565 version, not the GNAT version.
4566 @end ifclear
4567
4568 @item ^-w^/NO_BACK_END_WARNINGS^
4569 @cindex @option{-w} (@command{gcc})
4570 Turn off warnings generated by the back end of the compiler. Use of
4571 this switch also causes the default for front end warnings to be set
4572 to suppress (as though @option{-gnatws} had appeared at the start of
4573 the options).
4574
4575 @end table
4576
4577 @ifclear vms
4578 @c Combining qualifiers does not work on VMS
4579 You may combine a sequence of GNAT switches into a single switch. For
4580 example, the combined switch
4581
4582 @cindex Combining GNAT switches
4583 @smallexample
4584 -gnatofi3
4585 @end smallexample
4586
4587 @noindent
4588 is equivalent to specifying the following sequence of switches:
4589
4590 @smallexample
4591 -gnato -gnatf -gnati3
4592 @end smallexample
4593 @end ifclear
4594
4595 @noindent
4596 The following restrictions apply to the combination of switches
4597 in this manner:
4598
4599 @itemize @bullet
4600 @item
4601 The switch @option{-gnatc} if combined with other switches must come
4602 first in the string.
4603
4604 @item
4605 The switch @option{-gnats} if combined with other switches must come
4606 first in the string.
4607
4608 @item
4609 The switches
4610 ^^@option{/DISTRIBUTION_STUBS=},^
4611 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4612 switches, and only one of them may appear in the command line.
4613
4614 @item
4615 The switch @option{-gnat-p} may not be combined with any other switch.
4616
4617 @ifclear vms
4618 @item
4619 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4620 switch), then all further characters in the switch are interpreted
4621 as style modifiers (see description of @option{-gnaty}).
4622
4623 @item
4624 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4625 switch), then all further characters in the switch are interpreted
4626 as debug flags (see description of @option{-gnatd}).
4627
4628 @item
4629 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4630 switch), then all further characters in the switch are interpreted
4631 as warning mode modifiers (see description of @option{-gnatw}).
4632
4633 @item
4634 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4635 switch), then all further characters in the switch are interpreted
4636 as validity checking options (@pxref{Validity Checking}).
4637
4638 @item
4639 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4640 a combined list of options.
4641 @end ifclear
4642 @end itemize
4643
4644 @node Output and Error Message Control
4645 @subsection Output and Error Message Control
4646 @findex stderr
4647
4648 @noindent
4649 The standard default format for error messages is called ``brief format''.
4650 Brief format messages are written to @file{stderr} (the standard error
4651 file) and have the following form:
4652
4653 @smallexample
4654 e.adb:3:04: Incorrect spelling of keyword "function"
4655 e.adb:4:20: ";" should be "is"
4656 @end smallexample
4657
4658 @noindent
4659 The first integer after the file name is the line number in the file,
4660 and the second integer is the column number within the line.
4661 @ifclear vms
4662 @code{GPS} can parse the error messages
4663 and point to the referenced character.
4664 @end ifclear
4665 The following switches provide control over the error message
4666 format:
4667
4668 @table @option
4669 @c !sort!
4670 @item -gnatv
4671 @cindex @option{-gnatv} (@command{gcc})
4672 @findex stdout
4673 @ifclear vms
4674 The v stands for verbose.
4675 @end ifclear
4676 The effect of this setting is to write long-format error
4677 messages to @file{stdout} (the standard output file.
4678 The same program compiled with the
4679 @option{-gnatv} switch would generate:
4680
4681 @smallexample
4682 @cartouche
4683 3. funcion X (Q : Integer)
4684    |
4685 >>> Incorrect spelling of keyword "function"
4686 4. return Integer;
4687                  |
4688 >>> ";" should be "is"
4689 @end cartouche
4690 @end smallexample
4691
4692 @noindent
4693 The vertical bar indicates the location of the error, and the @samp{>>>}
4694 prefix can be used to search for error messages. When this switch is
4695 used the only source lines output are those with errors.
4696
4697 @item -gnatl
4698 @cindex @option{-gnatl} (@command{gcc})
4699 @ifclear vms
4700 The @code{l} stands for list.
4701 @end ifclear
4702 This switch causes a full listing of
4703 the file to be generated. In the case where a body is
4704 compiled, the corresponding spec is also listed, along
4705 with any subunits. Typical output from compiling a package
4706 body @file{p.adb} might look like:
4707
4708 @smallexample @c ada
4709 @cartouche
4710  Compiling: p.adb
4711
4712      1. package body p is
4713      2.    procedure a;
4714      3.    procedure a is separate;
4715      4. begin
4716      5.    null
4717                |
4718         >>> missing ";"
4719
4720      6. end;
4721
4722 Compiling: p.ads
4723
4724      1. package p is
4725      2.    pragma Elaborate_Body
4726                                 |
4727         >>> missing ";"
4728
4729      3. end p;
4730
4731 Compiling: p-a.adb
4732
4733      1. separate p
4734                 |
4735         >>> missing "("
4736
4737      2. procedure a is
4738      3. begin
4739      4.    null
4740                |
4741         >>> missing ";"
4742
4743      5. end;
4744 @end cartouche
4745 @end smallexample
4746
4747 @noindent
4748 @findex stderr
4749 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4750 standard output is redirected, a brief summary is written to
4751 @file{stderr} (standard error) giving the number of error messages and
4752 warning messages generated.
4753
4754 @item ^-gnatl^/OUTPUT_FILE^=file
4755 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4756 This has the same effect as @option{-gnatl} except that the output is
4757 written to a file instead of to standard output. If the given name
4758 @file{fname} does not start with a period, then it is the full name
4759 of the file to be written. If @file{fname} is an extension, it is
4760 appended to the name of the file being compiled. For example, if
4761 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4762 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4763
4764 @item -gnatU
4765 @cindex @option{-gnatU} (@command{gcc})
4766 This switch forces all error messages to be preceded by the unique
4767 string ``error:''. This means that error messages take a few more
4768 characters in space, but allows easy searching for and identification
4769 of error messages.
4770
4771 @item -gnatb
4772 @cindex @option{-gnatb} (@command{gcc})
4773 @ifclear vms
4774 The @code{b} stands for brief.
4775 @end ifclear
4776 This switch causes GNAT to generate the
4777 brief format error messages to @file{stderr} (the standard error
4778 file) as well as the verbose
4779 format message or full listing (which as usual is written to
4780 @file{stdout} (the standard output file).
4781
4782 @item -gnatm=@var{n}
4783 @cindex @option{-gnatm} (@command{gcc})
4784 @ifclear vms
4785 The @code{m} stands for maximum.
4786 @end ifclear
4787 @var{n} is a decimal integer in the
4788 range of 1 to 999999 and limits the number of error or warning
4789 messages to be generated. For example, using
4790 @option{-gnatm2} might yield
4791
4792 @smallexample
4793 e.adb:3:04: Incorrect spelling of keyword "function"
4794 e.adb:5:35: missing ".."
4795 fatal error: maximum number of errors detected
4796 compilation abandoned
4797 @end smallexample
4798
4799 @noindent
4800 The default setting if
4801 no switch is given is 9999. If the number of warnings reaches this
4802 limit, then a message is output and further warnings are suppressed,
4803 but the compilation is continued. If the number of error messages
4804 reaches this limit, then a message is output and the compilation
4805 is abandoned. A value of zero means that no limit applies.
4806
4807 @noindent
4808 Note that the equal sign is optional, so the switches
4809 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4810
4811 @item -gnatf
4812 @cindex @option{-gnatf} (@command{gcc})
4813 @cindex Error messages, suppressing
4814 @ifclear vms
4815 The @code{f} stands for full.
4816 @end ifclear
4817 Normally, the compiler suppresses error messages that are likely to be
4818 redundant. This switch causes all error
4819 messages to be generated. In particular, in the case of
4820 references to undefined variables. If a given variable is referenced
4821 several times, the normal format of messages is
4822 @smallexample
4823 e.adb:7:07: "V" is undefined (more references follow)
4824 @end smallexample
4825
4826 @noindent
4827 where the parenthetical comment warns that there are additional
4828 references to the variable @code{V}. Compiling the same program with the
4829 @option{-gnatf} switch yields
4830
4831 @smallexample
4832 e.adb:7:07: "V" is undefined
4833 e.adb:8:07: "V" is undefined
4834 e.adb:8:12: "V" is undefined
4835 e.adb:8:16: "V" is undefined
4836 e.adb:9:07: "V" is undefined
4837 e.adb:9:12: "V" is undefined
4838 @end smallexample
4839
4840 @noindent
4841 The @option{-gnatf} switch also generates additional information for
4842 some error messages.  Some examples are:
4843
4844 @itemize @bullet
4845 @item
4846 Details on possibly non-portable unchecked conversion
4847 @item
4848 List possible interpretations for ambiguous calls
4849 @item
4850 Additional details on incorrect parameters
4851 @end itemize
4852
4853 @item -gnatjnn
4854 @cindex @option{-gnatjnn} (@command{gcc})
4855 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4856 with continuation lines are treated as though the continuation lines were
4857 separate messages (and so a warning with two continuation lines counts as
4858 three warnings, and is listed as three separate messages).
4859
4860 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4861 messages are output in a different manner. A message and all its continuation
4862 lines are treated as a unit, and count as only one warning or message in the
4863 statistics totals. Furthermore, the message is reformatted so that no line
4864 is longer than nn characters.
4865
4866 @item -gnatq
4867 @cindex @option{-gnatq} (@command{gcc})
4868 @ifclear vms
4869 The @code{q} stands for quit (really ``don't quit'').
4870 @end ifclear
4871 In normal operation mode, the compiler first parses the program and
4872 determines if there are any syntax errors. If there are, appropriate
4873 error messages are generated and compilation is immediately terminated.
4874 This switch tells
4875 GNAT to continue with semantic analysis even if syntax errors have been
4876 found. This may enable the detection of more errors in a single run. On
4877 the other hand, the semantic analyzer is more likely to encounter some
4878 internal fatal error when given a syntactically invalid tree.
4879
4880 @item -gnatQ
4881 @cindex @option{-gnatQ} (@command{gcc})
4882 In normal operation mode, the @file{ALI} file is not generated if any
4883 illegalities are detected in the program. The use of @option{-gnatQ} forces
4884 generation of the @file{ALI} file. This file is marked as being in
4885 error, so it cannot be used for binding purposes, but it does contain
4886 reasonably complete cross-reference information, and thus may be useful
4887 for use by tools (e.g., semantic browsing tools or integrated development
4888 environments) that are driven from the @file{ALI} file. This switch
4889 implies @option{-gnatq}, since the semantic phase must be run to get a
4890 meaningful ALI file.
4891
4892 In addition, if @option{-gnatt} is also specified, then the tree file is
4893 generated even if there are illegalities. It may be useful in this case
4894 to also specify @option{-gnatq} to ensure that full semantic processing
4895 occurs. The resulting tree file can be processed by ASIS, for the purpose
4896 of providing partial information about illegal units, but if the error
4897 causes the tree to be badly malformed, then ASIS may crash during the
4898 analysis.
4899
4900 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4901 being in error, @command{gnatmake} will attempt to recompile the source when it
4902 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4903
4904 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4905 since ALI files are never generated if @option{-gnats} is set.
4906
4907 @end table
4908
4909 @node Warning Message Control
4910 @subsection Warning Message Control
4911 @cindex Warning messages
4912 @noindent
4913 In addition to error messages, which correspond to illegalities as defined
4914 in the Ada Reference Manual, the compiler detects two kinds of warning
4915 situations.
4916
4917 First, the compiler considers some constructs suspicious and generates a
4918 warning message to alert you to a possible error. Second, if the
4919 compiler detects a situation that is sure to raise an exception at
4920 run time, it generates a warning message. The following shows an example
4921 of warning messages:
4922 @smallexample
4923 e.adb:4:24: warning: creation of object may raise Storage_Error
4924 e.adb:10:17: warning: static value out of range
4925 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4926 @end smallexample
4927
4928 @noindent
4929 GNAT considers a large number of situations as appropriate
4930 for the generation of warning messages. As always, warnings are not
4931 definite indications of errors. For example, if you do an out-of-range
4932 assignment with the deliberate intention of raising a
4933 @code{Constraint_Error} exception, then the warning that may be
4934 issued does not indicate an error. Some of the situations for which GNAT
4935 issues warnings (at least some of the time) are given in the following
4936 list. This list is not complete, and new warnings are often added to
4937 subsequent versions of GNAT. The list is intended to give a general idea
4938 of the kinds of warnings that are generated.
4939
4940 @itemize @bullet
4941 @item
4942 Possible infinitely recursive calls
4943
4944 @item
4945 Out-of-range values being assigned
4946
4947 @item
4948 Possible order of elaboration problems
4949
4950 @item
4951 Assertions (pragma Assert) that are sure to fail
4952
4953 @item
4954 Unreachable code
4955
4956 @item
4957 Address clauses with possibly unaligned values, or where an attempt is
4958 made to overlay a smaller variable with a larger one.
4959
4960 @item
4961 Fixed-point type declarations with a null range
4962
4963 @item
4964 Direct_IO or Sequential_IO instantiated with a type that has access values
4965
4966 @item
4967 Variables that are never assigned a value
4968
4969 @item
4970 Variables that are referenced before being initialized
4971
4972 @item
4973 Task entries with no corresponding @code{accept} statement
4974
4975 @item
4976 Duplicate accepts for the same task entry in a @code{select}
4977
4978 @item
4979 Objects that take too much storage
4980
4981 @item
4982 Unchecked conversion between types of differing sizes
4983
4984 @item
4985 Missing @code{return} statement along some execution path in a function
4986
4987 @item
4988 Incorrect (unrecognized) pragmas
4989
4990 @item
4991 Incorrect external names
4992
4993 @item
4994 Allocation from empty storage pool
4995
4996 @item
4997 Potentially blocking operation in protected type
4998
4999 @item
5000 Suspicious parenthesization of expressions
5001
5002 @item
5003 Mismatching bounds in an aggregate
5004
5005 @item
5006 Attempt to return local value by reference
5007
5008 @item
5009 Premature instantiation of a generic body
5010
5011 @item
5012 Attempt to pack aliased components
5013
5014 @item
5015 Out of bounds array subscripts
5016
5017 @item
5018 Wrong length on string assignment
5019
5020 @item
5021 Violations of style rules if style checking is enabled
5022
5023 @item
5024 Unused @code{with} clauses
5025
5026 @item
5027 @code{Bit_Order} usage that does not have any effect
5028
5029 @item
5030 @code{Standard.Duration} used to resolve universal fixed expression
5031
5032 @item
5033 Dereference of possibly null value
5034
5035 @item
5036 Declaration that is likely to cause storage error
5037
5038 @item
5039 Internal GNAT unit @code{with}'ed by application unit
5040
5041 @item
5042 Values known to be out of range at compile time
5043
5044 @item
5045 Unreferenced labels and variables
5046
5047 @item
5048 Address overlays that could clobber memory
5049
5050 @item
5051 Unexpected initialization when address clause present
5052
5053 @item
5054 Bad alignment for address clause
5055
5056 @item
5057 Useless type conversions
5058
5059 @item
5060 Redundant assignment statements and other redundant constructs
5061
5062 @item
5063 Useless exception handlers
5064
5065 @item
5066 Accidental hiding of name by child unit
5067
5068 @item
5069 Access before elaboration detected at compile time
5070
5071 @item
5072 A range in a @code{for} loop that is known to be null or might be null
5073
5074 @end itemize
5075
5076 @noindent
5077 The following section lists compiler switches that are available
5078 to control the handling of warning messages. It is also possible
5079 to exercise much finer control over what warnings are issued and
5080 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5081 gnat_rm, GNAT Reference manual}.
5082
5083 @table @option
5084 @c !sort!
5085 @item -gnatwa
5086 @emph{Activate most optional warnings.}
5087 @cindex @option{-gnatwa} (@command{gcc})
5088 This switch activates most optional warning messages.  See the remaining list
5089 in this section for details on optional warning messages that can be
5090 individually controlled.  The warnings that are not turned on by this
5091 switch are
5092 @option{-gnatwd} (implicit dereferencing),
5093 @option{-gnatwh} (hiding),
5094 @option{-gnatw.h} (holes (gaps) in record layouts)
5095 @option{-gnatwl} (elaboration warnings),
5096 @option{-gnatw.o} (warn on values set by out parameters ignored)
5097 and @option{-gnatwt} (tracking of deleted conditional code).
5098 All other optional warnings are turned on.
5099
5100 @item -gnatwA
5101 @emph{Suppress all optional errors.}
5102 @cindex @option{-gnatwA} (@command{gcc})
5103 This switch suppresses all optional warning messages, see remaining list
5104 in this section for details on optional warning messages that can be
5105 individually controlled.
5106
5107 @item -gnatw.a
5108 @emph{Activate warnings on failing assertions.}
5109 @cindex @option{-gnatw.a} (@command{gcc})
5110 @cindex Assert failures
5111 This switch activates warnings for assertions where the compiler can tell at
5112 compile time that the assertion will fail. Note that this warning is given
5113 even if assertions are disabled. The default is that such warnings are
5114 generated.
5115
5116 @item -gnatw.A
5117 @emph{Suppress warnings on failing assertions.}
5118 @cindex @option{-gnatw.A} (@command{gcc})
5119 @cindex Assert failures
5120 This switch suppresses warnings for assertions where the compiler can tell at
5121 compile time that the assertion will fail.
5122
5123 @item -gnatwb
5124 @emph{Activate warnings on bad fixed values.}
5125 @cindex @option{-gnatwb} (@command{gcc})
5126 @cindex Bad fixed values
5127 @cindex Fixed-point Small value
5128 @cindex Small value
5129 This switch activates warnings for static fixed-point expressions whose
5130 value is not an exact multiple of Small. Such values are implementation
5131 dependent, since an implementation is free to choose either of the multiples
5132 that surround the value. GNAT always chooses the closer one, but this is not
5133 required behavior, and it is better to specify a value that is an exact
5134 multiple, ensuring predictable execution. The default is that such warnings
5135 are not generated.
5136
5137 @item -gnatwB
5138 @emph{Suppress warnings on bad fixed values.}
5139 @cindex @option{-gnatwB} (@command{gcc})
5140 This switch suppresses warnings for static fixed-point expressions whose
5141 value is not an exact multiple of Small.
5142
5143 @item -gnatw.b
5144 @emph{Activate warnings on biased representation.}
5145 @cindex @option{-gnatw.b} (@command{gcc})
5146 @cindex Biased representation
5147 This switch activates warnings when a size clause, value size clause, component
5148 clause, or component size clause forces the use of biased representation for an
5149 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5150 to represent 10/11). The default is that such warnings are generated.
5151
5152 @item -gnatw.B
5153 @emph{Suppress warnings on biased representation.}
5154 @cindex @option{-gnatwB} (@command{gcc})
5155 This switch suppresses warnings for representation clauses that force the use
5156 of biased representation.
5157
5158 @item -gnatwc
5159 @emph{Activate warnings on conditionals.}
5160 @cindex @option{-gnatwc} (@command{gcc})
5161 @cindex Conditionals, constant
5162 This switch activates warnings for conditional expressions used in
5163 tests that are known to be True or False at compile time. The default
5164 is that such warnings are not generated.
5165 Note that this warning does
5166 not get issued for the use of boolean variables or constants whose
5167 values are known at compile time, since this is a standard technique
5168 for conditional compilation in Ada, and this would generate too many
5169 false positive warnings.
5170
5171 This warning option also activates a special test for comparisons using
5172 the operators ``>='' and`` <=''.
5173 If the compiler can tell that only the equality condition is possible,
5174 then it will warn that the ``>'' or ``<'' part of the test
5175 is useless and that the operator could be replaced by ``=''.
5176 An example would be comparing a @code{Natural} variable <= 0.
5177
5178 This warning option also generates warnings if
5179 one or both tests is optimized away in a membership test for integer
5180 values if the result can be determined at compile time. Range tests on
5181 enumeration types are not included, since it is common for such tests
5182 to include an end point.
5183
5184 This warning can also be turned on using @option{-gnatwa}.
5185
5186 @item -gnatwC
5187 @emph{Suppress warnings on conditionals.}
5188 @cindex @option{-gnatwC} (@command{gcc})
5189 This switch suppresses warnings for conditional expressions used in
5190 tests that are known to be True or False at compile time.
5191
5192 @item -gnatw.c
5193 @emph{Activate warnings on missing component clauses.}
5194 @cindex @option{-gnatw.c} (@command{gcc})
5195 @cindex Component clause, missing
5196 This switch activates warnings for record components where a record
5197 representation clause is present and has component clauses for the
5198 majority, but not all, of the components. A warning is given for each
5199 component for which no component clause is present.
5200
5201 This warning can also be turned on using @option{-gnatwa}.
5202
5203 @item -gnatw.C
5204 @emph{Suppress warnings on missing component clauses.}
5205 @cindex @option{-gnatwC} (@command{gcc})
5206 This switch suppresses warnings for record components that are
5207 missing a component clause in the situation described above.
5208
5209 @item -gnatwd
5210 @emph{Activate warnings on implicit dereferencing.}
5211 @cindex @option{-gnatwd} (@command{gcc})
5212 If this switch is set, then the use of a prefix of an access type
5213 in an indexed component, slice, or selected component without an
5214 explicit @code{.all} will generate a warning. With this warning
5215 enabled, access checks occur only at points where an explicit
5216 @code{.all} appears in the source code (assuming no warnings are
5217 generated as a result of this switch). The default is that such
5218 warnings are not generated.
5219 Note that @option{-gnatwa} does not affect the setting of
5220 this warning option.
5221
5222 @item -gnatwD
5223 @emph{Suppress warnings on implicit dereferencing.}
5224 @cindex @option{-gnatwD} (@command{gcc})
5225 @cindex Implicit dereferencing
5226 @cindex Dereferencing, implicit
5227 This switch suppresses warnings for implicit dereferences in
5228 indexed components, slices, and selected components.
5229
5230 @item -gnatwe
5231 @emph{Treat warnings and style checks as errors.}
5232 @cindex @option{-gnatwe} (@command{gcc})
5233 @cindex Warnings, treat as error
5234 This switch causes warning messages and style check messages to be
5235 treated as errors.
5236 The warning string still appears, but the warning messages are counted
5237 as errors, and prevent the generation of an object file. Note that this
5238 is the only -gnatw switch that affects the handling of style check messages.
5239
5240 @item -gnatw.e
5241 @emph{Activate every optional warning}
5242 @cindex @option{-gnatw.e} (@command{gcc})
5243 @cindex Warnings, activate every optional warning
5244 This switch activates all optional warnings, including those which
5245 are not activated by @code{-gnatwa}.
5246
5247 @item -gnatwf
5248 @emph{Activate warnings on unreferenced formals.}
5249 @cindex @option{-gnatwf} (@command{gcc})
5250 @cindex Formals, unreferenced
5251 This switch causes a warning to be generated if a formal parameter
5252 is not referenced in the body of the subprogram. This warning can
5253 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5254 default is that these warnings are not generated.
5255
5256 @item -gnatwF
5257 @emph{Suppress warnings on unreferenced formals.}
5258 @cindex @option{-gnatwF} (@command{gcc})
5259 This switch suppresses warnings for unreferenced formal
5260 parameters. Note that the
5261 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5262 effect of warning on unreferenced entities other than subprogram
5263 formals.
5264
5265 @item -gnatwg
5266 @emph{Activate warnings on unrecognized pragmas.}
5267 @cindex @option{-gnatwg} (@command{gcc})
5268 @cindex Pragmas, unrecognized
5269 This switch causes a warning to be generated if an unrecognized
5270 pragma is encountered. Apart from issuing this warning, the
5271 pragma is ignored and has no effect. This warning can
5272 also be turned on using @option{-gnatwa}. The default
5273 is that such warnings are issued (satisfying the Ada Reference
5274 Manual requirement that such warnings appear).
5275
5276 @item -gnatwG
5277 @emph{Suppress warnings on unrecognized pragmas.}
5278 @cindex @option{-gnatwG} (@command{gcc})
5279 This switch suppresses warnings for unrecognized pragmas.
5280
5281 @item -gnatwh
5282 @emph{Activate warnings on hiding.}
5283 @cindex @option{-gnatwh} (@command{gcc})
5284 @cindex Hiding of Declarations
5285 This switch activates warnings on hiding declarations.
5286 A declaration is considered hiding
5287 if it is for a non-overloadable entity, and it declares an entity with the
5288 same name as some other entity that is directly or use-visible. The default
5289 is that such warnings are not generated.
5290 Note that @option{-gnatwa} does not affect the setting of this warning option.
5291
5292 @item -gnatwH
5293 @emph{Suppress warnings on hiding.}
5294 @cindex @option{-gnatwH} (@command{gcc})
5295 This switch suppresses warnings on hiding declarations.
5296
5297 @item -gnatw.h
5298 @emph{Activate warnings on holes/gaps in records.}
5299 @cindex @option{-gnatw.h} (@command{gcc})
5300 @cindex Record Representation (gaps)
5301 This switch activates warnings on component clauses in record
5302 representation clauses that leave holes (gaps) in the record layout.
5303 If this warning option is active, then record representation clauses
5304 should specify a contiguous layout, adding unused fill fields if needed.
5305 Note that @option{-gnatwa} does not affect the setting of this warning option.
5306
5307 @item -gnatw.H
5308 @emph{Suppress warnings on holes/gaps in records.}
5309 @cindex @option{-gnatw.H} (@command{gcc})
5310 This switch suppresses warnings on component clauses in record
5311 representation clauses that leave holes (haps) in the record layout.
5312
5313 @item -gnatwi
5314 @emph{Activate warnings on implementation units.}
5315 @cindex @option{-gnatwi} (@command{gcc})
5316 This switch activates warnings for a @code{with} of an internal GNAT
5317 implementation unit, defined as any unit from the @code{Ada},
5318 @code{Interfaces}, @code{GNAT},
5319 ^^@code{DEC},^ or @code{System}
5320 hierarchies that is not
5321 documented in either the Ada Reference Manual or the GNAT
5322 Programmer's Reference Manual. Such units are intended only
5323 for internal implementation purposes and should not be @code{with}'ed
5324 by user programs. The default is that such warnings are generated
5325 This warning can also be turned on using @option{-gnatwa}.
5326
5327 @item -gnatwI
5328 @emph{Disable warnings on implementation units.}
5329 @cindex @option{-gnatwI} (@command{gcc})
5330 This switch disables warnings for a @code{with} of an internal GNAT
5331 implementation unit.
5332
5333 @item -gnatw.i
5334 @emph{Activate warnings on overlapping actuals.}
5335 @cindex @option{-gnatw.i} (@command{gcc})
5336 This switch enables a warning on statically detectable overlapping actuals in
5337 a subprogram call, when one of the actuals is an in-out parameter, and the
5338 types of the actuals are not by-copy types. The warning is off by default,
5339 and is not included under -gnatwa.
5340
5341 @item -gnatw.I
5342 @emph{Disable warnings on overlapping actuals.}
5343 @cindex @option{-gnatw.I} (@command{gcc})
5344 This switch disables warnings on overlapping actuals in a call..
5345
5346 @item -gnatwj
5347 @emph{Activate warnings on obsolescent features (Annex J).}
5348 @cindex @option{-gnatwj} (@command{gcc})
5349 @cindex Features, obsolescent
5350 @cindex Obsolescent features
5351 If this warning option is activated, then warnings are generated for
5352 calls to subprograms marked with @code{pragma Obsolescent} and
5353 for use of features in Annex J of the Ada Reference Manual. In the
5354 case of Annex J, not all features are flagged. In particular use
5355 of the renamed packages (like @code{Text_IO}) and use of package
5356 @code{ASCII} are not flagged, since these are very common and
5357 would generate many annoying positive warnings. The default is that
5358 such warnings are not generated. This warning is also turned on by
5359 the use of @option{-gnatwa}.
5360
5361 In addition to the above cases, warnings are also generated for
5362 GNAT features that have been provided in past versions but which
5363 have been superseded (typically by features in the new Ada standard).
5364 For example, @code{pragma Ravenscar} will be flagged since its
5365 function is replaced by @code{pragma Profile(Ravenscar)}.
5366
5367 Note that this warning option functions differently from the
5368 restriction @code{No_Obsolescent_Features} in two respects.
5369 First, the restriction applies only to annex J features.
5370 Second, the restriction does flag uses of package @code{ASCII}.
5371
5372 @item -gnatwJ
5373 @emph{Suppress warnings on obsolescent features (Annex J).}
5374 @cindex @option{-gnatwJ} (@command{gcc})
5375 This switch disables warnings on use of obsolescent features.
5376
5377 @item -gnatwk
5378 @emph{Activate warnings on variables that could be constants.}
5379 @cindex @option{-gnatwk} (@command{gcc})
5380 This switch activates warnings for variables that are initialized but
5381 never modified, and then could be declared constants. The default is that
5382 such warnings are not given.
5383 This warning can also be turned on using @option{-gnatwa}.
5384
5385 @item -gnatwK
5386 @emph{Suppress warnings on variables that could be constants.}
5387 @cindex @option{-gnatwK} (@command{gcc})
5388 This switch disables warnings on variables that could be declared constants.
5389
5390 @item -gnatwl
5391 @emph{Activate warnings for elaboration pragmas.}
5392 @cindex @option{-gnatwl} (@command{gcc})
5393 @cindex Elaboration, warnings
5394 This switch activates warnings on missing
5395 @code{Elaborate_All} and @code{Elaborate} pragmas.
5396 See the section in this guide on elaboration checking for details on
5397 when such pragmas should be used. In dynamic elaboration mode, this switch
5398 generations warnings about the need to add elaboration pragmas. Note however,
5399 that if you blindly follow these warnings, and add @code{Elaborate_All}
5400 warnings wherever they are recommended, you basically end up with the
5401 equivalent of the static elaboration model, which may not be what you want for
5402 legacy code for which the static model does not work.
5403
5404 For the static model, the messages generated are labeled "info:" (for
5405 information messages). They are not warnings to add elaboration pragmas,
5406 merely informational messages showing what implicit elaboration pragmas
5407 have been added, for use in analyzing elaboration circularity problems.
5408
5409 Warnings are also generated if you
5410 are using the static mode of elaboration, and a @code{pragma Elaborate}
5411 is encountered. The default is that such warnings
5412 are not generated.
5413 This warning is not automatically turned on by the use of @option{-gnatwa}.
5414
5415 @item -gnatwL
5416 @emph{Suppress warnings for elaboration pragmas.}
5417 @cindex @option{-gnatwL} (@command{gcc})
5418 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5419 See the section in this guide on elaboration checking for details on
5420 when such pragmas should be used.
5421
5422 @item -gnatwm
5423 @emph{Activate warnings on modified but unreferenced variables.}
5424 @cindex @option{-gnatwm} (@command{gcc})
5425 This switch activates warnings for variables that are assigned (using
5426 an initialization value or with one or more assignment statements) but
5427 whose value is never read. The warning is suppressed for volatile
5428 variables and also for variables that are renamings of other variables
5429 or for which an address clause is given.
5430 This warning can also be turned on using @option{-gnatwa}.
5431 The default is that these warnings are not given.
5432
5433 @item -gnatwM
5434 @emph{Disable warnings on modified but unreferenced variables.}
5435 @cindex @option{-gnatwM} (@command{gcc})
5436 This switch disables warnings for variables that are assigned or
5437 initialized, but never read.
5438
5439 @item -gnatw.m
5440 @emph{Activate warnings on suspicious modulus values.}
5441 @cindex @option{-gnatw.m} (@command{gcc})
5442 This switch activates warnings for modulus values that seem suspicious.
5443 The cases caught are where the size is the same as the modulus (e.g.
5444 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5445 with no size clause. The guess in both cases is that 2**x was intended
5446 rather than x. The default is that these warnings are given.
5447
5448 @item -gnatw.M
5449 @emph{Disable warnings on suspicious modulus values.}
5450 @cindex @option{-gnatw.M} (@command{gcc})
5451 This switch disables warnings for suspicious modulus values.
5452
5453 @item -gnatwn
5454 @emph{Set normal warnings mode.}
5455 @cindex @option{-gnatwn} (@command{gcc})
5456 This switch sets normal warning mode, in which enabled warnings are
5457 issued and treated as warnings rather than errors. This is the default
5458 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5459 an explicit @option{-gnatws} or
5460 @option{-gnatwe}. It also cancels the effect of the
5461 implicit @option{-gnatwe} that is activated by the
5462 use of @option{-gnatg}.
5463
5464 @item -gnatwo
5465 @emph{Activate warnings on address clause overlays.}
5466 @cindex @option{-gnatwo} (@command{gcc})
5467 @cindex Address Clauses, warnings
5468 This switch activates warnings for possibly unintended initialization
5469 effects of defining address clauses that cause one variable to overlap
5470 another. The default is that such warnings are generated.
5471 This warning can also be turned on using @option{-gnatwa}.
5472
5473 @item -gnatwO
5474 @emph{Suppress warnings on address clause overlays.}
5475 @cindex @option{-gnatwO} (@command{gcc})
5476 This switch suppresses warnings on possibly unintended initialization
5477 effects of defining address clauses that cause one variable to overlap
5478 another.
5479
5480 @item -gnatw.o
5481 @emph{Activate warnings on modified but unreferenced out parameters.}
5482 @cindex @option{-gnatw.o} (@command{gcc})
5483 This switch activates warnings for variables that are modified by using
5484 them as actuals for a call to a procedure with an out mode formal, where
5485 the resulting assigned value is never read. It is applicable in the case
5486 where there is more than one out mode formal. If there is only one out
5487 mode formal, the warning is issued by default (controlled by -gnatwu).
5488 The warning is suppressed for volatile
5489 variables and also for variables that are renamings of other variables
5490 or for which an address clause is given.
5491 The default is that these warnings are not given. Note that this warning
5492 is not included in -gnatwa, it must be activated explicitly.
5493
5494 @item -gnatw.O
5495 @emph{Disable warnings on modified but unreferenced out parameters.}
5496 @cindex @option{-gnatw.O} (@command{gcc})
5497 This switch suppresses warnings for variables that are modified by using
5498 them as actuals for a call to a procedure with an out mode formal, where
5499 the resulting assigned value is never read.
5500
5501 @item -gnatwp
5502 @emph{Activate warnings on ineffective pragma Inlines.}
5503 @cindex @option{-gnatwp} (@command{gcc})
5504 @cindex Inlining, warnings
5505 This switch activates warnings for failure of front end inlining
5506 (activated by @option{-gnatN}) to inline a particular call. There are
5507 many reasons for not being able to inline a call, including most
5508 commonly that the call is too complex to inline. The default is
5509 that such warnings are not given.
5510 This warning can also be turned on using @option{-gnatwa}.
5511 Warnings on ineffective inlining by the gcc back-end can be activated
5512 separately, using the gcc switch -Winline.
5513
5514 @item -gnatwP
5515 @emph{Suppress warnings on ineffective pragma Inlines.}
5516 @cindex @option{-gnatwP} (@command{gcc})
5517 This switch suppresses warnings on ineffective pragma Inlines. If the
5518 inlining mechanism cannot inline a call, it will simply ignore the
5519 request silently.
5520
5521 @item -gnatw.p
5522 @emph{Activate warnings on parameter ordering.}
5523 @cindex @option{-gnatw.p} (@command{gcc})
5524 @cindex Parameter order, warnings
5525 This switch activates warnings for cases of suspicious parameter
5526 ordering when the list of arguments are all simple identifiers that
5527 match the names of the formals, but are in a different order. The
5528 warning is suppressed if any use of named parameter notation is used,
5529 so this is the appropriate way to suppress a false positive (and
5530 serves to emphasize that the "misordering" is deliberate). The
5531 default is
5532 that such warnings are not given.
5533 This warning can also be turned on using @option{-gnatwa}.
5534
5535 @item -gnatw.P
5536 @emph{Suppress warnings on parameter ordering.}
5537 @cindex @option{-gnatw.P} (@command{gcc})
5538 This switch suppresses warnings on cases of suspicious parameter
5539 ordering.
5540
5541 @item -gnatwq
5542 @emph{Activate warnings on questionable missing parentheses.}
5543 @cindex @option{-gnatwq} (@command{gcc})
5544 @cindex Parentheses, warnings
5545 This switch activates warnings for cases where parentheses are not used and
5546 the result is potential ambiguity from a readers point of view. For example
5547 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5548 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5549 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5550 follow the rule of always parenthesizing to make the association clear, and
5551 this warning switch warns if such parentheses are not present. The default
5552 is that these warnings are given.
5553 This warning can also be turned on using @option{-gnatwa}.
5554
5555 @item -gnatwQ
5556 @emph{Suppress warnings on questionable missing parentheses.}
5557 @cindex @option{-gnatwQ} (@command{gcc})
5558 This switch suppresses warnings for cases where the association is not
5559 clear and the use of parentheses is preferred.
5560
5561 @item -gnatwr
5562 @emph{Activate warnings on redundant constructs.}
5563 @cindex @option{-gnatwr} (@command{gcc})
5564 This switch activates warnings for redundant constructs. The following
5565 is the current list of constructs regarded as redundant:
5566
5567 @itemize @bullet
5568 @item
5569 Assignment of an item to itself.
5570 @item
5571 Type conversion that converts an expression to its own type.
5572 @item
5573 Use of the attribute @code{Base} where @code{typ'Base} is the same
5574 as @code{typ}.
5575 @item
5576 Use of pragma @code{Pack} when all components are placed by a record
5577 representation clause.
5578 @item
5579 Exception handler containing only a reraise statement (raise with no
5580 operand) which has no effect.
5581 @item
5582 Use of the operator abs on an operand that is known at compile time
5583 to be non-negative
5584 @item
5585 Comparison of boolean expressions to an explicit True value.
5586 @end itemize
5587
5588 This warning can also be turned on using @option{-gnatwa}.
5589 The default is that warnings for redundant constructs are not given.
5590
5591 @item -gnatwR
5592 @emph{Suppress warnings on redundant constructs.}
5593 @cindex @option{-gnatwR} (@command{gcc})
5594 This switch suppresses warnings for redundant constructs.
5595
5596 @item -gnatw.r
5597 @emph{Activate warnings for object renaming function.}
5598 @cindex @option{-gnatw.r} (@command{gcc})
5599 This switch activates warnings for an object renaming that renames a
5600 function call, which is equivalent to a constant declaration (as
5601 opposed to renaming the function itself).  The default is that these
5602 warnings are given.  This warning can also be turned on using
5603 @option{-gnatwa}.
5604
5605 @item -gnatw.R
5606 @emph{Suppress warnings for object renaming function.}
5607 @cindex @option{-gnatwT} (@command{gcc})
5608 This switch suppresses warnings for object renaming function.
5609
5610 @item -gnatws
5611 @emph{Suppress all warnings.}
5612 @cindex @option{-gnatws} (@command{gcc})
5613 This switch completely suppresses the
5614 output of all warning messages from the GNAT front end.
5615 Note that it does not suppress warnings from the @command{gcc} back end.
5616 To suppress these back end warnings as well, use the switch @option{-w}
5617 in addition to @option{-gnatws}. Also this switch has no effect on the
5618 handling of style check messages.
5619
5620 @item -gnatw.s
5621 @emph{Activate warnings on overridden size clauses.}
5622 @cindex @option{-gnatw.s} (@command{gcc})
5623 @cindex Record Representation (component sizes)
5624 This switch activates warnings on component clauses in record
5625 representation clauses where the length given overrides that
5626 specified by an explicit size clause for the component type. A
5627 warning is similarly given in the array case if a specified
5628 component size overrides an explicit size clause for the array
5629 component type.
5630 Note that @option{-gnatwa} does not affect the setting of this warning option.
5631
5632 @item -gnatw.S
5633 @emph{Suppress warnings on overridden size clauses.}
5634 @cindex @option{-gnatw.S} (@command{gcc})
5635 This switch suppresses warnings on component clauses in record
5636 representation clauses that override size clauses, and similar
5637 warnings when an array component size overrides a size clause.
5638
5639 @item -gnatwt
5640 @emph{Activate warnings for tracking of deleted conditional code.}
5641 @cindex @option{-gnatwt} (@command{gcc})
5642 @cindex Deactivated code, warnings
5643 @cindex Deleted code, warnings
5644 This switch activates warnings for tracking of code in conditionals (IF and
5645 CASE statements) that is detected to be dead code which cannot be executed, and
5646 which is removed by the front end. This warning is off by default, and is not
5647 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5648 useful for detecting deactivated code in certified applications.
5649
5650 @item -gnatwT
5651 @emph{Suppress warnings for tracking of deleted conditional code.}
5652 @cindex @option{-gnatwT} (@command{gcc})
5653 This switch suppresses warnings for tracking of deleted conditional code.
5654
5655 @item -gnatwu
5656 @emph{Activate warnings on unused entities.}
5657 @cindex @option{-gnatwu} (@command{gcc})
5658 This switch activates warnings to be generated for entities that
5659 are declared but not referenced, and for units that are @code{with}'ed
5660 and not
5661 referenced. In the case of packages, a warning is also generated if
5662 no entities in the package are referenced. This means that if a with'ed
5663 package is referenced but the only references are in @code{use}
5664 clauses or @code{renames}
5665 declarations, a warning is still generated. A warning is also generated
5666 for a generic package that is @code{with}'ed but never instantiated.
5667 In the case where a package or subprogram body is compiled, and there
5668 is a @code{with} on the corresponding spec
5669 that is only referenced in the body,
5670 a warning is also generated, noting that the
5671 @code{with} can be moved to the body. The default is that
5672 such warnings are not generated.
5673 This switch also activates warnings on unreferenced formals
5674 (it includes the effect of @option{-gnatwf}).
5675 This warning can also be turned on using @option{-gnatwa}.
5676
5677 @item -gnatwU
5678 @emph{Suppress warnings on unused entities.}
5679 @cindex @option{-gnatwU} (@command{gcc})
5680 This switch suppresses warnings for unused entities and packages.
5681 It also turns off warnings on unreferenced formals (and thus includes
5682 the effect of @option{-gnatwF}).
5683
5684 @item -gnatw.u
5685 @emph{Activate warnings on unordered enumeration types.}
5686 @cindex @option{-gnatw.u} (@command{gcc})
5687 This switch causes enumeration types to be considered as conceptually
5688 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5689 The effect is to generate warnings in clients that use explicit comparisons
5690 or subranges, since these constructs both treat objects of the type as
5691 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5692 which the type is declared, or its body or subunits.) Please refer to
5693 the description of pragma @code{Ordered} in the
5694 @cite{@value{EDITION} Reference Manual} for further details.
5695
5696 @item -gnatw.U
5697 @emph{Deactivate warnings on unordered enumeration types.}
5698 @cindex @option{-gnatw.U} (@command{gcc})
5699 This switch causes all enumeration types to be considered as ordered, so
5700 that no warnings are given for comparisons or subranges for any type.
5701
5702 @item -gnatwv
5703 @emph{Activate warnings on unassigned variables.}
5704 @cindex @option{-gnatwv} (@command{gcc})
5705 @cindex Unassigned variable warnings
5706 This switch activates warnings for access to variables which
5707 may not be properly initialized. The default is that
5708 such warnings are generated.
5709 This warning can also be turned on using @option{-gnatwa}.
5710
5711 @item -gnatwV
5712 @emph{Suppress warnings on unassigned variables.}
5713 @cindex @option{-gnatwV} (@command{gcc})
5714 This switch suppresses warnings for access to variables which
5715 may not be properly initialized.
5716 For variables of a composite type, the warning can also be suppressed in
5717 Ada 2005 by using a default initialization with a box. For example, if
5718 Table is an array of records whose components are only partially uninitialized,
5719 then the following code:
5720
5721 @smallexample @c ada
5722    Tab : Table := (others => <>);
5723 @end smallexample
5724
5725 will suppress warnings on subsequent statements that access components
5726 of variable Tab.
5727
5728 @item -gnatww
5729 @emph{Activate warnings on wrong low bound assumption.}
5730 @cindex @option{-gnatww} (@command{gcc})
5731 @cindex String indexing warnings
5732 This switch activates warnings for indexing an unconstrained string parameter
5733 with a literal or S'Length. This is a case where the code is assuming that the
5734 low bound is one, which is in general not true (for example when a slice is
5735 passed). The default is that such warnings are generated.
5736 This warning can also be turned on using @option{-gnatwa}.
5737
5738 @item -gnatwW
5739 @emph{Suppress warnings on wrong low bound assumption.}
5740 @cindex @option{-gnatwW} (@command{gcc})
5741 This switch suppresses warnings for indexing an unconstrained string parameter
5742 with a literal or S'Length. Note that this warning can also be suppressed
5743 in a particular case by adding an
5744 assertion that the lower bound is 1,
5745 as shown in the following example.
5746
5747 @smallexample @c ada
5748    procedure K (S : String) is
5749       pragma Assert (S'First = 1);
5750       @dots{}
5751 @end smallexample
5752
5753 @item -gnatw.w
5754 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5755 @cindex @option{-gnatw.w} (@command{gcc})
5756 @cindex Warnings Off control
5757 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5758 where either the pragma is entirely useless (because it suppresses no
5759 warnings), or it could be replaced by @code{pragma Unreferenced} or
5760 @code{pragma Unmodified}. The default is that these warnings are not given.
5761 Note that this warning is not included in -gnatwa, it must be
5762 activated explicitly.
5763
5764 @item -gnatw.W
5765 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5766 @cindex @option{-gnatw.W} (@command{gcc})
5767 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5768
5769 @item -gnatwx
5770 @emph{Activate warnings on Export/Import pragmas.}
5771 @cindex @option{-gnatwx} (@command{gcc})
5772 @cindex Export/Import pragma warnings
5773 This switch activates warnings on Export/Import pragmas when
5774 the compiler detects a possible conflict between the Ada and
5775 foreign language calling sequences. For example, the use of
5776 default parameters in a convention C procedure is dubious
5777 because the C compiler cannot supply the proper default, so
5778 a warning is issued. The default is that such warnings are
5779 generated.
5780 This warning can also be turned on using @option{-gnatwa}.
5781
5782 @item -gnatwX
5783 @emph{Suppress warnings on Export/Import pragmas.}
5784 @cindex @option{-gnatwX} (@command{gcc})
5785 This switch suppresses warnings on Export/Import pragmas.
5786 The sense of this is that you are telling the compiler that
5787 you know what you are doing in writing the pragma, and it
5788 should not complain at you.
5789
5790 @item -gnatw.x
5791 @emph{Activate warnings for No_Exception_Propagation mode.}
5792 @cindex @option{-gnatwm} (@command{gcc})
5793 This switch activates warnings for exception usage when pragma Restrictions
5794 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5795 explicit exception raises which are not covered by a local handler, and for
5796 exception handlers which do not cover a local raise. The default is that these
5797 warnings are not given.
5798
5799 @item -gnatw.X
5800 @emph{Disable warnings for No_Exception_Propagation mode.}
5801 This switch disables warnings for exception usage when pragma Restrictions
5802 (No_Exception_Propagation) is in effect.
5803
5804 @item -gnatwy
5805 @emph{Activate warnings for Ada compatibility issues.}
5806 @cindex @option{-gnatwy} (@command{gcc})
5807 @cindex Ada compatibility issues warnings
5808 For the most part, newer versions of Ada are upwards compatible
5809 with older versions. For example, Ada 2005 programs will almost
5810 always work when compiled as Ada 2012.
5811 However there are some exceptions (for example the fact that
5812 @code{some} is now a reserved word in Ada 2012). This
5813 switch activates several warnings to help in identifying
5814 and correcting such incompatibilities. The default is that
5815 these warnings are generated. Note that at one point Ada 2005
5816 was called Ada 0Y, hence the choice of character.
5817 This warning can also be turned on using @option{-gnatwa}.
5818
5819 @item -gnatwY
5820 @emph{Disable warnings for Ada compatibility issues.}
5821 @cindex @option{-gnatwY} (@command{gcc})
5822 @cindex Ada compatibility issues warnings
5823 This switch suppresses the warnings intended to help in identifying
5824 incompatibilities between Ada language versions.
5825
5826 @item -gnatwz
5827 @emph{Activate warnings on unchecked conversions.}
5828 @cindex @option{-gnatwz} (@command{gcc})
5829 @cindex Unchecked_Conversion warnings
5830 This switch activates warnings for unchecked conversions
5831 where the types are known at compile time to have different
5832 sizes. The default
5833 is that such warnings are generated. Warnings are also
5834 generated for subprogram pointers with different conventions,
5835 and, on VMS only, for data pointers with different conventions.
5836 This warning can also be turned on using @option{-gnatwa}.
5837
5838 @item -gnatwZ
5839 @emph{Suppress warnings on unchecked conversions.}
5840 @cindex @option{-gnatwZ} (@command{gcc})
5841 This switch suppresses warnings for unchecked conversions
5842 where the types are known at compile time to have different
5843 sizes or conventions.
5844
5845 @item ^-Wunused^WARNINGS=UNUSED^
5846 @cindex @option{-Wunused}
5847 The warnings controlled by the @option{-gnatw} switch are generated by
5848 the front end of the compiler. The @option{GCC} back end can provide
5849 additional warnings and they are controlled by the @option{-W} switch.
5850 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5851 warnings for entities that are declared but not referenced.
5852
5853 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5854 @cindex @option{-Wuninitialized}
5855 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5856 the back end warning for uninitialized variables. This switch must be
5857 used in conjunction with an optimization level greater than zero.
5858
5859 @item -Wstack-usage=@var{len}
5860 @cindex @option{-Wstack-usage}
5861 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5862 See @ref{Static Stack Usage Analysis} for details.
5863
5864 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5865 @cindex @option{-Wall}
5866 This switch enables most warnings from the @option{GCC} back end.
5867 The code generator detects a number of warning situations that are missed
5868 by the @option{GNAT} front end, and this switch can be used to activate them.
5869 The use of this switch also sets the default front end warning mode to
5870 @option{-gnatwa}, that is, most front end warnings activated as well.
5871
5872 @item ^-w^/NO_BACK_END_WARNINGS^
5873 @cindex @option{-w}
5874 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5875 The use of this switch also sets the default front end warning mode to
5876 @option{-gnatws}, that is, front end warnings suppressed as well.
5877
5878 @end table
5879
5880 @noindent
5881 @ifclear vms
5882 A string of warning parameters can be used in the same parameter. For example:
5883
5884 @smallexample
5885 -gnatwaLe
5886 @end smallexample
5887
5888 @noindent
5889 will turn on all optional warnings except for elaboration pragma warnings,
5890 and also specify that warnings should be treated as errors.
5891 @end ifclear
5892 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5893
5894 @table @option
5895 @c !sort!
5896 @item -gnatwC
5897 @item -gnatwD
5898 @item -gnatwF
5899 @item -gnatwg
5900 @item -gnatwH
5901 @item -gnatwi
5902 @item -gnatwJ
5903 @item -gnatwK
5904 @item -gnatwL
5905 @item -gnatwM
5906 @item -gnatwn
5907 @item -gnatwo
5908 @item -gnatwP
5909 @item -gnatwR
5910 @item -gnatwU
5911 @item -gnatwv
5912 @item -gnatwz
5913 @item -gnatwx
5914
5915 @end table
5916
5917 @node Debugging and Assertion Control
5918 @subsection Debugging and Assertion Control
5919
5920 @table @option
5921 @item -gnata
5922 @cindex @option{-gnata} (@command{gcc})
5923 @findex Assert
5924 @findex Debug
5925 @cindex Assertions
5926
5927 @noindent
5928 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5929 are ignored. This switch, where @samp{a} stands for assert, causes
5930 @code{Assert} and @code{Debug} pragmas to be activated.
5931
5932 The pragmas have the form:
5933
5934 @smallexample
5935 @cartouche
5936    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5937                       @var{static-string-expression}@r{]})
5938    @b{pragma} Debug (@var{procedure call})
5939 @end cartouche
5940 @end smallexample
5941
5942 @noindent
5943 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5944 If the result is @code{True}, the pragma has no effect (other than
5945 possible side effects from evaluating the expression). If the result is
5946 @code{False}, the exception @code{Assert_Failure} declared in the package
5947 @code{System.Assertions} is
5948 raised (passing @var{static-string-expression}, if present, as the
5949 message associated with the exception). If no string expression is
5950 given the default is a string giving the file name and line number
5951 of the pragma.
5952
5953 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5954 @code{pragma Debug} may appear within a declaration sequence, allowing
5955 debugging procedures to be called between declarations.
5956
5957 @ifset vms
5958 @item /DEBUG@r{[}=debug-level@r{]}
5959 @itemx  /NODEBUG
5960 Specifies how much debugging information is to be included in
5961 the resulting object file where 'debug-level' is one of the following:
5962 @table @code
5963 @item   TRACEBACK
5964 Include both debugger symbol records and traceback
5965 the object file.
5966 This is the default setting.
5967 @item   ALL
5968 Include both debugger symbol records and traceback in
5969 object file.
5970 @item   NONE
5971 Excludes both debugger symbol records and traceback
5972 the object file. Same as /NODEBUG.
5973 @item   SYMBOLS
5974 Includes only debugger symbol records in the object
5975 file. Note that this doesn't include traceback information.
5976 @end table
5977 @end ifset
5978 @end table
5979
5980 @node Validity Checking
5981 @subsection Validity Checking
5982 @findex Validity Checking
5983
5984 @noindent
5985 The Ada Reference Manual defines the concept of invalid values (see
5986 RM 13.9.1). The primary source of invalid values is uninitialized
5987 variables. A scalar variable that is left uninitialized may contain
5988 an invalid value; the concept of invalid does not apply to access or
5989 composite types.
5990
5991 It is an error to read an invalid value, but the RM does not require
5992 run-time checks to detect such errors, except for some minimal
5993 checking to prevent erroneous execution (i.e. unpredictable
5994 behavior). This corresponds to the @option{-gnatVd} switch below,
5995 which is the default. For example, by default, if the expression of a
5996 case statement is invalid, it will raise Constraint_Error rather than
5997 causing a wild jump, and if an array index on the left-hand side of an
5998 assignment is invalid, it will raise Constraint_Error rather than
5999 overwriting an arbitrary memory location.
6000
6001 The @option{-gnatVa} may be used to enable additional validity checks,
6002 which are not required by the RM. These checks are often very
6003 expensive (which is why the RM does not require them). These checks
6004 are useful in tracking down uninitialized variables, but they are
6005 not usually recommended for production builds.
6006
6007 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6008 control; you can enable whichever validity checks you desire. However,
6009 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6010 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6011 sufficient for non-debugging use.
6012
6013 The @option{-gnatB} switch tells the compiler to assume that all
6014 values are valid (that is, within their declared subtype range)
6015 except in the context of a use of the Valid attribute. This means
6016 the compiler can generate more efficient code, since the range
6017 of values is better known at compile time. However, an uninitialized
6018 variable can cause wild jumps and memory corruption in this mode.
6019
6020 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6021 checking mode as described below.
6022 @ifclear vms
6023 The @code{x} argument is a string of letters that
6024 indicate validity checks that are performed or not performed in addition
6025 to the default checks required by Ada as described above.
6026 @end ifclear
6027 @ifset vms
6028 The options allowed for this qualifier
6029 indicate validity checks that are performed or not performed in addition
6030 to the default checks required by Ada as described above.
6031 @end ifset
6032
6033 @table @option
6034 @c !sort!
6035 @item -gnatVa
6036 @emph{All validity checks.}
6037 @cindex @option{-gnatVa} (@command{gcc})
6038 All validity checks are turned on.
6039 @ifclear vms
6040 That is, @option{-gnatVa} is
6041 equivalent to @option{gnatVcdfimorst}.
6042 @end ifclear
6043
6044 @item -gnatVc
6045 @emph{Validity checks for copies.}
6046 @cindex @option{-gnatVc} (@command{gcc})
6047 The right hand side of assignments, and the initializing values of
6048 object declarations are validity checked.
6049
6050 @item -gnatVd
6051 @emph{Default (RM) validity checks.}
6052 @cindex @option{-gnatVd} (@command{gcc})
6053 Some validity checks are done by default following normal Ada semantics
6054 (RM 13.9.1 (9-11)).
6055 A check is done in case statements that the expression is within the range
6056 of the subtype. If it is not, Constraint_Error is raised.
6057 For assignments to array components, a check is done that the expression used
6058 as index is within the range. If it is not, Constraint_Error is raised.
6059 Both these validity checks may be turned off using switch @option{-gnatVD}.
6060 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6061 switch @option{-gnatVd} will leave the checks turned on.
6062 Switch @option{-gnatVD} should be used only if you are sure that all such
6063 expressions have valid values. If you use this switch and invalid values
6064 are present, then the program is erroneous, and wild jumps or memory
6065 overwriting may occur.
6066
6067 @item -gnatVe
6068 @emph{Validity checks for elementary components.}
6069 @cindex @option{-gnatVe} (@command{gcc})
6070 In the absence of this switch, assignments to record or array components are
6071 not validity checked, even if validity checks for assignments generally
6072 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6073 require valid data, but assignment of individual components does. So for
6074 example, there is a difference between copying the elements of an array with a
6075 slice assignment, compared to assigning element by element in a loop. This
6076 switch allows you to turn off validity checking for components, even when they
6077 are assigned component by component.
6078
6079 @item -gnatVf
6080 @emph{Validity checks for floating-point values.}
6081 @cindex @option{-gnatVf} (@command{gcc})
6082 In the absence of this switch, validity checking occurs only for discrete
6083 values. If @option{-gnatVf} is specified, then validity checking also applies
6084 for floating-point values, and NaNs and infinities are considered invalid,
6085 as well as out of range values for constrained types. Note that this means
6086 that standard IEEE infinity mode is not allowed. The exact contexts
6087 in which floating-point values are checked depends on the setting of other
6088 options. For example,
6089 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6090 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6091 (the order does not matter) specifies that floating-point parameters of mode
6092 @code{in} should be validity checked.
6093
6094 @item -gnatVi
6095 @emph{Validity checks for @code{in} mode parameters}
6096 @cindex @option{-gnatVi} (@command{gcc})
6097 Arguments for parameters of mode @code{in} are validity checked in function
6098 and procedure calls at the point of call.
6099
6100 @item -gnatVm
6101 @emph{Validity checks for @code{in out} mode parameters.}
6102 @cindex @option{-gnatVm} (@command{gcc})
6103 Arguments for parameters of mode @code{in out} are validity checked in
6104 procedure calls at the point of call. The @code{'m'} here stands for
6105 modify, since this concerns parameters that can be modified by the call.
6106 Note that there is no specific option to test @code{out} parameters,
6107 but any reference within the subprogram will be tested in the usual
6108 manner, and if an invalid value is copied back, any reference to it
6109 will be subject to validity checking.
6110
6111 @item -gnatVn
6112 @emph{No validity checks.}
6113 @cindex @option{-gnatVn} (@command{gcc})
6114 This switch turns off all validity checking, including the default checking
6115 for case statements and left hand side subscripts. Note that the use of
6116 the switch @option{-gnatp} suppresses all run-time checks, including
6117 validity checks, and thus implies @option{-gnatVn}. When this switch
6118 is used, it cancels any other @option{-gnatV} previously issued.
6119
6120 @item -gnatVo
6121 @emph{Validity checks for operator and attribute operands.}
6122 @cindex @option{-gnatVo} (@command{gcc})
6123 Arguments for predefined operators and attributes are validity checked.
6124 This includes all operators in package @code{Standard},
6125 the shift operators defined as intrinsic in package @code{Interfaces}
6126 and operands for attributes such as @code{Pos}. Checks are also made
6127 on individual component values for composite comparisons, and on the
6128 expressions in type conversions and qualified expressions. Checks are
6129 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6130
6131 @item -gnatVp
6132 @emph{Validity checks for parameters.}
6133 @cindex @option{-gnatVp} (@command{gcc})
6134 This controls the treatment of parameters within a subprogram (as opposed
6135 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6136 of parameters on a call. If either of these call options is used, then
6137 normally an assumption is made within a subprogram that the input arguments
6138 have been validity checking at the point of call, and do not need checking
6139 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6140 is not made, and parameters are not assumed to be valid, so their validity
6141 will be checked (or rechecked) within the subprogram.
6142
6143 @item -gnatVr
6144 @emph{Validity checks for function returns.}
6145 @cindex @option{-gnatVr} (@command{gcc})
6146 The expression in @code{return} statements in functions is validity
6147 checked.
6148
6149 @item -gnatVs
6150 @emph{Validity checks for subscripts.}
6151 @cindex @option{-gnatVs} (@command{gcc})
6152 All subscripts expressions are checked for validity, whether they appear
6153 on the right side or left side (in default mode only left side subscripts
6154 are validity checked).
6155
6156 @item -gnatVt
6157 @emph{Validity checks for tests.}
6158 @cindex @option{-gnatVt} (@command{gcc})
6159 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6160 statements are checked, as well as guard expressions in entry calls.
6161
6162 @end table
6163
6164 @noindent
6165 The @option{-gnatV} switch may be followed by
6166 ^a string of letters^a list of options^
6167 to turn on a series of validity checking options.
6168 For example,
6169 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6170 specifies that in addition to the default validity checking, copies and
6171 function return expressions are to be validity checked.
6172 In order to make it easier
6173 to specify the desired combination of effects,
6174 @ifclear vms
6175 the upper case letters @code{CDFIMORST} may
6176 be used to turn off the corresponding lower case option.
6177 @end ifclear
6178 @ifset vms
6179 the prefix @code{NO} on an option turns off the corresponding validity
6180 checking:
6181 @itemize @bullet
6182 @item @code{NOCOPIES}
6183 @item @code{NODEFAULT}
6184 @item @code{NOFLOATS}
6185 @item @code{NOIN_PARAMS}
6186 @item @code{NOMOD_PARAMS}
6187 @item @code{NOOPERANDS}
6188 @item @code{NORETURNS}
6189 @item @code{NOSUBSCRIPTS}
6190 @item @code{NOTESTS}
6191 @end itemize
6192 @end ifset
6193 Thus
6194 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6195 turns on all validity checking options except for
6196 checking of @code{@b{in out}} procedure arguments.
6197
6198 The specification of additional validity checking generates extra code (and
6199 in the case of @option{-gnatVa} the code expansion can be substantial).
6200 However, these additional checks can be very useful in detecting
6201 uninitialized variables, incorrect use of unchecked conversion, and other
6202 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6203 is useful in conjunction with the extra validity checking, since this
6204 ensures that wherever possible uninitialized variables have invalid values.
6205
6206 See also the pragma @code{Validity_Checks} which allows modification of
6207 the validity checking mode at the program source level, and also allows for
6208 temporary disabling of validity checks.
6209
6210 @node Style Checking
6211 @subsection Style Checking
6212 @findex Style checking
6213
6214 @noindent
6215 The @option{-gnaty^x^(option,option,@dots{})^} switch
6216 @cindex @option{-gnaty} (@command{gcc})
6217 causes the compiler to
6218 enforce specified style rules. A limited set of style rules has been used
6219 in writing the GNAT sources themselves. This switch allows user programs
6220 to activate all or some of these checks. If the source program fails a
6221 specified style check, an appropriate message is given, preceded by
6222 the character sequence ``(style)''. This message does not prevent
6223 successful compilation (unless the @option{-gnatwe} switch is used).
6224
6225 Note that this is by no means intended to be a general facility for
6226 checking arbitrary coding standards. It is simply an embedding of the
6227 style rules we have chosen for the GNAT sources. If you are starting
6228 a project which does not have established style standards, you may
6229 find it useful to adopt the entire set of GNAT coding standards, or
6230 some subset of them. If you already have an established set of coding
6231 standards, then it may be that selected style checking options do
6232 indeed correspond to choices you have made, but for general checking
6233 of an existing set of coding rules, you should look to the gnatcheck
6234 tool, which is designed for that purpose.
6235
6236 @ifset vms
6237 @code{(option,option,@dots{})} is a sequence of keywords
6238 @end ifset
6239 @ifclear vms
6240 The string @var{x} is a sequence of letters or digits
6241 @end ifclear
6242 indicating the particular style
6243 checks to be performed. The following checks are defined:
6244
6245 @table @option
6246 @c !sort!
6247 @item 0-9
6248 @emph{Specify indentation level.}
6249 If a digit from 1-9 appears
6250 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6251 then proper indentation is checked, with the digit indicating the
6252 indentation level required. A value of zero turns off this style check.
6253 The general style of required indentation is as specified by
6254 the examples in the Ada Reference Manual. Full line comments must be
6255 aligned with the @code{--} starting on a column that is a multiple of
6256 the alignment level, or they may be aligned the same way as the following
6257 non-blank line (this is useful when full line comments appear in the middle
6258 of a statement.
6259
6260 @item ^a^ATTRIBUTE^
6261 @emph{Check attribute casing.}
6262 Attribute names, including the case of keywords such as @code{digits}
6263 used as attributes names, must be written in mixed case, that is, the
6264 initial letter and any letter following an underscore must be uppercase.
6265 All other letters must be lowercase.
6266
6267 @item ^A^ARRAY_INDEXES^
6268 @emph{Use of array index numbers in array attributes.}
6269 When using the array attributes First, Last, Range,
6270 or Length, the index number must be omitted for one-dimensional arrays
6271 and is required for multi-dimensional arrays.
6272
6273 @item ^b^BLANKS^
6274 @emph{Blanks not allowed at statement end.}
6275 Trailing blanks are not allowed at the end of statements. The purpose of this
6276 rule, together with h (no horizontal tabs), is to enforce a canonical format
6277 for the use of blanks to separate source tokens.
6278
6279 @item ^B^BOOLEAN_OPERATORS^
6280 @emph{Check Boolean operators.}
6281 The use of AND/OR operators is not permitted except in the cases of modular
6282 operands, array operands, and simple stand-alone boolean variables or
6283 boolean constants. In all other cases AND THEN/OR ELSE are required.
6284
6285 @item ^c^COMMENTS^ (double space)
6286 @emph{Check comments, double space.}
6287 Comments must meet the following set of rules:
6288
6289 @itemize @bullet
6290
6291 @item
6292 The ``@code{--}'' that starts the column must either start in column one,
6293 or else at least one blank must precede this sequence.
6294
6295 @item
6296 Comments that follow other tokens on a line must have at least one blank
6297 following the ``@code{--}'' at the start of the comment.
6298
6299 @item
6300 Full line comments must have at least two blanks following the
6301 ``@code{--}'' that starts the comment, with the following exceptions.
6302
6303 @item
6304 A line consisting only of the ``@code{--}'' characters, possibly preceded
6305 by blanks is permitted.
6306
6307 @item
6308 A comment starting with ``@code{--x}'' where @code{x} is a special character
6309 is permitted.
6310 This allows proper processing of the output generated by specialized tools
6311 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6312 annotation
6313 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6314 special character is defined as being in one of the ASCII ranges
6315 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6316 Note that this usage is not permitted
6317 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6318
6319 @item
6320 A line consisting entirely of minus signs, possibly preceded by blanks, is
6321 permitted. This allows the construction of box comments where lines of minus
6322 signs are used to form the top and bottom of the box.
6323
6324 @item
6325 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6326 least one blank follows the initial ``@code{--}''. Together with the preceding
6327 rule, this allows the construction of box comments, as shown in the following
6328 example:
6329 @smallexample
6330 ---------------------------
6331 -- This is a box comment --
6332 -- with two text lines.  --
6333 ---------------------------
6334 @end smallexample
6335 @end itemize
6336
6337 @item ^C^COMMENTS1^ (single space)
6338 @emph{Check comments, single space.}
6339 This is identical to @code{^c^COMMENTS^} except that only one space
6340 is required following the @code{--} of a comment instead of two.
6341
6342 @item ^d^DOS_LINE_ENDINGS^
6343 @emph{Check no DOS line terminators present.}
6344 All lines must be terminated by a single ASCII.LF
6345 character (in particular the DOS line terminator sequence CR/LF is not
6346 allowed).
6347
6348 @item ^e^END^
6349 @emph{Check end/exit labels.}
6350 Optional labels on @code{end} statements ending subprograms and on
6351 @code{exit} statements exiting named loops, are required to be present.
6352
6353 @item ^f^VTABS^
6354 @emph{No form feeds or vertical tabs.}
6355 Neither form feeds nor vertical tab characters are permitted
6356 in the source text.
6357
6358 @item ^g^GNAT^
6359 @emph{GNAT style mode}
6360 The set of style check switches is set to match that used by the GNAT sources.
6361 This may be useful when developing code that is eventually intended to be
6362 incorporated into GNAT. For further details, see GNAT sources.
6363
6364 @item ^h^HTABS^
6365 @emph{No horizontal tabs.}
6366 Horizontal tab characters are not permitted in the source text.
6367 Together with the b (no blanks at end of line) check, this
6368 enforces a canonical form for the use of blanks to separate
6369 source tokens.
6370
6371 @item ^i^IF_THEN^
6372 @emph{Check if-then layout.}
6373 The keyword @code{then} must appear either on the same
6374 line as corresponding @code{if}, or on a line on its own, lined
6375 up under the @code{if} with at least one non-blank line in between
6376 containing all or part of the condition to be tested.
6377
6378 @item ^I^IN_MODE^
6379 @emph{check mode IN keywords}
6380 Mode @code{in} (the default mode) is not
6381 allowed to be given explicitly. @code{in out} is fine,
6382 but not @code{in} on its own.
6383
6384 @item ^k^KEYWORD^
6385 @emph{Check keyword casing.}
6386 All keywords must be in lower case (with the exception of keywords
6387 such as @code{digits} used as attribute names to which this check
6388 does not apply).
6389
6390 @item ^l^LAYOUT^
6391 @emph{Check layout.}
6392 Layout of statement and declaration constructs must follow the
6393 recommendations in the Ada Reference Manual, as indicated by the
6394 form of the syntax rules. For example an @code{else} keyword must
6395 be lined up with the corresponding @code{if} keyword.
6396
6397 There are two respects in which the style rule enforced by this check
6398 option are more liberal than those in the Ada Reference Manual. First
6399 in the case of record declarations, it is permissible to put the
6400 @code{record} keyword on the same line as the @code{type} keyword, and
6401 then the @code{end} in @code{end record} must line up under @code{type}.
6402 This is also permitted when the type declaration is split on two lines.
6403 For example, any of the following three layouts is acceptable:
6404
6405 @smallexample @c ada
6406 @cartouche
6407 type q is record
6408    a : integer;
6409    b : integer;
6410 end record;
6411
6412 type q is
6413    record
6414       a : integer;
6415       b : integer;
6416    end record;
6417
6418 type q is
6419    record
6420       a : integer;
6421       b : integer;
6422 end record;
6423
6424 @end cartouche
6425 @end smallexample
6426
6427 @noindent
6428 Second, in the case of a block statement, a permitted alternative
6429 is to put the block label on the same line as the @code{declare} or
6430 @code{begin} keyword, and then line the @code{end} keyword up under
6431 the block label. For example both the following are permitted:
6432
6433 @smallexample @c ada
6434 @cartouche
6435 Block : declare
6436    A : Integer := 3;
6437 begin
6438    Proc (A, A);
6439 end Block;
6440
6441 Block :
6442    declare
6443       A : Integer := 3;
6444    begin
6445       Proc (A, A);
6446    end Block;
6447 @end cartouche
6448 @end smallexample
6449
6450 @noindent
6451 The same alternative format is allowed for loops. For example, both of
6452 the following are permitted:
6453
6454 @smallexample @c ada
6455 @cartouche
6456 Clear : while J < 10 loop
6457    A (J) := 0;
6458 end loop Clear;
6459
6460 Clear :
6461    while J < 10 loop
6462       A (J) := 0;
6463    end loop Clear;
6464 @end cartouche
6465 @end smallexample
6466
6467 @item ^Lnnn^MAX_NESTING=nnn^
6468 @emph{Set maximum nesting level}
6469 The maximum level of nesting of constructs (including subprograms, loops,
6470 blocks, packages, and conditionals) may not exceed the given value
6471 @option{nnn}. A value of zero disconnects this style check.
6472
6473 @item ^m^LINE_LENGTH^
6474 @emph{Check maximum line length.}
6475 The length of source lines must not exceed 79 characters, including
6476 any trailing blanks. The value of 79 allows convenient display on an
6477 80 character wide device or window, allowing for possible special
6478 treatment of 80 character lines. Note that this count is of
6479 characters in the source text. This means that a tab character counts
6480 as one character in this count but a wide character sequence counts as
6481 a single character (however many bytes are needed in the encoding).
6482
6483 @item ^Mnnn^MAX_LENGTH=nnn^
6484 @emph{Set maximum line length.}
6485 The length of lines must not exceed the
6486 given value @option{nnn}. The maximum value that can be specified is 32767.
6487
6488 @item ^n^STANDARD_CASING^
6489 @emph{Check casing of entities in Standard.}
6490 Any identifier from Standard must be cased
6491 to match the presentation in the Ada Reference Manual (for example,
6492 @code{Integer} and @code{ASCII.NUL}).
6493
6494 @item ^N^NONE^
6495 @emph{Turn off all style checks}
6496 All style check options are turned off.
6497
6498 @item ^o^ORDERED_SUBPROGRAMS^
6499 @emph{Check order of subprogram bodies.}
6500 All subprogram bodies in a given scope
6501 (e.g.@: a package body) must be in alphabetical order. The ordering
6502 rule uses normal Ada rules for comparing strings, ignoring casing
6503 of letters, except that if there is a trailing numeric suffix, then
6504 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6505 before Junk10).
6506
6507 @item ^O^OVERRIDING_INDICATORS^
6508 @emph{Check that overriding subprograms are explicitly marked as such.}
6509 The declaration of a primitive operation of a type extension that overrides
6510 an inherited operation must carry an overriding indicator.
6511
6512 @item ^p^PRAGMA^
6513 @emph{Check pragma casing.}
6514 Pragma names must be written in mixed case, that is, the
6515 initial letter and any letter following an underscore must be uppercase.
6516 All other letters must be lowercase.
6517
6518 @item ^r^REFERENCES^
6519 @emph{Check references.}
6520 All identifier references must be cased in the same way as the
6521 corresponding declaration. No specific casing style is imposed on
6522 identifiers. The only requirement is for consistency of references
6523 with declarations.
6524
6525 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6526 @emph{Check no statements after THEN/ELSE.}
6527 No statements are allowed
6528 on the same line as a THEN or ELSE keyword following the
6529 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6530 and a special exception allows a pragma to appear after ELSE.
6531
6532 @item ^s^SPECS^
6533 @emph{Check separate specs.}
6534 Separate declarations (``specs'') are required for subprograms (a
6535 body is not allowed to serve as its own declaration). The only
6536 exception is that parameterless library level procedures are
6537 not required to have a separate declaration. This exception covers
6538 the most frequent form of main program procedures.
6539
6540 @item ^t^TOKEN^
6541 @emph{Check token spacing.}
6542 The following token spacing rules are enforced:
6543
6544 @itemize @bullet
6545
6546 @item
6547 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6548
6549 @item
6550 The token @code{=>} must be surrounded by spaces.
6551
6552 @item
6553 The token @code{<>} must be preceded by a space or a left parenthesis.
6554
6555 @item
6556 Binary operators other than @code{**} must be surrounded by spaces.
6557 There is no restriction on the layout of the @code{**} binary operator.
6558
6559 @item
6560 Colon must be surrounded by spaces.
6561
6562 @item
6563 Colon-equal (assignment, initialization) must be surrounded by spaces.
6564
6565 @item
6566 Comma must be the first non-blank character on the line, or be
6567 immediately preceded by a non-blank character, and must be followed
6568 by a space.
6569
6570 @item
6571 If the token preceding a left parenthesis ends with a letter or digit, then
6572 a space must separate the two tokens.
6573
6574 @item
6575 if the token following a right parenthesis starts with a letter or digit, then
6576 a space must separate the two tokens.
6577
6578 @item
6579 A right parenthesis must either be the first non-blank character on
6580 a line, or it must be preceded by a non-blank character.
6581
6582 @item
6583 A semicolon must not be preceded by a space, and must not be followed by
6584 a non-blank character.
6585
6586 @item
6587 A unary plus or minus may not be followed by a space.
6588
6589 @item
6590 A vertical bar must be surrounded by spaces.
6591 @end itemize
6592
6593 @item ^u^UNNECESSARY_BLANK_LINES^
6594 @emph{Check unnecessary blank lines.}
6595 Unnecessary blank lines are not allowed. A blank line is considered
6596 unnecessary if it appears at the end of the file, or if more than
6597 one blank line occurs in sequence.
6598
6599 @item ^x^XTRA_PARENS^
6600 @emph{Check extra parentheses.}
6601 Unnecessary extra level of parentheses (C-style) are not allowed
6602 around conditions in @code{if} statements, @code{while} statements and
6603 @code{exit} statements.
6604
6605 @item ^y^ALL_BUILTIN^
6606 @emph{Set all standard style check options}
6607 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6608 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6609 @option{-gnatyS}, @option{-gnatyLnnn},
6610 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6611
6612 @ifclear vms
6613 @item -
6614 @emph{Remove style check options}
6615 This causes any subsequent options in the string to act as canceling the
6616 corresponding style check option. To cancel maximum nesting level control,
6617 use @option{L} parameter witout any integer value after that, because any
6618 digit following @option{-} in the parameter string of the @option{-gnaty}
6619 option will be threated as canceling indentation check. The same is true
6620 for @option{M} parameter. @option{y} and @option{N} parameters are not
6621 allowed after @option{-}.
6622
6623 @item +
6624 This causes any subsequent options in the string to enable the corresponding
6625 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6626 if any.
6627 @end ifclear
6628
6629 @ifset vms
6630 @item NOxxx
6631 @emph{Removing style check options}
6632 If the name of a style check is preceded by @option{NO} then the corresponding
6633 style check is turned off. For example @option{NOCOMMENTS} turns off style
6634 checking for comments.
6635 @end ifset
6636 @end table
6637
6638 @noindent
6639 In the above rules, appearing in column one is always permitted, that is,
6640 counts as meeting either a requirement for a required preceding space,
6641 or as meeting a requirement for no preceding space.
6642
6643 Appearing at the end of a line is also always permitted, that is, counts
6644 as meeting either a requirement for a following space, or as meeting
6645 a requirement for no following space.
6646
6647 @noindent
6648 If any of these style rules is violated, a message is generated giving
6649 details on the violation. The initial characters of such messages are
6650 always ``@code{(style)}''. Note that these messages are treated as warning
6651 messages, so they normally do not prevent the generation of an object
6652 file. The @option{-gnatwe} switch can be used to treat warning messages,
6653 including style messages, as fatal errors.
6654
6655 The switch
6656 @ifclear vms
6657 @option{-gnaty} on its own (that is not
6658 followed by any letters or digits), then the effect is equivalent
6659 to the use of @option{-gnatyy}, as described above, that is all
6660 built-in standard style check options are enabled.
6661
6662 @end ifclear
6663 @ifset vms
6664 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6665 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6666 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6667 @end ifset
6668
6669 The switch
6670 @ifclear vms
6671 @option{-gnatyN}
6672 @end ifclear
6673 @ifset vms
6674 /STYLE_CHECKS=NONE
6675 @end ifset
6676 clears any previously set style checks.
6677
6678 @node Run-Time Checks
6679 @subsection Run-Time Checks
6680 @cindex Division by zero
6681 @cindex Access before elaboration
6682 @cindex Checks, division by zero
6683 @cindex Checks, access before elaboration
6684 @cindex Checks, stack overflow checking
6685
6686 @noindent
6687 By default, the following checks are suppressed: integer overflow
6688 checks, stack overflow checks, and checks for access before
6689 elaboration on subprogram calls. All other checks, including range
6690 checks and array bounds checks, are turned on by default. The
6691 following @command{gcc} switches refine this default behavior.
6692
6693 @table @option
6694 @c !sort!
6695 @item -gnatp
6696 @cindex @option{-gnatp} (@command{gcc})
6697 @cindex Suppressing checks
6698 @cindex Checks, suppressing
6699 @findex Suppress
6700 This switch causes the unit to be compiled
6701 as though @code{pragma Suppress (All_checks)}
6702 had been present in the source. Validity checks are also eliminated (in
6703 other words @option{-gnatp} also implies @option{-gnatVn}.
6704 Use this switch to improve the performance
6705 of the code at the expense of safety in the presence of invalid data or
6706 program bugs.
6707
6708 Note that when checks are suppressed, the compiler is allowed, but not
6709 required, to omit the checking code. If the run-time cost of the
6710 checking code is zero or near-zero, the compiler will generate it even
6711 if checks are suppressed. In particular, if the compiler can prove
6712 that a certain check will necessarily fail, it will generate code to
6713 do an unconditional ``raise'', even if checks are suppressed. The
6714 compiler warns in this case. Another case in which checks may not be
6715 eliminated is when they are embedded in certain run time routines such
6716 as math library routines.
6717
6718 Of course, run-time checks are omitted whenever the compiler can prove
6719 that they will not fail, whether or not checks are suppressed.
6720
6721 Note that if you suppress a check that would have failed, program
6722 execution is erroneous, which means the behavior is totally
6723 unpredictable. The program might crash, or print wrong answers, or
6724 do anything else. It might even do exactly what you wanted it to do
6725 (and then it might start failing mysteriously next week or next
6726 year). The compiler will generate code based on the assumption that
6727 the condition being checked is true, which can result in disaster if
6728 that assumption is wrong.
6729
6730 The @option{-gnatp} switch has no effect if a subsequent
6731 @option{-gnat-p} switch appears.
6732
6733 @item -gnat-p
6734 @cindex @option{-gnat-p} (@command{gcc})
6735 @cindex Suppressing checks
6736 @cindex Checks, suppressing
6737 @findex Suppress
6738 This switch cancels the effect of a previous @option{gnatp} switch.
6739
6740 @item -gnato
6741 @cindex @option{-gnato} (@command{gcc})
6742 @cindex Overflow checks
6743 @cindex Check, overflow
6744 Enables overflow checking for integer operations.
6745 This causes GNAT to generate slower and larger executable
6746 programs by adding code to check for overflow (resulting in raising
6747 @code{Constraint_Error} as required by standard Ada
6748 semantics). These overflow checks correspond to situations in which
6749 the true value of the result of an operation may be outside the base
6750 range of the result type. The following example shows the distinction:
6751
6752 @smallexample @c ada
6753 X1 : Integer := "Integer'Last";
6754 X2 : Integer range 1 .. 5 := "5";
6755 X3 : Integer := "Integer'Last";
6756 X4 : Integer range 1 .. 5 := "5";
6757 F  : Float := "2.0E+20";
6758 @dots{}
6759 X1 := X1 + 1;
6760 X2 := X2 + 1;
6761 X3 := Integer (F);
6762 X4 := Integer (F);
6763 @end smallexample
6764
6765 @noindent
6766 Note that if explicit values are assigned at compile time, the
6767 compiler may be able to detect overflow at compile time, in which case
6768 no actual run-time checking code is required, and Constraint_Error
6769 will be raised unconditionally, with or without
6770 @option{-gnato}. That's why the assigned values in the above fragment
6771 are in quotes, the meaning is "assign a value not known to the
6772 compiler that happens to be equal to ...". The remaining discussion
6773 assumes that the compiler cannot detect the values at compile time.
6774
6775 Here the first addition results in a value that is outside the base range
6776 of Integer, and hence requires an overflow check for detection of the
6777 constraint error. Thus the first assignment to @code{X1} raises a
6778 @code{Constraint_Error} exception only if @option{-gnato} is set.
6779
6780 The second increment operation results in a violation of the explicit
6781 range constraint; such range checks are performed by default, and are
6782 unaffected by @option{-gnato}.
6783
6784 The two conversions of @code{F} both result in values that are outside
6785 the base range of type @code{Integer} and thus will raise
6786 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6787 The fact that the result of the second conversion is assigned to
6788 variable @code{X4} with a restricted range is irrelevant, since the problem
6789 is in the conversion, not the assignment.
6790
6791 Basically the rule is that in the default mode (@option{-gnato} not
6792 used), the generated code assures that all integer variables stay
6793 within their declared ranges, or within the base range if there is
6794 no declared range. This prevents any serious problems like indexes
6795 out of range for array operations.
6796
6797 What is not checked in default mode is an overflow that results in
6798 an in-range, but incorrect value. In the above example, the assignments
6799 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6800 range of the target variable, but the result is wrong in the sense that
6801 it is too large to be represented correctly. Typically the assignment
6802 to @code{X1} will result in wrap around to the largest negative number.
6803 The conversions of @code{F} will result in some @code{Integer} value
6804 and if that integer value is out of the @code{X4} range then the
6805 subsequent assignment would generate an exception.
6806
6807 @findex Machine_Overflows
6808 Note that the @option{-gnato} switch does not affect the code generated
6809 for any floating-point operations; it applies only to integer
6810 semantics).
6811 For floating-point, GNAT has the @code{Machine_Overflows}
6812 attribute set to @code{False} and the normal mode of operation is to
6813 generate IEEE NaN and infinite values on overflow or invalid operations
6814 (such as dividing 0.0 by 0.0).
6815
6816 The reason that we distinguish overflow checking from other kinds of
6817 range constraint checking is that a failure of an overflow check, unlike
6818 for example the failure of a range check, can result in an incorrect
6819 value, but cannot cause random memory destruction (like an out of range
6820 subscript), or a wild jump (from an out of range case value). Overflow
6821 checking is also quite expensive in time and space, since in general it
6822 requires the use of double length arithmetic.
6823
6824 Note again that @option{-gnato} is off by default, so overflow checking is
6825 not performed in default mode. This means that out of the box, with the
6826 default settings, GNAT does not do all the checks expected from the
6827 language description in the Ada Reference Manual. If you want all constraint
6828 checks to be performed, as described in this Manual, then you must
6829 explicitly use the -gnato switch either on the @command{gnatmake} or
6830 @command{gcc} command.
6831
6832 @item -gnatE
6833 @cindex @option{-gnatE} (@command{gcc})
6834 @cindex Elaboration checks
6835 @cindex Check, elaboration
6836 Enables dynamic checks for access-before-elaboration
6837 on subprogram calls and generic instantiations.
6838 Note that @option{-gnatE} is not necessary for safety, because in the
6839 default mode, GNAT ensures statically that the checks would not fail.
6840 For full details of the effect and use of this switch,
6841 @xref{Compiling Using gcc}.
6842
6843 @item -fstack-check
6844 @cindex @option{-fstack-check} (@command{gcc})
6845 @cindex Stack Overflow Checking
6846 @cindex Checks, stack overflow checking
6847 Activates stack overflow checking. For full details of the effect and use of
6848 this switch see @ref{Stack Overflow Checking}.
6849 @end table
6850
6851 @findex Unsuppress
6852 @noindent
6853 The setting of these switches only controls the default setting of the
6854 checks. You may modify them using either @code{Suppress} (to remove
6855 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6856 the program source.
6857
6858 @node Using gcc for Syntax Checking
6859 @subsection Using @command{gcc} for Syntax Checking
6860 @table @option
6861 @item -gnats
6862 @cindex @option{-gnats} (@command{gcc})
6863 @ifclear vms
6864
6865 @noindent
6866 The @code{s} stands for ``syntax''.
6867 @end ifclear
6868
6869 Run GNAT in syntax checking only mode. For
6870 example, the command
6871
6872 @smallexample
6873 $ gcc -c -gnats x.adb
6874 @end smallexample
6875
6876 @noindent
6877 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6878 series of files in a single command
6879 @ifclear vms
6880 , and can use wild cards to specify such a group of files.
6881 Note that you must specify the @option{-c} (compile
6882 only) flag in addition to the @option{-gnats} flag.
6883 @end ifclear
6884 .
6885 You may use other switches in conjunction with @option{-gnats}. In
6886 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6887 format of any generated error messages.
6888
6889 When the source file is empty or contains only empty lines and/or comments,
6890 the output is a warning:
6891
6892 @smallexample
6893 $ gcc -c -gnats -x ada toto.txt
6894 toto.txt:1:01: warning: empty file, contains no compilation units
6895 $
6896 @end smallexample
6897
6898 Otherwise, the output is simply the error messages, if any. No object file or
6899 ALI file is generated by a syntax-only compilation. Also, no units other
6900 than the one specified are accessed. For example, if a unit @code{X}
6901 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6902 check only mode does not access the source file containing unit
6903 @code{Y}.
6904
6905 @cindex Multiple units, syntax checking
6906 Normally, GNAT allows only a single unit in a source file. However, this
6907 restriction does not apply in syntax-check-only mode, and it is possible
6908 to check a file containing multiple compilation units concatenated
6909 together. This is primarily used by the @code{gnatchop} utility
6910 (@pxref{Renaming Files Using gnatchop}).
6911 @end table
6912
6913 @node Using gcc for Semantic Checking
6914 @subsection Using @command{gcc} for Semantic Checking
6915 @table @option
6916 @item -gnatc
6917 @cindex @option{-gnatc} (@command{gcc})
6918
6919 @ifclear vms
6920 @noindent
6921 The @code{c} stands for ``check''.
6922 @end ifclear
6923 Causes the compiler to operate in semantic check mode,
6924 with full checking for all illegalities specified in the
6925 Ada Reference Manual, but without generation of any object code
6926 (no object file is generated).
6927
6928 Because dependent files must be accessed, you must follow the GNAT
6929 semantic restrictions on file structuring to operate in this mode:
6930
6931 @itemize @bullet
6932 @item
6933 The needed source files must be accessible
6934 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6935
6936 @item
6937 Each file must contain only one compilation unit.
6938
6939 @item
6940 The file name and unit name must match (@pxref{File Naming Rules}).
6941 @end itemize
6942
6943 The output consists of error messages as appropriate. No object file is
6944 generated. An @file{ALI} file is generated for use in the context of
6945 cross-reference tools, but this file is marked as not being suitable
6946 for binding (since no object file is generated).
6947 The checking corresponds exactly to the notion of
6948 legality in the Ada Reference Manual.
6949
6950 Any unit can be compiled in semantics-checking-only mode, including
6951 units that would not normally be compiled (subunits,
6952 and specifications where a separate body is present).
6953 @end table
6954
6955 @node Compiling Different Versions of Ada
6956 @subsection Compiling Different Versions of Ada
6957
6958 @noindent
6959 The switches described in this section allow you to explicitly specify
6960 the version of the Ada language that your programs are written in.
6961 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6962 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6963 indicate Ada 83 compatibility mode.
6964
6965 @table @option
6966 @cindex Compatibility with Ada 83
6967
6968 @item -gnat83 (Ada 83 Compatibility Mode)
6969 @cindex @option{-gnat83} (@command{gcc})
6970 @cindex ACVC, Ada 83 tests
6971 @cindex Ada 83 mode
6972
6973 @noindent
6974 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6975 specifies that the program is to be compiled in Ada 83 mode. With
6976 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6977 semantics where this can be done easily.
6978 It is not possible to guarantee this switch does a perfect
6979 job; some subtle tests, such as are
6980 found in earlier ACVC tests (and that have been removed from the ACATS suite
6981 for Ada 95), might not compile correctly.
6982 Nevertheless, this switch may be useful in some circumstances, for example
6983 where, due to contractual reasons, existing code needs to be maintained
6984 using only Ada 83 features.
6985
6986 With few exceptions (most notably the need to use @code{<>} on
6987 @cindex Generic formal parameters
6988 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6989 reserved words, and the use of packages
6990 with optional bodies), it is not necessary to specify the
6991 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6992 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6993 a correct Ada 83 program is usually also a correct program
6994 in these later versions of the language standard.
6995 For further information, please refer to @ref{Compatibility and Porting Guide}.
6996
6997 @item -gnat95 (Ada 95 mode)
6998 @cindex @option{-gnat95} (@command{gcc})
6999 @cindex Ada 95 mode
7000
7001 @noindent
7002 This switch directs the compiler to implement the Ada 95 version of the
7003 language.
7004 Since Ada 95 is almost completely upwards
7005 compatible with Ada 83, Ada 83 programs may generally be compiled using
7006 this switch (see the description of the @option{-gnat83} switch for further
7007 information about Ada 83 mode).
7008 If an Ada 2005 program is compiled in Ada 95 mode,
7009 uses of the new Ada 2005 features will cause error
7010 messages or warnings.
7011
7012 This switch also can be used to cancel the effect of a previous
7013 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7014 switch earlier in the command line.
7015
7016 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7017 @cindex @option{-gnat05} (@command{gcc})
7018 @cindex @option{-gnat2005} (@command{gcc})
7019 @cindex Ada 2005 mode
7020
7021 @noindent
7022 This switch directs the compiler to implement the Ada 2005 version of the
7023 language, as documented in the official Ada standards document.
7024 Since Ada 2005 is almost completely upwards
7025 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7026 may generally be compiled using this switch (see the description of the
7027 @option{-gnat83} and @option{-gnat95} switches for further
7028 information).
7029
7030 @ifset PROEDITION
7031 Note that even though Ada 2005 is the current official version of the
7032 language, GNAT still compiles in Ada 95 mode by default, so if you are
7033 using Ada 2005 features in your program, you must use this switch (or
7034 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7035 @end ifset
7036
7037 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7038 @cindex @option{-gnat12} (@command{gcc})
7039 @cindex @option{-gnat2012} (@command{gcc})
7040 @cindex Ada 2012 mode
7041
7042 @noindent
7043 This switch directs the compiler to implement the Ada 2012 version of the
7044 language.
7045 Since Ada 2012 is almost completely upwards
7046 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7047 Ada 83 and Ada 95 programs
7048 may generally be compiled using this switch (see the description of the
7049 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7050 for further information).
7051
7052 For information about the approved ``Ada Issues'' that have been incorporated
7053 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7054 Included with GNAT releases is a file @file{features-ada12} that describes
7055 the set of implemented Ada 2012 features.
7056
7057 @item -gnatX (Enable GNAT Extensions)
7058 @cindex @option{-gnatX} (@command{gcc})
7059 @cindex Ada language extensions
7060 @cindex GNAT extensions
7061
7062 @noindent
7063 This switch directs the compiler to implement the latest version of the
7064 language (currently Ada 2012) and also to enable certain GNAT implementation
7065 extensions that are not part of any Ada standard. For a full list of these
7066 extensions, see the GNAT reference manual.
7067
7068 @end table
7069
7070 @node Character Set Control
7071 @subsection Character Set Control
7072 @table @option
7073 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7074 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7075
7076 @noindent
7077 Normally GNAT recognizes the Latin-1 character set in source program
7078 identifiers, as described in the Ada Reference Manual.
7079 This switch causes
7080 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7081 single character ^^or word^ indicating the character set, as follows:
7082
7083 @table @code
7084 @item 1
7085 ISO 8859-1 (Latin-1) identifiers
7086
7087 @item 2
7088 ISO 8859-2 (Latin-2) letters allowed in identifiers
7089
7090 @item 3
7091 ISO 8859-3 (Latin-3) letters allowed in identifiers
7092
7093 @item 4
7094 ISO 8859-4 (Latin-4) letters allowed in identifiers
7095
7096 @item 5
7097 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7098
7099 @item 9
7100 ISO 8859-15 (Latin-9) letters allowed in identifiers
7101
7102 @item ^p^PC^
7103 IBM PC letters (code page 437) allowed in identifiers
7104
7105 @item ^8^PC850^
7106 IBM PC letters (code page 850) allowed in identifiers
7107
7108 @item ^f^FULL_UPPER^
7109 Full upper-half codes allowed in identifiers
7110
7111 @item ^n^NO_UPPER^
7112 No upper-half codes allowed in identifiers
7113
7114 @item ^w^WIDE^
7115 Wide-character codes (that is, codes greater than 255)
7116 allowed in identifiers
7117 @end table
7118
7119 @xref{Foreign Language Representation}, for full details on the
7120 implementation of these character sets.
7121
7122 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7123 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7124 Specify the method of encoding for wide characters.
7125 @var{e} is one of the following:
7126
7127 @table @code
7128
7129 @item ^h^HEX^
7130 Hex encoding (brackets coding also recognized)
7131
7132 @item ^u^UPPER^
7133 Upper half encoding (brackets encoding also recognized)
7134
7135 @item ^s^SHIFT_JIS^
7136 Shift/JIS encoding (brackets encoding also recognized)
7137
7138 @item ^e^EUC^
7139 EUC encoding (brackets encoding also recognized)
7140
7141 @item ^8^UTF8^
7142 UTF-8 encoding (brackets encoding also recognized)
7143
7144 @item ^b^BRACKETS^
7145 Brackets encoding only (default value)
7146 @end table
7147 For full details on these encoding
7148 methods see @ref{Wide Character Encodings}.
7149 Note that brackets coding is always accepted, even if one of the other
7150 options is specified, so for example @option{-gnatW8} specifies that both
7151 brackets and UTF-8 encodings will be recognized. The units that are
7152 with'ed directly or indirectly will be scanned using the specified
7153 representation scheme, and so if one of the non-brackets scheme is
7154 used, it must be used consistently throughout the program. However,
7155 since brackets encoding is always recognized, it may be conveniently
7156 used in standard libraries, allowing these libraries to be used with
7157 any of the available coding schemes.
7158
7159 Note that brackets encoding only applies to program text. Within comments,
7160 brackets are considered to be normal graphic characters, and bracket sequences
7161 are never recognized as wide characters.
7162
7163 If no @option{-gnatW?} parameter is present, then the default
7164 representation is normally Brackets encoding only. However, if the
7165 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7166 byte order mark or BOM for UTF-8), then these three characters are
7167 skipped and the default representation for the file is set to UTF-8.
7168
7169 Note that the wide character representation that is specified (explicitly
7170 or by default) for the main program also acts as the default encoding used
7171 for Wide_Text_IO files if not specifically overridden by a WCEM form
7172 parameter.
7173
7174 @end table
7175
7176 When no @option{-gnatW?} is specified, then characters (other than wide
7177 characters represented using brackets notation) are treated as 8-bit
7178 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7179 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7180 characters in the range 16#00#..16#1F# are not accepted in program text
7181 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7182 in program text, but allowed and ignored in comments. Note in particular
7183 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7184 as an end of line in this default mode. If your source program contains
7185 instances of the NEL character used as a line terminator,
7186 you must use UTF-8 encoding for the whole
7187 source program. In default mode, all lines must be ended by a standard
7188 end of line sequence (CR, CR/LF, or LF).
7189
7190 Note that the convention of simply accepting all upper half characters in
7191 comments means that programs that use standard ASCII for program text, but
7192 UTF-8 encoding for comments are accepted in default mode, providing that the
7193 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7194 This is a common mode for many programs with foreign language comments.
7195
7196 @node File Naming Control
7197 @subsection File Naming Control
7198
7199 @table @option
7200 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7201 @cindex @option{-gnatk} (@command{gcc})
7202 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7203 1-999, indicates the maximum allowable length of a file name (not
7204 including the @file{.ads} or @file{.adb} extension). The default is not
7205 to enable file name krunching.
7206
7207 For the source file naming rules, @xref{File Naming Rules}.
7208 @end table
7209
7210 @node Subprogram Inlining Control
7211 @subsection Subprogram Inlining Control
7212
7213 @table @option
7214 @c !sort!
7215 @item -gnatn
7216 @cindex @option{-gnatn} (@command{gcc})
7217 @ifclear vms
7218 The @code{n} here is intended to suggest the first syllable of the
7219 word ``inline''.
7220 @end ifclear
7221 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7222 inlining to actually occur, optimization must be enabled. To enable
7223 inlining of subprograms specified by pragma @code{Inline},
7224 you must also specify this switch.
7225 In the absence of this switch, GNAT does not attempt
7226 inlining and does not need to access the bodies of
7227 subprograms for which @code{pragma Inline} is specified if they are not
7228 in the current unit.
7229
7230 If you specify this switch the compiler will access these bodies,
7231 creating an extra source dependency for the resulting object file, and
7232 where possible, the call will be inlined.
7233 For further details on when inlining is possible
7234 see @ref{Inlining of Subprograms}.
7235
7236 @item -gnatN
7237 @cindex @option{-gnatN} (@command{gcc})
7238 This switch activates front-end inlining which also
7239 generates additional dependencies.
7240
7241 When using a gcc-based back end (in practice this means using any version
7242 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7243 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7244 Historically front end inlining was more extensive than the gcc back end
7245 inlining, but that is no longer the case.
7246 @end table
7247
7248 @node Auxiliary Output Control
7249 @subsection Auxiliary Output Control
7250
7251 @table @option
7252 @item -gnatt
7253 @cindex @option{-gnatt} (@command{gcc})
7254 @cindex Writing internal trees
7255 @cindex Internal trees, writing to file
7256 Causes GNAT to write the internal tree for a unit to a file (with the
7257 extension @file{.adt}.
7258 This not normally required, but is used by separate analysis tools.
7259 Typically
7260 these tools do the necessary compilations automatically, so you should
7261 not have to specify this switch in normal operation.
7262 Note that the combination of switches @option{-gnatct}
7263 generates a tree in the form required by ASIS applications.
7264
7265 @item -gnatu
7266 @cindex @option{-gnatu} (@command{gcc})
7267 Print a list of units required by this compilation on @file{stdout}.
7268 The listing includes all units on which the unit being compiled depends
7269 either directly or indirectly.
7270
7271 @ifclear vms
7272 @item -pass-exit-codes
7273 @cindex @option{-pass-exit-codes} (@command{gcc})
7274 If this switch is not used, the exit code returned by @command{gcc} when
7275 compiling multiple files indicates whether all source files have
7276 been successfully used to generate object files or not.
7277
7278 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7279 exit status and allows an integrated development environment to better
7280 react to a compilation failure. Those exit status are:
7281
7282 @table @asis
7283 @item 5
7284 There was an error in at least one source file.
7285 @item 3
7286 At least one source file did not generate an object file.
7287 @item 2
7288 The compiler died unexpectedly (internal error for example).
7289 @item 0
7290 An object file has been generated for every source file.
7291 @end table
7292 @end ifclear
7293 @end table
7294
7295 @node Debugging Control
7296 @subsection Debugging Control
7297
7298 @table @option
7299 @c !sort!
7300 @cindex Debugging options
7301 @ifclear vms
7302 @item -gnatd@var{x}
7303 @cindex @option{-gnatd} (@command{gcc})
7304 Activate internal debugging switches. @var{x} is a letter or digit, or
7305 string of letters or digits, which specifies the type of debugging
7306 outputs desired. Normally these are used only for internal development
7307 or system debugging purposes. You can find full documentation for these
7308 switches in the body of the @code{Debug} unit in the compiler source
7309 file @file{debug.adb}.
7310 @end ifclear
7311
7312 @item -gnatG[=nn]
7313 @cindex @option{-gnatG} (@command{gcc})
7314 This switch causes the compiler to generate auxiliary output containing
7315 a pseudo-source listing of the generated expanded code. Like most Ada
7316 compilers, GNAT works by first transforming the high level Ada code into
7317 lower level constructs. For example, tasking operations are transformed
7318 into calls to the tasking run-time routines. A unique capability of GNAT
7319 is to list this expanded code in a form very close to normal Ada source.
7320 This is very useful in understanding the implications of various Ada
7321 usage on the efficiency of the generated code. There are many cases in
7322 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7323 generate a lot of run-time code. By using @option{-gnatG} you can identify
7324 these cases, and consider whether it may be desirable to modify the coding
7325 approach to improve efficiency.
7326
7327 The optional parameter @code{nn} if present after -gnatG specifies an
7328 alternative maximum line length that overrides the normal default of 72.
7329 This value is in the range 40-999999, values less than 40 being silently
7330 reset to 40. The equal sign is optional.
7331
7332 The format of the output is very similar to standard Ada source, and is
7333 easily understood by an Ada programmer. The following special syntactic
7334 additions correspond to low level features used in the generated code that
7335 do not have any exact analogies in pure Ada source form. The following
7336 is a partial list of these special constructions. See the spec
7337 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7338
7339 If the switch @option{-gnatL} is used in conjunction with
7340 @cindex @option{-gnatL} (@command{gcc})
7341 @option{-gnatG}, then the original source lines are interspersed
7342 in the expanded source (as comment lines with the original line number).
7343
7344 @table @code
7345 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7346 Shows the storage pool being used for an allocator.
7347
7348 @item at end @var{procedure-name};
7349 Shows the finalization (cleanup) procedure for a scope.
7350
7351 @item (if @var{expr} then @var{expr} else @var{expr})
7352 Conditional expression equivalent to the @code{x?y:z} construction in C.
7353
7354 @item @var{target}^^^(@var{source})
7355 A conversion with floating-point truncation instead of rounding.
7356
7357 @item @var{target}?(@var{source})
7358 A conversion that bypasses normal Ada semantic checking. In particular
7359 enumeration types and fixed-point types are treated simply as integers.
7360
7361 @item @var{target}?^^^(@var{source})
7362 Combines the above two cases.
7363
7364 @item @var{x} #/ @var{y}
7365 @itemx @var{x} #mod @var{y}
7366 @itemx @var{x} #* @var{y}
7367 @itemx @var{x} #rem @var{y}
7368 A division or multiplication of fixed-point values which are treated as
7369 integers without any kind of scaling.
7370
7371 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7372 Shows the storage pool associated with a @code{free} statement.
7373
7374 @item [subtype or type declaration]
7375 Used to list an equivalent declaration for an internally generated
7376 type that is referenced elsewhere in the listing.
7377
7378 @c @item freeze @var{type-name} @ovar{actions}
7379 @c Expanding @ovar macro inline (explanation in macro def comments)
7380 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7381 Shows the point at which @var{type-name} is frozen, with possible
7382 associated actions to be performed at the freeze point.
7383
7384 @item reference @var{itype}
7385 Reference (and hence definition) to internal type @var{itype}.
7386
7387 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7388 Intrinsic function call.
7389
7390 @item @var{label-name} : label
7391 Declaration of label @var{labelname}.
7392
7393 @item #$ @var{subprogram-name}
7394 An implicit call to a run-time support routine
7395 (to meet the requirement of H.3.1(9) in a
7396 convenient manner).
7397
7398 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7399 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7400 @var{expr}, but handled more efficiently).
7401
7402 @item [constraint_error]
7403 Raise the @code{Constraint_Error} exception.
7404
7405 @item @var{expression}'reference
7406 A pointer to the result of evaluating @var{expression}.
7407
7408 @item @var{target-type}!(@var{source-expression})
7409 An unchecked conversion of @var{source-expression} to @var{target-type}.
7410
7411 @item [@var{numerator}/@var{denominator}]
7412 Used to represent internal real literals (that) have no exact
7413 representation in base 2-16 (for example, the result of compile time
7414 evaluation of the expression 1.0/27.0).
7415 @end table
7416
7417 @item -gnatD[=nn]
7418 @cindex @option{-gnatD} (@command{gcc})
7419 When used in conjunction with @option{-gnatG}, this switch causes
7420 the expanded source, as described above for
7421 @option{-gnatG} to be written to files with names
7422 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7423 instead of to the standard output file. For
7424 example, if the source file name is @file{hello.adb}, then a file
7425 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7426 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7427 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7428 you to do source level debugging using the generated code which is
7429 sometimes useful for complex code, for example to find out exactly
7430 which part of a complex construction raised an exception. This switch
7431 also suppress generation of cross-reference information (see
7432 @option{-gnatx}) since otherwise the cross-reference information
7433 would refer to the @file{^.dg^.DG^} file, which would cause
7434 confusion since this is not the original source file.
7435
7436 Note that @option{-gnatD} actually implies @option{-gnatG}
7437 automatically, so it is not necessary to give both options.
7438 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7439
7440 If the switch @option{-gnatL} is used in conjunction with
7441 @cindex @option{-gnatL} (@command{gcc})
7442 @option{-gnatDG}, then the original source lines are interspersed
7443 in the expanded source (as comment lines with the original line number).
7444
7445 The optional parameter @code{nn} if present after -gnatD specifies an
7446 alternative maximum line length that overrides the normal default of 72.
7447 This value is in the range 40-999999, values less than 40 being silently
7448 reset to 40. The equal sign is optional.
7449
7450 @item -gnatr
7451 @cindex @option{-gnatr} (@command{gcc})
7452 @cindex pragma Restrictions
7453 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7454 so that violation of restrictions causes warnings rather than illegalities.
7455 This is useful during the development process when new restrictions are added
7456 or investigated. The switch also causes pragma Profile to be treated as
7457 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7458 restriction warnings rather than restrictions.
7459
7460 @ifclear vms
7461 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7462 @cindex @option{-gnatR} (@command{gcc})
7463 This switch controls output from the compiler of a listing showing
7464 representation information for declared types and objects. For
7465 @option{-gnatR0}, no information is output (equivalent to omitting
7466 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7467 so @option{-gnatR} with no parameter has the same effect), size and alignment
7468 information is listed for declared array and record types. For
7469 @option{-gnatR2}, size and alignment information is listed for all
7470 declared types and objects. Finally @option{-gnatR3} includes symbolic
7471 expressions for values that are computed at run time for
7472 variant records. These symbolic expressions have a mostly obvious
7473 format with #n being used to represent the value of the n'th
7474 discriminant. See source files @file{repinfo.ads/adb} in the
7475 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7476 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7477 the output is to a file with the name @file{^file.rep^file_REP^} where
7478 file is the name of the corresponding source file.
7479 @end ifclear
7480 @ifset vms
7481 @item /REPRESENTATION_INFO
7482 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7483 This qualifier controls output from the compiler of a listing showing
7484 representation information for declared types and objects. For
7485 @option{/REPRESENTATION_INFO=NONE}, no information is output
7486 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7487 @option{/REPRESENTATION_INFO} without option is equivalent to
7488 @option{/REPRESENTATION_INFO=ARRAYS}.
7489 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7490 information is listed for declared array and record types. For
7491 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7492 is listed for all expression information for values that are computed
7493 at run time for variant records. These symbolic expressions have a mostly
7494 obvious format with #n being used to represent the value of the n'th
7495 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7496 @code{GNAT} sources for full details on the format of
7497 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7498 If _FILE is added at the end of an option
7499 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7500 then the output is to a file with the name @file{file_REP} where
7501 file is the name of the corresponding source file.
7502 @end ifset
7503 Note that it is possible for record components to have zero size. In
7504 this case, the component clause uses an obvious extension of permitted
7505 Ada syntax, for example @code{at 0 range 0 .. -1}.
7506
7507 Representation information requires that code be generated (since it is the
7508 code generator that lays out complex data structures). If an attempt is made
7509 to output representation information when no code is generated, for example
7510 when a subunit is compiled on its own, then no information can be generated
7511 and the compiler outputs a message to this effect.
7512
7513 @item -gnatS
7514 @cindex @option{-gnatS} (@command{gcc})
7515 The use of the switch @option{-gnatS} for an
7516 Ada compilation will cause the compiler to output a
7517 representation of package Standard in a form very
7518 close to standard Ada. It is not quite possible to
7519 do this entirely in standard Ada (since new
7520 numeric base types cannot be created in standard
7521 Ada), but the output is easily
7522 readable to any Ada programmer, and is useful to
7523 determine the characteristics of target dependent
7524 types in package Standard.
7525
7526 @item -gnatx
7527 @cindex @option{-gnatx} (@command{gcc})
7528 Normally the compiler generates full cross-referencing information in
7529 the @file{ALI} file. This information is used by a number of tools,
7530 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7531 suppresses this information. This saves some space and may slightly
7532 speed up compilation, but means that these tools cannot be used.
7533 @end table
7534
7535 @node Exception Handling Control
7536 @subsection Exception Handling Control
7537
7538 @noindent
7539 GNAT uses two methods for handling exceptions at run-time. The
7540 @code{setjmp/longjmp} method saves the context when entering
7541 a frame with an exception handler. Then when an exception is
7542 raised, the context can be restored immediately, without the
7543 need for tracing stack frames. This method provides very fast
7544 exception propagation, but introduces significant overhead for
7545 the use of exception handlers, even if no exception is raised.
7546
7547 The other approach is called ``zero cost'' exception handling.
7548 With this method, the compiler builds static tables to describe
7549 the exception ranges. No dynamic code is required when entering
7550 a frame containing an exception handler. When an exception is
7551 raised, the tables are used to control a back trace of the
7552 subprogram invocation stack to locate the required exception
7553 handler. This method has considerably poorer performance for
7554 the propagation of exceptions, but there is no overhead for
7555 exception handlers if no exception is raised. Note that in this
7556 mode and in the context of mixed Ada and C/C++ programming,
7557 to propagate an exception through a C/C++ code, the C/C++ code
7558 must be compiled with the @option{-funwind-tables} GCC's
7559 option.
7560
7561 The following switches may be used to control which of the
7562 two exception handling methods is used.
7563
7564 @table @option
7565 @c !sort!
7566
7567 @item --RTS=sjlj
7568 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7569 This switch causes the setjmp/longjmp run-time (when available) to be used
7570 for exception handling. If the default
7571 mechanism for the target is zero cost exceptions, then
7572 this switch can be used to modify this default, and must be
7573 used for all units in the partition.
7574 This option is rarely used. One case in which it may be
7575 advantageous is if you have an application where exception
7576 raising is common and the overall performance of the
7577 application is improved by favoring exception propagation.
7578
7579 @item --RTS=zcx
7580 @cindex @option{--RTS=zcx} (@command{gnatmake})
7581 @cindex Zero Cost Exceptions
7582 This switch causes the zero cost approach to be used
7583 for exception handling. If this is the default mechanism for the
7584 target (see below), then this switch is unneeded. If the default
7585 mechanism for the target is setjmp/longjmp exceptions, then
7586 this switch can be used to modify this default, and must be
7587 used for all units in the partition.
7588 This option can only be used if the zero cost approach
7589 is available for the target in use, otherwise it will generate an error.
7590 @end table
7591
7592 @noindent
7593 The same option @option{--RTS} must be used both for @command{gcc}
7594 and @command{gnatbind}. Passing this option to @command{gnatmake}
7595 (@pxref{Switches for gnatmake}) will ensure the required consistency
7596 through the compilation and binding steps.
7597
7598 @node Units to Sources Mapping Files
7599 @subsection Units to Sources Mapping Files
7600
7601 @table @option
7602
7603 @item -gnatem=@var{path}
7604 @cindex @option{-gnatem} (@command{gcc})
7605 A mapping file is a way to communicate to the compiler two mappings:
7606 from unit names to file names (without any directory information) and from
7607 file names to path names (with full directory information). These mappings
7608 are used by the compiler to short-circuit the path search.
7609
7610 The use of mapping files is not required for correct operation of the
7611 compiler, but mapping files can improve efficiency, particularly when
7612 sources are read over a slow network connection. In normal operation,
7613 you need not be concerned with the format or use of mapping files,
7614 and the @option{-gnatem} switch is not a switch that you would use
7615 explicitly. It is intended primarily for use by automatic tools such as
7616 @command{gnatmake} running under the project file facility. The
7617 description here of the format of mapping files is provided
7618 for completeness and for possible use by other tools.
7619
7620 A mapping file is a sequence of sets of three lines. In each set, the
7621 first line is the unit name, in lower case, with @code{%s} appended
7622 for specs and @code{%b} appended for bodies; the second line is the
7623 file name; and the third line is the path name.
7624
7625 Example:
7626 @smallexample
7627    main%b
7628    main.2.ada
7629    /gnat/project1/sources/main.2.ada
7630 @end smallexample
7631
7632 When the switch @option{-gnatem} is specified, the compiler will
7633 create in memory the two mappings from the specified file. If there is
7634 any problem (nonexistent file, truncated file or duplicate entries),
7635 no mapping will be created.
7636
7637 Several @option{-gnatem} switches may be specified; however, only the
7638 last one on the command line will be taken into account.
7639
7640 When using a project file, @command{gnatmake} creates a temporary
7641 mapping file and communicates it to the compiler using this switch.
7642
7643 @end table
7644
7645 @node Integrated Preprocessing
7646 @subsection Integrated Preprocessing
7647
7648 @noindent
7649 GNAT sources may be preprocessed immediately before compilation.
7650 In this case, the actual
7651 text of the source is not the text of the source file, but is derived from it
7652 through a process called preprocessing. Integrated preprocessing is specified
7653 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7654 indicates, through a text file, the preprocessing data to be used.
7655 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7656
7657 @noindent
7658 Note that when integrated preprocessing is used, the output from the
7659 preprocessor is not written to any external file. Instead it is passed
7660 internally to the compiler. If you need to preserve the result of
7661 preprocessing in a file, then you should use @command{gnatprep}
7662 to perform the desired preprocessing in stand-alone mode.
7663
7664 @noindent
7665 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7666 used when Integrated Preprocessing is used. The reason is that preprocessing
7667 with another Preprocessing Data file without changing the sources will
7668 not trigger recompilation without this switch.
7669
7670 @noindent
7671 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7672 always trigger recompilation for sources that are preprocessed,
7673 because @command{gnatmake} cannot compute the checksum of the source after
7674 preprocessing.
7675
7676 @noindent
7677 The actual preprocessing function is described in details in section
7678 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7679 preprocessing is triggered and parameterized.
7680
7681 @table @code
7682
7683 @item -gnatep=@var{file}
7684 @cindex @option{-gnatep} (@command{gcc})
7685 This switch indicates to the compiler the file name (without directory
7686 information) of the preprocessor data file to use. The preprocessor data file
7687 should be found in the source directories. Note that when the compiler is
7688 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7689 file, if the object directory is not also a source directory, the builder needs
7690 to be called with @option{-x}.
7691
7692 @noindent
7693 A preprocessing data file is a text file with significant lines indicating
7694 how should be preprocessed either a specific source or all sources not
7695 mentioned in other lines. A significant line is a nonempty, non-comment line.
7696 Comments are similar to Ada comments.
7697
7698 @noindent
7699 Each significant line starts with either a literal string or the character '*'.
7700 A literal string is the file name (without directory information) of the source
7701 to preprocess. A character '*' indicates the preprocessing for all the sources
7702 that are not specified explicitly on other lines (order of the lines is not
7703 significant). It is an error to have two lines with the same file name or two
7704 lines starting with the character '*'.
7705
7706 @noindent
7707 After the file name or the character '*', another optional literal string
7708 indicating the file name of the definition file to be used for preprocessing
7709 (@pxref{Form of Definitions File}). The definition files are found by the
7710 compiler in one of the source directories. In some cases, when compiling
7711 a source in a directory other than the current directory, if the definition
7712 file is in the current directory, it may be necessary to add the current
7713 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7714 the compiler would not find the definition file.
7715
7716 @noindent
7717 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7718 be found. Those ^switches^switches^ are:
7719
7720 @table @code
7721
7722 @item -b
7723 Causes both preprocessor lines and the lines deleted by
7724 preprocessing to be replaced by blank lines, preserving the line number.
7725 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7726 it cancels the effect of @option{-c}.
7727
7728 @item -c
7729 Causes both preprocessor lines and the lines deleted
7730 by preprocessing to be retained as comments marked
7731 with the special string ``@code{--! }''.
7732
7733 @item -Dsymbol=value
7734 Define or redefine a symbol, associated with value. A symbol is an Ada
7735 identifier, or an Ada reserved word, with the exception of @code{if},
7736 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7737 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7738 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7739 same name defined in a definition file.
7740
7741 @item -s
7742 Causes a sorted list of symbol names and values to be
7743 listed on the standard output file.
7744
7745 @item -u
7746 Causes undefined symbols to be treated as having the value @code{FALSE}
7747 in the context
7748 of a preprocessor test. In the absence of this option, an undefined symbol in
7749 a @code{#if} or @code{#elsif} test will be treated as an error.
7750
7751 @end table
7752
7753 @noindent
7754 Examples of valid lines in a preprocessor data file:
7755
7756 @smallexample
7757   "toto.adb"  "prep.def" -u
7758   --  preprocess "toto.adb", using definition file "prep.def",
7759   --  undefined symbol are False.
7760
7761   * -c -DVERSION=V101
7762   --  preprocess all other sources without a definition file;
7763   --  suppressed lined are commented; symbol VERSION has the value V101.
7764
7765   "titi.adb" "prep2.def" -s
7766   --  preprocess "titi.adb", using definition file "prep2.def";
7767   --  list all symbols with their values.
7768 @end smallexample
7769
7770 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7771 @cindex @option{-gnateD} (@command{gcc})
7772 Define or redefine a preprocessing symbol, associated with value. If no value
7773 is given on the command line, then the value of the symbol is @code{True}.
7774 A symbol is an identifier, following normal Ada (case-insensitive)
7775 rules for its syntax, and value is any sequence (including an empty sequence)
7776 of characters from the set (letters, digits, period, underline).
7777 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7778 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7779
7780 @noindent
7781 A symbol declared with this ^switch^switch^ on the command line replaces a
7782 symbol with the same name either in a definition file or specified with a
7783 ^switch^switch^ -D in the preprocessor data file.
7784
7785 @noindent
7786 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7787
7788 @item -gnateG
7789 When integrated preprocessing is performed and the preprocessor modifies
7790 the source text, write the result of this preprocessing into a file
7791 <source>^.prep^_prep^.
7792
7793 @end table
7794
7795 @node Code Generation Control
7796 @subsection Code Generation Control
7797
7798 @noindent
7799
7800 The GCC technology provides a wide range of target dependent
7801 @option{-m} switches for controlling
7802 details of code generation with respect to different versions of
7803 architectures. This includes variations in instruction sets (e.g.@:
7804 different members of the power pc family), and different requirements
7805 for optimal arrangement of instructions (e.g.@: different members of
7806 the x86 family). The list of available @option{-m} switches may be
7807 found in the GCC documentation.
7808
7809 Use of these @option{-m} switches may in some cases result in improved
7810 code performance.
7811
7812 The @value{EDITION} technology is tested and qualified without any
7813 @option{-m} switches,
7814 so generally the most reliable approach is to avoid the use of these
7815 switches. However, we generally expect most of these switches to work
7816 successfully with @value{EDITION}, and many customers have reported successful
7817 use of these options.
7818
7819 Our general advice is to avoid the use of @option{-m} switches unless
7820 special needs lead to requirements in this area. In particular,
7821 there is no point in using @option{-m} switches to improve performance
7822 unless you actually see a performance improvement.
7823
7824 @ifset vms
7825 @node Return Codes
7826 @subsection Return Codes
7827 @cindex Return Codes
7828 @cindex @option{/RETURN_CODES=VMS}
7829
7830 @noindent
7831 On VMS, GNAT compiled programs return POSIX-style codes by default,
7832 e.g.@: @option{/RETURN_CODES=POSIX}.
7833
7834 To enable VMS style return codes, use GNAT BIND and LINK with the option
7835 @option{/RETURN_CODES=VMS}. For example:
7836
7837 @smallexample
7838 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7839 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7840 @end smallexample
7841
7842 @noindent
7843 Programs built with /RETURN_CODES=VMS are suitable to be called in
7844 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7845 are suitable for spawning with appropriate GNAT RTL routines.
7846
7847 @end ifset
7848
7849 @node Search Paths and the Run-Time Library (RTL)
7850 @section Search Paths and the Run-Time Library (RTL)
7851
7852 @noindent
7853 With the GNAT source-based library system, the compiler must be able to
7854 find source files for units that are needed by the unit being compiled.
7855 Search paths are used to guide this process.
7856
7857 The compiler compiles one source file whose name must be given
7858 explicitly on the command line. In other words, no searching is done
7859 for this file. To find all other source files that are needed (the most
7860 common being the specs of units), the compiler examines the following
7861 directories, in the following order:
7862
7863 @enumerate
7864 @item
7865 The directory containing the source file of the main unit being compiled
7866 (the file name on the command line).
7867
7868 @item
7869 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7870 @command{gcc} command line, in the order given.
7871
7872 @item
7873 @findex ADA_PRJ_INCLUDE_FILE
7874 Each of the directories listed in the text file whose name is given
7875 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7876
7877 @noindent
7878 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7879 driver when project files are used. It should not normally be set
7880 by other means.
7881
7882 @item
7883 @findex ADA_INCLUDE_PATH
7884 Each of the directories listed in the value of the
7885 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7886 @ifclear vms
7887 Construct this value
7888 exactly as the @env{PATH} environment variable: a list of directory
7889 names separated by colons (semicolons when working with the NT version).
7890 @end ifclear
7891 @ifset vms
7892 Normally, define this value as a logical name containing a comma separated
7893 list of directory names.
7894
7895 This variable can also be defined by means of an environment string
7896 (an argument to the HP C exec* set of functions).
7897
7898 Logical Name:
7899 @smallexample
7900 DEFINE ANOTHER_PATH FOO:[BAG]
7901 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7902 @end smallexample
7903
7904 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7905 first, followed by the standard Ada
7906 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7907 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7908 (Text_IO, Sequential_IO, etc)
7909 instead of the standard Ada packages. Thus, in order to get the standard Ada
7910 packages by default, ADA_INCLUDE_PATH must be redefined.
7911 @end ifset
7912
7913 @item
7914 The content of the @file{ada_source_path} file which is part of the GNAT
7915 installation tree and is used to store standard libraries such as the
7916 GNAT Run Time Library (RTL) source files.
7917 @ifclear vms
7918 @ref{Installing a library}
7919 @end ifclear
7920 @end enumerate
7921
7922 @noindent
7923 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7924 inhibits the use of the directory
7925 containing the source file named in the command line. You can still
7926 have this directory on your search path, but in this case it must be
7927 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7928
7929 Specifying the switch @option{-nostdinc}
7930 inhibits the search of the default location for the GNAT Run Time
7931 Library (RTL) source files.
7932
7933 The compiler outputs its object files and ALI files in the current
7934 working directory.
7935 @ifclear vms
7936 Caution: The object file can be redirected with the @option{-o} switch;
7937 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7938 so the @file{ALI} file will not go to the right place. Therefore, you should
7939 avoid using the @option{-o} switch.
7940 @end ifclear
7941
7942 @findex System.IO
7943 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7944 children make up the GNAT RTL, together with the simple @code{System.IO}
7945 package used in the @code{"Hello World"} example. The sources for these units
7946 are needed by the compiler and are kept together in one directory. Not
7947 all of the bodies are needed, but all of the sources are kept together
7948 anyway. In a normal installation, you need not specify these directory
7949 names when compiling or binding. Either the environment variables or
7950 the built-in defaults cause these files to be found.
7951
7952 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7953 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7954 consisting of child units of @code{GNAT}. This is a collection of generally
7955 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7956 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7957
7958 Besides simplifying access to the RTL, a major use of search paths is
7959 in compiling sources from multiple directories. This can make
7960 development environments much more flexible.
7961
7962 @node Order of Compilation Issues
7963 @section Order of Compilation Issues
7964
7965 @noindent
7966 If, in our earlier example, there was a spec for the @code{hello}
7967 procedure, it would be contained in the file @file{hello.ads}; yet this
7968 file would not have to be explicitly compiled. This is the result of the
7969 model we chose to implement library management. Some of the consequences
7970 of this model are as follows:
7971
7972 @itemize @bullet
7973 @item
7974 There is no point in compiling specs (except for package
7975 specs with no bodies) because these are compiled as needed by clients. If
7976 you attempt a useless compilation, you will receive an error message.
7977 It is also useless to compile subunits because they are compiled as needed
7978 by the parent.
7979
7980 @item
7981 There are no order of compilation requirements: performing a
7982 compilation never obsoletes anything. The only way you can obsolete
7983 something and require recompilations is to modify one of the
7984 source files on which it depends.
7985
7986 @item
7987 There is no library as such, apart from the ALI files
7988 (@pxref{The Ada Library Information Files}, for information on the format
7989 of these files). For now we find it convenient to create separate ALI files,
7990 but eventually the information therein may be incorporated into the object
7991 file directly.
7992
7993 @item
7994 When you compile a unit, the source files for the specs of all units
7995 that it @code{with}'s, all its subunits, and the bodies of any generics it
7996 instantiates must be available (reachable by the search-paths mechanism
7997 described above), or you will receive a fatal error message.
7998 @end itemize
7999
8000 @node Examples
8001 @section Examples
8002
8003 @noindent
8004 The following are some typical Ada compilation command line examples:
8005
8006 @table @code
8007 @item $ gcc -c xyz.adb
8008 Compile body in file @file{xyz.adb} with all default options.
8009
8010 @ifclear vms
8011 @item $ gcc -c -O2 -gnata xyz-def.adb
8012 @end ifclear
8013 @ifset vms
8014 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8015 @end ifset
8016
8017 Compile the child unit package in file @file{xyz-def.adb} with extensive
8018 optimizations, and pragma @code{Assert}/@code{Debug} statements
8019 enabled.
8020
8021 @item $ gcc -c -gnatc abc-def.adb
8022 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8023 mode.
8024 @end table
8025
8026 @node Binding Using gnatbind
8027 @chapter Binding Using @code{gnatbind}
8028 @findex gnatbind
8029
8030 @menu
8031 * Running gnatbind::
8032 * Switches for gnatbind::
8033 * Command-Line Access::
8034 * Search Paths for gnatbind::
8035 * Examples of gnatbind Usage::
8036 @end menu
8037
8038 @noindent
8039 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8040 to bind compiled GNAT objects.
8041
8042 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8043 driver (see @ref{The GNAT Driver and Project Files}).
8044
8045 The @code{gnatbind} program performs four separate functions:
8046
8047 @enumerate
8048 @item
8049 Checks that a program is consistent, in accordance with the rules in
8050 Chapter 10 of the Ada Reference Manual. In particular, error
8051 messages are generated if a program uses inconsistent versions of a
8052 given unit.
8053
8054 @item
8055 Checks that an acceptable order of elaboration exists for the program
8056 and issues an error message if it cannot find an order of elaboration
8057 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8058
8059 @item
8060 Generates a main program incorporating the given elaboration order.
8061 This program is a small Ada package (body and spec) that
8062 must be subsequently compiled
8063 using the GNAT compiler. The necessary compilation step is usually
8064 performed automatically by @command{gnatlink}. The two most important
8065 functions of this program
8066 are to call the elaboration routines of units in an appropriate order
8067 and to call the main program.
8068
8069 @item
8070 Determines the set of object files required by the given main program.
8071 This information is output in the forms of comments in the generated program,
8072 to be read by the @command{gnatlink} utility used to link the Ada application.
8073 @end enumerate
8074
8075 @node Running gnatbind
8076 @section Running @code{gnatbind}
8077
8078 @noindent
8079 The form of the @code{gnatbind} command is
8080
8081 @smallexample
8082 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8083 @c Expanding @ovar macro inline (explanation in macro def comments)
8084 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8085 @end smallexample
8086
8087 @noindent
8088 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8089 unit body. @code{gnatbind} constructs an Ada
8090 package in two files whose names are
8091 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8092 For example, if given the
8093 parameter @file{hello.ali}, for a main program contained in file
8094 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8095 and @file{b~hello.adb}.
8096
8097 When doing consistency checking, the binder takes into consideration
8098 any source files it can locate. For example, if the binder determines
8099 that the given main program requires the package @code{Pack}, whose
8100 @file{.ALI}
8101 file is @file{pack.ali} and whose corresponding source spec file is
8102 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8103 (using the same search path conventions as previously described for the
8104 @command{gcc} command). If it can locate this source file, it checks that
8105 the time stamps
8106 or source checksums of the source and its references to in @file{ALI} files
8107 match. In other words, any @file{ALI} files that mentions this spec must have
8108 resulted from compiling this version of the source file (or in the case
8109 where the source checksums match, a version close enough that the
8110 difference does not matter).
8111
8112 @cindex Source files, use by binder
8113 The effect of this consistency checking, which includes source files, is
8114 that the binder ensures that the program is consistent with the latest
8115 version of the source files that can be located at bind time. Editing a
8116 source file without compiling files that depend on the source file cause
8117 error messages to be generated by the binder.
8118
8119 For example, suppose you have a main program @file{hello.adb} and a
8120 package @code{P}, from file @file{p.ads} and you perform the following
8121 steps:
8122
8123 @enumerate
8124 @item
8125 Enter @code{gcc -c hello.adb} to compile the main program.
8126
8127 @item
8128 Enter @code{gcc -c p.ads} to compile package @code{P}.
8129
8130 @item
8131 Edit file @file{p.ads}.
8132
8133 @item
8134 Enter @code{gnatbind hello}.
8135 @end enumerate
8136
8137 @noindent
8138 At this point, the file @file{p.ali} contains an out-of-date time stamp
8139 because the file @file{p.ads} has been edited. The attempt at binding
8140 fails, and the binder generates the following error messages:
8141
8142 @smallexample
8143 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8144 error: "p.ads" has been modified and must be recompiled
8145 @end smallexample
8146
8147 @noindent
8148 Now both files must be recompiled as indicated, and then the bind can
8149 succeed, generating a main program. You need not normally be concerned
8150 with the contents of this file, but for reference purposes a sample
8151 binder output file is given in @ref{Example of Binder Output File}.
8152
8153 In most normal usage, the default mode of @command{gnatbind} which is to
8154 generate the main package in Ada, as described in the previous section.
8155 In particular, this means that any Ada programmer can read and understand
8156 the generated main program. It can also be debugged just like any other
8157 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8158 @command{gnatbind} and @command{gnatlink}.
8159
8160 @node Switches for gnatbind
8161 @section Switches for @command{gnatbind}
8162
8163 @noindent
8164 The following switches are available with @code{gnatbind}; details will
8165 be presented in subsequent sections.
8166
8167 @menu
8168 * Consistency-Checking Modes::
8169 * Binder Error Message Control::
8170 * Elaboration Control::
8171 * Output Control::
8172 * Dynamic Allocation Control::
8173 * Binding with Non-Ada Main Programs::
8174 * Binding Programs with No Main Subprogram::
8175 @end menu
8176
8177 @table @option
8178 @c !sort!
8179
8180 @item --version
8181 @cindex @option{--version} @command{gnatbind}
8182 Display Copyright and version, then exit disregarding all other options.
8183
8184 @item --help
8185 @cindex @option{--help} @command{gnatbind}
8186 If @option{--version} was not used, display usage, then exit disregarding
8187 all other options.
8188
8189 @item -a
8190 @cindex @option{-a} @command{gnatbind}
8191 Indicates that, if supported by the platform, the adainit procedure should
8192 be treated as an initialisation routine by the linker (a constructor). This
8193 is intended to be used by the Project Manager to automatically initialize
8194 shared Stand-Alone Libraries.
8195
8196 @item ^-aO^/OBJECT_SEARCH^
8197 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8198 Specify directory to be searched for ALI files.
8199
8200 @item ^-aI^/SOURCE_SEARCH^
8201 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8202 Specify directory to be searched for source file.
8203
8204 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8205 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8206 Output ALI list (to standard output or to the named file).
8207
8208 @item ^-b^/REPORT_ERRORS=BRIEF^
8209 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8210 Generate brief messages to @file{stderr} even if verbose mode set.
8211
8212 @item ^-c^/NOOUTPUT^
8213 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8214 Check only, no generation of binder output file.
8215
8216 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8217 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8218 This switch can be used to change the default task stack size value
8219 to a specified size @var{nn}, which is expressed in bytes by default, or
8220 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8221 with @var{m}.
8222 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8223 in effect, to completing all task specs with
8224 @smallexample @c ada
8225    pragma Storage_Size (nn);
8226 @end smallexample
8227 When they do not already have such a pragma.
8228
8229 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8230 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8231 This switch can be used to change the default secondary stack size value
8232 to a specified size @var{nn}, which is expressed in bytes by default, or
8233 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8234 with @var{m}.
8235
8236 The secondary stack is used to deal with functions that return a variable
8237 sized result, for example a function returning an unconstrained
8238 String. There are two ways in which this secondary stack is allocated.
8239
8240 For most targets, the secondary stack is growing on demand and is allocated
8241 as a chain of blocks in the heap. The -D option is not very
8242 relevant. It only give some control over the size of the allocated
8243 blocks (whose size is the minimum of the default secondary stack size value,
8244 and the actual size needed for the current allocation request).
8245
8246 For certain targets, notably VxWorks 653,
8247 the secondary stack is allocated by carving off a fixed ratio chunk of the
8248 primary task stack. The -D option is used to define the
8249 size of the environment task's secondary stack.
8250
8251 @item ^-e^/ELABORATION_DEPENDENCIES^
8252 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8253 Output complete list of elaboration-order dependencies.
8254
8255 @item ^-E^/STORE_TRACEBACKS^
8256 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8257 Store tracebacks in exception occurrences when the target supports it.
8258 @ignore
8259 @c The following may get moved to an appendix
8260 This option is currently supported on the following targets:
8261 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8262 @end ignore
8263 See also the packages @code{GNAT.Traceback} and
8264 @code{GNAT.Traceback.Symbolic} for more information.
8265 @ifclear vms
8266 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8267 @command{gcc} option.
8268 @end ifclear
8269
8270 @item ^-F^/FORCE_ELABS_FLAGS^
8271 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8272 Force the checks of elaboration flags. @command{gnatbind} does not normally
8273 generate checks of elaboration flags for the main executable, except when
8274 a Stand-Alone Library is used. However, there are cases when this cannot be
8275 detected by gnatbind. An example is importing an interface of a Stand-Alone
8276 Library through a pragma Import and only specifying through a linker switch
8277 this Stand-Alone Library. This switch is used to guarantee that elaboration
8278 flag checks are generated.
8279
8280 @item ^-h^/HELP^
8281 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8282 Output usage (help) information
8283
8284 @item ^-H32^/32_MALLOC^
8285 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8286 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8287 For further details see @ref{Dynamic Allocation Control}.
8288
8289 @item ^-H64^/64_MALLOC^
8290 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8291 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8292 @cindex @code{__gnat_malloc}
8293 For further details see @ref{Dynamic Allocation Control}.
8294
8295 @item ^-I^/SEARCH^
8296 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8297 Specify directory to be searched for source and ALI files.
8298
8299 @item ^-I-^/NOCURRENT_DIRECTORY^
8300 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8301 Do not look for sources in the current directory where @code{gnatbind} was
8302 invoked, and do not look for ALI files in the directory containing the
8303 ALI file named in the @code{gnatbind} command line.
8304
8305 @item ^-l^/ORDER_OF_ELABORATION^
8306 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8307 Output chosen elaboration order.
8308
8309 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8310 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8311 Bind the units for library building. In this case the adainit and
8312 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8313 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8314 ^@var{xxx}final^@var{XXX}FINAL^.
8315 Implies ^-n^/NOCOMPILE^.
8316 @ifclear vms
8317 (@xref{GNAT and Libraries}, for more details.)
8318 @end ifclear
8319 @ifset vms
8320 On OpenVMS, these init and final procedures are exported in uppercase
8321 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8322 the init procedure will be "TOTOINIT" and the exported name of the final
8323 procedure will be "TOTOFINAL".
8324 @end ifset
8325
8326 @item ^-Mxyz^/RENAME_MAIN=xyz^
8327 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8328 Rename generated main program from main to xyz. This option is
8329 supported on cross environments only.
8330
8331 @item ^-m^/ERROR_LIMIT=^@var{n}
8332 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8333 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8334 in the range 1..999999. The default value if no switch is
8335 given is 9999. If the number of warnings reaches this limit, then a
8336 message is output and further warnings are suppressed, the bind
8337 continues in this case. If the number of errors reaches this
8338 limit, then a message is output and the bind is abandoned.
8339 A value of zero means that no limit is enforced. The equal
8340 sign is optional.
8341
8342 @ifset unw
8343 Furthermore, under Windows, the sources pointed to by the libraries path
8344 set in the registry are not searched for.
8345 @end ifset
8346
8347 @item ^-n^/NOMAIN^
8348 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8349 No main program.
8350
8351 @item -nostdinc
8352 @cindex @option{-nostdinc} (@command{gnatbind})
8353 Do not look for sources in the system default directory.
8354
8355 @item -nostdlib
8356 @cindex @option{-nostdlib} (@command{gnatbind})
8357 Do not look for library files in the system default directory.
8358
8359 @item --RTS=@var{rts-path}
8360 @cindex @option{--RTS} (@code{gnatbind})
8361 Specifies the default location of the runtime library. Same meaning as the
8362 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8363
8364 @item ^-o ^/OUTPUT=^@var{file}
8365 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8366 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8367 Note that if this option is used, then linking must be done manually,
8368 gnatlink cannot be used.
8369
8370 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8371 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8372 Output object list (to standard output or to the named file).
8373
8374 @item ^-p^/PESSIMISTIC_ELABORATION^
8375 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8376 Pessimistic (worst-case) elaboration order
8377
8378 @item ^-P^-P^
8379 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8380 Generate binder file suitable for CodePeer.
8381
8382 @item ^-R^-R^
8383 @cindex @option{^-R^-R^} (@command{gnatbind})
8384 Output closure source list.
8385
8386 @item ^-s^/READ_SOURCES=ALL^
8387 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8388 Require all source files to be present.
8389
8390 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8391 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8392 Specifies the value to be used when detecting uninitialized scalar
8393 objects with pragma Initialize_Scalars.
8394 The @var{xxx} ^string specified with the switch^option^ may be either
8395 @itemize @bullet
8396 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8397 @item ``@option{^lo^LOW^}'' for the lowest possible value
8398 @item ``@option{^hi^HIGH^}'' for the highest possible value
8399 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8400 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8401 @end itemize
8402
8403 In addition, you can specify @option{-Sev} to indicate that the value is
8404 to be set at run time. In this case, the program will look for an environment
8405 @cindex GNAT_INIT_SCALARS
8406 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8407 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8408 If no environment variable is found, or if it does not have a valid value,
8409 then the default is @option{in} (invalid values).
8410
8411 @ifclear vms
8412 @item -static
8413 @cindex @option{-static} (@code{gnatbind})
8414 Link against a static GNAT run time.
8415
8416 @item -shared
8417 @cindex @option{-shared} (@code{gnatbind})
8418 Link against a shared GNAT run time when available.
8419 @end ifclear
8420
8421 @item ^-t^/NOTIME_STAMP_CHECK^
8422 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8423 Tolerate time stamp and other consistency errors
8424
8425 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8426 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8427 Set the time slice value to @var{n} milliseconds. If the system supports
8428 the specification of a specific time slice value, then the indicated value
8429 is used. If the system does not support specific time slice values, but
8430 does support some general notion of round-robin scheduling, then any
8431 nonzero value will activate round-robin scheduling.
8432
8433 A value of zero is treated specially. It turns off time
8434 slicing, and in addition, indicates to the tasking run time that the
8435 semantics should match as closely as possible the Annex D
8436 requirements of the Ada RM, and in particular sets the default
8437 scheduling policy to @code{FIFO_Within_Priorities}.
8438
8439 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8440 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8441 Enable dynamic stack usage, with @var{n} results stored and displayed
8442 at program termination. A result is generated when a task
8443 terminates. Results that can't be stored are displayed on the fly, at
8444 task termination. This option is currently not supported on Itanium
8445 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8446
8447 @item ^-v^/REPORT_ERRORS=VERBOSE^
8448 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8449 Verbose mode. Write error messages, header, summary output to
8450 @file{stdout}.
8451
8452 @ifclear vms
8453 @item -w@var{x}
8454 @cindex @option{-w} (@code{gnatbind})
8455 Warning mode (@var{x}=s/e for suppress/treat as error)
8456 @end ifclear
8457
8458 @ifset vms
8459 @item /WARNINGS=NORMAL
8460 @cindex @option{/WARNINGS} (@code{gnatbind})
8461 Normal warnings mode. Warnings are issued but ignored
8462
8463 @item /WARNINGS=SUPPRESS
8464 @cindex @option{/WARNINGS} (@code{gnatbind})
8465 All warning messages are suppressed
8466
8467 @item /WARNINGS=ERROR
8468 @cindex @option{/WARNINGS} (@code{gnatbind})
8469 Warning messages are treated as fatal errors
8470 @end ifset
8471
8472 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8473 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8474 Override default wide character encoding for standard Text_IO files.
8475
8476 @item ^-x^/READ_SOURCES=NONE^
8477 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8478 Exclude source files (check object consistency only).
8479
8480 @ifset vms
8481 @item /READ_SOURCES=AVAILABLE
8482 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8483 Default mode, in which sources are checked for consistency only if
8484 they are available.
8485 @end ifset
8486
8487 @item ^-y^/ENABLE_LEAP_SECONDS^
8488 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8489 Enable leap seconds support in @code{Ada.Calendar} and its children.
8490
8491 @item ^-z^/ZERO_MAIN^
8492 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8493 No main subprogram.
8494 @end table
8495
8496 @ifclear vms
8497 @noindent
8498 You may obtain this listing of switches by running @code{gnatbind} with
8499 no arguments.
8500 @end ifclear
8501
8502 @node Consistency-Checking Modes
8503 @subsection Consistency-Checking Modes
8504
8505 @noindent
8506 As described earlier, by default @code{gnatbind} checks
8507 that object files are consistent with one another and are consistent
8508 with any source files it can locate. The following switches control binder
8509 access to sources.
8510
8511 @table @option
8512 @c !sort!
8513 @item ^-s^/READ_SOURCES=ALL^
8514 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8515 Require source files to be present. In this mode, the binder must be
8516 able to locate all source files that are referenced, in order to check
8517 their consistency. In normal mode, if a source file cannot be located it
8518 is simply ignored. If you specify this switch, a missing source
8519 file is an error.
8520
8521 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8522 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8523 Override default wide character encoding for standard Text_IO files.
8524 Normally the default wide character encoding method used for standard
8525 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8526 the main source input (see description of switch
8527 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8528 use of this switch for the binder (which has the same set of
8529 possible arguments) overrides this default as specified.
8530
8531 @item ^-x^/READ_SOURCES=NONE^
8532 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8533 Exclude source files. In this mode, the binder only checks that ALI
8534 files are consistent with one another. Source files are not accessed.
8535 The binder runs faster in this mode, and there is still a guarantee that
8536 the resulting program is self-consistent.
8537 If a source file has been edited since it was last compiled, and you
8538 specify this switch, the binder will not detect that the object
8539 file is out of date with respect to the source file. Note that this is the
8540 mode that is automatically used by @command{gnatmake} because in this
8541 case the checking against sources has already been performed by
8542 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8543
8544 @ifset vms
8545 @item /READ_SOURCES=AVAILABLE
8546 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8547 This is the default mode in which source files are checked if they are
8548 available, and ignored if they are not available.
8549 @end ifset
8550 @end table
8551
8552 @node Binder Error Message Control
8553 @subsection Binder Error Message Control
8554
8555 @noindent
8556 The following switches provide control over the generation of error
8557 messages from the binder:
8558
8559 @table @option
8560 @c !sort!
8561 @item ^-v^/REPORT_ERRORS=VERBOSE^
8562 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8563 Verbose mode. In the normal mode, brief error messages are generated to
8564 @file{stderr}. If this switch is present, a header is written
8565 to @file{stdout} and any error messages are directed to @file{stdout}.
8566 All that is written to @file{stderr} is a brief summary message.
8567
8568 @item ^-b^/REPORT_ERRORS=BRIEF^
8569 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8570 Generate brief error messages to @file{stderr} even if verbose mode is
8571 specified. This is relevant only when used with the
8572 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8573
8574 @ifclear vms
8575 @item -m@var{n}
8576 @cindex @option{-m} (@code{gnatbind})
8577 Limits the number of error messages to @var{n}, a decimal integer in the
8578 range 1-999. The binder terminates immediately if this limit is reached.
8579
8580 @item -M@var{xxx}
8581 @cindex @option{-M} (@code{gnatbind})
8582 Renames the generated main program from @code{main} to @code{xxx}.
8583 This is useful in the case of some cross-building environments, where
8584 the actual main program is separate from the one generated
8585 by @code{gnatbind}.
8586 @end ifclear
8587
8588 @item ^-ws^/WARNINGS=SUPPRESS^
8589 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8590 @cindex Warnings
8591 Suppress all warning messages.
8592
8593 @item ^-we^/WARNINGS=ERROR^
8594 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8595 Treat any warning messages as fatal errors.
8596
8597 @ifset vms
8598 @item /WARNINGS=NORMAL
8599 Standard mode with warnings generated, but warnings do not get treated
8600 as errors.
8601 @end ifset
8602
8603 @item ^-t^/NOTIME_STAMP_CHECK^
8604 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8605 @cindex Time stamp checks, in binder
8606 @cindex Binder consistency checks
8607 @cindex Consistency checks, in binder
8608 The binder performs a number of consistency checks including:
8609
8610 @itemize @bullet
8611 @item
8612 Check that time stamps of a given source unit are consistent
8613 @item
8614 Check that checksums of a given source unit are consistent
8615 @item
8616 Check that consistent versions of @code{GNAT} were used for compilation
8617 @item
8618 Check consistency of configuration pragmas as required
8619 @end itemize
8620
8621 @noindent
8622 Normally failure of such checks, in accordance with the consistency
8623 requirements of the Ada Reference Manual, causes error messages to be
8624 generated which abort the binder and prevent the output of a binder
8625 file and subsequent link to obtain an executable.
8626
8627 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8628 into warnings, so that
8629 binding and linking can continue to completion even in the presence of such
8630 errors. The result may be a failed link (due to missing symbols), or a
8631 non-functional executable which has undefined semantics.
8632 @emph{This means that
8633 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8634 with extreme care.}
8635 @end table
8636
8637 @node Elaboration Control
8638 @subsection Elaboration Control
8639
8640 @noindent
8641 The following switches provide additional control over the elaboration
8642 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8643
8644 @table @option
8645 @item ^-p^/PESSIMISTIC_ELABORATION^
8646 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8647 Normally the binder attempts to choose an elaboration order that is
8648 likely to minimize the likelihood of an elaboration order error resulting
8649 in raising a @code{Program_Error} exception. This switch reverses the
8650 action of the binder, and requests that it deliberately choose an order
8651 that is likely to maximize the likelihood of an elaboration error.
8652 This is useful in ensuring portability and avoiding dependence on
8653 accidental fortuitous elaboration ordering.
8654
8655 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8656 switch if dynamic
8657 elaboration checking is used (@option{-gnatE} switch used for compilation).
8658 This is because in the default static elaboration mode, all necessary
8659 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8660 These implicit pragmas are still respected by the binder in
8661 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8662 safe elaboration order is assured.
8663
8664 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8665 production use; it is more for debugging/experimental use.
8666 @end table
8667
8668 @node Output Control
8669 @subsection Output Control
8670
8671 @noindent
8672 The following switches allow additional control over the output
8673 generated by the binder.
8674
8675 @table @option
8676 @c !sort!
8677
8678 @item ^-c^/NOOUTPUT^
8679 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8680 Check only. Do not generate the binder output file. In this mode the
8681 binder performs all error checks but does not generate an output file.
8682
8683 @item ^-e^/ELABORATION_DEPENDENCIES^
8684 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8685 Output complete list of elaboration-order dependencies, showing the
8686 reason for each dependency. This output can be rather extensive but may
8687 be useful in diagnosing problems with elaboration order. The output is
8688 written to @file{stdout}.
8689
8690 @item ^-h^/HELP^
8691 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8692 Output usage information. The output is written to @file{stdout}.
8693
8694 @item ^-K^/LINKER_OPTION_LIST^
8695 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8696 Output linker options to @file{stdout}. Includes library search paths,
8697 contents of pragmas Ident and Linker_Options, and libraries added
8698 by @code{gnatbind}.
8699
8700 @item ^-l^/ORDER_OF_ELABORATION^
8701 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8702 Output chosen elaboration order. The output is written to @file{stdout}.
8703
8704 @item ^-O^/OBJECT_LIST^
8705 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8706 Output full names of all the object files that must be linked to provide
8707 the Ada component of the program. The output is written to @file{stdout}.
8708 This list includes the files explicitly supplied and referenced by the user
8709 as well as implicitly referenced run-time unit files. The latter are
8710 omitted if the corresponding units reside in shared libraries. The
8711 directory names for the run-time units depend on the system configuration.
8712
8713 @item ^-o ^/OUTPUT=^@var{file}
8714 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8715 Set name of output file to @var{file} instead of the normal
8716 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8717 binder generated body filename.
8718 Note that if this option is used, then linking must be done manually.
8719 It is not possible to use gnatlink in this case, since it cannot locate
8720 the binder file.
8721
8722 @item ^-r^/RESTRICTION_LIST^
8723 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8724 Generate list of @code{pragma Restrictions} that could be applied to
8725 the current unit. This is useful for code audit purposes, and also may
8726 be used to improve code generation in some cases.
8727
8728 @end table
8729
8730 @node Dynamic Allocation Control
8731 @subsection Dynamic Allocation Control
8732
8733 @noindent
8734 The heap control switches -- @option{-H32} and @option{-H64} --
8735 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8736 They only affect compiler-generated allocations via @code{__gnat_malloc};
8737 explicit calls to @code{malloc} and related functions from the C
8738 run-time library are unaffected.
8739
8740 @table @option
8741 @item -H32
8742 Allocate memory on 32-bit heap
8743
8744 @item -H64
8745 Allocate memory on 64-bit heap.  This is the default
8746 unless explicitly overridden by a @code{'Size} clause on the access type.
8747 @end table
8748
8749 @ifset vms
8750 @noindent
8751 See also @ref{Access types and 32/64-bit allocation}.
8752 @end ifset
8753 @ifclear vms
8754 @noindent
8755 These switches are only effective on VMS platforms.
8756 @end ifclear
8757
8758
8759 @node Binding with Non-Ada Main Programs
8760 @subsection Binding with Non-Ada Main Programs
8761
8762 @noindent
8763 In our description so far we have assumed that the main
8764 program is in Ada, and that the task of the binder is to generate a
8765 corresponding function @code{main} that invokes this Ada main
8766 program. GNAT also supports the building of executable programs where
8767 the main program is not in Ada, but some of the called routines are
8768 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8769 The following switch is used in this situation:
8770
8771 @table @option
8772 @item ^-n^/NOMAIN^
8773 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8774 No main program. The main program is not in Ada.
8775 @end table
8776
8777 @noindent
8778 In this case, most of the functions of the binder are still required,
8779 but instead of generating a main program, the binder generates a file
8780 containing the following callable routines:
8781
8782 @table @code
8783 @item adainit
8784 @findex adainit
8785 You must call this routine to initialize the Ada part of the program by
8786 calling the necessary elaboration routines. A call to @code{adainit} is
8787 required before the first call to an Ada subprogram.
8788
8789 Note that it is assumed that the basic execution environment must be setup
8790 to be appropriate for Ada execution at the point where the first Ada
8791 subprogram is called. In particular, if the Ada code will do any
8792 floating-point operations, then the FPU must be setup in an appropriate
8793 manner. For the case of the x86, for example, full precision mode is
8794 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8795 that the FPU is in the right state.
8796
8797 @item adafinal
8798 @findex adafinal
8799 You must call this routine to perform any library-level finalization
8800 required by the Ada subprograms. A call to @code{adafinal} is required
8801 after the last call to an Ada subprogram, and before the program
8802 terminates.
8803 @end table
8804
8805 @noindent
8806 If the @option{^-n^/NOMAIN^} switch
8807 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8808 @cindex Binder, multiple input files
8809 is given, more than one ALI file may appear on
8810 the command line for @code{gnatbind}. The normal @dfn{closure}
8811 calculation is performed for each of the specified units. Calculating
8812 the closure means finding out the set of units involved by tracing
8813 @code{with} references. The reason it is necessary to be able to
8814 specify more than one ALI file is that a given program may invoke two or
8815 more quite separate groups of Ada units.
8816
8817 The binder takes the name of its output file from the last specified ALI
8818 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8819 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8820 The output is an Ada unit in source form that can be compiled with GNAT.
8821 This compilation occurs automatically as part of the @command{gnatlink}
8822 processing.
8823
8824 Currently the GNAT run time requires a FPU using 80 bits mode
8825 precision. Under targets where this is not the default it is required to
8826 call GNAT.Float_Control.Reset before using floating point numbers (this
8827 include float computation, float input and output) in the Ada code. A
8828 side effect is that this could be the wrong mode for the foreign code
8829 where floating point computation could be broken after this call.
8830
8831 @node Binding Programs with No Main Subprogram
8832 @subsection Binding Programs with No Main Subprogram
8833
8834 @noindent
8835 It is possible to have an Ada program which does not have a main
8836 subprogram. This program will call the elaboration routines of all the
8837 packages, then the finalization routines.
8838
8839 The following switch is used to bind programs organized in this manner:
8840
8841 @table @option
8842 @item ^-z^/ZERO_MAIN^
8843 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8844 Normally the binder checks that the unit name given on the command line
8845 corresponds to a suitable main subprogram. When this switch is used,
8846 a list of ALI files can be given, and the execution of the program
8847 consists of elaboration of these units in an appropriate order. Note
8848 that the default wide character encoding method for standard Text_IO
8849 files is always set to Brackets if this switch is set (you can use
8850 the binder switch
8851 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8852 @end table
8853
8854 @node Command-Line Access
8855 @section Command-Line Access
8856
8857 @noindent
8858 The package @code{Ada.Command_Line} provides access to the command-line
8859 arguments and program name. In order for this interface to operate
8860 correctly, the two variables
8861
8862 @smallexample
8863 @group
8864 int gnat_argc;
8865 char **gnat_argv;
8866 @end group
8867 @end smallexample
8868
8869 @noindent
8870 @findex gnat_argv
8871 @findex gnat_argc
8872 are declared in one of the GNAT library routines. These variables must
8873 be set from the actual @code{argc} and @code{argv} values passed to the
8874 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8875 generates the C main program to automatically set these variables.
8876 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8877 set these variables. If they are not set, the procedures in
8878 @code{Ada.Command_Line} will not be available, and any attempt to use
8879 them will raise @code{Constraint_Error}. If command line access is
8880 required, your main program must set @code{gnat_argc} and
8881 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8882 it.
8883
8884 @node Search Paths for gnatbind
8885 @section Search Paths for @code{gnatbind}
8886
8887 @noindent
8888 The binder takes the name of an ALI file as its argument and needs to
8889 locate source files as well as other ALI files to verify object consistency.
8890
8891 For source files, it follows exactly the same search rules as @command{gcc}
8892 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8893 directories searched are:
8894
8895 @enumerate
8896 @item
8897 The directory containing the ALI file named in the command line, unless
8898 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8899
8900 @item
8901 All directories specified by @option{^-I^/SEARCH^}
8902 switches on the @code{gnatbind}
8903 command line, in the order given.
8904
8905 @item
8906 @findex ADA_PRJ_OBJECTS_FILE
8907 Each of the directories listed in the text file whose name is given
8908 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8909
8910 @noindent
8911 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8912 driver when project files are used. It should not normally be set
8913 by other means.
8914
8915 @item
8916 @findex ADA_OBJECTS_PATH
8917 Each of the directories listed in the value of the
8918 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8919 @ifset unw
8920 Construct this value
8921 exactly as the @env{PATH} environment variable: a list of directory
8922 names separated by colons (semicolons when working with the NT version
8923 of GNAT).
8924 @end ifset
8925 @ifset vms
8926 Normally, define this value as a logical name containing a comma separated
8927 list of directory names.
8928
8929 This variable can also be defined by means of an environment string
8930 (an argument to the HP C exec* set of functions).
8931
8932 Logical Name:
8933 @smallexample
8934 DEFINE ANOTHER_PATH FOO:[BAG]
8935 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8936 @end smallexample
8937
8938 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8939 first, followed by the standard Ada
8940 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8941 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8942 (Text_IO, Sequential_IO, etc)
8943 instead of the standard Ada packages. Thus, in order to get the standard Ada
8944 packages by default, ADA_OBJECTS_PATH must be redefined.
8945 @end ifset
8946
8947 @item
8948 The content of the @file{ada_object_path} file which is part of the GNAT
8949 installation tree and is used to store standard libraries such as the
8950 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8951 specified.
8952 @ifclear vms
8953 @ref{Installing a library}
8954 @end ifclear
8955 @end enumerate
8956
8957 @noindent
8958 In the binder the switch @option{^-I^/SEARCH^}
8959 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8960 is used to specify both source and
8961 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8962 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8963 instead if you want to specify
8964 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8965 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8966 if you want to specify library paths
8967 only. This means that for the binder
8968 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8969 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8970 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8971 The binder generates the bind file (a C language source file) in the
8972 current working directory.
8973
8974 @findex Ada
8975 @findex System
8976 @findex Interfaces
8977 @findex GNAT
8978 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8979 children make up the GNAT Run-Time Library, together with the package
8980 GNAT and its children, which contain a set of useful additional
8981 library functions provided by GNAT. The sources for these units are
8982 needed by the compiler and are kept together in one directory. The ALI
8983 files and object files generated by compiling the RTL are needed by the
8984 binder and the linker and are kept together in one directory, typically
8985 different from the directory containing the sources. In a normal
8986 installation, you need not specify these directory names when compiling
8987 or binding. Either the environment variables or the built-in defaults
8988 cause these files to be found.
8989
8990 Besides simplifying access to the RTL, a major use of search paths is
8991 in compiling sources from multiple directories. This can make
8992 development environments much more flexible.
8993
8994 @node Examples of gnatbind Usage
8995 @section Examples of @code{gnatbind} Usage
8996
8997 @noindent
8998 This section contains a number of examples of using the GNAT binding
8999 utility @code{gnatbind}.
9000
9001 @table @code
9002 @item gnatbind hello
9003 The main program @code{Hello} (source program in @file{hello.adb}) is
9004 bound using the standard switch settings. The generated main program is
9005 @file{b~hello.adb}. This is the normal, default use of the binder.
9006
9007 @ifclear vms
9008 @item gnatbind hello -o mainprog.adb
9009 @end ifclear
9010 @ifset vms
9011 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9012 @end ifset
9013 The main program @code{Hello} (source program in @file{hello.adb}) is
9014 bound using the standard switch settings. The generated main program is
9015 @file{mainprog.adb} with the associated spec in
9016 @file{mainprog.ads}. Note that you must specify the body here not the
9017 spec. Note that if this option is used, then linking must be done manually,
9018 since gnatlink will not be able to find the generated file.
9019 @end table
9020
9021 @c ------------------------------------
9022 @node Linking Using gnatlink
9023 @chapter Linking Using @command{gnatlink}
9024 @c ------------------------------------
9025 @findex gnatlink
9026
9027 @noindent
9028 This chapter discusses @command{gnatlink}, a tool that links
9029 an Ada program and builds an executable file. This utility
9030 invokes the system linker ^(via the @command{gcc} command)^^
9031 with a correct list of object files and library references.
9032 @command{gnatlink} automatically determines the list of files and
9033 references for the Ada part of a program. It uses the binder file
9034 generated by the @command{gnatbind} to determine this list.
9035
9036 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9037 driver (see @ref{The GNAT Driver and Project Files}).
9038
9039 @menu
9040 * Running gnatlink::
9041 * Switches for gnatlink::
9042 @end menu
9043
9044 @node Running gnatlink
9045 @section Running @command{gnatlink}
9046
9047 @noindent
9048 The form of the @command{gnatlink} command is
9049
9050 @smallexample
9051 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9052 @c            @ovar{non-Ada objects} @ovar{linker options}
9053 @c Expanding @ovar macro inline (explanation in macro def comments)
9054 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9055            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9056
9057 @end smallexample
9058
9059 @noindent
9060 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9061 non-Ada objects
9062 or linker options) may be in any order, provided that no non-Ada object may
9063 be mistaken for a main @file{ALI} file.
9064 Any file name @file{F} without the @file{.ali}
9065 extension will be taken as the main @file{ALI} file if a file exists
9066 whose name is the concatenation of @file{F} and @file{.ali}.
9067
9068 @noindent
9069 @file{@var{mainprog}.ali} references the ALI file of the main program.
9070 The @file{.ali} extension of this file can be omitted. From this
9071 reference, @command{gnatlink} locates the corresponding binder file
9072 @file{b~@var{mainprog}.adb} and, using the information in this file along
9073 with the list of non-Ada objects and linker options, constructs a
9074 linker command file to create the executable.
9075
9076 The arguments other than the @command{gnatlink} switches and the main
9077 @file{ALI} file are passed to the linker uninterpreted.
9078 They typically include the names of
9079 object files for units written in other languages than Ada and any library
9080 references required to resolve references in any of these foreign language
9081 units, or in @code{Import} pragmas in any Ada units.
9082
9083 @var{linker options} is an optional list of linker specific
9084 switches.
9085 The default linker called by gnatlink is @command{gcc} which in
9086 turn calls the appropriate system linker.
9087
9088 One useful option for the linker is @option{-s}: it reduces the size of the
9089 executable by removing all symbol table and relocation information from the
9090 executable.
9091
9092 Standard options for the linker such as @option{-lmy_lib} or
9093 @option{-Ldir} can be added as is.
9094 For options that are not recognized by
9095 @command{gcc} as linker options, use the @command{gcc} switches
9096 @option{-Xlinker} or @option{-Wl,}.
9097
9098 Refer to the GCC documentation for
9099 details.
9100
9101 Here is an example showing how to generate a linker map:
9102
9103 @smallexample
9104 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9105 @end smallexample
9106
9107 Using @var{linker options} it is possible to set the program stack and
9108 heap size.
9109 @ifset unw
9110 See @ref{Setting Stack Size from gnatlink} and
9111 @ref{Setting Heap Size from gnatlink}.
9112 @end ifset
9113
9114 @command{gnatlink} determines the list of objects required by the Ada
9115 program and prepends them to the list of objects passed to the linker.
9116 @command{gnatlink} also gathers any arguments set by the use of
9117 @code{pragma Linker_Options} and adds them to the list of arguments
9118 presented to the linker.
9119
9120 @ifset vms
9121 @command{gnatlink} accepts the following types of extra files on the command
9122 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9123 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9124 handled according to their extension.
9125 @end ifset
9126
9127 @node Switches for gnatlink
9128 @section Switches for @command{gnatlink}
9129
9130 @noindent
9131 The following switches are available with the @command{gnatlink} utility:
9132
9133 @table @option
9134 @c !sort!
9135
9136 @item --version
9137 @cindex @option{--version} @command{gnatlink}
9138 Display Copyright and version, then exit disregarding all other options.
9139
9140 @item --help
9141 @cindex @option{--help} @command{gnatlink}
9142 If @option{--version} was not used, display usage, then exit disregarding
9143 all other options.
9144
9145 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9146 @cindex Command line length
9147 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9148 On some targets, the command line length is limited, and @command{gnatlink}
9149 will generate a separate file for the linker if the list of object files
9150 is too long.
9151 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9152 to be generated even if
9153 the limit is not exceeded. This is useful in some cases to deal with
9154 special situations where the command line length is exceeded.
9155
9156 @item ^-g^/DEBUG^
9157 @cindex Debugging information, including
9158 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9159 The option to include debugging information causes the Ada bind file (in
9160 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9161 @option{^-g^/DEBUG^}.
9162 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9163 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9164 Without @option{^-g^/DEBUG^}, the binder removes these files by
9165 default. The same procedure apply if a C bind file was generated using
9166 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9167 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9168
9169 @item ^-n^/NOCOMPILE^
9170 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9171 Do not compile the file generated by the binder. This may be used when
9172 a link is rerun with different options, but there is no need to recompile
9173 the binder file.
9174
9175 @item ^-v^/VERBOSE^
9176 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9177 Causes additional information to be output, including a full list of the
9178 included object files. This switch option is most useful when you want
9179 to see what set of object files are being used in the link step.
9180
9181 @item ^-v -v^/VERBOSE/VERBOSE^
9182 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9183 Very verbose mode. Requests that the compiler operate in verbose mode when
9184 it compiles the binder file, and that the system linker run in verbose mode.
9185
9186 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9187 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9188 @var{exec-name} specifies an alternate name for the generated
9189 executable program. If this switch is omitted, the executable has the same
9190 name as the main unit. For example, @code{gnatlink try.ali} creates
9191 an executable called @file{^try^TRY.EXE^}.
9192
9193 @ifclear vms
9194 @item -b @var{target}
9195 @cindex @option{-b} (@command{gnatlink})
9196 Compile your program to run on @var{target}, which is the name of a
9197 system configuration. You must have a GNAT cross-compiler built if
9198 @var{target} is not the same as your host system.
9199
9200 @item -B@var{dir}
9201 @cindex @option{-B} (@command{gnatlink})
9202 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9203 from @var{dir} instead of the default location. Only use this switch
9204 when multiple versions of the GNAT compiler are available.
9205 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9206 for further details. You would normally use the @option{-b} or
9207 @option{-V} switch instead.
9208
9209 @item -M
9210 When linking an executable, create a map file. The name of the map file
9211 has the same name as the executable with extension ".map".
9212
9213 @item -M=mapfile
9214 When linking an executable, create a map file. The name of the map file is
9215 "mapfile".
9216
9217 @item --GCC=@var{compiler_name}
9218 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9219 Program used for compiling the binder file. The default is
9220 @command{gcc}. You need to use quotes around @var{compiler_name} if
9221 @code{compiler_name} contains spaces or other separator characters.
9222 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9223 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9224 inserted after your command name. Thus in the above example the compiler
9225 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9226 A limitation of this syntax is that the name and path name of the executable
9227 itself must not include any embedded spaces. If the compiler executable is
9228 different from the default one (gcc or <prefix>-gcc), then the back-end
9229 switches in the ALI file are not used to compile the binder generated source.
9230 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9231 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9232 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9233 is taken into account. However, all the additional switches are also taken
9234 into account. Thus,
9235 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9236 @option{--GCC="bar -x -y -z -t"}.
9237
9238 @item --LINK=@var{name}
9239 @cindex @option{--LINK=} (@command{gnatlink})
9240 @var{name} is the name of the linker to be invoked. This is especially
9241 useful in mixed language programs since languages such as C++ require
9242 their own linker to be used. When this switch is omitted, the default
9243 name for the linker is @command{gcc}. When this switch is used, the
9244 specified linker is called instead of @command{gcc} with exactly the same
9245 parameters that would have been passed to @command{gcc} so if the desired
9246 linker requires different parameters it is necessary to use a wrapper
9247 script that massages the parameters before invoking the real linker. It
9248 may be useful to control the exact invocation by using the verbose
9249 switch.
9250
9251 @end ifclear
9252
9253 @ifset vms
9254 @item /DEBUG=TRACEBACK
9255 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9256 This qualifier causes sufficient information to be included in the
9257 executable file to allow a traceback, but does not include the full
9258 symbol information needed by the debugger.
9259
9260 @item /IDENTIFICATION="<string>"
9261 @code{"<string>"} specifies the string to be stored in the image file
9262 identification field in the image header.
9263 It overrides any pragma @code{Ident} specified string.
9264
9265 @item /NOINHIBIT-EXEC
9266 Generate the executable file even if there are linker warnings.
9267
9268 @item /NOSTART_FILES
9269 Don't link in the object file containing the ``main'' transfer address.
9270 Used when linking with a foreign language main program compiled with an
9271 HP compiler.
9272
9273 @item /STATIC
9274 Prefer linking with object libraries over sharable images, even without
9275 /DEBUG.
9276 @end ifset
9277
9278 @end table
9279
9280 @node The GNAT Make Program gnatmake
9281 @chapter The GNAT Make Program @command{gnatmake}
9282 @findex gnatmake
9283
9284 @menu
9285 * Running gnatmake::
9286 * Switches for gnatmake::
9287 * Mode Switches for gnatmake::
9288 * Notes on the Command Line::
9289 * How gnatmake Works::
9290 * Examples of gnatmake Usage::
9291 @end menu
9292 @noindent
9293 A typical development cycle when working on an Ada program consists of
9294 the following steps:
9295
9296 @enumerate
9297 @item
9298 Edit some sources to fix bugs.
9299
9300 @item
9301 Add enhancements.
9302
9303 @item
9304 Compile all sources affected.
9305
9306 @item
9307 Rebind and relink.
9308
9309 @item
9310 Test.
9311 @end enumerate
9312
9313 @noindent
9314 The third step can be tricky, because not only do the modified files
9315 @cindex Dependency rules
9316 have to be compiled, but any files depending on these files must also be
9317 recompiled. The dependency rules in Ada can be quite complex, especially
9318 in the presence of overloading, @code{use} clauses, generics and inlined
9319 subprograms.
9320
9321 @command{gnatmake} automatically takes care of the third and fourth steps
9322 of this process. It determines which sources need to be compiled,
9323 compiles them, and binds and links the resulting object files.
9324
9325 Unlike some other Ada make programs, the dependencies are always
9326 accurately recomputed from the new sources. The source based approach of
9327 the GNAT compilation model makes this possible. This means that if
9328 changes to the source program cause corresponding changes in
9329 dependencies, they will always be tracked exactly correctly by
9330 @command{gnatmake}.
9331
9332 @node Running gnatmake
9333 @section Running @command{gnatmake}
9334
9335 @noindent
9336 The usual form of the @command{gnatmake} command is
9337
9338 @smallexample
9339 @c $ gnatmake @ovar{switches} @var{file_name}
9340 @c       @ovar{file_names} @ovar{mode_switches}
9341 @c Expanding @ovar macro inline (explanation in macro def comments)
9342 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9343       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9344 @end smallexample
9345
9346 @noindent
9347 The only required argument is one @var{file_name}, which specifies
9348 a compilation unit that is a main program. Several @var{file_names} can be
9349 specified: this will result in several executables being built.
9350 If @code{switches} are present, they can be placed before the first
9351 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9352 If @var{mode_switches} are present, they must always be placed after
9353 the last @var{file_name} and all @code{switches}.
9354
9355 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9356 extension may be omitted from the @var{file_name} arguments. However, if
9357 you are using non-standard extensions, then it is required that the
9358 extension be given. A relative or absolute directory path can be
9359 specified in a @var{file_name}, in which case, the input source file will
9360 be searched for in the specified directory only. Otherwise, the input
9361 source file will first be searched in the directory where
9362 @command{gnatmake} was invoked and if it is not found, it will be search on
9363 the source path of the compiler as described in
9364 @ref{Search Paths and the Run-Time Library (RTL)}.
9365
9366 All @command{gnatmake} output (except when you specify
9367 @option{^-M^/DEPENDENCIES_LIST^}) is to
9368 @file{stderr}. The output produced by the
9369 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9370 @file{stdout}.
9371
9372 @node Switches for gnatmake
9373 @section Switches for @command{gnatmake}
9374
9375 @noindent
9376 You may specify any of the following switches to @command{gnatmake}:
9377
9378 @table @option
9379 @c !sort!
9380
9381 @item --version
9382 @cindex @option{--version} @command{gnatmake}
9383 Display Copyright and version, then exit disregarding all other options.
9384
9385 @item --help
9386 @cindex @option{--help} @command{gnatmake}
9387 If @option{--version} was not used, display usage, then exit disregarding
9388 all other options.
9389
9390 @ifclear vms
9391 @item --GCC=@var{compiler_name}
9392 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9393 Program used for compiling. The default is `@command{gcc}'. You need to use
9394 quotes around @var{compiler_name} if @code{compiler_name} contains
9395 spaces or other separator characters. As an example @option{--GCC="foo -x
9396 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9397 compiler. A limitation of this syntax is that the name and path name of
9398 the executable itself must not include any embedded spaces. Note that
9399 switch @option{-c} is always inserted after your command name. Thus in the
9400 above example the compiler command that will be used by @command{gnatmake}
9401 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9402 used, only the last @var{compiler_name} is taken into account. However,
9403 all the additional switches are also taken into account. Thus,
9404 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9405 @option{--GCC="bar -x -y -z -t"}.
9406
9407 @item --GNATBIND=@var{binder_name}
9408 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9409 Program used for binding. The default is `@code{gnatbind}'. You need to
9410 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9411 or other separator characters. As an example @option{--GNATBIND="bar -x
9412 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9413 binder. Binder switches that are normally appended by @command{gnatmake}
9414 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9415 A limitation of this syntax is that the name and path name of the executable
9416 itself must not include any embedded spaces.
9417
9418 @item --GNATLINK=@var{linker_name}
9419 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9420 Program used for linking. The default is `@command{gnatlink}'. You need to
9421 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9422 or other separator characters. As an example @option{--GNATLINK="lan -x
9423 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9424 linker. Linker switches that are normally appended by @command{gnatmake} to
9425 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9426 A limitation of this syntax is that the name and path name of the executable
9427 itself must not include any embedded spaces.
9428
9429 @end ifclear
9430
9431 @item ^--subdirs^/SUBDIRS^=subdir
9432 Actual object directory of each project file is the subdirectory subdir of the
9433 object directory specified or defaulted in the project file.
9434
9435 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9436 Disallow simultaneous compilations in the same object directory when
9437 project files are used.
9438
9439 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9440 By default, shared library projects are not allowed to import static library
9441 projects. When this switch is used on the command line, this restriction is
9442 relaxed.
9443
9444 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9445 Specify a source info file. This switch is active only when project files
9446 are used. If the source info file is specified as a relative path, then it is
9447 relative to the object directory of the main project. If the source info file
9448 does not exist, then after the Project Manager has successfully parsed and
9449 processed the project files and found the sources, it creates the source info
9450 file. If the source info file already exists and can be read successfully,
9451 then the Project Manager will get all the needed information about the sources
9452 from the source info file and will not look for them. This reduces the time
9453 to process the project files, especially when looking for sources that take a
9454 long time. If the source info file exists but cannot be parsed successfully,
9455 the Project Manager will attempt to recreate it. If the Project Manager fails
9456 to create the source info file, a message is issued, but gnatmake does not
9457 fail. @command{gnatmake} "trusts" the source info file. This means that
9458 if the source files have changed (addition, deletion, moving to a different
9459 source directory), then the source info file need to be deleted and recreated.
9460
9461 @ifclear vms
9462 @item --create-map-file
9463 When linking an executable, create a map file. The name of the map file
9464 has the same name as the executable with extension ".map".
9465
9466 @item --create-map-file=mapfile
9467 When linking an executable, create a map file. The name of the map file is
9468 "mapfile".
9469
9470 @end ifclear
9471
9472 @item ^-a^/ALL_FILES^
9473 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9474 Consider all files in the make process, even the GNAT internal system
9475 files (for example, the predefined Ada library files), as well as any
9476 locked files. Locked files are files whose ALI file is write-protected.
9477 By default,
9478 @command{gnatmake} does not check these files,
9479 because the assumption is that the GNAT internal files are properly up
9480 to date, and also that any write protected ALI files have been properly
9481 installed. Note that if there is an installation problem, such that one
9482 of these files is not up to date, it will be properly caught by the
9483 binder.
9484 You may have to specify this switch if you are working on GNAT
9485 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9486 in conjunction with @option{^-f^/FORCE_COMPILE^}
9487 if you need to recompile an entire application,
9488 including run-time files, using special configuration pragmas,
9489 such as a @code{Normalize_Scalars} pragma.
9490
9491 By default
9492 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9493 internal files with
9494 @ifclear vms
9495 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9496 @end ifclear
9497 @ifset vms
9498 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9499 @end ifset
9500
9501 @item ^-b^/ACTIONS=BIND^
9502 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9503 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9504 compilation and binding, but no link.
9505 Can be combined with @option{^-l^/ACTIONS=LINK^}
9506 to do binding and linking. When not combined with
9507 @option{^-c^/ACTIONS=COMPILE^}
9508 all the units in the closure of the main program must have been previously
9509 compiled and must be up to date. The root unit specified by @var{file_name}
9510 may be given without extension, with the source extension or, if no GNAT
9511 Project File is specified, with the ALI file extension.
9512
9513 @item ^-c^/ACTIONS=COMPILE^
9514 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9515 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9516 is also specified. Do not perform linking, except if both
9517 @option{^-b^/ACTIONS=BIND^} and
9518 @option{^-l^/ACTIONS=LINK^} are also specified.
9519 If the root unit specified by @var{file_name} is not a main unit, this is the
9520 default. Otherwise @command{gnatmake} will attempt binding and linking
9521 unless all objects are up to date and the executable is more recent than
9522 the objects.
9523
9524 @item ^-C^/MAPPING^
9525 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9526 Use a temporary mapping file. A mapping file is a way to communicate
9527 to the compiler two mappings: from unit names to file names (without
9528 any directory information) and from file names to path names (with
9529 full directory information). A mapping file can make the compiler's
9530 file searches faster, especially if there are many source directories,
9531 or the sources are read over a slow network connection. If
9532 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9533 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9534 is initially populated based on the project file. If
9535 @option{^-C^/MAPPING^} is used without
9536 @option{^-P^/PROJECT_FILE^},
9537 the mapping file is initially empty. Each invocation of the compiler
9538 will add any newly accessed sources to the mapping file.
9539
9540 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9541 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9542 Use a specific mapping file. The file, specified as a path name (absolute or
9543 relative) by this switch, should already exist, otherwise the switch is
9544 ineffective. The specified mapping file will be communicated to the compiler.
9545 This switch is not compatible with a project file
9546 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9547 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9548
9549 @item ^-d^/DISPLAY_PROGRESS^
9550 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9551 Display progress for each source, up to date or not, as a single line
9552
9553 @smallexample
9554 completed x out of y (zz%)
9555 @end smallexample
9556
9557 If the file needs to be compiled this is displayed after the invocation of
9558 the compiler. These lines are displayed even in quiet output mode.
9559
9560 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9561 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9562 Put all object files and ALI file in directory @var{dir}.
9563 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9564 and ALI files go in the current working directory.
9565
9566 This switch cannot be used when using a project file.
9567
9568 @item -eInnn
9569 @cindex @option{-eI} (@command{gnatmake})
9570 Indicates that the main source is a multi-unit source and the rank of the unit
9571 in the source file is nnn. nnn needs to be a positive number and a valid
9572 index in the source. This switch cannot be used when @command{gnatmake} is
9573 invoked for several mains.
9574
9575 @ifclear vms
9576 @item -eL
9577 @cindex @option{-eL} (@command{gnatmake})
9578 @cindex symbolic links
9579 Follow all symbolic links when processing project files.
9580 This should be used if your project uses symbolic links for files or
9581 directories, but is not needed in other cases.
9582
9583 @cindex naming scheme
9584 This also assumes that no directory matches the naming scheme for files (for
9585 instance that you do not have a directory called "sources.ads" when using the
9586 default GNAT naming scheme).
9587
9588 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9589 save a lot of system calls (several per source file and object file), which
9590 can result in a significant speed up to load and manipulate a project file,
9591 especially when using source files from a remote system.
9592
9593 @end ifclear
9594
9595 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9596 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9597 Output the commands for the compiler, the binder and the linker
9598 on ^standard output^SYS$OUTPUT^,
9599 instead of ^standard error^SYS$ERROR^.
9600
9601 @item ^-f^/FORCE_COMPILE^
9602 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9603 Force recompilations. Recompile all sources, even though some object
9604 files may be up to date, but don't recompile predefined or GNAT internal
9605 files or locked files (files with a write-protected ALI file),
9606 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9607
9608 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9609 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9610 When using project files, if some errors or warnings are detected during
9611 parsing and verbose mode is not in effect (no use of switch
9612 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9613 file, rather than its simple file name.
9614
9615 @item ^-g^/DEBUG^
9616 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9617 Enable debugging. This switch is simply passed to the compiler and to the
9618 linker.
9619
9620 @item ^-i^/IN_PLACE^
9621 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9622 In normal mode, @command{gnatmake} compiles all object files and ALI files
9623 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9624 then instead object files and ALI files that already exist are overwritten
9625 in place. This means that once a large project is organized into separate
9626 directories in the desired manner, then @command{gnatmake} will automatically
9627 maintain and update this organization. If no ALI files are found on the
9628 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9629 the new object and ALI files are created in the
9630 directory containing the source being compiled. If another organization
9631 is desired, where objects and sources are kept in different directories,
9632 a useful technique is to create dummy ALI files in the desired directories.
9633 When detecting such a dummy file, @command{gnatmake} will be forced to
9634 recompile the corresponding source file, and it will be put the resulting
9635 object and ALI files in the directory where it found the dummy file.
9636
9637 @item ^-j^/PROCESSES=^@var{n}
9638 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9639 @cindex Parallel make
9640 Use @var{n} processes to carry out the (re)compilations. On a
9641 multiprocessor machine compilations will occur in parallel. In the
9642 event of compilation errors, messages from various compilations might
9643 get interspersed (but @command{gnatmake} will give you the full ordered
9644 list of failing compiles at the end). If this is problematic, rerun
9645 the make process with n set to 1 to get a clean list of messages.
9646
9647 @item ^-k^/CONTINUE_ON_ERROR^
9648 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9649 Keep going. Continue as much as possible after a compilation error. To
9650 ease the programmer's task in case of compilation errors, the list of
9651 sources for which the compile fails is given when @command{gnatmake}
9652 terminates.
9653
9654 If @command{gnatmake} is invoked with several @file{file_names} and with this
9655 switch, if there are compilation errors when building an executable,
9656 @command{gnatmake} will not attempt to build the following executables.
9657
9658 @item ^-l^/ACTIONS=LINK^
9659 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9660 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9661 and linking. Linking will not be performed if combined with
9662 @option{^-c^/ACTIONS=COMPILE^}
9663 but not with @option{^-b^/ACTIONS=BIND^}.
9664 When not combined with @option{^-b^/ACTIONS=BIND^}
9665 all the units in the closure of the main program must have been previously
9666 compiled and must be up to date, and the main program needs to have been bound.
9667 The root unit specified by @var{file_name}
9668 may be given without extension, with the source extension or, if no GNAT
9669 Project File is specified, with the ALI file extension.
9670
9671 @item ^-m^/MINIMAL_RECOMPILATION^
9672 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9673 Specify that the minimum necessary amount of recompilations
9674 be performed. In this mode @command{gnatmake} ignores time
9675 stamp differences when the only
9676 modifications to a source file consist in adding/removing comments,
9677 empty lines, spaces or tabs. This means that if you have changed the
9678 comments in a source file or have simply reformatted it, using this
9679 switch will tell @command{gnatmake} not to recompile files that depend on it
9680 (provided other sources on which these files depend have undergone no
9681 semantic modifications). Note that the debugging information may be
9682 out of date with respect to the sources if the @option{-m} switch causes
9683 a compilation to be switched, so the use of this switch represents a
9684 trade-off between compilation time and accurate debugging information.
9685
9686 @item ^-M^/DEPENDENCIES_LIST^
9687 @cindex Dependencies, producing list
9688 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9689 Check if all objects are up to date. If they are, output the object
9690 dependences to @file{stdout} in a form that can be directly exploited in
9691 a @file{Makefile}. By default, each source file is prefixed with its
9692 (relative or absolute) directory name. This name is whatever you
9693 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9694 and @option{^-I^/SEARCH^} switches. If you use
9695 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9696 @option{^-q^/QUIET^}
9697 (see below), only the source file names,
9698 without relative paths, are output. If you just specify the
9699 @option{^-M^/DEPENDENCIES_LIST^}
9700 switch, dependencies of the GNAT internal system files are omitted. This
9701 is typically what you want. If you also specify
9702 the @option{^-a^/ALL_FILES^} switch,
9703 dependencies of the GNAT internal files are also listed. Note that
9704 dependencies of the objects in external Ada libraries (see switch
9705 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9706 are never reported.
9707
9708 @item ^-n^/DO_OBJECT_CHECK^
9709 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9710 Don't compile, bind, or link. Checks if all objects are up to date.
9711 If they are not, the full name of the first file that needs to be
9712 recompiled is printed.
9713 Repeated use of this option, followed by compiling the indicated source
9714 file, will eventually result in recompiling all required units.
9715
9716 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9717 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9718 Output executable name. The name of the final executable program will be
9719 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9720 name for the executable will be the name of the input file in appropriate form
9721 for an executable file on the host system.
9722
9723 This switch cannot be used when invoking @command{gnatmake} with several
9724 @file{file_names}.
9725
9726 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9727 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9728 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9729 automatically missing object directories, library directories and exec
9730 directories.
9731
9732 @item ^-P^/PROJECT_FILE=^@var{project}
9733 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9734 Use project file @var{project}. Only one such switch can be used.
9735 @xref{gnatmake and Project Files}.
9736
9737 @item ^-q^/QUIET^
9738 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9739 Quiet. When this flag is not set, the commands carried out by
9740 @command{gnatmake} are displayed.
9741
9742 @item ^-s^/SWITCH_CHECK/^
9743 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9744 Recompile if compiler switches have changed since last compilation.
9745 All compiler switches but -I and -o are taken into account in the
9746 following way:
9747 orders between different ``first letter'' switches are ignored, but
9748 orders between same switches are taken into account. For example,
9749 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9750 is equivalent to @option{-O -g}.
9751
9752 This switch is recommended when Integrated Preprocessing is used.
9753
9754 @item ^-u^/UNIQUE^
9755 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9756 Unique. Recompile at most the main files. It implies -c. Combined with
9757 -f, it is equivalent to calling the compiler directly. Note that using
9758 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9759 (@pxref{Project Files and Main Subprograms}).
9760
9761 @item ^-U^/ALL_PROJECTS^
9762 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9763 When used without a project file or with one or several mains on the command
9764 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9765 on the command line, all sources of all project files are checked and compiled
9766 if not up to date, and libraries are rebuilt, if necessary.
9767
9768 @item ^-v^/REASONS^
9769 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9770 Verbose. Display the reason for all recompilations @command{gnatmake}
9771 decides are necessary, with the highest verbosity level.
9772
9773 @item ^-vl^/LOW_VERBOSITY^
9774 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9775 Verbosity level Low. Display fewer lines than in verbosity Medium.
9776
9777 @item ^-vm^/MEDIUM_VERBOSITY^
9778 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9779 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9780
9781 @item ^-vh^/HIGH_VERBOSITY^
9782 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9783 Verbosity level High. Equivalent to ^-v^/REASONS^.
9784
9785 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9786 Indicate the verbosity of the parsing of GNAT project files.
9787 @xref{Switches Related to Project Files}.
9788
9789 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9790 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9791 Indicate that sources that are not part of any Project File may be compiled.
9792 Normally, when using Project Files, only sources that are part of a Project
9793 File may be compile. When this switch is used, a source outside of all Project
9794 Files may be compiled. The ALI file and the object file will be put in the
9795 object directory of the main Project. The compilation switches used will only
9796 be those specified on the command line. Even when
9797 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9798 command line need to be sources of a project file.
9799
9800 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9801 Indicate that external variable @var{name} has the value @var{value}.
9802 The Project Manager will use this value for occurrences of
9803 @code{external(name)} when parsing the project file.
9804 @xref{Switches Related to Project Files}.
9805
9806 @item ^-z^/NOMAIN^
9807 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9808 No main subprogram. Bind and link the program even if the unit name
9809 given on the command line is a package name. The resulting executable
9810 will execute the elaboration routines of the package and its closure,
9811 then the finalization routines.
9812
9813 @end table
9814
9815 @table @asis
9816 @item @command{gcc} @asis{switches}
9817 @ifclear vms
9818 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9819 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9820 @end ifclear
9821 @ifset vms
9822 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9823 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9824 automatically treated as a compiler switch, and passed on to all
9825 compilations that are carried out.
9826 @end ifset
9827 @end table
9828
9829 @noindent
9830 Source and library search path switches:
9831
9832 @table @option
9833 @c !sort!
9834 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9835 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9836 When looking for source files also look in directory @var{dir}.
9837 The order in which source files search is undertaken is
9838 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9839
9840 @item ^-aL^/SKIP_MISSING=^@var{dir}
9841 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9842 Consider @var{dir} as being an externally provided Ada library.
9843 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9844 files have been located in directory @var{dir}. This allows you to have
9845 missing bodies for the units in @var{dir} and to ignore out of date bodies
9846 for the same units. You still need to specify
9847 the location of the specs for these units by using the switches
9848 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9849 or @option{^-I^/SEARCH=^@var{dir}}.
9850 Note: this switch is provided for compatibility with previous versions
9851 of @command{gnatmake}. The easier method of causing standard libraries
9852 to be excluded from consideration is to write-protect the corresponding
9853 ALI files.
9854
9855 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9856 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9857 When searching for library and object files, look in directory
9858 @var{dir}. The order in which library files are searched is described in
9859 @ref{Search Paths for gnatbind}.
9860
9861 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9862 @cindex Search paths, for @command{gnatmake}
9863 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9864 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9865 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9866
9867 @item ^-I^/SEARCH=^@var{dir}
9868 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9869 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9870 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9871
9872 @item ^-I-^/NOCURRENT_DIRECTORY^
9873 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9874 @cindex Source files, suppressing search
9875 Do not look for source files in the directory containing the source
9876 file named in the command line.
9877 Do not look for ALI or object files in the directory
9878 where @command{gnatmake} was invoked.
9879
9880 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9881 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9882 @cindex Linker libraries
9883 Add directory @var{dir} to the list of directories in which the linker
9884 will search for libraries. This is equivalent to
9885 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9886 @ifclear vms
9887 Furthermore, under Windows, the sources pointed to by the libraries path
9888 set in the registry are not searched for.
9889 @end ifclear
9890
9891 @item -nostdinc
9892 @cindex @option{-nostdinc} (@command{gnatmake})
9893 Do not look for source files in the system default directory.
9894
9895 @item -nostdlib
9896 @cindex @option{-nostdlib} (@command{gnatmake})
9897 Do not look for library files in the system default directory.
9898
9899 @item --RTS=@var{rts-path}
9900 @cindex @option{--RTS} (@command{gnatmake})
9901 Specifies the default location of the runtime library. GNAT looks for the
9902 runtime
9903 in the following directories, and stops as soon as a valid runtime is found
9904 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9905 @file{ada_object_path} present):
9906
9907 @itemize @bullet
9908 @item <current directory>/$rts_path
9909
9910 @item <default-search-dir>/$rts_path
9911
9912 @item <default-search-dir>/rts-$rts_path
9913 @end itemize
9914
9915 @noindent
9916 The selected path is handled like a normal RTS path.
9917
9918 @end table
9919
9920 @node Mode Switches for gnatmake
9921 @section Mode Switches for @command{gnatmake}
9922
9923 @noindent
9924 The mode switches (referred to as @code{mode_switches}) allow the
9925 inclusion of switches that are to be passed to the compiler itself, the
9926 binder or the linker. The effect of a mode switch is to cause all
9927 subsequent switches up to the end of the switch list, or up to the next
9928 mode switch, to be interpreted as switches to be passed on to the
9929 designated component of GNAT.
9930
9931 @table @option
9932 @c !sort!
9933 @item -cargs @var{switches}
9934 @cindex @option{-cargs} (@command{gnatmake})
9935 Compiler switches. Here @var{switches} is a list of switches
9936 that are valid switches for @command{gcc}. They will be passed on to
9937 all compile steps performed by @command{gnatmake}.
9938
9939 @item -bargs @var{switches}
9940 @cindex @option{-bargs} (@command{gnatmake})
9941 Binder switches. Here @var{switches} is a list of switches
9942 that are valid switches for @code{gnatbind}. They will be passed on to
9943 all bind steps performed by @command{gnatmake}.
9944
9945 @item -largs @var{switches}
9946 @cindex @option{-largs} (@command{gnatmake})
9947 Linker switches. Here @var{switches} is a list of switches
9948 that are valid switches for @command{gnatlink}. They will be passed on to
9949 all link steps performed by @command{gnatmake}.
9950
9951 @item -margs @var{switches}
9952 @cindex @option{-margs} (@command{gnatmake})
9953 Make switches. The switches are directly interpreted by @command{gnatmake},
9954 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9955 or @option{-largs}.
9956 @end table
9957
9958 @node Notes on the Command Line
9959 @section Notes on the Command Line
9960
9961 @noindent
9962 This section contains some additional useful notes on the operation
9963 of the @command{gnatmake} command.
9964
9965 @itemize @bullet
9966 @item
9967 @cindex Recompilation, by @command{gnatmake}
9968 If @command{gnatmake} finds no ALI files, it recompiles the main program
9969 and all other units required by the main program.
9970 This means that @command{gnatmake}
9971 can be used for the initial compile, as well as during subsequent steps of
9972 the development cycle.
9973
9974 @item
9975 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9976 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9977 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9978 warning.
9979
9980 @item
9981 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9982 is used to specify both source and
9983 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9984 instead if you just want to specify
9985 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9986 if you want to specify library paths
9987 only.
9988
9989 @item
9990 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9991 This may conveniently be used to exclude standard libraries from
9992 consideration and in particular it means that the use of the
9993 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9994 unless @option{^-a^/ALL_FILES^} is also specified.
9995
9996 @item
9997 @command{gnatmake} has been designed to make the use of Ada libraries
9998 particularly convenient. Assume you have an Ada library organized
9999 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10000 of your Ada compilation units,
10001 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10002 specs of these units, but no bodies. Then to compile a unit
10003 stored in @code{main.adb}, which uses this Ada library you would just type
10004
10005 @smallexample
10006 @ifclear vms
10007 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10008 @end ifclear
10009 @ifset vms
10010 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10011            /SKIP_MISSING=@i{[OBJ_DIR]} main
10012 @end ifset
10013 @end smallexample
10014
10015 @item
10016 Using @command{gnatmake} along with the
10017 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10018 switch provides a mechanism for avoiding unnecessary recompilations. Using
10019 this switch,
10020 you can update the comments/format of your
10021 source files without having to recompile everything. Note, however, that
10022 adding or deleting lines in a source files may render its debugging
10023 info obsolete. If the file in question is a spec, the impact is rather
10024 limited, as that debugging info will only be useful during the
10025 elaboration phase of your program. For bodies the impact can be more
10026 significant. In all events, your debugger will warn you if a source file
10027 is more recent than the corresponding object, and alert you to the fact
10028 that the debugging information may be out of date.
10029 @end itemize
10030
10031 @node How gnatmake Works
10032 @section How @command{gnatmake} Works
10033
10034 @noindent
10035 Generally @command{gnatmake} automatically performs all necessary
10036 recompilations and you don't need to worry about how it works. However,
10037 it may be useful to have some basic understanding of the @command{gnatmake}
10038 approach and in particular to understand how it uses the results of
10039 previous compilations without incorrectly depending on them.
10040
10041 First a definition: an object file is considered @dfn{up to date} if the
10042 corresponding ALI file exists and if all the source files listed in the
10043 dependency section of this ALI file have time stamps matching those in
10044 the ALI file. This means that neither the source file itself nor any
10045 files that it depends on have been modified, and hence there is no need
10046 to recompile this file.
10047
10048 @command{gnatmake} works by first checking if the specified main unit is up
10049 to date. If so, no compilations are required for the main unit. If not,
10050 @command{gnatmake} compiles the main program to build a new ALI file that
10051 reflects the latest sources. Then the ALI file of the main unit is
10052 examined to find all the source files on which the main program depends,
10053 and @command{gnatmake} recursively applies the above procedure on all these
10054 files.
10055
10056 This process ensures that @command{gnatmake} only trusts the dependencies
10057 in an existing ALI file if they are known to be correct. Otherwise it
10058 always recompiles to determine a new, guaranteed accurate set of
10059 dependencies. As a result the program is compiled ``upside down'' from what may
10060 be more familiar as the required order of compilation in some other Ada
10061 systems. In particular, clients are compiled before the units on which
10062 they depend. The ability of GNAT to compile in any order is critical in
10063 allowing an order of compilation to be chosen that guarantees that
10064 @command{gnatmake} will recompute a correct set of new dependencies if
10065 necessary.
10066
10067 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10068 imported by several of the executables, it will be recompiled at most once.
10069
10070 Note: when using non-standard naming conventions
10071 (@pxref{Using Other File Names}), changing through a configuration pragmas
10072 file the version of a source and invoking @command{gnatmake} to recompile may
10073 have no effect, if the previous version of the source is still accessible
10074 by @command{gnatmake}. It may be necessary to use the switch
10075 ^-f^/FORCE_COMPILE^.
10076
10077 @node Examples of gnatmake Usage
10078 @section Examples of @command{gnatmake} Usage
10079
10080 @table @code
10081 @item gnatmake hello.adb
10082 Compile all files necessary to bind and link the main program
10083 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10084 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10085
10086 @item gnatmake main1 main2 main3
10087 Compile all files necessary to bind and link the main programs
10088 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10089 (containing unit @code{Main2}) and @file{main3.adb}
10090 (containing unit @code{Main3}) and bind and link the resulting object files
10091 to generate three executable files @file{^main1^MAIN1.EXE^},
10092 @file{^main2^MAIN2.EXE^}
10093 and @file{^main3^MAIN3.EXE^}.
10094
10095 @ifclear vms
10096 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10097 @end ifclear
10098
10099 @ifset vms
10100 @item gnatmake Main_Unit /QUIET
10101 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10102 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10103 @end ifset
10104 Compile all files necessary to bind and link the main program unit
10105 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10106 be done with optimization level 2 and the order of elaboration will be
10107 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10108 displaying commands it is executing.
10109 @end table
10110
10111 @c *************************
10112 @node Improving Performance
10113 @chapter Improving Performance
10114 @cindex Improving performance
10115
10116 @noindent
10117 This chapter presents several topics related to program performance.
10118 It first describes some of the tradeoffs that need to be considered
10119 and some of the techniques for making your program run faster.
10120 It then documents the @command{gnatelim} tool and unused subprogram/data
10121 elimination feature, which can reduce the size of program executables.
10122
10123 @ifnottex
10124 @menu
10125 * Performance Considerations::
10126 * Text_IO Suggestions::
10127 * Reducing Size of Ada Executables with gnatelim::
10128 * Reducing Size of Executables with unused subprogram/data elimination::
10129 @end menu
10130 @end ifnottex
10131
10132 @c *****************************
10133 @node Performance Considerations
10134 @section Performance Considerations
10135
10136 @noindent
10137 The GNAT system provides a number of options that allow a trade-off
10138 between
10139
10140 @itemize @bullet
10141 @item
10142 performance of the generated code
10143
10144 @item
10145 speed of compilation
10146
10147 @item
10148 minimization of dependences and recompilation
10149
10150 @item
10151 the degree of run-time checking.
10152 @end itemize
10153
10154 @noindent
10155 The defaults (if no options are selected) aim at improving the speed
10156 of compilation and minimizing dependences, at the expense of performance
10157 of the generated code:
10158
10159 @itemize @bullet
10160 @item
10161 no optimization
10162
10163 @item
10164 no inlining of subprogram calls
10165
10166 @item
10167 all run-time checks enabled except overflow and elaboration checks
10168 @end itemize
10169
10170 @noindent
10171 These options are suitable for most program development purposes. This
10172 chapter describes how you can modify these choices, and also provides
10173 some guidelines on debugging optimized code.
10174
10175 @menu
10176 * Controlling Run-Time Checks::
10177 * Use of Restrictions::
10178 * Optimization Levels::
10179 * Debugging Optimized Code::
10180 * Inlining of Subprograms::
10181 * Vectorization of loops::
10182 * Other Optimization Switches::
10183 * Optimization and Strict Aliasing::
10184
10185 @ifset vms
10186 * Coverage Analysis::
10187 @end ifset
10188 @end menu
10189
10190 @node Controlling Run-Time Checks
10191 @subsection Controlling Run-Time Checks
10192
10193 @noindent
10194 By default, GNAT generates all run-time checks, except integer overflow
10195 checks, stack overflow checks, and checks for access before elaboration on
10196 subprogram calls. The latter are not required in default mode, because all
10197 necessary checking is done at compile time.
10198 @cindex @option{-gnatp} (@command{gcc})
10199 @cindex @option{-gnato} (@command{gcc})
10200 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10201 be modified. @xref{Run-Time Checks}.
10202
10203 Our experience is that the default is suitable for most development
10204 purposes.
10205
10206 We treat integer overflow specially because these
10207 are quite expensive and in our experience are not as important as other
10208 run-time checks in the development process. Note that division by zero
10209 is not considered an overflow check, and divide by zero checks are
10210 generated where required by default.
10211
10212 Elaboration checks are off by default, and also not needed by default, since
10213 GNAT uses a static elaboration analysis approach that avoids the need for
10214 run-time checking. This manual contains a full chapter discussing the issue
10215 of elaboration checks, and if the default is not satisfactory for your use,
10216 you should read this chapter.
10217
10218 For validity checks, the minimal checks required by the Ada Reference
10219 Manual (for case statements and assignments to array elements) are on
10220 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10221 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10222 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10223 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10224 are also suppressed entirely if @option{-gnatp} is used.
10225
10226 @cindex Overflow checks
10227 @cindex Checks, overflow
10228 @findex Suppress
10229 @findex Unsuppress
10230 @cindex pragma Suppress
10231 @cindex pragma Unsuppress
10232 Note that the setting of the switches controls the default setting of
10233 the checks. They may be modified using either @code{pragma Suppress} (to
10234 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10235 checks) in the program source.
10236
10237 @node Use of Restrictions
10238 @subsection Use of Restrictions
10239
10240 @noindent
10241 The use of pragma Restrictions allows you to control which features are
10242 permitted in your program. Apart from the obvious point that if you avoid
10243 relatively expensive features like finalization (enforceable by the use
10244 of pragma Restrictions (No_Finalization), the use of this pragma does not
10245 affect the generated code in most cases.
10246
10247 One notable exception to this rule is that the possibility of task abort
10248 results in some distributed overhead, particularly if finalization or
10249 exception handlers are used. The reason is that certain sections of code
10250 have to be marked as non-abortable.
10251
10252 If you use neither the @code{abort} statement, nor asynchronous transfer
10253 of control (@code{select @dots{} then abort}), then this distributed overhead
10254 is removed, which may have a general positive effect in improving
10255 overall performance.  Especially code involving frequent use of tasking
10256 constructs and controlled types will show much improved performance.
10257 The relevant restrictions pragmas are
10258
10259 @smallexample @c ada
10260    pragma Restrictions (No_Abort_Statements);
10261    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10262 @end smallexample
10263
10264 @noindent
10265 It is recommended that these restriction pragmas be used if possible. Note
10266 that this also means that you can write code without worrying about the
10267 possibility of an immediate abort at any point.
10268
10269 @node Optimization Levels
10270 @subsection Optimization Levels
10271 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10272
10273 @noindent
10274 Without any optimization ^option,^qualifier,^
10275 the compiler's goal is to reduce the cost of
10276 compilation and to make debugging produce the expected results.
10277 Statements are independent: if you stop the program with a breakpoint between
10278 statements, you can then assign a new value to any variable or change
10279 the program counter to any other statement in the subprogram and get exactly
10280 the results you would expect from the source code.
10281
10282 Turning on optimization makes the compiler attempt to improve the
10283 performance and/or code size at the expense of compilation time and
10284 possibly the ability to debug the program.
10285
10286 If you use multiple
10287 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10288 the last such option is the one that is effective.
10289
10290 @noindent
10291 The default is optimization off. This results in the fastest compile
10292 times, but GNAT makes absolutely no attempt to optimize, and the
10293 generated programs are considerably larger and slower than when
10294 optimization is enabled. You can use the
10295 @ifclear vms
10296 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10297 @option{-O2}, @option{-O3}, and @option{-Os})
10298 @end ifclear
10299 @ifset vms
10300 @code{OPTIMIZE} qualifier
10301 @end ifset
10302 to @command{gcc} to control the optimization level:
10303
10304 @table @option
10305 @item ^-O0^/OPTIMIZE=NONE^
10306 No optimization (the default);
10307 generates unoptimized code but has
10308 the fastest compilation time.
10309
10310 Note that many other compilers do fairly extensive optimization
10311 even if ``no optimization'' is specified. With gcc, it is
10312 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10313 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10314 really does mean no optimization at all. This difference between
10315 gcc and other compilers should be kept in mind when doing
10316 performance comparisons.
10317
10318 @item ^-O1^/OPTIMIZE=SOME^
10319 Moderate optimization;
10320 optimizes reasonably well but does not
10321 degrade compilation time significantly.
10322
10323 @item ^-O2^/OPTIMIZE=ALL^
10324 @ifset vms
10325 @itemx /OPTIMIZE=DEVELOPMENT
10326 @end ifset
10327 Full optimization;
10328 generates highly optimized code and has
10329 the slowest compilation time.
10330
10331 @item ^-O3^/OPTIMIZE=INLINING^
10332 Full optimization as in @option{-O2};
10333 also uses more aggressive automatic inlining of subprograms within a unit
10334 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10335
10336 @item ^-Os^/OPTIMIZE=SPACE^
10337 Optimize space usage (code and data) of resulting program.
10338 @end table
10339
10340 @noindent
10341 Higher optimization levels perform more global transformations on the
10342 program and apply more expensive analysis algorithms in order to generate
10343 faster and more compact code. The price in compilation time, and the
10344 resulting improvement in execution time,
10345 both depend on the particular application and the hardware environment.
10346 You should experiment to find the best level for your application.
10347
10348 Since the precise set of optimizations done at each level will vary from
10349 release to release (and sometime from target to target), it is best to think
10350 of the optimization settings in general terms.
10351 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10352 the GNU Compiler Collection (GCC)}, for details about
10353 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10354 individually enable or disable specific optimizations.
10355
10356 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10357 been tested extensively at all optimization levels. There are some bugs
10358 which appear only with optimization turned on, but there have also been
10359 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10360 level of optimization does not improve the reliability of the code
10361 generator, which in practice is highly reliable at all optimization
10362 levels.
10363
10364 Note regarding the use of @option{-O3}: The use of this optimization level
10365 is generally discouraged with GNAT, since it often results in larger
10366 executables which may run more slowly. See further discussion of this point
10367 in @ref{Inlining of Subprograms}.
10368
10369 @node Debugging Optimized Code
10370 @subsection Debugging Optimized Code
10371 @cindex Debugging optimized code
10372 @cindex Optimization and debugging
10373
10374 @noindent
10375 Although it is possible to do a reasonable amount of debugging at
10376 @ifclear vms
10377 nonzero optimization levels,
10378 the higher the level the more likely that
10379 @end ifclear
10380 @ifset vms
10381 @option{/OPTIMIZE} settings other than @code{NONE},
10382 such settings will make it more likely that
10383 @end ifset
10384 source-level constructs will have been eliminated by optimization.
10385 For example, if a loop is strength-reduced, the loop
10386 control variable may be completely eliminated and thus cannot be
10387 displayed in the debugger.
10388 This can only happen at @option{-O2} or @option{-O3}.
10389 Explicit temporary variables that you code might be eliminated at
10390 ^level^setting^ @option{-O1} or higher.
10391
10392 The use of the @option{^-g^/DEBUG^} switch,
10393 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10394 which is needed for source-level debugging,
10395 affects the size of the program executable on disk,
10396 and indeed the debugging information can be quite large.
10397 However, it has no effect on the generated code (and thus does not
10398 degrade performance)
10399
10400 Since the compiler generates debugging tables for a compilation unit before
10401 it performs optimizations, the optimizing transformations may invalidate some
10402 of the debugging data.  You therefore need to anticipate certain
10403 anomalous situations that may arise while debugging optimized code.
10404 These are the most common cases:
10405
10406 @enumerate
10407 @item
10408 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10409 commands show
10410 the PC bouncing back and forth in the code.  This may result from any of
10411 the following optimizations:
10412
10413 @itemize @bullet
10414 @item
10415 @i{Common subexpression elimination:} using a single instance of code for a
10416 quantity that the source computes several times.  As a result you
10417 may not be able to stop on what looks like a statement.
10418
10419 @item
10420 @i{Invariant code motion:} moving an expression that does not change within a
10421 loop, to the beginning of the loop.
10422
10423 @item
10424 @i{Instruction scheduling:} moving instructions so as to
10425 overlap loads and stores (typically) with other code, or in
10426 general to move computations of values closer to their uses. Often
10427 this causes you to pass an assignment statement without the assignment
10428 happening and then later bounce back to the statement when the
10429 value is actually needed.  Placing a breakpoint on a line of code
10430 and then stepping over it may, therefore, not always cause all the
10431 expected side-effects.
10432 @end itemize
10433
10434 @item
10435 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10436 two identical pieces of code are merged and the program counter suddenly
10437 jumps to a statement that is not supposed to be executed, simply because
10438 it (and the code following) translates to the same thing as the code
10439 that @emph{was} supposed to be executed.  This effect is typically seen in
10440 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10441 a @code{break} in a C @code{^switch^switch^} statement.
10442
10443 @item
10444 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10445 There are various reasons for this effect:
10446
10447 @itemize @bullet
10448 @item
10449 In a subprogram prologue, a parameter may not yet have been moved to its
10450 ``home''.
10451
10452 @item
10453 A variable may be dead, and its register re-used.  This is
10454 probably the most common cause.
10455
10456 @item
10457 As mentioned above, the assignment of a value to a variable may
10458 have been moved.
10459
10460 @item
10461 A variable may be eliminated entirely by value propagation or
10462 other means.  In this case, GCC may incorrectly generate debugging
10463 information for the variable
10464 @end itemize
10465
10466 @noindent
10467 In general, when an unexpected value appears for a local variable or parameter
10468 you should first ascertain if that value was actually computed by
10469 your program, as opposed to being incorrectly reported by the debugger.
10470 Record fields or
10471 array elements in an object designated by an access value
10472 are generally less of a problem, once you have ascertained that the access
10473 value is sensible.
10474 Typically, this means checking variables in the preceding code and in the
10475 calling subprogram to verify that the value observed is explainable from other
10476 values (one must apply the procedure recursively to those
10477 other values); or re-running the code and stopping a little earlier
10478 (perhaps before the call) and stepping to better see how the variable obtained
10479 the value in question; or continuing to step @emph{from} the point of the
10480 strange value to see if code motion had simply moved the variable's
10481 assignments later.
10482 @end enumerate
10483
10484 @noindent
10485 In light of such anomalies, a recommended technique is to use @option{-O0}
10486 early in the software development cycle, when extensive debugging capabilities
10487 are most needed, and then move to @option{-O1} and later @option{-O2} as
10488 the debugger becomes less critical.
10489 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10490 a release management issue.
10491 @ifclear vms
10492 Note that if you use @option{-g} you can then use the @command{strip} program
10493 on the resulting executable,
10494 which removes both debugging information and global symbols.
10495 @end ifclear
10496
10497 @node Inlining of Subprograms
10498 @subsection Inlining of Subprograms
10499
10500 @noindent
10501 A call to a subprogram in the current unit is inlined if all the
10502 following conditions are met:
10503
10504 @itemize @bullet
10505 @item
10506 The optimization level is at least @option{-O1}.
10507
10508 @item
10509 The called subprogram is suitable for inlining: It must be small enough
10510 and not contain something that @command{gcc} cannot support in inlined
10511 subprograms.
10512
10513 @item
10514 @cindex pragma Inline
10515 @findex Inline
10516 Any one of the following applies: @code{pragma Inline} is applied to the
10517 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10518 subprogram is local to the unit and called once from within it; the
10519 subprogram is small and optimization level @option{-O2} is specified;
10520 optimization level @option{-O3}) is specified.
10521 @end itemize
10522
10523 @noindent
10524 Calls to subprograms in @code{with}'ed units are normally not inlined.
10525 To achieve actual inlining (that is, replacement of the call by the code
10526 in the body of the subprogram), the following conditions must all be true.
10527
10528 @itemize @bullet
10529 @item
10530 The optimization level is at least @option{-O1}.
10531
10532 @item
10533 The called subprogram is suitable for inlining: It must be small enough
10534 and not contain something that @command{gcc} cannot support in inlined
10535 subprograms.
10536
10537 @item
10538 The call appears in a body (not in a package spec).
10539
10540 @item
10541 There is a @code{pragma Inline} for the subprogram.
10542
10543 @item
10544 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10545 @end itemize
10546
10547 Even if all these conditions are met, it may not be possible for
10548 the compiler to inline the call, due to the length of the body,
10549 or features in the body that make it impossible for the compiler
10550 to do the inlining.
10551
10552 Note that specifying the @option{-gnatn} switch causes additional
10553 compilation dependencies. Consider the following:
10554
10555 @smallexample @c ada
10556 @cartouche
10557 package R is
10558    procedure Q;
10559    pragma Inline (Q);
10560 end R;
10561 package body R is
10562    @dots{}
10563 end R;
10564
10565 with R;
10566 procedure Main is
10567 begin
10568    @dots{}
10569    R.Q;
10570 end Main;
10571 @end cartouche
10572 @end smallexample
10573
10574 @noindent
10575 With the default behavior (no @option{-gnatn} switch specified), the
10576 compilation of the @code{Main} procedure depends only on its own source,
10577 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10578 means that editing the body of @code{R} does not require recompiling
10579 @code{Main}.
10580
10581 On the other hand, the call @code{R.Q} is not inlined under these
10582 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10583 is compiled, the call will be inlined if the body of @code{Q} is small
10584 enough, but now @code{Main} depends on the body of @code{R} in
10585 @file{r.adb} as well as on the spec. This means that if this body is edited,
10586 the main program must be recompiled. Note that this extra dependency
10587 occurs whether or not the call is in fact inlined by @command{gcc}.
10588
10589 The use of front end inlining with @option{-gnatN} generates similar
10590 additional dependencies.
10591
10592 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10593 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10594 can be used to prevent
10595 all inlining. This switch overrides all other conditions and ensures
10596 that no inlining occurs. The extra dependences resulting from
10597 @option{-gnatn} will still be active, even if
10598 this switch is used to suppress the resulting inlining actions.
10599
10600 @cindex @option{-fno-inline-functions} (@command{gcc})
10601 Note: The @option{-fno-inline-functions} switch can be used to prevent
10602 automatic inlining of subprograms if @option{-O3} is used.
10603
10604 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10605 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10606 automatic inlining of small subprograms if @option{-O2} is used.
10607
10608 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10609 Note: The @option{-fno-inline-functions-called-once} switch
10610 can be used to prevent inlining of subprograms local to the unit
10611 and called once from within it if @option{-O1} is used.
10612
10613 Note regarding the use of @option{-O3}: There is no difference in inlining
10614 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10615 pragma @code{Inline} assuming the use of @option{-gnatn}
10616 or @option{-gnatN} (the switches that activate inlining). If you have used
10617 pragma @code{Inline} in appropriate cases, then it is usually much better
10618 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10619 in this case only has the effect of inlining subprograms you did not
10620 think should be inlined. We often find that the use of @option{-O3} slows
10621 down code by performing excessive inlining, leading to increased instruction
10622 cache pressure from the increased code size. So the bottom line here is
10623 that you should not automatically assume that @option{-O3} is better than
10624 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10625 it actually improves performance.
10626
10627 @node Vectorization of loops
10628 @subsection Vectorization of loops
10629 @cindex Optimization Switches
10630
10631 You can take advantage of the auto-vectorizer present in the @command{gcc}
10632 back end to vectorize loops with GNAT.  The corresponding command line switch
10633 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10634 and other aggressive optimizations helpful for vectorization also are enabled
10635 by default at this level, using @option{-O3} directly is recommended.
10636
10637 You also need to make sure that the target architecture features a supported
10638 SIMD instruction set.  For example, for the x86 architecture, you should at
10639 least specify @option{-msse2} to get significant vectorization (but you don't
10640 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10641 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10642
10643 The preferred loop form for vectorization is the @code{for} iteration scheme.
10644 Loops with a @code{while} iteration scheme can also be vectorized if they are
10645 very simple, but the vectorizer will quickly give up otherwise.  With either
10646 iteration scheme, the flow of control must be straight, in particular no
10647 @code{exit} statement may appear in the loop body.  The loop may however
10648 contain a single nested loop, if it can be vectorized when considered alone:
10649
10650 @smallexample @c ada
10651 @cartouche
10652    A : array (1..4, 1..4) of Long_Float;
10653    S : array (1..4) of Long_Float;
10654
10655    procedure Sum is
10656    begin
10657       for I in A'Range(1) loop
10658          for J in A'Range(2) loop
10659             S (I) := S (I) + A (I, J);
10660          end loop;
10661       end loop;
10662    end Sum;
10663 @end cartouche
10664 @end smallexample
10665
10666 The vectorizable operations depend on the targeted SIMD instruction set, but
10667 the adding and some of the multiplying operators are generally supported, as
10668 well as the logical operators for modular types.  Note that, in the former
10669 case, enabling overflow checks, for example with @option{-gnato}, totally
10670 disables vectorization.  The other checks are not supposed to have the same
10671 definitive effect, although compiling with @option{-gnatp} might well reveal
10672 cases where some checks do thwart vectorization.
10673
10674 Type conversions may also prevent vectorization if they involve semantics that
10675 are not directly supported by the code generator or the SIMD instruction set.
10676 A typical example is direct conversion from floating-point to integer types.
10677 The solution in this case is to use the following idiom:
10678
10679 @smallexample @c ada
10680    Integer (S'Truncation (F))
10681 @end smallexample
10682
10683 @noindent
10684 if @code{S} is the subtype of floating-point object @code{F}.
10685
10686 In most cases, the vectorizable loops are loops that iterate over arrays.
10687 All kinds of array types are supported, i.e. constrained array types with
10688 static bounds:
10689
10690 @smallexample @c ada
10691    type Array_Type is array (1 .. 4) of Long_Float;
10692 @end smallexample
10693
10694 @noindent
10695 constrained array types with dynamic bounds:
10696
10697 @smallexample @c ada
10698    type Array_Type is array (1 .. Q.N) of Long_Float;
10699
10700    type Array_Type is array (Q.K .. 4) of Long_Float;
10701
10702    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10703 @end smallexample
10704
10705 @noindent
10706 or unconstrained array types:
10707
10708 @smallexample @c ada
10709   type Array_Type is array (Positive range <>) of Long_Float;
10710 @end smallexample
10711
10712 @noindent
10713 The quality of the generated code decreases when the dynamic aspect of the
10714 array type increases, the worst code being generated for unconstrained array
10715 types.  This is so because, the less information the compiler has about the
10716 bounds of the array, the more fallback code it needs to generate in order to
10717 fix things up at run time.
10718
10719 You can obtain information about the vectorization performed by the compiler
10720 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10721 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10722 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10723
10724 @node Other Optimization Switches
10725 @subsection Other Optimization Switches
10726 @cindex Optimization Switches
10727
10728 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10729 @command{gcc} optimization switches are potentially usable. These switches
10730 have not been extensively tested with GNAT but can generally be expected
10731 to work. Examples of switches in this category are @option{-funroll-loops}
10732 and the various target-specific @option{-m} options (in particular, it has
10733 been observed that @option{-march=xxx} can significantly improve performance
10734 on appropriate machines). For full details of these switches, see
10735 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10736 the GNU Compiler Collection (GCC)}.
10737
10738 @node Optimization and Strict Aliasing
10739 @subsection Optimization and Strict Aliasing
10740 @cindex Aliasing
10741 @cindex Strict Aliasing
10742 @cindex No_Strict_Aliasing
10743
10744 @noindent
10745 The strong typing capabilities of Ada allow an optimizer to generate
10746 efficient code in situations where other languages would be forced to
10747 make worst case assumptions preventing such optimizations. Consider
10748 the following example:
10749
10750 @smallexample @c ada
10751 @cartouche
10752 procedure R is
10753    type Int1 is new Integer;
10754    type Int2 is new Integer;
10755    type Int1A is access Int1;
10756    type Int2A is access Int2;
10757    Int1V : Int1A;
10758    Int2V : Int2A;
10759    @dots{}
10760
10761 begin
10762    @dots{}
10763    for J in Data'Range loop
10764       if Data (J) = Int1V.all then
10765          Int2V.all := Int2V.all + 1;
10766       end if;
10767    end loop;
10768    @dots{}
10769 end R;
10770 @end cartouche
10771 @end smallexample
10772
10773 @noindent
10774 In this example, since the variable @code{Int1V} can only access objects
10775 of type @code{Int1}, and @code{Int2V} can only access objects of type
10776 @code{Int2}, there is no possibility that the assignment to
10777 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10778 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10779 for all iterations of the loop and avoid the extra memory reference
10780 required to dereference it each time through the loop.
10781
10782 This kind of optimization, called strict aliasing analysis, is
10783 triggered by specifying an optimization level of @option{-O2} or
10784 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10785 when access values are involved.
10786
10787 However, although this optimization is always correct in terms of
10788 the formal semantics of the Ada Reference Manual, difficulties can
10789 arise if features like @code{Unchecked_Conversion} are used to break
10790 the typing system. Consider the following complete program example:
10791
10792 @smallexample @c ada
10793 @cartouche
10794 package p1 is
10795    type int1 is new integer;
10796    type int2 is new integer;
10797    type a1 is access int1;
10798    type a2 is access int2;
10799 end p1;
10800
10801 with p1; use p1;
10802 package p2 is
10803    function to_a2 (Input : a1) return a2;
10804 end p2;
10805
10806 with Unchecked_Conversion;
10807 package body p2 is
10808    function to_a2 (Input : a1) return a2 is
10809       function to_a2u is
10810         new Unchecked_Conversion (a1, a2);
10811    begin
10812       return to_a2u (Input);
10813    end to_a2;
10814 end p2;
10815
10816 with p2; use p2;
10817 with p1; use p1;
10818 with Text_IO; use Text_IO;
10819 procedure m is
10820    v1 : a1 := new int1;
10821    v2 : a2 := to_a2 (v1);
10822 begin
10823    v1.all := 1;
10824    v2.all := 0;
10825    put_line (int1'image (v1.all));
10826 end;
10827 @end cartouche
10828 @end smallexample
10829
10830 @noindent
10831 This program prints out 0 in @option{-O0} or @option{-O1}
10832 mode, but it prints out 1 in @option{-O2} mode. That's
10833 because in strict aliasing mode, the compiler can and
10834 does assume that the assignment to @code{v2.all} could not
10835 affect the value of @code{v1.all}, since different types
10836 are involved.
10837
10838 This behavior is not a case of non-conformance with the standard, since
10839 the Ada RM specifies that an unchecked conversion where the resulting
10840 bit pattern is not a correct value of the target type can result in an
10841 abnormal value and attempting to reference an abnormal value makes the
10842 execution of a program erroneous.  That's the case here since the result
10843 does not point to an object of type @code{int2}.  This means that the
10844 effect is entirely unpredictable.
10845
10846 However, although that explanation may satisfy a language
10847 lawyer, in practice an applications programmer expects an
10848 unchecked conversion involving pointers to create true
10849 aliases and the behavior of printing 1 seems plain wrong.
10850 In this case, the strict aliasing optimization is unwelcome.
10851
10852 Indeed the compiler recognizes this possibility, and the
10853 unchecked conversion generates a warning:
10854
10855 @smallexample
10856 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10857 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10858 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10859 @end smallexample
10860
10861 @noindent
10862 Unfortunately the problem is recognized when compiling the body of
10863 package @code{p2}, but the actual "bad" code is generated while
10864 compiling the body of @code{m} and this latter compilation does not see
10865 the suspicious @code{Unchecked_Conversion}.
10866
10867 As implied by the warning message, there are approaches you can use to
10868 avoid the unwanted strict aliasing optimization in a case like this.
10869
10870 One possibility is to simply avoid the use of @option{-O2}, but
10871 that is a bit drastic, since it throws away a number of useful
10872 optimizations that do not involve strict aliasing assumptions.
10873
10874 A less drastic approach is to compile the program using the
10875 option @option{-fno-strict-aliasing}. Actually it is only the
10876 unit containing the dereferencing of the suspicious pointer
10877 that needs to be compiled. So in this case, if we compile
10878 unit @code{m} with this switch, then we get the expected
10879 value of zero printed. Analyzing which units might need
10880 the switch can be painful, so a more reasonable approach
10881 is to compile the entire program with options @option{-O2}
10882 and @option{-fno-strict-aliasing}. If the performance is
10883 satisfactory with this combination of options, then the
10884 advantage is that the entire issue of possible "wrong"
10885 optimization due to strict aliasing is avoided.
10886
10887 To avoid the use of compiler switches, the configuration
10888 pragma @code{No_Strict_Aliasing} with no parameters may be
10889 used to specify that for all access types, the strict
10890 aliasing optimization should be suppressed.
10891
10892 However, these approaches are still overkill, in that they causes
10893 all manipulations of all access values to be deoptimized. A more
10894 refined approach is to concentrate attention on the specific
10895 access type identified as problematic.
10896
10897 First, if a careful analysis of uses of the pointer shows
10898 that there are no possible problematic references, then
10899 the warning can be suppressed by bracketing the
10900 instantiation of @code{Unchecked_Conversion} to turn
10901 the warning off:
10902
10903 @smallexample @c ada
10904    pragma Warnings (Off);
10905    function to_a2u is
10906      new Unchecked_Conversion (a1, a2);
10907    pragma Warnings (On);
10908 @end smallexample
10909
10910 @noindent
10911 Of course that approach is not appropriate for this particular
10912 example, since indeed there is a problematic reference. In this
10913 case we can take one of two other approaches.
10914
10915 The first possibility is to move the instantiation of unchecked
10916 conversion to the unit in which the type is declared. In
10917 this example, we would move the instantiation of
10918 @code{Unchecked_Conversion} from the body of package
10919 @code{p2} to the spec of package @code{p1}. Now the
10920 warning disappears. That's because any use of the
10921 access type knows there is a suspicious unchecked
10922 conversion, and the strict aliasing optimization
10923 is automatically suppressed for the type.
10924
10925 If it is not practical to move the unchecked conversion to the same unit
10926 in which the destination access type is declared (perhaps because the
10927 source type is not visible in that unit), you may use pragma
10928 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10929 same declarative sequence as the declaration of the access type:
10930
10931 @smallexample @c ada
10932    type a2 is access int2;
10933    pragma No_Strict_Aliasing (a2);
10934 @end smallexample
10935
10936 @noindent
10937 Here again, the compiler now knows that the strict aliasing optimization
10938 should be suppressed for any reference to type @code{a2} and the
10939 expected behavior is obtained.
10940
10941 Finally, note that although the compiler can generate warnings for
10942 simple cases of unchecked conversions, there are tricker and more
10943 indirect ways of creating type incorrect aliases which the compiler
10944 cannot detect. Examples are the use of address overlays and unchecked
10945 conversions involving composite types containing access types as
10946 components. In such cases, no warnings are generated, but there can
10947 still be aliasing problems. One safe coding practice is to forbid the
10948 use of address clauses for type overlaying, and to allow unchecked
10949 conversion only for primitive types. This is not really a significant
10950 restriction since any possible desired effect can be achieved by
10951 unchecked conversion of access values.
10952
10953 The aliasing analysis done in strict aliasing mode can certainly
10954 have significant benefits. We have seen cases of large scale
10955 application code where the time is increased by up to 5% by turning
10956 this optimization off. If you have code that includes significant
10957 usage of unchecked conversion, you might want to just stick with
10958 @option{-O1} and avoid the entire issue. If you get adequate
10959 performance at this level of optimization level, that's probably
10960 the safest approach. If tests show that you really need higher
10961 levels of optimization, then you can experiment with @option{-O2}
10962 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10963 has on size and speed of the code. If you really need to use
10964 @option{-O2} with strict aliasing in effect, then you should
10965 review any uses of unchecked conversion of access types,
10966 particularly if you are getting the warnings described above.
10967
10968 @ifset vms
10969 @node Coverage Analysis
10970 @subsection Coverage Analysis
10971
10972 @noindent
10973 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10974 the user to determine the distribution of execution time across a program,
10975 @pxref{Profiling} for details of usage.
10976 @end ifset
10977
10978
10979 @node Text_IO Suggestions
10980 @section @code{Text_IO} Suggestions
10981 @cindex @code{Text_IO} and performance
10982
10983 @noindent
10984 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10985 the requirement of maintaining page and line counts. If performance
10986 is critical, a recommendation is to use @code{Stream_IO} instead of
10987 @code{Text_IO} for volume output, since this package has less overhead.
10988
10989 If @code{Text_IO} must be used, note that by default output to the standard
10990 output and standard error files is unbuffered (this provides better
10991 behavior when output statements are used for debugging, or if the
10992 progress of a program is observed by tracking the output, e.g. by
10993 using the Unix @command{tail -f} command to watch redirected output.
10994
10995 If you are generating large volumes of output with @code{Text_IO} and
10996 performance is an important factor, use a designated file instead
10997 of the standard output file, or change the standard output file to
10998 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10999
11000
11001
11002 @node Reducing Size of Ada Executables with gnatelim
11003 @section Reducing Size of Ada Executables with @code{gnatelim}
11004 @findex gnatelim
11005
11006 @noindent
11007 This section describes @command{gnatelim}, a tool which detects unused
11008 subprograms and helps the compiler to create a smaller executable for your
11009 program.
11010
11011 @menu
11012 * About gnatelim::
11013 * Running gnatelim::
11014 * Processing Precompiled Libraries::
11015 * Correcting the List of Eliminate Pragmas::
11016 * Making Your Executables Smaller::
11017 * Summary of the gnatelim Usage Cycle::
11018 @end menu
11019
11020 @node About gnatelim
11021 @subsection About @code{gnatelim}
11022
11023 @noindent
11024 When a program shares a set of Ada
11025 packages with other programs, it may happen that this program uses
11026 only a fraction of the subprograms defined in these packages. The code
11027 created for these unused subprograms increases the size of the executable.
11028
11029 @code{gnatelim} tracks unused subprograms in an Ada program and
11030 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11031 subprograms that are declared but never called. By placing the list of
11032 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11033 recompiling your program, you may decrease the size of its executable,
11034 because the compiler will not generate the code for 'eliminated' subprograms.
11035 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11036 information about this pragma.
11037
11038 @code{gnatelim} needs as its input data the name of the main subprogram.
11039
11040 If a set of source files is specified as @code{gnatelim} arguments, it
11041 treats these files as a complete set of sources making up a program to
11042 analyse, and analyses only these sources.
11043
11044 After a full successful build of the main subprogram @code{gnatelim} can be
11045 called without  specifying sources to analyse, in this case it computes
11046 the source closure of the main unit from the @file{ALI} files.
11047
11048 The following command will create the set of @file{ALI} files needed for
11049 @code{gnatelim}:
11050
11051 @smallexample
11052 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11053 @end smallexample
11054
11055 Note that @code{gnatelim} does not need object files.
11056
11057 @node Running gnatelim
11058 @subsection Running @code{gnatelim}
11059
11060 @noindent
11061 @code{gnatelim} has the following command-line interface:
11062
11063 @smallexample
11064 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11065 @end smallexample
11066
11067 @noindent
11068 @var{main_unit_name} should be a name of a source file that contains the main
11069 subprogram of a program (partition).
11070
11071 Each @var{filename} is the name (including the extension) of a source
11072 file to process. ``Wildcards'' are allowed, and
11073 the file name may contain path information.
11074
11075 @samp{@var{gcc_switches}} is a list of switches for
11076 @command{gcc}. They will be passed on to all compiler invocations made by
11077 @command{gnatelim} to generate the ASIS trees. Here you can provide
11078 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11079 use the @option{-gnatec} switch to set the configuration file,
11080 use the @option{-gnat05} switch if sources should be compiled in
11081 Ada 2005 mode etc.
11082
11083 @code{gnatelim} has the following switches:
11084
11085 @table @option
11086 @c !sort!
11087 @item ^-files^/FILES^=@var{filename}
11088 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11089 Take the argument source files from the specified file. This file should be an
11090 ordinary text file containing file names separated by spaces or
11091 line breaks. You can use this switch more than once in the same call to
11092 @command{gnatelim}. You also can combine this switch with
11093 an explicit list of files.
11094
11095 @item ^-log^/LOG^
11096 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11097 Duplicate all the output sent to @file{stderr} into a log file. The log file
11098 is named @file{gnatelim.log} and is located in the current directory.
11099
11100 @item ^-log^/LOGFILE^=@var{filename}
11101 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11102 Duplicate all the output sent to @file{stderr} into a specified log file.
11103
11104 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11105 @item ^--no-elim-dispatch^/NO_DISPATCH^
11106 Do not generate pragmas for dispatching operations.
11107
11108 @item ^--ignore^/IGNORE^=@var{filename}
11109 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11110 Do not generate pragmas for subprograms declared in the sources
11111 listed in a specified file
11112
11113 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11114 @item ^-o^/OUTPUT^=@var{report_file}
11115 Put @command{gnatelim} output into a specified file. If this file already exists,
11116 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11117 into @file{stderr}
11118
11119 @item ^-q^/QUIET^
11120 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11121 Quiet mode: by default @code{gnatelim} outputs to the standard error
11122 stream the number of program units left to be processed. This option turns
11123 this trace off.
11124
11125 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11126 @item ^-t^/TIME^
11127 Print out execution time.
11128
11129 @item ^-v^/VERBOSE^
11130 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11131 Verbose mode: @code{gnatelim} version information is printed as Ada
11132 comments to the standard output stream. Also, in addition to the number of
11133 program units left @code{gnatelim} will output the name of the current unit
11134 being processed.
11135
11136 @item ^-wq^/WARNINGS=QUIET^
11137 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11138 Quiet warning mode - some warnings are suppressed. In particular warnings that
11139 indicate that the analysed set of sources is incomplete to make up a
11140 partition and that some subprogram bodies are missing are not generated.
11141 @end table
11142
11143 @noindent
11144 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11145 driver (see @ref{The GNAT Driver and Project Files}).
11146
11147 @node Processing Precompiled Libraries
11148 @subsection Processing Precompiled Libraries
11149
11150 @noindent
11151 If some program uses a precompiled Ada library, it can be processed by
11152 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11153 Eliminate pragma for a subprogram if the body of this subprogram has not
11154 been analysed, this is a typical case for subprograms from precompiled
11155 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11156 warnings about missing source files and non-analyzed subprogram bodies
11157 that can be generated when processing precompiled Ada libraries.
11158
11159 @node Correcting the List of Eliminate Pragmas
11160 @subsection Correcting the List of Eliminate Pragmas
11161
11162 @noindent
11163 In some rare cases @code{gnatelim} may try to eliminate
11164 subprograms that are actually called in the program. In this case, the
11165 compiler will generate an error message of the form:
11166
11167 @smallexample
11168 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11169 @end smallexample
11170
11171 @noindent
11172 You will need to manually remove the wrong @code{Eliminate} pragmas from
11173 the configuration file indicated in the error message. You should recompile
11174 your program from scratch after that, because you need a consistent
11175 configuration file(s) during the entire compilation.
11176
11177 @node Making Your Executables Smaller
11178 @subsection Making Your Executables Smaller
11179
11180 @noindent
11181 In order to get a smaller executable for your program you now have to
11182 recompile the program completely with the configuration file containing
11183 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11184 @file{gnat.adc} file located in your current directory, just do:
11185
11186 @smallexample
11187 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11188 @end smallexample
11189
11190 @noindent
11191 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11192 recompile everything
11193 with the set of pragmas @code{Eliminate} that you have obtained with
11194 @command{gnatelim}).
11195
11196 Be aware that the set of @code{Eliminate} pragmas is specific to each
11197 program. It is not recommended to merge sets of @code{Eliminate}
11198 pragmas created for different programs in one configuration file.
11199
11200 @node Summary of the gnatelim Usage Cycle
11201 @subsection Summary of the @code{gnatelim} Usage Cycle
11202
11203 @noindent
11204 Here is a quick summary of the steps to be taken in order to reduce
11205 the size of your executables with @code{gnatelim}. You may use
11206 other GNAT options to control the optimization level,
11207 to produce the debugging information, to set search path, etc.
11208
11209 @enumerate
11210 @item
11211 Create a complete set of @file{ALI} files (if the program has not been
11212 built already)
11213
11214 @smallexample
11215 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11216 @end smallexample
11217
11218 @item
11219 Generate a list of @code{Eliminate} pragmas in default configuration file
11220 @file{gnat.adc} in the current directory
11221 @smallexample
11222 @ifset vms
11223 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11224 @end ifset
11225 @ifclear vms
11226 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11227 @end ifclear
11228 @end smallexample
11229
11230 @item
11231 Recompile the application
11232
11233 @smallexample
11234 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11235 @end smallexample
11236
11237 @end enumerate
11238
11239 @node Reducing Size of Executables with unused subprogram/data elimination
11240 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11241 @findex unused subprogram/data elimination
11242
11243 @noindent
11244 This section describes how you can eliminate unused subprograms and data from
11245 your executable just by setting options at compilation time.
11246
11247 @menu
11248 * About unused subprogram/data elimination::
11249 * Compilation options::
11250 * Example of unused subprogram/data elimination::
11251 @end menu
11252
11253 @node About unused subprogram/data elimination
11254 @subsection About unused subprogram/data elimination
11255
11256 @noindent
11257 By default, an executable contains all code and data of its composing objects
11258 (directly linked or coming from statically linked libraries), even data or code
11259 never used by this executable.
11260
11261 This feature will allow you to eliminate such unused code from your
11262 executable, making it smaller (in disk and in memory).
11263
11264 This functionality is available on all Linux platforms except for the IA-64
11265 architecture and on all cross platforms using the ELF binary file format.
11266 In both cases GNU binutils version 2.16 or later are required to enable it.
11267
11268 @node Compilation options
11269 @subsection Compilation options
11270
11271 @noindent
11272 The operation of eliminating the unused code and data from the final executable
11273 is directly performed by the linker.
11274
11275 In order to do this, it has to work with objects compiled with the
11276 following options:
11277 @option{-ffunction-sections} @option{-fdata-sections}.
11278 @cindex @option{-ffunction-sections} (@command{gcc})
11279 @cindex @option{-fdata-sections} (@command{gcc})
11280 These options are usable with C and Ada files.
11281 They will place respectively each
11282 function or data in a separate section in the resulting object file.
11283
11284 Once the objects and static libraries are created with these options, the
11285 linker can perform the dead code elimination. You can do this by setting
11286 the @option{-Wl,--gc-sections} option to gcc command or in the
11287 @option{-largs} section of @command{gnatmake}. This will perform a
11288 garbage collection of code and data never referenced.
11289
11290 If the linker performs a partial link (@option{-r} ld linker option), then you
11291 will need to provide one or several entry point using the
11292 @option{-e} / @option{--entry} ld option.
11293
11294 Note that objects compiled without the @option{-ffunction-sections} and
11295 @option{-fdata-sections} options can still be linked with the executable.
11296 However, no dead code elimination will be performed on those objects (they will
11297 be linked as is).
11298
11299 The GNAT static library is now compiled with -ffunction-sections and
11300 -fdata-sections on some platforms. This allows you to eliminate the unused code
11301 and data of the GNAT library from your executable.
11302
11303 @node Example of unused subprogram/data elimination
11304 @subsection Example of unused subprogram/data elimination
11305
11306 @noindent
11307 Here is a simple example:
11308
11309 @smallexample @c ada
11310 with Aux;
11311
11312 procedure Test is
11313 begin
11314    Aux.Used (10);
11315 end Test;
11316
11317 package Aux is
11318    Used_Data   : Integer;
11319    Unused_Data : Integer;
11320
11321    procedure Used   (Data : Integer);
11322    procedure Unused (Data : Integer);
11323 end Aux;
11324
11325 package body Aux is
11326    procedure Used (Data : Integer) is
11327    begin
11328       Used_Data := Data;
11329    end Used;
11330
11331    procedure Unused (Data : Integer) is
11332    begin
11333       Unused_Data := Data;
11334    end Unused;
11335 end Aux;
11336 @end smallexample
11337
11338 @noindent
11339 @code{Unused} and @code{Unused_Data} are never referenced in this code
11340 excerpt, and hence they may be safely removed from the final executable.
11341
11342 @smallexample
11343 $ gnatmake test
11344
11345 $ nm test | grep used
11346 020015f0 T aux__unused
11347 02005d88 B aux__unused_data
11348 020015cc T aux__used
11349 02005d84 B aux__used_data
11350
11351 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11352      -largs -Wl,--gc-sections
11353
11354 $ nm test | grep used
11355 02005350 T aux__used
11356 0201ffe0 B aux__used_data
11357 @end smallexample
11358
11359 @noindent
11360 It can be observed that the procedure @code{Unused} and the object
11361 @code{Unused_Data} are removed by the linker when using the
11362 appropriate options.
11363
11364 @c ********************************
11365 @node Renaming Files Using gnatchop
11366 @chapter Renaming Files Using @code{gnatchop}
11367 @findex gnatchop
11368
11369 @noindent
11370 This chapter discusses how to handle files with multiple units by using
11371 the @code{gnatchop} utility. This utility is also useful in renaming
11372 files to meet the standard GNAT default file naming conventions.
11373
11374 @menu
11375 * Handling Files with Multiple Units::
11376 * Operating gnatchop in Compilation Mode::
11377 * Command Line for gnatchop::
11378 * Switches for gnatchop::
11379 * Examples of gnatchop Usage::
11380 @end menu
11381
11382 @node Handling Files with Multiple Units
11383 @section Handling Files with Multiple Units
11384
11385 @noindent
11386 The basic compilation model of GNAT requires that a file submitted to the
11387 compiler have only one unit and there be a strict correspondence
11388 between the file name and the unit name.
11389
11390 The @code{gnatchop} utility allows both of these rules to be relaxed,
11391 allowing GNAT to process files which contain multiple compilation units
11392 and files with arbitrary file names. @code{gnatchop}
11393 reads the specified file and generates one or more output files,
11394 containing one unit per file. The unit and the file name correspond,
11395 as required by GNAT.
11396
11397 If you want to permanently restructure a set of ``foreign'' files so that
11398 they match the GNAT rules, and do the remaining development using the
11399 GNAT structure, you can simply use @command{gnatchop} once, generate the
11400 new set of files and work with them from that point on.
11401
11402 Alternatively, if you want to keep your files in the ``foreign'' format,
11403 perhaps to maintain compatibility with some other Ada compilation
11404 system, you can set up a procedure where you use @command{gnatchop} each
11405 time you compile, regarding the source files that it writes as temporary
11406 files that you throw away.
11407
11408 Note that if your file containing multiple units starts with a byte order
11409 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11410 will each start with a copy of this BOM, meaning that they can be compiled
11411 automatically in UTF-8 mode without needing to specify an explicit encoding.
11412
11413 @node Operating gnatchop in Compilation Mode
11414 @section Operating gnatchop in Compilation Mode
11415
11416 @noindent
11417 The basic function of @code{gnatchop} is to take a file with multiple units
11418 and split it into separate files. The boundary between files is reasonably
11419 clear, except for the issue of comments and pragmas. In default mode, the
11420 rule is that any pragmas between units belong to the previous unit, except
11421 that configuration pragmas always belong to the following unit. Any comments
11422 belong to the following unit. These rules
11423 almost always result in the right choice of
11424 the split point without needing to mark it explicitly and most users will
11425 find this default to be what they want. In this default mode it is incorrect to
11426 submit a file containing only configuration pragmas, or one that ends in
11427 configuration pragmas, to @code{gnatchop}.
11428
11429 However, using a special option to activate ``compilation mode'',
11430 @code{gnatchop}
11431 can perform another function, which is to provide exactly the semantics
11432 required by the RM for handling of configuration pragmas in a compilation.
11433 In the absence of configuration pragmas (at the main file level), this
11434 option has no effect, but it causes such configuration pragmas to be handled
11435 in a quite different manner.
11436
11437 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11438 only configuration pragmas, then this file is appended to the
11439 @file{gnat.adc} file in the current directory. This behavior provides
11440 the required behavior described in the RM for the actions to be taken
11441 on submitting such a file to the compiler, namely that these pragmas
11442 should apply to all subsequent compilations in the same compilation
11443 environment. Using GNAT, the current directory, possibly containing a
11444 @file{gnat.adc} file is the representation
11445 of a compilation environment. For more information on the
11446 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11447
11448 Second, in compilation mode, if @code{gnatchop}
11449 is given a file that starts with
11450 configuration pragmas, and contains one or more units, then these
11451 configuration pragmas are prepended to each of the chopped files. This
11452 behavior provides the required behavior described in the RM for the
11453 actions to be taken on compiling such a file, namely that the pragmas
11454 apply to all units in the compilation, but not to subsequently compiled
11455 units.
11456
11457 Finally, if configuration pragmas appear between units, they are appended
11458 to the previous unit. This results in the previous unit being illegal,
11459 since the compiler does not accept configuration pragmas that follow
11460 a unit. This provides the required RM behavior that forbids configuration
11461 pragmas other than those preceding the first compilation unit of a
11462 compilation.
11463
11464 For most purposes, @code{gnatchop} will be used in default mode. The
11465 compilation mode described above is used only if you need exactly
11466 accurate behavior with respect to compilations, and you have files
11467 that contain multiple units and configuration pragmas. In this
11468 circumstance the use of @code{gnatchop} with the compilation mode
11469 switch provides the required behavior, and is for example the mode
11470 in which GNAT processes the ACVC tests.
11471
11472 @node Command Line for gnatchop
11473 @section Command Line for @code{gnatchop}
11474
11475 @noindent
11476 The @code{gnatchop} command has the form:
11477
11478 @smallexample
11479 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11480 @c      @ovar{directory}
11481 @c Expanding @ovar macro inline (explanation in macro def comments)
11482 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11483       @r{[}@var{directory}@r{]}
11484 @end smallexample
11485
11486 @noindent
11487 The only required argument is the file name of the file to be chopped.
11488 There are no restrictions on the form of this file name. The file itself
11489 contains one or more Ada units, in normal GNAT format, concatenated
11490 together. As shown, more than one file may be presented to be chopped.
11491
11492 When run in default mode, @code{gnatchop} generates one output file in
11493 the current directory for each unit in each of the files.
11494
11495 @var{directory}, if specified, gives the name of the directory to which
11496 the output files will be written. If it is not specified, all files are
11497 written to the current directory.
11498
11499 For example, given a
11500 file called @file{hellofiles} containing
11501
11502 @smallexample @c ada
11503 @group
11504 @cartouche
11505 procedure hello;
11506
11507 with Text_IO; use Text_IO;
11508 procedure hello is
11509 begin
11510    Put_Line ("Hello");
11511 end hello;
11512 @end cartouche
11513 @end group
11514 @end smallexample
11515
11516 @noindent
11517 the command
11518
11519 @smallexample
11520 $ gnatchop ^hellofiles^HELLOFILES.^
11521 @end smallexample
11522
11523 @noindent
11524 generates two files in the current directory, one called
11525 @file{hello.ads} containing the single line that is the procedure spec,
11526 and the other called @file{hello.adb} containing the remaining text. The
11527 original file is not affected. The generated files can be compiled in
11528 the normal manner.
11529
11530 @noindent
11531 When gnatchop is invoked on a file that is empty or that contains only empty
11532 lines and/or comments, gnatchop will not fail, but will not produce any
11533 new sources.
11534
11535 For example, given a
11536 file called @file{toto.txt} containing
11537
11538 @smallexample @c ada
11539 @group
11540 @cartouche
11541 --  Just a comment
11542 @end cartouche
11543 @end group
11544 @end smallexample
11545
11546 @noindent
11547 the command
11548
11549 @smallexample
11550 $ gnatchop ^toto.txt^TOT.TXT^
11551 @end smallexample
11552
11553 @noindent
11554 will not produce any new file and will result in the following warnings:
11555
11556 @smallexample
11557 toto.txt:1:01: warning: empty file, contains no compilation units
11558 no compilation units found
11559 no source files written
11560 @end smallexample
11561
11562 @node Switches for gnatchop
11563 @section Switches for @code{gnatchop}
11564
11565 @noindent
11566 @command{gnatchop} recognizes the following switches:
11567
11568 @table @option
11569 @c !sort!
11570
11571 @item --version
11572 @cindex @option{--version} @command{gnatchop}
11573 Display Copyright and version, then exit disregarding all other options.
11574
11575 @item --help
11576 @cindex @option{--help} @command{gnatchop}
11577 If @option{--version} was not used, display usage, then exit disregarding
11578 all other options.
11579
11580 @item ^-c^/COMPILATION^
11581 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11582 Causes @code{gnatchop} to operate in compilation mode, in which
11583 configuration pragmas are handled according to strict RM rules. See
11584 previous section for a full description of this mode.
11585
11586 @ifclear vms
11587 @item -gnat@var{xxx}
11588 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11589 used to parse the given file. Not all @var{xxx} options make sense,
11590 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11591 process a source file that uses Latin-2 coding for identifiers.
11592 @end ifclear
11593
11594 @item ^-h^/HELP^
11595 Causes @code{gnatchop} to generate a brief help summary to the standard
11596 output file showing usage information.
11597
11598 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11599 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11600 Limit generated file names to the specified number @code{mm}
11601 of characters.
11602 This is useful if the
11603 resulting set of files is required to be interoperable with systems
11604 which limit the length of file names.
11605 @ifset vms
11606 If no value is given, or
11607 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11608 a default of 39, suitable for OpenVMS Alpha
11609 Systems, is assumed
11610 @end ifset
11611 @ifclear vms
11612 No space is allowed between the @option{-k} and the numeric value. The numeric
11613 value may be omitted in which case a default of @option{-k8},
11614 suitable for use
11615 with DOS-like file systems, is used. If no @option{-k} switch
11616 is present then
11617 there is no limit on the length of file names.
11618 @end ifclear
11619
11620 @item ^-p^/PRESERVE^
11621 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11622 Causes the file ^modification^creation^ time stamp of the input file to be
11623 preserved and used for the time stamp of the output file(s). This may be
11624 useful for preserving coherency of time stamps in an environment where
11625 @code{gnatchop} is used as part of a standard build process.
11626
11627 @item ^-q^/QUIET^
11628 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11629 Causes output of informational messages indicating the set of generated
11630 files to be suppressed. Warnings and error messages are unaffected.
11631
11632 @item ^-r^/REFERENCE^
11633 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11634 @findex Source_Reference
11635 Generate @code{Source_Reference} pragmas. Use this switch if the output
11636 files are regarded as temporary and development is to be done in terms
11637 of the original unchopped file. This switch causes
11638 @code{Source_Reference} pragmas to be inserted into each of the
11639 generated files to refers back to the original file name and line number.
11640 The result is that all error messages refer back to the original
11641 unchopped file.
11642 In addition, the debugging information placed into the object file (when
11643 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11644 specified)
11645 also refers back to this original file so that tools like profilers and
11646 debuggers will give information in terms of the original unchopped file.
11647
11648 If the original file to be chopped itself contains
11649 a @code{Source_Reference}
11650 pragma referencing a third file, then gnatchop respects
11651 this pragma, and the generated @code{Source_Reference} pragmas
11652 in the chopped file refer to the original file, with appropriate
11653 line numbers. This is particularly useful when @code{gnatchop}
11654 is used in conjunction with @code{gnatprep} to compile files that
11655 contain preprocessing statements and multiple units.
11656
11657 @item ^-v^/VERBOSE^
11658 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11659 Causes @code{gnatchop} to operate in verbose mode. The version
11660 number and copyright notice are output, as well as exact copies of
11661 the gnat1 commands spawned to obtain the chop control information.
11662
11663 @item ^-w^/OVERWRITE^
11664 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11665 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11666 fatal error if there is already a file with the same name as a
11667 file it would otherwise output, in other words if the files to be
11668 chopped contain duplicated units. This switch bypasses this
11669 check, and causes all but the last instance of such duplicated
11670 units to be skipped.
11671
11672 @ifclear vms
11673 @item --GCC=@var{xxxx}
11674 @cindex @option{--GCC=} (@code{gnatchop})
11675 Specify the path of the GNAT parser to be used. When this switch is used,
11676 no attempt is made to add the prefix to the GNAT parser executable.
11677 @end ifclear
11678 @end table
11679
11680 @node Examples of gnatchop Usage
11681 @section Examples of @code{gnatchop} Usage
11682
11683 @table @code
11684 @ifset vms
11685 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11686 @end ifset
11687 @ifclear vms
11688 @item gnatchop -w hello_s.ada prerelease/files
11689 @end ifclear
11690
11691 Chops the source file @file{hello_s.ada}. The output files will be
11692 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11693 overwriting any
11694 files with matching names in that directory (no files in the current
11695 directory are modified).
11696
11697 @item gnatchop ^archive^ARCHIVE.^
11698 Chops the source file @file{^archive^ARCHIVE.^}
11699 into the current directory. One
11700 useful application of @code{gnatchop} is in sending sets of sources
11701 around, for example in email messages. The required sources are simply
11702 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11703 command), and then
11704 @command{gnatchop} is used at the other end to reconstitute the original
11705 file names.
11706
11707 @item gnatchop file1 file2 file3 direc
11708 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11709 the resulting files in the directory @file{direc}. Note that if any units
11710 occur more than once anywhere within this set of files, an error message
11711 is generated, and no files are written. To override this check, use the
11712 @option{^-w^/OVERWRITE^} switch,
11713 in which case the last occurrence in the last file will
11714 be the one that is output, and earlier duplicate occurrences for a given
11715 unit will be skipped.
11716 @end table
11717
11718 @node Configuration Pragmas
11719 @chapter Configuration Pragmas
11720 @cindex Configuration pragmas
11721 @cindex Pragmas, configuration
11722
11723 @noindent
11724 Configuration pragmas include those pragmas described as
11725 such in the Ada Reference Manual, as well as
11726 implementation-dependent pragmas that are configuration pragmas.
11727 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11728 for details on these additional GNAT-specific configuration pragmas.
11729 Most notably, the pragma @code{Source_File_Name}, which allows
11730 specifying non-default names for source files, is a configuration
11731 pragma. The following is a complete list of configuration pragmas
11732 recognized by GNAT:
11733
11734 @smallexample
11735    Ada_83
11736    Ada_95
11737    Ada_05
11738    Ada_2005
11739    Ada_12
11740    Ada_2012
11741    Annotate
11742    Assertion_Policy
11743    Assume_No_Invalid_Values
11744    C_Pass_By_Copy
11745    Check_Name
11746    Check_Policy
11747    Compile_Time_Error
11748    Compile_Time_Warning
11749    Compiler_Unit
11750    Component_Alignment
11751    Convention_Identifier
11752    Debug_Policy
11753    Detect_Blocking
11754    Default_Storage_Pool
11755    Discard_Names
11756    Elaboration_Checks
11757    Eliminate
11758    Extend_System
11759    Extensions_Allowed
11760    External_Name_Casing
11761    Fast_Math
11762    Favor_Top_Level
11763    Float_Representation
11764    Implicit_Packing
11765    Initialize_Scalars
11766    Interrupt_State
11767    License
11768    Locking_Policy
11769    Long_Float
11770    No_Run_Time
11771    No_Strict_Aliasing
11772    Normalize_Scalars
11773    Optimize_Alignment
11774    Persistent_BSS
11775    Polling
11776    Priority_Specific_Dispatching
11777    Profile
11778    Profile_Warnings
11779    Propagate_Exceptions
11780    Queuing_Policy
11781    Ravenscar
11782    Restricted_Run_Time
11783    Restrictions
11784    Restrictions_Warnings
11785    Reviewable
11786    Short_Circuit_And_Or
11787    Source_File_Name
11788    Source_File_Name_Project
11789    Style_Checks
11790    Suppress
11791    Suppress_Exception_Locations
11792    Task_Dispatching_Policy
11793    Universal_Data
11794    Unsuppress
11795    Use_VADS_Size
11796    Validity_Checks
11797    Warnings
11798    Wide_Character_Encoding
11799
11800 @end smallexample
11801
11802 @menu
11803 * Handling of Configuration Pragmas::
11804 * The Configuration Pragmas Files::
11805 @end menu
11806
11807 @node Handling of Configuration Pragmas
11808 @section Handling of Configuration Pragmas
11809
11810 Configuration pragmas may either appear at the start of a compilation
11811 unit, or they can appear in a configuration pragma file to apply to
11812 all compilations performed in a given compilation environment.
11813
11814 GNAT also provides the @code{gnatchop} utility to provide an automatic
11815 way to handle configuration pragmas following the semantics for
11816 compilations (that is, files with multiple units), described in the RM.
11817 See @ref{Operating gnatchop in Compilation Mode} for details.
11818 However, for most purposes, it will be more convenient to edit the
11819 @file{gnat.adc} file that contains configuration pragmas directly,
11820 as described in the following section.
11821
11822 In the case of @code{Restrictions} pragmas appearing as configuration
11823 pragmas in individual compilation units, the exact handling depends on
11824 the type of restriction.
11825
11826 Restrictions that require partition-wide consistency (like
11827 @code{No_Tasking}) are
11828 recognized wherever they appear
11829 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11830 unit. This makes sense since the binder will in any case insist on seeing
11831 consistent use, so any unit not conforming to any restrictions that are
11832 anywhere in the partition will be rejected, and you might as well find
11833 that out at compile time rather than at bind time.
11834
11835 For restrictions that do not require partition-wide consistency, e.g.
11836 SPARK or No_Implementation_Attributes, in general the restriction applies
11837 only to the unit in which the pragma appears, and not to any other units.
11838
11839 The exception is No_Elaboration_Code which always applies to the entire
11840 object file from a compilation, i.e. to the body, spec, and all subunits.
11841 This restriction can be specified in a configuration pragma file, or it
11842 can be on the body and/or the spec (in eithe case it applies to all the
11843 relevant units). It can appear on a subunit only if it has previously
11844 appeared in the body of spec.
11845
11846 @node The Configuration Pragmas Files
11847 @section The Configuration Pragmas Files
11848 @cindex @file{gnat.adc}
11849
11850 @noindent
11851 In GNAT a compilation environment is defined by the current
11852 directory at the time that a compile command is given. This current
11853 directory is searched for a file whose name is @file{gnat.adc}. If
11854 this file is present, it is expected to contain one or more
11855 configuration pragmas that will be applied to the current compilation.
11856 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11857 considered.
11858
11859 Configuration pragmas may be entered into the @file{gnat.adc} file
11860 either by running @code{gnatchop} on a source file that consists only of
11861 configuration pragmas, or more conveniently  by
11862 direct editing of the @file{gnat.adc} file, which is a standard format
11863 source file.
11864
11865 In addition to @file{gnat.adc}, additional files containing configuration
11866 pragmas may be applied to the current compilation using the switch
11867 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11868 contains only configuration pragmas. These configuration pragmas are
11869 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11870 is present and switch @option{-gnatA} is not used).
11871
11872 It is allowed to specify several switches @option{-gnatec}, all of which
11873 will be taken into account.
11874
11875 If you are using project file, a separate mechanism is provided using
11876 project attributes, see @ref{Specifying Configuration Pragmas} for more
11877 details.
11878
11879 @ifset vms
11880 Of special interest to GNAT OpenVMS Alpha is the following
11881 configuration pragma:
11882
11883 @smallexample @c ada
11884 @cartouche
11885 pragma Extend_System (Aux_DEC);
11886 @end cartouche
11887 @end smallexample
11888
11889 @noindent
11890 In the presence of this pragma, GNAT adds to the definition of the
11891 predefined package SYSTEM all the additional types and subprograms that are
11892 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11893 @end ifset
11894
11895 @node Handling Arbitrary File Naming Conventions Using gnatname
11896 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11897 @cindex Arbitrary File Naming Conventions
11898
11899 @menu
11900 * Arbitrary File Naming Conventions::
11901 * Running gnatname::
11902 * Switches for gnatname::
11903 * Examples of gnatname Usage::
11904 @end menu
11905
11906 @node Arbitrary File Naming Conventions
11907 @section Arbitrary File Naming Conventions
11908
11909 @noindent
11910 The GNAT compiler must be able to know the source file name of a compilation
11911 unit.  When using the standard GNAT default file naming conventions
11912 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11913 does not need additional information.
11914
11915 @noindent
11916 When the source file names do not follow the standard GNAT default file naming
11917 conventions, the GNAT compiler must be given additional information through
11918 a configuration pragmas file (@pxref{Configuration Pragmas})
11919 or a project file.
11920 When the non-standard file naming conventions are well-defined,
11921 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11922 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11923 if the file naming conventions are irregular or arbitrary, a number
11924 of pragma @code{Source_File_Name} for individual compilation units
11925 must be defined.
11926 To help maintain the correspondence between compilation unit names and
11927 source file names within the compiler,
11928 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11929 set of files.
11930
11931 @node Running gnatname
11932 @section Running @code{gnatname}
11933
11934 @noindent
11935 The usual form of the @code{gnatname} command is
11936
11937 @smallexample
11938 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11939 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11940 @c Expanding @ovar macro inline (explanation in macro def comments)
11941 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11942       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11943 @end smallexample
11944
11945 @noindent
11946 All of the arguments are optional. If invoked without any argument,
11947 @code{gnatname} will display its usage.
11948
11949 @noindent
11950 When used with at least one naming pattern, @code{gnatname} will attempt to
11951 find all the compilation units in files that follow at least one of the
11952 naming patterns. To find these compilation units,
11953 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11954 regular files.
11955
11956 @noindent
11957 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11958 Each Naming Pattern is enclosed between double quotes (or single
11959 quotes on Windows).
11960 A Naming Pattern is a regular expression similar to the wildcard patterns
11961 used in file names by the Unix shells or the DOS prompt.
11962
11963 @noindent
11964 @code{gnatname} may be called with several sections of directories/patterns.
11965 Sections are separated by switch @code{--and}. In each section, there must be
11966 at least one pattern. If no directory is specified in a section, the current
11967 directory (or the project directory is @code{-P} is used) is implied.
11968 The options other that the directory switches and the patterns apply globally
11969 even if they are in different sections.
11970
11971 @noindent
11972 Examples of Naming Patterns are
11973
11974 @smallexample
11975    "*.[12].ada"
11976    "*.ad[sb]*"
11977    "body_*"    "spec_*"
11978 @end smallexample
11979
11980 @noindent
11981 For a more complete description of the syntax of Naming Patterns,
11982 see the second kind of regular expressions described in @file{g-regexp.ads}
11983 (the ``Glob'' regular expressions).
11984
11985 @noindent
11986 When invoked with no switch @code{-P}, @code{gnatname} will create a
11987 configuration pragmas file @file{gnat.adc} in the current working directory,
11988 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11989 unit.
11990
11991 @node Switches for gnatname
11992 @section Switches for @code{gnatname}
11993
11994 @noindent
11995 Switches for @code{gnatname} must precede any specified Naming Pattern.
11996
11997 @noindent
11998 You may specify any of the following switches to @code{gnatname}:
11999
12000 @table @option
12001 @c !sort!
12002
12003 @item --version
12004 @cindex @option{--version} @command{gnatname}
12005 Display Copyright and version, then exit disregarding all other options.
12006
12007 @item --help
12008 @cindex @option{--help} @command{gnatname}
12009 If @option{--version} was not used, display usage, then exit disregarding
12010 all other options.
12011
12012 @item --and
12013 Start another section of directories/patterns.
12014
12015 @item ^-c^/CONFIG_FILE=^@file{file}
12016 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12017 Create a configuration pragmas file @file{file} (instead of the default
12018 @file{gnat.adc}).
12019 @ifclear vms
12020 There may be zero, one or more space between @option{-c} and
12021 @file{file}.
12022 @end ifclear
12023 @file{file} may include directory information. @file{file} must be
12024 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12025 When a switch @option{^-c^/CONFIG_FILE^} is
12026 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12027
12028 @item ^-d^/SOURCE_DIRS=^@file{dir}
12029 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12030 Look for source files in directory @file{dir}. There may be zero, one or more
12031 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12032 When a switch @option{^-d^/SOURCE_DIRS^}
12033 is specified, the current working directory will not be searched for source
12034 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12035 or @option{^-D^/DIR_FILES^} switch.
12036 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12037 If @file{dir} is a relative path, it is relative to the directory of
12038 the configuration pragmas file specified with switch
12039 @option{^-c^/CONFIG_FILE^},
12040 or to the directory of the project file specified with switch
12041 @option{^-P^/PROJECT_FILE^} or,
12042 if neither switch @option{^-c^/CONFIG_FILE^}
12043 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12044 current working directory. The directory
12045 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12046
12047 @item ^-D^/DIRS_FILE=^@file{file}
12048 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12049 Look for source files in all directories listed in text file @file{file}.
12050 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12051 and @file{file}.
12052 @file{file} must be an existing, readable text file.
12053 Each nonempty line in @file{file} must be a directory.
12054 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12055 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12056 @file{file}.
12057
12058 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12059 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12060 Foreign patterns. Using this switch, it is possible to add sources of languages
12061 other than Ada to the list of sources of a project file.
12062 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12063 For example,
12064 @smallexample
12065 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12066 @end smallexample
12067 @noindent
12068 will look for Ada units in all files with the @file{.ada} extension,
12069 and will add to the list of file for project @file{prj.gpr} the C files
12070 with extension @file{.^c^C^}.
12071
12072 @item ^-h^/HELP^
12073 @cindex @option{^-h^/HELP^} (@code{gnatname})
12074 Output usage (help) information. The output is written to @file{stdout}.
12075
12076 @item ^-P^/PROJECT_FILE=^@file{proj}
12077 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12078 Create or update project file @file{proj}. There may be zero, one or more space
12079 between @option{-P} and @file{proj}. @file{proj} may include directory
12080 information. @file{proj} must be writable.
12081 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12082 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12083 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12084
12085 @item ^-v^/VERBOSE^
12086 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12087 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12088 This includes name of the file written, the name of the directories to search
12089 and, for each file in those directories whose name matches at least one of
12090 the Naming Patterns, an indication of whether the file contains a unit,
12091 and if so the name of the unit.
12092
12093 @item ^-v -v^/VERBOSE /VERBOSE^
12094 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12095 Very Verbose mode. In addition to the output produced in verbose mode,
12096 for each file in the searched directories whose name matches none of
12097 the Naming Patterns, an indication is given that there is no match.
12098
12099 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12100 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12101 Excluded patterns. Using this switch, it is possible to exclude some files
12102 that would match the name patterns. For example,
12103 @smallexample
12104 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12105 @end smallexample
12106 @noindent
12107 will look for Ada units in all files with the @file{.ada} extension,
12108 except those whose names end with @file{_nt.ada}.
12109
12110 @end table
12111
12112 @node Examples of gnatname Usage
12113 @section Examples of @code{gnatname} Usage
12114
12115 @ifset vms
12116 @smallexample
12117 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12118 @end smallexample
12119 @end ifset
12120
12121 @ifclear vms
12122 @smallexample
12123 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12124 @end smallexample
12125 @end ifclear
12126
12127 @noindent
12128 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12129 and be writable. In addition, the directory
12130 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12131 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12132
12133 @ifclear vms
12134 Note the optional spaces after @option{-c} and @option{-d}.
12135 @end ifclear
12136
12137 @smallexample
12138 @ifclear vms
12139 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12140   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12141 @end ifclear
12142 @ifset vms
12143 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12144   /EXCLUDED_PATTERN=*_nt_body.ada
12145   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12146   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12147 @end ifset
12148 @end smallexample
12149
12150 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12151 even in conjunction with one or several switches
12152 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12153 are used in this example.
12154
12155 @c *****************************************
12156 @c * G N A T  P r o j e c t  M a n a g e r *
12157 @c *****************************************
12158
12159 @c ------ macros for projects.texi
12160 @c These macros are needed when building the gprbuild documentation, but
12161 @c should have no effect in the gnat user's guide
12162
12163 @macro CODESAMPLE{TXT}
12164 @smallexample
12165 @group
12166 \TXT\
12167 @end group
12168 @end smallexample
12169 @end macro
12170
12171 @macro PROJECTFILE{TXT}
12172 @CODESAMPLE{\TXT\}
12173 @end macro
12174
12175 @c simulates a newline when in a @CODESAMPLE
12176 @macro NL{}
12177 @end macro
12178
12179 @macro TIP{TXT}
12180 @quotation
12181 @noindent
12182 \TXT\
12183 @end quotation
12184 @end macro
12185
12186 @macro TIPHTML{TXT}
12187 \TXT\
12188 @end macro
12189
12190 @macro IMPORTANT{TXT}
12191 @quotation
12192 @noindent
12193 \TXT\
12194 @end quotation
12195
12196 @end macro
12197
12198 @macro NOTE{TXT}
12199 @quotation
12200 @noindent
12201 \TXT\
12202 @end quotation
12203 @end macro
12204
12205 @include projects.texi
12206
12207 @c *****************************************
12208 @c * Cross-referencing tools
12209 @c *****************************************
12210
12211 @node The Cross-Referencing Tools gnatxref and gnatfind
12212 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12213 @findex gnatxref
12214 @findex gnatfind
12215
12216 @noindent
12217 The compiler generates cross-referencing information (unless
12218 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12219 This information indicates where in the source each entity is declared and
12220 referenced. Note that entities in package Standard are not included, but
12221 entities in all other predefined units are included in the output.
12222
12223 Before using any of these two tools, you need to compile successfully your
12224 application, so that GNAT gets a chance to generate the cross-referencing
12225 information.
12226
12227 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12228 information to provide the user with the capability to easily locate the
12229 declaration and references to an entity. These tools are quite similar,
12230 the difference being that @code{gnatfind} is intended for locating
12231 definitions and/or references to a specified entity or entities, whereas
12232 @code{gnatxref} is oriented to generating a full report of all
12233 cross-references.
12234
12235 To use these tools, you must not compile your application using the
12236 @option{-gnatx} switch on the @command{gnatmake} command line
12237 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12238 information will not be generated.
12239
12240 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12241 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12242
12243 @menu
12244 * Switches for gnatxref::
12245 * Switches for gnatfind::
12246 * Project Files for gnatxref and gnatfind::
12247 * Regular Expressions in gnatfind and gnatxref::
12248 * Examples of gnatxref Usage::
12249 * Examples of gnatfind Usage::
12250 @end menu
12251
12252 @node Switches for gnatxref
12253 @section @code{gnatxref} Switches
12254
12255 @noindent
12256 The command invocation for @code{gnatxref} is:
12257 @smallexample
12258 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12259 @c Expanding @ovar macro inline (explanation in macro def comments)
12260 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12261 @end smallexample
12262
12263 @noindent
12264 where
12265
12266 @table @var
12267 @item sourcefile1
12268 @itemx sourcefile2
12269 identifies the source files for which a report is to be generated. The
12270 ``with''ed units will be processed too. You must provide at least one file.
12271
12272 These file names are considered to be regular expressions, so for instance
12273 specifying @file{source*.adb} is the same as giving every file in the current
12274 directory whose name starts with @file{source} and whose extension is
12275 @file{adb}.
12276
12277 You shouldn't specify any directory name, just base names. @command{gnatxref}
12278 and @command{gnatfind} will be able to locate these files by themselves using
12279 the source path. If you specify directories, no result is produced.
12280
12281 @end table
12282
12283 @noindent
12284 The switches can be:
12285 @table @option
12286 @c !sort!
12287 @item --version
12288 @cindex @option{--version} @command{gnatxref}
12289 Display Copyright and version, then exit disregarding all other options.
12290
12291 @item --help
12292 @cindex @option{--help} @command{gnatxref}
12293 If @option{--version} was not used, display usage, then exit disregarding
12294 all other options.
12295
12296 @item ^-a^/ALL_FILES^
12297 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12298 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12299 the read-only files found in the library search path. Otherwise, these files
12300 will be ignored. This option can be used to protect Gnat sources or your own
12301 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12302 much faster, and their output much smaller. Read-only here refers to access
12303 or permissions status in the file system for the current user.
12304
12305 @item -aIDIR
12306 @cindex @option{-aIDIR} (@command{gnatxref})
12307 When looking for source files also look in directory DIR. The order in which
12308 source file search is undertaken is the same as for @command{gnatmake}.
12309
12310 @item -aODIR
12311 @cindex @option{-aODIR} (@command{gnatxref})
12312 When searching for library and object files, look in directory
12313 DIR. The order in which library files are searched is the same as for
12314 @command{gnatmake}.
12315
12316 @item -nostdinc
12317 @cindex @option{-nostdinc} (@command{gnatxref})
12318 Do not look for sources in the system default directory.
12319
12320 @item -nostdlib
12321 @cindex @option{-nostdlib} (@command{gnatxref})
12322 Do not look for library files in the system default directory.
12323
12324 @item --ext=@var{extension}
12325 @cindex @option{--ext} (@command{gnatxref})
12326 Specify an alternate ali file extension. The default is @code{ali} and other
12327 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12328 switch. Note that if this switch overrides the default, which means that only
12329 the new extension will be considered.
12330
12331 @item --RTS=@var{rts-path}
12332 @cindex @option{--RTS} (@command{gnatxref})
12333 Specifies the default location of the runtime library. Same meaning as the
12334 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12335
12336 @item ^-d^/DERIVED_TYPES^
12337 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12338 If this switch is set @code{gnatxref} will output the parent type
12339 reference for each matching derived types.
12340
12341 @item ^-f^/FULL_PATHNAME^
12342 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12343 If this switch is set, the output file names will be preceded by their
12344 directory (if the file was found in the search path). If this switch is
12345 not set, the directory will not be printed.
12346
12347 @item ^-g^/IGNORE_LOCALS^
12348 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12349 If this switch is set, information is output only for library-level
12350 entities, ignoring local entities. The use of this switch may accelerate
12351 @code{gnatfind} and @code{gnatxref}.
12352
12353 @item -IDIR
12354 @cindex @option{-IDIR} (@command{gnatxref})
12355 Equivalent to @samp{-aODIR -aIDIR}.
12356
12357 @item -pFILE
12358 @cindex @option{-pFILE} (@command{gnatxref})
12359 Specify a project file to use @xref{GNAT Project Manager}.
12360 If you need to use the @file{.gpr}
12361 project files, you should use gnatxref through the GNAT driver
12362 (@command{gnat xref -Pproject}).
12363
12364 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12365 project file in the current directory.
12366
12367 If a project file is either specified or found by the tools, then the content
12368 of the source directory and object directory lines are added as if they
12369 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12370 and @samp{^-aO^OBJECT_SEARCH^}.
12371 @item ^-u^/UNUSED^
12372 Output only unused symbols. This may be really useful if you give your
12373 main compilation unit on the command line, as @code{gnatxref} will then
12374 display every unused entity and 'with'ed package.
12375
12376 @ifclear vms
12377 @item -v
12378 Instead of producing the default output, @code{gnatxref} will generate a
12379 @file{tags} file that can be used by vi. For examples how to use this
12380 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12381 to the standard output, thus you will have to redirect it to a file.
12382 @end ifclear
12383
12384 @end table
12385
12386 @noindent
12387 All these switches may be in any order on the command line, and may even
12388 appear after the file names. They need not be separated by spaces, thus
12389 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12390 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12391
12392 @node Switches for gnatfind
12393 @section @code{gnatfind} Switches
12394
12395 @noindent
12396 The command line for @code{gnatfind} is:
12397
12398 @smallexample
12399 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12400 @c       @r{[}@var{file1} @var{file2} @dots{}]
12401 @c Expanding @ovar macro inline (explanation in macro def comments)
12402 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12403       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12404 @end smallexample
12405
12406 @noindent
12407 where
12408
12409 @table @var
12410 @item pattern
12411 An entity will be output only if it matches the regular expression found
12412 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12413
12414 Omitting the pattern is equivalent to specifying @samp{*}, which
12415 will match any entity. Note that if you do not provide a pattern, you
12416 have to provide both a sourcefile and a line.
12417
12418 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12419 for matching purposes. At the current time there is no support for
12420 8-bit codes other than Latin-1, or for wide characters in identifiers.
12421
12422 @item sourcefile
12423 @code{gnatfind} will look for references, bodies or declarations
12424 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12425 and column @var{column}. See @ref{Examples of gnatfind Usage}
12426 for syntax examples.
12427
12428 @item line
12429 is a decimal integer identifying the line number containing
12430 the reference to the entity (or entities) to be located.
12431
12432 @item column
12433 is a decimal integer identifying the exact location on the
12434 line of the first character of the identifier for the
12435 entity reference. Columns are numbered from 1.
12436
12437 @item file1 file2 @dots{}
12438 The search will be restricted to these source files. If none are given, then
12439 the search will be done for every library file in the search path.
12440 These file must appear only after the pattern or sourcefile.
12441
12442 These file names are considered to be regular expressions, so for instance
12443 specifying @file{source*.adb} is the same as giving every file in the current
12444 directory whose name starts with @file{source} and whose extension is
12445 @file{adb}.
12446
12447 The location of the spec of the entity will always be displayed, even if it
12448 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12449 occurrences of the entity in the separate units of the ones given on the
12450 command line will also be displayed.
12451
12452 Note that if you specify at least one file in this part, @code{gnatfind} may
12453 sometimes not be able to find the body of the subprograms.
12454
12455 @end table
12456
12457 @noindent
12458 At least one of 'sourcefile' or 'pattern' has to be present on
12459 the command line.
12460
12461 The following switches are available:
12462 @table @option
12463 @c !sort!
12464
12465 @cindex @option{--version} @command{gnatfind}
12466 Display Copyright and version, then exit disregarding all other options.
12467
12468 @item --help
12469 @cindex @option{--help} @command{gnatfind}
12470 If @option{--version} was not used, display usage, then exit disregarding
12471 all other options.
12472
12473 @item ^-a^/ALL_FILES^
12474 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12475 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12476 the read-only files found in the library search path. Otherwise, these files
12477 will be ignored. This option can be used to protect Gnat sources or your own
12478 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12479 much faster, and their output much smaller. Read-only here refers to access
12480 or permission status in the file system for the current user.
12481
12482 @item -aIDIR
12483 @cindex @option{-aIDIR} (@command{gnatfind})
12484 When looking for source files also look in directory DIR. The order in which
12485 source file search is undertaken is the same as for @command{gnatmake}.
12486
12487 @item -aODIR
12488 @cindex @option{-aODIR} (@command{gnatfind})
12489 When searching for library and object files, look in directory
12490 DIR. The order in which library files are searched is the same as for
12491 @command{gnatmake}.
12492
12493 @item -nostdinc
12494 @cindex @option{-nostdinc} (@command{gnatfind})
12495 Do not look for sources in the system default directory.
12496
12497 @item -nostdlib
12498 @cindex @option{-nostdlib} (@command{gnatfind})
12499 Do not look for library files in the system default directory.
12500
12501 @item --ext=@var{extension}
12502 @cindex @option{--ext} (@command{gnatfind})
12503 Specify an alternate ali file extension. The default is @code{ali} and other
12504 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12505 switch. Note that if this switch overrides the default, which means that only
12506 the new extension will be considered.
12507
12508 @item --RTS=@var{rts-path}
12509 @cindex @option{--RTS} (@command{gnatfind})
12510 Specifies the default location of the runtime library. Same meaning as the
12511 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12512
12513 @item ^-d^/DERIVED_TYPE_INFORMATION^
12514 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12515 If this switch is set, then @code{gnatfind} will output the parent type
12516 reference for each matching derived types.
12517
12518 @item ^-e^/EXPRESSIONS^
12519 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12520 By default, @code{gnatfind} accept the simple regular expression set for
12521 @samp{pattern}. If this switch is set, then the pattern will be
12522 considered as full Unix-style regular expression.
12523
12524 @item ^-f^/FULL_PATHNAME^
12525 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12526 If this switch is set, the output file names will be preceded by their
12527 directory (if the file was found in the search path). If this switch is
12528 not set, the directory will not be printed.
12529
12530 @item ^-g^/IGNORE_LOCALS^
12531 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12532 If this switch is set, information is output only for library-level
12533 entities, ignoring local entities. The use of this switch may accelerate
12534 @code{gnatfind} and @code{gnatxref}.
12535
12536 @item -IDIR
12537 @cindex @option{-IDIR} (@command{gnatfind})
12538 Equivalent to @samp{-aODIR -aIDIR}.
12539
12540 @item -pFILE
12541 @cindex @option{-pFILE} (@command{gnatfind})
12542 Specify a project file (@pxref{GNAT Project Manager}) to use.
12543 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12544 project file in the current directory.
12545
12546 If a project file is either specified or found by the tools, then the content
12547 of the source directory and object directory lines are added as if they
12548 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12549 @samp{^-aO^/OBJECT_SEARCH^}.
12550
12551 @item ^-r^/REFERENCES^
12552 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12553 By default, @code{gnatfind} will output only the information about the
12554 declaration, body or type completion of the entities. If this switch is
12555 set, the @code{gnatfind} will locate every reference to the entities in
12556 the files specified on the command line (or in every file in the search
12557 path if no file is given on the command line).
12558
12559 @item ^-s^/PRINT_LINES^
12560 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12561 If this switch is set, then @code{gnatfind} will output the content
12562 of the Ada source file lines were the entity was found.
12563
12564 @item ^-t^/TYPE_HIERARCHY^
12565 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12566 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12567 the specified type. It act like -d option but recursively from parent
12568 type to parent type. When this switch is set it is not possible to
12569 specify more than one file.
12570
12571 @end table
12572
12573 @noindent
12574 All these switches may be in any order on the command line, and may even
12575 appear after the file names. They need not be separated by spaces, thus
12576 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12577 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12578
12579 As stated previously, gnatfind will search in every directory in the
12580 search path. You can force it to look only in the current directory if
12581 you specify @code{*} at the end of the command line.
12582
12583 @node Project Files for gnatxref and gnatfind
12584 @section Project Files for @command{gnatxref} and @command{gnatfind}
12585
12586 @noindent
12587 Project files allow a programmer to specify how to compile its
12588 application, where to find sources, etc.  These files are used
12589 @ifclear vms
12590 primarily by GPS, but they can also be used
12591 @end ifclear
12592 by the two tools
12593 @code{gnatxref} and @code{gnatfind}.
12594
12595 A project file name must end with @file{.gpr}. If a single one is
12596 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12597 extract the information from it. If multiple project files are found, none of
12598 them is read, and you have to use the @samp{-p} switch to specify the one
12599 you want to use.
12600
12601 The following lines can be included, even though most of them have default
12602 values which can be used in most cases.
12603 The lines can be entered in any order in the file.
12604 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12605 each line. If you have multiple instances, only the last one is taken into
12606 account.
12607
12608 @table @code
12609 @item src_dir=DIR
12610 [default: @code{"^./^[]^"}]
12611 specifies a directory where to look for source files. Multiple @code{src_dir}
12612 lines can be specified and they will be searched in the order they
12613 are specified.
12614
12615 @item obj_dir=DIR
12616 [default: @code{"^./^[]^"}]
12617 specifies a directory where to look for object and library files. Multiple
12618 @code{obj_dir} lines can be specified, and they will be searched in the order
12619 they are specified
12620
12621 @item comp_opt=SWITCHES
12622 [default: @code{""}]
12623 creates a variable which can be referred to subsequently by using
12624 the @code{$@{comp_opt@}} notation. This is intended to store the default
12625 switches given to @command{gnatmake} and @command{gcc}.
12626
12627 @item bind_opt=SWITCHES
12628 [default: @code{""}]
12629 creates a variable which can be referred to subsequently by using
12630 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12631 switches given to @command{gnatbind}.
12632
12633 @item link_opt=SWITCHES
12634 [default: @code{""}]
12635 creates a variable which can be referred to subsequently by using
12636 the @samp{$@{link_opt@}} notation. This is intended to store the default
12637 switches given to @command{gnatlink}.
12638
12639 @item main=EXECUTABLE
12640 [default: @code{""}]
12641 specifies the name of the executable for the application. This variable can
12642 be referred to in the following lines by using the @samp{$@{main@}} notation.
12643
12644 @ifset vms
12645 @item comp_cmd=COMMAND
12646 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12647 @end ifset
12648 @ifclear vms
12649 @item comp_cmd=COMMAND
12650 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12651 @end ifclear
12652 specifies the command used to compile a single file in the application.
12653
12654 @ifset vms
12655 @item make_cmd=COMMAND
12656 [default: @code{"GNAT MAKE $@{main@}
12657 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12658 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12659 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12660 @end ifset
12661 @ifclear vms
12662 @item make_cmd=COMMAND
12663 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12664 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12665 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12666 @end ifclear
12667 specifies the command used to recompile the whole application.
12668
12669 @item run_cmd=COMMAND
12670 [default: @code{"$@{main@}"}]
12671 specifies the command used to run the application.
12672
12673 @item debug_cmd=COMMAND
12674 [default: @code{"gdb $@{main@}"}]
12675 specifies the command used to debug the application
12676
12677 @end table
12678
12679 @noindent
12680 @command{gnatxref} and @command{gnatfind} only take into account the
12681 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12682
12683 @node Regular Expressions in gnatfind and gnatxref
12684 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12685
12686 @noindent
12687 As specified in the section about @command{gnatfind}, the pattern can be a
12688 regular expression. Actually, there are to set of regular expressions
12689 which are recognized by the program:
12690
12691 @table @code
12692 @item globbing patterns
12693 These are the most usual regular expression. They are the same that you
12694 generally used in a Unix shell command line, or in a DOS session.
12695
12696 Here is a more formal grammar:
12697 @smallexample
12698 @group
12699 @iftex
12700 @leftskip=.5cm
12701 @end iftex
12702 regexp ::= term
12703 term   ::= elmt            -- matches elmt
12704 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12705 term   ::= *               -- any string of 0 or more characters
12706 term   ::= ?               -- matches any character
12707 term   ::= [char @{char@}]   -- matches any character listed
12708 term   ::= [char - char]   -- matches any character in range
12709 @end group
12710 @end smallexample
12711
12712 @item full regular expression
12713 The second set of regular expressions is much more powerful. This is the
12714 type of regular expressions recognized by utilities such a @file{grep}.
12715
12716 The following is the form of a regular expression, expressed in Ada
12717 reference manual style BNF is as follows
12718
12719 @smallexample
12720 @iftex
12721 @leftskip=.5cm
12722 @end iftex
12723 @group
12724 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12725
12726 term ::= item @{item@}       -- concatenation (item then item)
12727
12728 item ::= elmt              -- match elmt
12729 item ::= elmt *            -- zero or more elmt's
12730 item ::= elmt +            -- one or more elmt's
12731 item ::= elmt ?            -- matches elmt or nothing
12732 @end group
12733 @group
12734 elmt ::= nschar            -- matches given character
12735 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12736 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12737 elmt ::= [char - char]     -- matches chars in given range
12738 elmt ::= \ char            -- matches given character
12739 elmt ::= .                 -- matches any single character
12740 elmt ::= ( regexp )        -- parens used for grouping
12741
12742 char ::= any character, including special characters
12743 nschar ::= any character except ()[].*+?^^^
12744 @end group
12745 @end smallexample
12746
12747 Following are a few examples:
12748
12749 @table @samp
12750 @item abcde|fghi
12751 will match any of the two strings @samp{abcde} and @samp{fghi},
12752
12753 @item abc*d
12754 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12755 @samp{abcccd}, and so on,
12756
12757 @item [a-z]+
12758 will match any string which has only lowercase characters in it (and at
12759 least one character.
12760
12761 @end table
12762 @end table
12763
12764 @node Examples of gnatxref Usage
12765 @section Examples of @code{gnatxref} Usage
12766
12767 @subsection General Usage
12768
12769 @noindent
12770 For the following examples, we will consider the following units:
12771
12772 @smallexample @c ada
12773 @group
12774 @cartouche
12775 main.ads:
12776 1: with Bar;
12777 2: package Main is
12778 3:     procedure Foo (B : in Integer);
12779 4:     C : Integer;
12780 5: private
12781 6:     D : Integer;
12782 7: end Main;
12783
12784 main.adb:
12785 1: package body Main is
12786 2:     procedure Foo (B : in Integer) is
12787 3:     begin
12788 4:        C := B;
12789 5:        D := B;
12790 6:        Bar.Print (B);
12791 7:        Bar.Print (C);
12792 8:     end Foo;
12793 9: end Main;
12794
12795 bar.ads:
12796 1: package Bar is
12797 2:     procedure Print (B : Integer);
12798 3: end bar;
12799 @end cartouche
12800 @end group
12801 @end smallexample
12802
12803 @table @code
12804
12805 @noindent
12806 The first thing to do is to recompile your application (for instance, in
12807 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12808 the cross-referencing information.
12809 You can then issue any of the following commands:
12810
12811 @item gnatxref main.adb
12812 @code{gnatxref} generates cross-reference information for main.adb
12813 and every unit 'with'ed by main.adb.
12814
12815 The output would be:
12816 @smallexample
12817 @iftex
12818 @leftskip=0cm
12819 @end iftex
12820 B                                                      Type: Integer
12821   Decl: bar.ads           2:22
12822 B                                                      Type: Integer
12823   Decl: main.ads          3:20
12824   Body: main.adb          2:20
12825   Ref:  main.adb          4:13     5:13     6:19
12826 Bar                                                    Type: Unit
12827   Decl: bar.ads           1:9
12828   Ref:  main.adb          6:8      7:8
12829        main.ads           1:6
12830 C                                                      Type: Integer
12831   Decl: main.ads          4:5
12832   Modi: main.adb          4:8
12833   Ref:  main.adb          7:19
12834 D                                                      Type: Integer
12835   Decl: main.ads          6:5
12836   Modi: main.adb          5:8
12837 Foo                                                    Type: Unit
12838   Decl: main.ads          3:15
12839   Body: main.adb          2:15
12840 Main                                                    Type: Unit
12841   Decl: main.ads          2:9
12842   Body: main.adb          1:14
12843 Print                                                   Type: Unit
12844   Decl: bar.ads           2:15
12845   Ref:  main.adb          6:12     7:12
12846 @end smallexample
12847
12848 @noindent
12849 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12850 its body is in main.adb, line 1, column 14 and is not referenced any where.
12851
12852 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12853 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12854
12855 @item gnatxref package1.adb package2.ads
12856 @code{gnatxref} will generates cross-reference information for
12857 package1.adb, package2.ads and any other package 'with'ed by any
12858 of these.
12859
12860 @end table
12861
12862 @ifclear vms
12863 @subsection Using gnatxref with vi
12864
12865 @code{gnatxref} can generate a tags file output, which can be used
12866 directly from @command{vi}. Note that the standard version of @command{vi}
12867 will not work properly with overloaded symbols. Consider using another
12868 free implementation of @command{vi}, such as @command{vim}.
12869
12870 @smallexample
12871 $ gnatxref -v gnatfind.adb > tags
12872 @end smallexample
12873
12874 @noindent
12875 will generate the tags file for @code{gnatfind} itself (if the sources
12876 are in the search path!).
12877
12878 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12879 (replacing @var{entity} by whatever you are looking for), and vi will
12880 display a new file with the corresponding declaration of entity.
12881 @end ifclear
12882
12883 @node Examples of gnatfind Usage
12884 @section Examples of @code{gnatfind} Usage
12885
12886 @table @code
12887
12888 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12889 Find declarations for all entities xyz referenced at least once in
12890 main.adb. The references are search in every library file in the search
12891 path.
12892
12893 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12894 switch is set)
12895
12896 The output will look like:
12897 @smallexample
12898 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12899 ^directory/^[directory]^main.adb:24:10: xyz <= body
12900 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12901 @end smallexample
12902
12903 @noindent
12904 that is to say, one of the entities xyz found in main.adb is declared at
12905 line 12 of main.ads (and its body is in main.adb), and another one is
12906 declared at line 45 of foo.ads
12907
12908 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12909 This is the same command as the previous one, instead @code{gnatfind} will
12910 display the content of the Ada source file lines.
12911
12912 The output will look like:
12913
12914 @smallexample
12915 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12916    procedure xyz;
12917 ^directory/^[directory]^main.adb:24:10: xyz <= body
12918    procedure xyz is
12919 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12920    xyz : Integer;
12921 @end smallexample
12922
12923 @noindent
12924 This can make it easier to find exactly the location your are looking
12925 for.
12926
12927 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12928 Find references to all entities containing an x that are
12929 referenced on line 123 of main.ads.
12930 The references will be searched only in main.ads and foo.adb.
12931
12932 @item gnatfind main.ads:123
12933 Find declarations and bodies for all entities that are referenced on
12934 line 123 of main.ads.
12935
12936 This is the same as @code{gnatfind "*":main.adb:123}.
12937
12938 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12939 Find the declaration for the entity referenced at column 45 in
12940 line 123 of file main.adb in directory mydir. Note that it
12941 is usual to omit the identifier name when the column is given,
12942 since the column position identifies a unique reference.
12943
12944 The column has to be the beginning of the identifier, and should not
12945 point to any character in the middle of the identifier.
12946
12947 @end table
12948
12949 @c *********************************
12950 @node The GNAT Pretty-Printer gnatpp
12951 @chapter The GNAT Pretty-Printer @command{gnatpp}
12952 @findex gnatpp
12953 @cindex Pretty-Printer
12954
12955 @noindent
12956 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12957 for source reformatting / pretty-printing.
12958 It takes an Ada source file as input and generates a reformatted
12959 version as output.
12960 You can specify various style directives via switches; e.g.,
12961 identifier case conventions, rules of indentation, and comment layout.
12962
12963 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12964 tree for the input source and thus requires the input to be syntactically and
12965 semantically legal.
12966 If this condition is not met, @command{gnatpp} will terminate with an
12967 error message; no output file will be generated.
12968
12969 If the source files presented to @command{gnatpp} contain
12970 preprocessing directives, then the output file will
12971 correspond to the generated source after all
12972 preprocessing is carried out. There is no way
12973 using @command{gnatpp} to obtain pretty printed files that
12974 include the preprocessing directives.
12975
12976 If the compilation unit
12977 contained in the input source depends semantically upon units located
12978 outside the current directory, you have to provide the source search path
12979 when invoking @command{gnatpp}, if these units are contained in files with
12980 names that do not follow the GNAT file naming rules, you have to provide
12981 the configuration file describing the corresponding naming scheme;
12982 see the description of the @command{gnatpp}
12983 switches below. Another possibility is to use a project file and to
12984 call @command{gnatpp} through the @command{gnat} driver
12985 (see @ref{The GNAT Driver and Project Files}).
12986
12987 The @command{gnatpp} command has the form
12988
12989 @smallexample
12990 @c $ gnatpp @ovar{switches} @var{filename}
12991 @c Expanding @ovar macro inline (explanation in macro def comments)
12992 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12993 @end smallexample
12994
12995 @noindent
12996 where
12997 @itemize @bullet
12998 @item
12999 @var{switches} is an optional sequence of switches defining such properties as
13000 the formatting rules, the source search path, and the destination for the
13001 output source file
13002
13003 @item
13004 @var{filename} is the name (including the extension) of the source file to
13005 reformat; ``wildcards'' or several file names on the same gnatpp command are
13006 allowed.  The file name may contain path information; it does not have to
13007 follow the GNAT file naming rules
13008
13009 @item
13010 @samp{@var{gcc_switches}} is a list of switches for
13011 @command{gcc}. They will be passed on to all compiler invocations made by
13012 @command{gnatelim} to generate the ASIS trees. Here you can provide
13013 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13014 use the @option{-gnatec} switch to set the configuration file,
13015 use the @option{-gnat05} switch if sources should be compiled in
13016 Ada 2005 mode  etc.
13017 @end itemize
13018
13019 @menu
13020 * Switches for gnatpp::
13021 * Formatting Rules::
13022 @end menu
13023
13024 @node Switches for gnatpp
13025 @section Switches for @command{gnatpp}
13026
13027 @noindent
13028 The following subsections describe the various switches accepted by
13029 @command{gnatpp}, organized by category.
13030
13031 @ifclear vms
13032 You specify a switch by supplying a name and generally also a value.
13033 In many cases the values for a switch with a given name are incompatible with
13034 each other
13035 (for example the switch that controls the casing of a reserved word may have
13036 exactly one value: upper case, lower case, or
13037 mixed case) and thus exactly one such switch can be in effect for an
13038 invocation of @command{gnatpp}.
13039 If more than one is supplied, the last one is used.
13040 However, some values for the same switch are mutually compatible.
13041 You may supply several such switches to @command{gnatpp}, but then
13042 each must be specified in full, with both the name and the value.
13043 Abbreviated forms (the name appearing once, followed by each value) are
13044 not permitted.
13045 For example, to set
13046 the alignment of the assignment delimiter both in declarations and in
13047 assignment statements, you must write @option{-A2A3}
13048 (or @option{-A2 -A3}), but not @option{-A23}.
13049 @end ifclear
13050
13051 @ifset vms
13052 In many cases the set of options for a given qualifier are incompatible with
13053 each other (for example the qualifier that controls the casing of a reserved
13054 word may have exactly one option, which specifies either upper case, lower
13055 case, or mixed case), and thus exactly one such option can be in effect for
13056 an invocation of @command{gnatpp}.
13057 If more than one is supplied, the last one is used.
13058 However, some qualifiers have options that are mutually compatible,
13059 and then you may then supply several such options when invoking
13060 @command{gnatpp}.
13061 @end ifset
13062
13063 In most cases, it is obvious whether or not the
13064 ^values for a switch with a given name^options for a given qualifier^
13065 are compatible with each other.
13066 When the semantics might not be evident, the summaries below explicitly
13067 indicate the effect.
13068
13069 @menu
13070 * Alignment Control::
13071 * Casing Control::
13072 * Construct Layout Control::
13073 * General Text Layout Control::
13074 * Other Formatting Options::
13075 * Setting the Source Search Path::
13076 * Output File Control::
13077 * Other gnatpp Switches::
13078 @end menu
13079
13080 @node Alignment Control
13081 @subsection Alignment Control
13082 @cindex Alignment control in @command{gnatpp}
13083
13084 @noindent
13085 Programs can be easier to read if certain constructs are vertically aligned.
13086 By default all alignments are set ON.
13087 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13088 OFF, and then use one or more of the other
13089 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13090 to activate alignment for specific constructs.
13091
13092 @table @option
13093 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13094
13095 @ifset vms
13096 @item /ALIGN=ON
13097 Set all alignments to ON
13098 @end ifset
13099
13100 @item ^-A0^/ALIGN=OFF^
13101 Set all alignments to OFF
13102
13103 @item ^-A1^/ALIGN=COLONS^
13104 Align @code{:} in declarations
13105
13106 @item ^-A2^/ALIGN=DECLARATIONS^
13107 Align @code{:=} in initializations in declarations
13108
13109 @item ^-A3^/ALIGN=STATEMENTS^
13110 Align @code{:=} in assignment statements
13111
13112 @item ^-A4^/ALIGN=ARROWS^
13113 Align @code{=>} in associations
13114
13115 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13116 Align @code{at} keywords in the component clauses in record
13117 representation clauses
13118 @end table
13119
13120 @noindent
13121 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13122 is allowed.
13123
13124 @node Casing Control
13125 @subsection Casing Control
13126 @cindex Casing control in @command{gnatpp}
13127
13128 @noindent
13129 @command{gnatpp} allows you to specify the casing for reserved words,
13130 pragma names, attribute designators and identifiers.
13131 For identifiers you may define a
13132 general rule for name casing but also override this rule
13133 via a set of dictionary files.
13134
13135 Three types of casing are supported: lower case, upper case, and mixed case.
13136 Lower and upper case are self-explanatory (but since some letters in
13137 Latin1 and other GNAT-supported character sets
13138 exist only in lower-case form, an upper case conversion will have no
13139 effect on them.)
13140 ``Mixed case'' means that the first letter, and also each letter immediately
13141 following an underscore, are converted to their uppercase forms;
13142 all the other letters are converted to their lowercase forms.
13143
13144 @table @option
13145 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13146 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13147 Attribute designators are lower case
13148
13149 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13150 Attribute designators are upper case
13151
13152 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13153 Attribute designators are mixed case (this is the default)
13154
13155 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13156 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13157 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13158 lower case (this is the default)
13159
13160 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13161 Keywords are upper case
13162
13163 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13164 @item ^-nD^/NAME_CASING=AS_DECLARED^
13165 Name casing for defining occurrences are as they appear in the source file
13166 (this is the default)
13167
13168 @item ^-nU^/NAME_CASING=UPPER_CASE^
13169 Names are in upper case
13170
13171 @item ^-nL^/NAME_CASING=LOWER_CASE^
13172 Names are in lower case
13173
13174 @item ^-nM^/NAME_CASING=MIXED_CASE^
13175 Names are in mixed case
13176
13177 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13178 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13179 Enumeration literal casing for defining occurrences are as they appear in the
13180 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13181
13182 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13183 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13184 setting.
13185
13186 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13187 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13188 setting.
13189
13190 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13191 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13192 setting.
13193
13194 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13195 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13196 Names introduced by type and subtype declarations are always
13197 cased as they appear in the declaration in the source file.
13198 Overrides ^-n^/NAME_CASING^ casing setting.
13199
13200 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13201 Names introduced by type and subtype declarations are always in
13202 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13203
13204 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13205 Names introduced by type and subtype declarations are always in
13206 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13207
13208 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13209 Names introduced by type and subtype declarations are always in
13210 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13211
13212 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13213 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13214 Pragma names are lower case
13215
13216 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13217 Pragma names are upper case
13218
13219 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13220 Pragma names are mixed case (this is the default)
13221
13222 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13223 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13224 Use @var{file} as a @emph{dictionary file} that defines
13225 the casing for a set of specified names,
13226 thereby overriding the effect on these names by
13227 any explicit or implicit
13228 ^-n^/NAME_CASING^ switch.
13229 To supply more than one dictionary file,
13230 use ^several @option{-D} switches^a list of files as options^.
13231
13232 @noindent
13233 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13234 to define the casing for the Ada predefined names and
13235 the names declared in the GNAT libraries.
13236
13237 @item ^-D-^/SPECIFIC_CASING^
13238 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13239 Do not use the default dictionary file;
13240 instead, use the casing
13241 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13242 dictionary file(s)
13243 @end table
13244
13245 @noindent
13246 The structure of a dictionary file, and details on the conventions
13247 used in the default dictionary file, are defined in @ref{Name Casing}.
13248
13249 The @option{^-D-^/SPECIFIC_CASING^} and
13250 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13251 compatible.
13252
13253 @node Construct Layout Control
13254 @subsection Construct Layout Control
13255 @cindex Layout control in @command{gnatpp}
13256
13257 @noindent
13258 This group of @command{gnatpp} switches controls the layout of comments and
13259 complex syntactic constructs.  See @ref{Formatting Comments} for details
13260 on their effect.
13261
13262 @table @option
13263 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13264 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13265 All the comments remain unchanged
13266
13267 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13268 GNAT-style comment line indentation (this is the default).
13269
13270 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13271 Reference-manual comment line indentation.
13272
13273 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13274 GNAT-style comment beginning
13275
13276 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13277 Reformat comment blocks
13278
13279 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13280 Keep unchanged special form comments
13281
13282 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13283 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13284 GNAT-style layout (this is the default)
13285
13286 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13287 Compact layout
13288
13289 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13290 Uncompact layout
13291
13292 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13293 @item ^-N^/NOTABS^
13294 All the VT characters are removed from the comment text. All the HT characters
13295 are expanded with the sequences of space characters to get to the next tab
13296 stops.
13297
13298 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13299 @item ^--no-separate-is^/NO_SEPARATE_IS^
13300 Do not place the keyword @code{is} on a separate line in a subprogram body in
13301 case if the spec occupies more then one line.
13302
13303 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13304 @item ^--separate-label^/SEPARATE_LABEL^
13305 Place statement label(s) on a separate line, with the following statement
13306 on the next line.
13307
13308 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13309 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13310 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13311 keyword @code{then} in IF statements on a separate line.
13312
13313 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13314 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13315 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13316 keyword @code{then} in IF statements on a separate line. This option is
13317 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13318
13319 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13320 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13321 Start each USE clause in a context clause from a separate line.
13322
13323 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13324 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13325 Use a separate line for a loop or block statement name, but do not use an extra
13326 indentation level for the statement itself.
13327
13328 @end table
13329
13330 @ifclear vms
13331 @noindent
13332 The @option{-c1} and @option{-c2} switches are incompatible.
13333 The @option{-c3} and @option{-c4} switches are compatible with each other and
13334 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13335 the other comment formatting switches.
13336
13337 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13338 @end ifclear
13339
13340 @ifset vms
13341 @noindent
13342 For the @option{/COMMENTS_LAYOUT} qualifier:
13343 @itemize @bullet
13344 @item
13345 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13346 @item
13347 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13348 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13349 @end itemize
13350
13351 @noindent
13352 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13353 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13354 @end ifset
13355
13356 @node General Text Layout Control
13357 @subsection General Text Layout Control
13358
13359 @noindent
13360 These switches allow control over line length and indentation.
13361
13362 @table @option
13363 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13364 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13365 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13366
13367 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13368 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13369 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13370
13371 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13372 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13373 Indentation level for continuation lines (relative to the line being
13374 continued), @var{nnn} from 1@dots{}9.
13375 The default
13376 value is one less then the (normal) indentation level, unless the
13377 indentation is set to 1 (in which case the default value for continuation
13378 line indentation is also 1)
13379 @end table
13380
13381 @node Other Formatting Options
13382 @subsection Other Formatting Options
13383
13384 @noindent
13385 These switches control the inclusion of missing end/exit labels, and
13386 the indentation level in @b{case} statements.
13387
13388 @table @option
13389 @item ^-e^/NO_MISSED_LABELS^
13390 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13391 Do not insert missing end/exit labels. An end label is the name of
13392 a construct that may optionally be repeated at the end of the
13393 construct's declaration;
13394 e.g., the names of packages, subprograms, and tasks.
13395 An exit label is the name of a loop that may appear as target
13396 of an exit statement within the loop.
13397 By default, @command{gnatpp} inserts these end/exit labels when
13398 they are absent from the original source. This option suppresses such
13399 insertion, so that the formatted source reflects the original.
13400
13401 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13402 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13403 Insert a Form Feed character after a pragma Page.
13404
13405 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13406 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13407 Do not use an additional indentation level for @b{case} alternatives
13408 and variants if there are @var{nnn} or more (the default
13409 value is 10).
13410 If @var{nnn} is 0, an additional indentation level is
13411 used for @b{case} alternatives and variants regardless of their number.
13412
13413 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13414 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13415 If the number of parameter associations is greater than @var{nnn} and if at
13416 least one association uses named notation, start each association from
13417 a new line. If @var{nnn} is 0, no check for the number of associations
13418 is made, this is the default.
13419
13420 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13421 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13422 If the number of parameter specifications is greater than @var{nnn}
13423 (or equal to @var{nnn} in case of a function), start each specification from
13424 a new line. The default for @var{nnn} is 3.
13425 @end table
13426
13427 @node Setting the Source Search Path
13428 @subsection Setting the Source Search Path
13429
13430 @noindent
13431 To define the search path for the input source file, @command{gnatpp}
13432 uses the same switches as the GNAT compiler, with the same effects.
13433
13434 @table @option
13435 @item ^-I^/SEARCH=^@var{dir}
13436 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13437 The same as the corresponding gcc switch
13438
13439 @item ^-I-^/NOCURRENT_DIRECTORY^
13440 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13441 The same as the corresponding gcc switch
13442
13443 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13444 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13445 The same as the corresponding gcc switch
13446
13447 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13448 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13449 The same as the corresponding gcc switch
13450
13451 @end table
13452
13453 @node Output File Control
13454 @subsection Output File Control
13455
13456 @noindent
13457 By default the output is sent to the file whose name is obtained by appending
13458 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13459 (if the file with this name already exists, it is unconditionally overwritten).
13460 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13461 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13462 as output file.
13463 The output may be redirected by the following switches:
13464
13465 @table @option
13466 @item ^-pipe^/STANDARD_OUTPUT^
13467 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13468 Send the output to @code{Standard_Output}
13469
13470 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13471 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13472 Write the output into @var{output_file}.
13473 If @var{output_file} already exists, @command{gnatpp} terminates without
13474 reading or processing the input file.
13475
13476 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13477 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13478 Write the output into @var{output_file}, overwriting the existing file
13479 (if one is present).
13480
13481 @item ^-r^/REPLACE^
13482 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13483 Replace the input source file with the reformatted output, and copy the
13484 original input source into the file whose name is obtained by appending the
13485 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13486 If a file with this name already exists, @command{gnatpp} terminates without
13487 reading or processing the input file.
13488
13489 @item ^-rf^/OVERRIDING_REPLACE^
13490 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13491 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13492 already exists, it is overwritten.
13493
13494 @item ^-rnb^/REPLACE_NO_BACKUP^
13495 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13496 Replace the input source file with the reformatted output without
13497 creating any backup copy of the input source.
13498
13499 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13500 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13501 Specifies the format of the reformatted output file. The @var{xxx}
13502 ^string specified with the switch^option^ may be either
13503 @itemize @bullet
13504 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13505 @item ``@option{^crlf^CRLF^}''
13506 the same as @option{^crlf^CRLF^}
13507 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13508 @item ``@option{^lf^LF^}''
13509 the same as @option{^unix^UNIX^}
13510 @end itemize
13511
13512 @item ^-W^/RESULT_ENCODING=^@var{e}
13513 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13514 Specify the wide character encoding method used to write the code in the
13515 result file
13516 @var{e} is one of the following:
13517
13518 @itemize @bullet
13519
13520 @item ^h^HEX^
13521 Hex encoding
13522
13523 @item ^u^UPPER^
13524 Upper half encoding
13525
13526 @item ^s^SHIFT_JIS^
13527 Shift/JIS encoding
13528
13529 @item ^e^EUC^
13530 EUC encoding
13531
13532 @item ^8^UTF8^
13533 UTF-8 encoding
13534
13535 @item ^b^BRACKETS^
13536 Brackets encoding (default value)
13537 @end itemize
13538
13539 @end table
13540
13541 @noindent
13542 Options @option{^-pipe^/STANDARD_OUTPUT^},
13543 @option{^-o^/OUTPUT^} and
13544 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13545 contains only one file to reformat.
13546 Option
13547 @option{^--eol^/END_OF_LINE^}
13548 and
13549 @option{^-W^/RESULT_ENCODING^}
13550 cannot be used together
13551 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13552
13553 @node Other gnatpp Switches
13554 @subsection Other @code{gnatpp} Switches
13555
13556 @noindent
13557 The additional @command{gnatpp} switches are defined in this subsection.
13558
13559 @table @option
13560 @item ^-files @var{filename}^/FILES=@var{filename}^
13561 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13562 Take the argument source files from the specified file. This file should be an
13563 ordinary text file containing file names separated by spaces or
13564 line breaks. You can use this switch more than once in the same call to
13565 @command{gnatpp}. You also can combine this switch with an explicit list of
13566 files.
13567
13568 @item ^-v^/VERBOSE^
13569 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13570 Verbose mode;
13571 @command{gnatpp} generates version information and then
13572 a trace of the actions it takes to produce or obtain the ASIS tree.
13573
13574 @item ^-w^/WARNINGS^
13575 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13576 Warning mode;
13577 @command{gnatpp} generates a warning whenever it cannot provide
13578 a required layout in the result source.
13579 @end table
13580
13581 @node Formatting Rules
13582 @section Formatting Rules
13583
13584 @noindent
13585 The following subsections show how @command{gnatpp} treats ``white space'',
13586 comments, program layout, and name casing.
13587 They provide the detailed descriptions of the switches shown above.
13588
13589 @menu
13590 * White Space and Empty Lines::
13591 * Formatting Comments::
13592 * Construct Layout::
13593 * Name Casing::
13594 @end menu
13595
13596 @node White Space and Empty Lines
13597 @subsection White Space and Empty Lines
13598
13599 @noindent
13600 @command{gnatpp} does not have an option to control space characters.
13601 It will add or remove spaces according to the style illustrated by the
13602 examples in the @cite{Ada Reference Manual}.
13603
13604 The only format effectors
13605 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13606 that will appear in the output file are platform-specific line breaks,
13607 and also format effectors within (but not at the end of) comments.
13608 In particular, each horizontal tab character that is not inside
13609 a comment will be treated as a space and thus will appear in the
13610 output file as zero or more spaces depending on
13611 the reformatting of the line in which it appears.
13612 The only exception is a Form Feed character, which is inserted after a
13613 pragma @code{Page} when @option{-ff} is set.
13614
13615 The output file will contain no lines with trailing ``white space'' (spaces,
13616 format effectors).
13617
13618 Empty lines in the original source are preserved
13619 only if they separate declarations or statements.
13620 In such contexts, a
13621 sequence of two or more empty lines is replaced by exactly one empty line.
13622 Note that a blank line will be removed if it separates two ``comment blocks''
13623 (a comment block is a sequence of whole-line comments).
13624 In order to preserve a visual separation between comment blocks, use an
13625 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13626 Likewise, if for some reason you wish to have a sequence of empty lines,
13627 use a sequence of empty comments instead.
13628
13629 @node Formatting Comments
13630 @subsection Formatting Comments
13631
13632 @noindent
13633 Comments in Ada code are of two kinds:
13634 @itemize @bullet
13635 @item
13636 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13637 ``white space'') on a line
13638
13639 @item
13640 an @emph{end-of-line comment}, which follows some other Ada lexical element
13641 on the same line.
13642 @end itemize
13643
13644 @noindent
13645 The indentation of a whole-line comment is that of either
13646 the preceding or following line in
13647 the formatted source, depending on switch settings as will be described below.
13648
13649 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13650 between the end of the preceding Ada lexical element and the beginning
13651 of the comment as appear in the original source,
13652 unless either the comment has to be split to
13653 satisfy the line length limitation, or else the next line contains a
13654 whole line comment that is considered a continuation of this end-of-line
13655 comment (because it starts at the same position).
13656 In the latter two
13657 cases, the start of the end-of-line comment is moved right to the nearest
13658 multiple of the indentation level.
13659 This may result in a ``line overflow'' (the right-shifted comment extending
13660 beyond the maximum line length), in which case the comment is split as
13661 described below.
13662
13663 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13664 (GNAT-style comment line indentation)
13665 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13666 (reference-manual comment line indentation).
13667 With reference-manual style, a whole-line comment is indented as if it
13668 were a declaration or statement at the same place
13669 (i.e., according to the indentation of the preceding line(s)).
13670 With GNAT style, a whole-line comment that is immediately followed by an
13671 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13672 word @b{begin}, is indented based on the construct that follows it.
13673
13674 For example:
13675 @smallexample @c ada
13676 @cartouche
13677 if A then
13678     null;
13679        -- some comment
13680 else
13681    null;
13682 end if;
13683 @end cartouche
13684 @end smallexample
13685
13686 @noindent
13687 Reference-manual indentation produces:
13688
13689 @smallexample @c ada
13690 @cartouche
13691 if A then
13692    null;
13693    --  some comment
13694 else
13695    null;
13696 end if;
13697 @end cartouche
13698 @end smallexample
13699
13700 @noindent
13701 while GNAT-style indentation produces:
13702
13703 @smallexample @c ada
13704 @cartouche
13705 if A then
13706    null;
13707 --  some comment
13708 else
13709    null;
13710 end if;
13711 @end cartouche
13712 @end smallexample
13713
13714 @noindent
13715 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13716 (GNAT style comment beginning) has the following
13717 effect:
13718
13719 @itemize @bullet
13720 @item
13721 For each whole-line comment that does not end with two hyphens,
13722 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13723 to ensure that there are at least two spaces between these hyphens and the
13724 first non-blank character of the comment.
13725 @end itemize
13726
13727 @noindent
13728 For an end-of-line comment, if in the original source the next line is a
13729 whole-line comment that starts at the same position
13730 as the end-of-line comment,
13731 then the whole-line comment (and all whole-line comments
13732 that follow it and that start at the same position)
13733 will start at this position in the output file.
13734
13735 @noindent
13736 That is, if in the original source we have:
13737
13738 @smallexample @c ada
13739 @cartouche
13740 begin
13741 A := B + C;            --  B must be in the range Low1..High1
13742                        --  C must be in the range Low2..High2
13743              --B+C will be in the range Low1+Low2..High1+High2
13744 X := X + 1;
13745 @end cartouche
13746 @end smallexample
13747
13748 @noindent
13749 Then in the formatted source we get
13750
13751 @smallexample @c ada
13752 @cartouche
13753 begin
13754    A := B + C;            --  B must be in the range Low1..High1
13755                           --  C must be in the range Low2..High2
13756    --  B+C will be in the range Low1+Low2..High1+High2
13757    X := X + 1;
13758 @end cartouche
13759 @end smallexample
13760
13761 @noindent
13762 A comment that exceeds the line length limit will be split.
13763 Unless switch
13764 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13765 the line belongs to a reformattable block, splitting the line generates a
13766 @command{gnatpp} warning.
13767 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13768 comments may be reformatted in typical
13769 word processor style (that is, moving words between lines and putting as
13770 many words in a line as possible).
13771
13772 @noindent
13773 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13774 that has a special format (that is, a character that is neither a letter nor digit
13775 not white space nor line break immediately following the leading @code{--} of
13776 the comment) should be without any change moved from the argument source
13777 into reformatted source. This switch allows to preserve comments that are used
13778 as a special marks in the code (e.g.@: SPARK annotation).
13779
13780 @node Construct Layout
13781 @subsection Construct Layout
13782
13783 @noindent
13784 In several cases the suggested layout in the Ada Reference Manual includes
13785 an extra level of indentation that many programmers prefer to avoid. The
13786 affected cases include:
13787
13788 @itemize @bullet
13789
13790 @item Record type declaration (RM 3.8)
13791
13792 @item Record representation clause (RM 13.5.1)
13793
13794 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13795
13796 @item Block statement in case if a block has a statement identifier (RM 5.6)
13797 @end itemize
13798
13799 @noindent
13800 In compact mode (when GNAT style layout or compact layout is set),
13801 the pretty printer uses one level of indentation instead
13802 of two. This is achieved in the record definition and record representation
13803 clause cases by putting the @code{record} keyword on the same line as the
13804 start of the declaration or representation clause, and in the block and loop
13805 case by putting the block or loop header on the same line as the statement
13806 identifier.
13807
13808 @noindent
13809 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13810 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13811 layout on the one hand, and uncompact layout
13812 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13813 can be illustrated by the following examples:
13814
13815 @iftex
13816 @cartouche
13817 @multitable @columnfractions .5 .5
13818 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13819
13820 @item
13821 @smallexample @c ada
13822 type q is record
13823    a : integer;
13824    b : integer;
13825 end record;
13826 @end smallexample
13827 @tab
13828 @smallexample @c ada
13829 type q is
13830    record
13831       a : integer;
13832       b : integer;
13833    end record;
13834 @end smallexample
13835
13836 @item
13837 @smallexample @c ada
13838 for q use record
13839    a at 0 range  0 .. 31;
13840    b at 4 range  0 .. 31;
13841 end record;
13842 @end smallexample
13843 @tab
13844 @smallexample @c ada
13845 for q use
13846    record
13847       a at 0 range  0 .. 31;
13848       b at 4 range  0 .. 31;
13849    end record;
13850 @end smallexample
13851
13852 @item
13853 @smallexample @c ada
13854 Block : declare
13855    A : Integer := 3;
13856 begin
13857    Proc (A, A);
13858 end Block;
13859 @end smallexample
13860 @tab
13861 @smallexample @c ada
13862 Block :
13863    declare
13864       A : Integer := 3;
13865    begin
13866       Proc (A, A);
13867    end Block;
13868 @end smallexample
13869
13870 @item
13871 @smallexample @c ada
13872 Clear : for J in 1 .. 10 loop
13873    A (J) := 0;
13874 end loop Clear;
13875 @end smallexample
13876 @tab
13877 @smallexample @c ada
13878 Clear :
13879    for J in 1 .. 10 loop
13880       A (J) := 0;
13881    end loop Clear;
13882 @end smallexample
13883 @end multitable
13884 @end cartouche
13885 @end iftex
13886
13887 @ifnottex
13888 @smallexample
13889 @cartouche
13890 GNAT style, compact layout              Uncompact layout
13891
13892 type q is record                        type q is
13893    a : integer;                            record
13894    b : integer;                               a : integer;
13895 end record;                                   b : integer;
13896                                            end record;
13897
13898 for q use record                        for q use
13899    a at 0 range  0 .. 31;                  record
13900    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13901 end record;                                   b at 4 range  0 .. 31;
13902                                            end record;
13903
13904 Block : declare                         Block :
13905    A : Integer := 3;                       declare
13906 begin                                         A : Integer := 3;
13907    Proc (A, A);                            begin
13908 end Block;                                    Proc (A, A);
13909                                            end Block;
13910
13911 Clear : for J in 1 .. 10 loop           Clear :
13912    A (J) := 0;                             for J in 1 .. 10 loop
13913 end loop Clear;                               A (J) := 0;
13914                                            end loop Clear;
13915 @end cartouche
13916 @end smallexample
13917 @end ifnottex
13918
13919 @noindent
13920 A further difference between GNAT style layout and compact layout is that
13921 GNAT style layout inserts empty lines as separation for
13922 compound statements, return statements and bodies.
13923
13924 Note that the layout specified by
13925 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13926 for named block and loop statements overrides the layout defined by these
13927 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13928 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13929 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13930
13931 @node Name Casing
13932 @subsection Name Casing
13933
13934 @noindent
13935 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13936 the same casing as the corresponding defining identifier.
13937
13938 You control the casing for defining occurrences via the
13939 @option{^-n^/NAME_CASING^} switch.
13940 @ifclear vms
13941 With @option{-nD} (``as declared'', which is the default),
13942 @end ifclear
13943 @ifset vms
13944 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13945 @end ifset
13946 defining occurrences appear exactly as in the source file
13947 where they are declared.
13948 The other ^values for this switch^options for this qualifier^ ---
13949 @option{^-nU^UPPER_CASE^},
13950 @option{^-nL^LOWER_CASE^},
13951 @option{^-nM^MIXED_CASE^} ---
13952 result in
13953 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13954 If @command{gnatpp} changes the casing of a defining
13955 occurrence, it analogously changes the casing of all the
13956 usage occurrences of this name.
13957
13958 If the defining occurrence of a name is not in the source compilation unit
13959 currently being processed by @command{gnatpp}, the casing of each reference to
13960 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13961 switch (subject to the dictionary file mechanism described below).
13962 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13963 had affected the
13964 casing for the defining occurrence of the name.
13965
13966 Some names may need to be spelled with casing conventions that are not
13967 covered by the upper-, lower-, and mixed-case transformations.
13968 You can arrange correct casing by placing such names in a
13969 @emph{dictionary file},
13970 and then supplying a @option{^-D^/DICTIONARY^} switch.
13971 The casing of names from dictionary files overrides
13972 any @option{^-n^/NAME_CASING^} switch.
13973
13974 To handle the casing of Ada predefined names and the names from GNAT libraries,
13975 @command{gnatpp} assumes a default dictionary file.
13976 The name of each predefined entity is spelled with the same casing as is used
13977 for the entity in the @cite{Ada Reference Manual}.
13978 The name of each entity in the GNAT libraries is spelled with the same casing
13979 as is used in the declaration of that entity.
13980
13981 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13982 default dictionary file.
13983 Instead, the casing for predefined and GNAT-defined names will be established
13984 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13985 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13986 will appear as just shown,
13987 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13988 To ensure that even such names are rendered in uppercase,
13989 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13990 (or else, less conveniently, place these names in upper case in a dictionary
13991 file).
13992
13993 A dictionary file is
13994 a plain text file; each line in this file can be either a blank line
13995 (containing only space characters and ASCII.HT characters), an Ada comment
13996 line, or the specification of exactly one @emph{casing schema}.
13997
13998 A casing schema is a string that has the following syntax:
13999
14000 @smallexample
14001 @cartouche
14002   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14003
14004   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14005 @end cartouche
14006 @end smallexample
14007
14008 @noindent
14009 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14010 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14011
14012 The casing schema string can be followed by white space and/or an Ada-style
14013 comment; any amount of white space is allowed before the string.
14014
14015 If a dictionary file is passed as
14016 @ifclear vms
14017 the value of a @option{-D@var{file}} switch
14018 @end ifclear
14019 @ifset vms
14020 an option to the @option{/DICTIONARY} qualifier
14021 @end ifset
14022 then for every
14023 simple name and every identifier, @command{gnatpp} checks if the dictionary
14024 defines the casing for the name or for some of its parts (the term ``subword''
14025 is used below to denote the part of a name which is delimited by ``_'' or by
14026 the beginning or end of the word and which does not contain any ``_'' inside):
14027
14028 @itemize @bullet
14029 @item
14030 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14031 the casing defined by the dictionary; no subwords are checked for this word
14032
14033 @item
14034 for every subword @command{gnatpp} checks if the dictionary contains the
14035 corresponding string of the form @code{*@var{simple_identifier}*},
14036 and if it does, the casing of this @var{simple_identifier} is used
14037 for this subword
14038
14039 @item
14040 if the whole name does not contain any ``_'' inside, and if for this name
14041 the dictionary contains two entries - one of the form @var{identifier},
14042 and another - of the form *@var{simple_identifier}*, then the first one
14043 is applied to define the casing of this name
14044
14045 @item
14046 if more than one dictionary file is passed as @command{gnatpp} switches, each
14047 dictionary adds new casing exceptions and overrides all the existing casing
14048 exceptions set by the previous dictionaries
14049
14050 @item
14051 when @command{gnatpp} checks if the word or subword is in the dictionary,
14052 this check is not case sensitive
14053 @end itemize
14054
14055 @noindent
14056 For example, suppose we have the following source to reformat:
14057
14058 @smallexample @c ada
14059 @cartouche
14060 procedure test is
14061    name1 : integer := 1;
14062    name4_name3_name2 : integer := 2;
14063    name2_name3_name4 : Boolean;
14064    name1_var : Float;
14065 begin
14066    name2_name3_name4 := name4_name3_name2 > name1;
14067 end;
14068 @end cartouche
14069 @end smallexample
14070
14071 @noindent
14072 And suppose we have two dictionaries:
14073
14074 @smallexample
14075 @cartouche
14076 @i{dict1:}
14077    NAME1
14078    *NaMe3*
14079    *Name1*
14080 @end cartouche
14081
14082 @cartouche
14083 @i{dict2:}
14084   *NAME3*
14085 @end cartouche
14086 @end smallexample
14087
14088 @noindent
14089 If @command{gnatpp} is called with the following switches:
14090
14091 @smallexample
14092 @ifclear vms
14093 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14094 @end ifclear
14095 @ifset vms
14096 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14097 @end ifset
14098 @end smallexample
14099
14100 @noindent
14101 then we will get the following name casing in the @command{gnatpp} output:
14102
14103 @smallexample @c ada
14104 @cartouche
14105 procedure Test is
14106    NAME1             : Integer := 1;
14107    Name4_NAME3_Name2 : Integer := 2;
14108    Name2_NAME3_Name4 : Boolean;
14109    Name1_Var         : Float;
14110 begin
14111    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14112 end Test;
14113 @end cartouche
14114 @end smallexample
14115
14116 @c *********************************
14117 @node The GNAT Metric Tool gnatmetric
14118 @chapter The GNAT Metric Tool @command{gnatmetric}
14119 @findex gnatmetric
14120 @cindex Metric tool
14121
14122 @noindent
14123 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14124 for computing various program metrics.
14125 It takes an Ada source file as input and generates a file containing the
14126 metrics data as output. Various switches control which
14127 metrics are computed and output.
14128
14129 @command{gnatmetric} generates and uses the ASIS
14130 tree for the input source and thus requires the input to be syntactically and
14131 semantically legal.
14132 If this condition is not met, @command{gnatmetric} will generate
14133 an error message; no metric information for this file will be
14134 computed and reported.
14135
14136 If the compilation unit contained in the input source depends semantically
14137 upon units in files located outside the current directory, you have to provide
14138 the source search path when invoking @command{gnatmetric}.
14139 If it depends semantically upon units that are contained
14140 in files with names that do not follow the GNAT file naming rules, you have to
14141 provide the configuration file describing the corresponding naming scheme (see
14142 the description of the @command{gnatmetric} switches below.)
14143 Alternatively, you may use a project file and invoke @command{gnatmetric}
14144 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14145
14146 The @command{gnatmetric} command has the form
14147
14148 @smallexample
14149 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14150 @c Expanding @ovar macro inline (explanation in macro def comments)
14151 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14152 @end smallexample
14153
14154 @noindent
14155 where
14156 @itemize @bullet
14157 @item
14158 @var{switches} specify the metrics to compute and define the destination for
14159 the output
14160
14161 @item
14162 Each @var{filename} is the name (including the extension) of a source
14163 file to process. ``Wildcards'' are allowed, and
14164 the file name may contain path information.
14165 If no @var{filename} is supplied, then the @var{switches} list must contain
14166 at least one
14167 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14168 Including both a @option{-files} switch and one or more
14169 @var{filename} arguments is permitted.
14170
14171 @item
14172 @samp{@var{gcc_switches}} is a list of switches for
14173 @command{gcc}. They will be passed on to all compiler invocations made by
14174 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14175 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14176 and use the @option{-gnatec} switch to set the configuration file,
14177 use the @option{-gnat05} switch if sources should be compiled in
14178 Ada 2005 mode etc.
14179 @end itemize
14180
14181 @menu
14182 * Switches for gnatmetric::
14183 @end menu
14184
14185 @node Switches for gnatmetric
14186 @section Switches for @command{gnatmetric}
14187
14188 @noindent
14189 The following subsections describe the various switches accepted by
14190 @command{gnatmetric}, organized by category.
14191
14192 @menu
14193 * Output Files Control::
14194 * Disable Metrics For Local Units::
14195 * Specifying a set of metrics to compute::
14196 * Other gnatmetric Switches::
14197 * Generate project-wide metrics::
14198 @end menu
14199
14200 @node Output Files Control
14201 @subsection Output File Control
14202 @cindex Output file control in @command{gnatmetric}
14203
14204 @noindent
14205 @command{gnatmetric} has two output formats. It can generate a
14206 textual (human-readable) form, and also XML. By default only textual
14207 output is generated.
14208
14209 When generating the output in textual form, @command{gnatmetric} creates
14210 for each Ada source file a corresponding text file
14211 containing the computed metrics, except for the case when the set of metrics
14212 specified by gnatmetric parameters consists only of metrics that are computed
14213 for the whole set of analyzed sources, but not for each Ada source.
14214 By default, this file is placed in the same directory as where the source
14215 file is located, and its name is obtained
14216 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14217 input file.
14218
14219 All the output information generated in XML format is placed in a single
14220 file. By default this file is placed in the current directory and has the
14221 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14222
14223 Some of the computed metrics are summed over the units passed to
14224 @command{gnatmetric}; for example, the total number of lines of code.
14225 By default this information is sent to @file{stdout}, but a file
14226 can be specified with the @option{-og} switch.
14227
14228 The following switches control the @command{gnatmetric} output:
14229
14230 @table @option
14231 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14232 @item ^-x^/XML^
14233 Generate the XML output
14234
14235 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14236 @item ^-xs^/XSD^
14237 Generate the XML output and the XML schema file that describes the structure
14238 of the XML metric report, this schema is assigned to the XML file. The schema
14239 file has the same name as the XML output file with @file{.xml} suffix replaced
14240 with @file{.xsd}
14241
14242 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14243 @item ^-nt^/NO_TEXT^
14244 Do not generate the output in text form (implies @option{^-x^/XML^})
14245
14246 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14247 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14248 Put text files with detailed metrics into @var{output_dir}
14249
14250 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14251 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14252 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14253 in the name of the output file.
14254
14255 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14256 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14257 Put global metrics into @var{file_name}
14258
14259 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14260 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14261 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14262
14263 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14264 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14265 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14266 output includes the name(s) of the Ada source file(s) from which the metrics
14267 are computed.  By default each name includes the absolute path. The
14268 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14269 to exclude all directory information from the file names that are output.)
14270
14271 @end table
14272
14273 @node Disable Metrics For Local Units
14274 @subsection Disable Metrics For Local Units
14275 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14276
14277 @noindent
14278 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14279 one compilation
14280 unit per one source file. It computes line metrics for the whole source
14281 file, and it also computes syntax
14282 and complexity metrics for the file's outermost unit.
14283
14284 By default, @command{gnatmetric} will also compute all metrics for certain
14285 kinds of locally declared program units:
14286
14287 @itemize @bullet
14288 @item
14289 subprogram (and generic subprogram) bodies;
14290
14291 @item
14292 package (and generic package) specs and bodies;
14293
14294 @item
14295 task object and type specifications and bodies;
14296
14297 @item
14298 protected object and type specifications and bodies.
14299 @end itemize
14300
14301 @noindent
14302 These kinds of entities will be referred to as
14303 @emph{eligible local program units}, or simply @emph{eligible local units},
14304 @cindex Eligible local unit (for @command{gnatmetric})
14305 in the discussion below.
14306
14307 Note that a subprogram declaration, generic instantiation,
14308 or renaming declaration only receives metrics
14309 computation when it appear as the outermost entity
14310 in a source file.
14311
14312 Suppression of metrics computation for eligible local units can be
14313 obtained via the following switch:
14314
14315 @table @option
14316 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14317 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14318 Do not compute detailed metrics for eligible local program units
14319
14320 @end table
14321
14322 @node Specifying a set of metrics to compute
14323 @subsection Specifying a set of metrics to compute
14324
14325 @noindent
14326 By default all the metrics are computed and reported. The switches
14327 described in this subsection allow you to control, on an individual
14328 basis, whether metrics are computed and
14329 reported. If at least one positive metric
14330 switch is specified (that is, a switch that defines that a given
14331 metric or set of metrics is to be computed), then only
14332 explicitly specified metrics are reported.
14333
14334 @menu
14335 * Line Metrics Control::
14336 * Syntax Metrics Control::
14337 * Complexity Metrics Control::
14338 * Coupling Metrics Control::
14339 @end menu
14340
14341 @node Line Metrics Control
14342 @subsubsection Line Metrics Control
14343 @cindex Line metrics control in @command{gnatmetric}
14344
14345 @noindent
14346 For any (legal) source file, and for each of its
14347 eligible local program units, @command{gnatmetric} computes the following
14348 metrics:
14349
14350 @itemize @bullet
14351 @item
14352 the total number of lines;
14353
14354 @item
14355 the total number of code lines (i.e., non-blank lines that are not comments)
14356
14357 @item
14358 the number of comment lines
14359
14360 @item
14361 the number of code lines containing end-of-line comments;
14362
14363 @item
14364 the comment percentage: the ratio between the number of lines that contain
14365 comments and the number of all non-blank lines, expressed as a percentage;
14366
14367 @item
14368 the number of empty lines and lines containing only space characters and/or
14369 format effectors (blank lines)
14370
14371 @item
14372 the average number of code lines in subprogram bodies, task bodies, entry
14373 bodies and statement sequences in package bodies (this metric is only computed
14374 across the whole set of the analyzed units)
14375
14376 @end itemize
14377
14378 @noindent
14379 @command{gnatmetric} sums the values of the line metrics for all the
14380 files being processed and then generates the cumulative results. The tool
14381 also computes for all the files being processed the average number of code
14382 lines in bodies.
14383
14384 You can use the following switches to select the specific line metrics
14385 to be computed and reported.
14386
14387 @table @option
14388 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14389
14390 @ifclear vms
14391 @cindex @option{--no-lines@var{x}}
14392 @end ifclear
14393
14394 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14395 Report all the line metrics
14396
14397 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14398 Do not report any of line metrics
14399
14400 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14401 Report the number of all lines
14402
14403 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14404 Do not report the number of all lines
14405
14406 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14407 Report the number of code lines
14408
14409 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14410 Do not report the number of code lines
14411
14412 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14413 Report the number of comment lines
14414
14415 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14416 Do not report the number of comment lines
14417
14418 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14419 Report the number of code lines containing
14420 end-of-line comments
14421
14422 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14423 Do not report the number of code lines containing
14424 end-of-line comments
14425
14426 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14427 Report the comment percentage in the program text
14428
14429 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14430 Do not report the comment percentage in the program text
14431
14432 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14433 Report the number of blank lines
14434
14435 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14436 Do not report the number of blank lines
14437
14438 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14439 Report the average number of code lines in subprogram bodies, task bodies,
14440 entry bodies and statement sequences in package bodies. The metric is computed
14441 and reported for the whole set of processed Ada sources only.
14442
14443 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14444 Do not report the average number of code lines in subprogram bodies,
14445 task bodies, entry bodies and statement sequences in package bodies.
14446
14447 @end table
14448
14449 @node Syntax Metrics Control
14450 @subsubsection Syntax Metrics Control
14451 @cindex Syntax metrics control in @command{gnatmetric}
14452
14453 @noindent
14454 @command{gnatmetric} computes various syntactic metrics for the
14455 outermost unit and for each eligible local unit:
14456
14457 @table @emph
14458 @item LSLOC (``Logical Source Lines Of Code'')
14459 The total number of declarations and the total number of statements. Note
14460 that the definition of declarations is the one given in the reference
14461 manual:
14462
14463 @noindent
14464 ``Each of the following is defined to be a declaration: any basic_declaration;
14465 an enumeration_literal_specification; a discriminant_specification;
14466 a component_declaration; a loop_parameter_specification; a
14467 parameter_specification; a subprogram_body; an entry_declaration;
14468 an entry_index_specification; a choice_parameter_specification;
14469 a generic_formal_parameter_declaration.''
14470
14471 This means for example that each enumeration literal adds one to the count,
14472 as well as each subprogram parameter.
14473
14474 Thus the results from this metric will be significantly greater than might
14475 be expected from a naive view of counting semicolons.
14476
14477 @item Maximal static nesting level of inner program units
14478 According to
14479 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14480 package, a task unit, a protected unit, a
14481 protected entry, a generic unit, or an explicitly declared subprogram other
14482 than an enumeration literal.''
14483
14484 @item Maximal nesting level of composite syntactic constructs
14485 This corresponds to the notion of the
14486 maximum nesting level in the GNAT built-in style checks
14487 (@pxref{Style Checking})
14488 @end table
14489
14490 @noindent
14491 For the outermost unit in the file, @command{gnatmetric} additionally computes
14492 the following metrics:
14493
14494 @table @emph
14495 @item Public subprograms
14496 This metric is computed for package specs. It is the
14497 number of subprograms and generic subprograms declared in the visible
14498 part (including the visible part of nested packages, protected objects, and
14499 protected types).
14500
14501 @item All subprograms
14502 This metric is computed for bodies and subunits. The
14503 metric is equal to a total number of subprogram bodies in the compilation
14504 unit.
14505 Neither generic instantiations nor renamings-as-a-body nor body stubs
14506 are counted. Any subprogram body is counted, independently of its nesting
14507 level and enclosing constructs. Generic bodies and bodies of protected
14508 subprograms are counted in the same way as ``usual'' subprogram bodies.
14509
14510 @item Public types
14511 This metric is computed for package specs and
14512 generic package declarations. It is the total number of types
14513 that can be referenced from outside this compilation unit, plus the
14514 number of types from all the visible parts of all the visible generic
14515 packages. Generic formal types are not counted.  Only types, not subtypes,
14516 are included.
14517
14518 @noindent
14519 Along with the total number of public types, the following
14520 types are counted and reported separately:
14521
14522 @itemize @bullet
14523 @item
14524 Abstract types
14525
14526 @item
14527 Root tagged types (abstract, non-abstract, private, non-private). Type
14528 extensions are @emph{not} counted
14529
14530 @item
14531 Private types (including private extensions)
14532
14533 @item
14534 Task types
14535
14536 @item
14537 Protected types
14538
14539 @end itemize
14540
14541 @item All types
14542 This metric is computed for any compilation unit. It is equal to the total
14543 number of the declarations of different types given in the compilation unit.
14544 The private and the corresponding full type declaration are counted as one
14545 type declaration. Incomplete type declarations and generic formal types
14546 are not counted.
14547 No distinction is made among different kinds of types (abstract,
14548 private etc.); the total number of types is computed and reported.
14549
14550 @end table
14551
14552 @noindent
14553 By default, all the syntax metrics are computed and reported. You can use the
14554 following switches to select specific syntax metrics.
14555
14556 @table @option
14557
14558 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14559
14560 @ifclear vms
14561 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14562 @end ifclear
14563
14564 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14565 Report all the syntax metrics
14566
14567 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14568 Do not report any of syntax metrics
14569
14570 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14571 Report the total number of declarations
14572
14573 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14574 Do not report the total number of declarations
14575
14576 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14577 Report the total number of statements
14578
14579 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14580 Do not report the total number of statements
14581
14582 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14583 Report the number of public subprograms in a compilation unit
14584
14585 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14586 Do not report the number of public subprograms in a compilation unit
14587
14588 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14589 Report the number of all the subprograms in a compilation unit
14590
14591 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14592 Do not report the number of all the subprograms in a compilation unit
14593
14594 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14595 Report the number of public types in a compilation unit
14596
14597 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14598 Do not report the number of public types in a compilation unit
14599
14600 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14601 Report the number of all the types in a compilation unit
14602
14603 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14604 Do not report the number of all the types in a compilation unit
14605
14606 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14607 Report the maximal program unit nesting level
14608
14609 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14610 Do not report the maximal program unit nesting level
14611
14612 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14613 Report the maximal construct nesting level
14614
14615 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14616 Do not report the maximal construct nesting level
14617
14618 @end table
14619
14620 @node Complexity Metrics Control
14621 @subsubsection Complexity Metrics Control
14622 @cindex Complexity metrics control in @command{gnatmetric}
14623
14624 @noindent
14625 For a program unit that is an executable body (a subprogram body (including
14626 generic bodies), task body, entry body or a package body containing
14627 its own statement sequence) @command{gnatmetric} computes the following
14628 complexity metrics:
14629
14630 @itemize @bullet
14631 @item
14632 McCabe cyclomatic complexity;
14633
14634 @item
14635 McCabe essential complexity;
14636
14637 @item
14638 maximal loop nesting level;
14639
14640 @item
14641 extra exit points (for subprograms);
14642 @end itemize
14643
14644 @noindent
14645 The McCabe cyclomatic complexity metric is defined
14646 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14647
14648 According to McCabe, both control statements and short-circuit control forms
14649 should be taken into account when computing cyclomatic complexity. For each
14650 body, we compute three metric values:
14651
14652 @itemize @bullet
14653 @item
14654 the complexity introduced by control
14655 statements only, without taking into account short-circuit forms,
14656
14657 @item
14658 the complexity introduced by short-circuit control forms only, and
14659
14660 @item
14661 the total
14662 cyclomatic complexity, which is the sum of these two values.
14663 @end itemize
14664
14665 @noindent
14666
14667 The origin of cyclomatic complexity metric is the need to estimate the number
14668 of independent paths in the control flow graph that in turn gives the number
14669 of tests needed to satisfy paths coverage testing completeness criterion.
14670 Considered from the testing point of view, a static Ada @code{loop} (that is,
14671 the @code{loop} statement having static subtype in loop parameter
14672 specification) does not add to cyclomatic complexity. By providing
14673 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14674 may specify that such loops should not be counted when computing the
14675 cyclomatic complexity metric
14676
14677 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14678 counted for the code that is reduced by excluding all the pure structural Ada
14679 control statements. An compound statement is considered as a non-structural
14680 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14681 or if it contains a @code{goto} statement that transfers the control outside
14682 the operator. A selective accept statement with @code{terminate} alternative
14683 is considered as non-structural statement. When computing this metric,
14684 @code{exit} statements are treated in the same way as @code{goto}
14685 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14686
14687 The Ada essential complexity metric defined here is intended to quantify
14688 the extent to which the software is unstructured. It is adapted from
14689 the McCabe essential complexity metric defined in
14690 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14691 suitable for typical Ada usage. For example, short circuit forms
14692 are not penalized as unstructured in the Ada essential complexity metric.
14693
14694 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14695 the code in the exception handlers and in all the nested program units.
14696
14697 By default, all the complexity metrics are computed and reported.
14698 For more fine-grained control you can use
14699 the following switches:
14700
14701 @table @option
14702 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14703
14704 @ifclear vms
14705 @cindex @option{--no-complexity@var{x}}
14706 @end ifclear
14707
14708 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14709 Report all the complexity metrics
14710
14711 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14712 Do not report any of complexity metrics
14713
14714 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14715 Report the McCabe Cyclomatic Complexity
14716
14717 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14718 Do not report the McCabe Cyclomatic Complexity
14719
14720 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14721 Report the Essential Complexity
14722
14723 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14724 Do not report the Essential Complexity
14725
14726 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14727 Report maximal loop nesting level
14728
14729 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14730 Do not report maximal loop nesting level
14731
14732 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14733 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14734 task bodies, entry bodies and statement sequences in package bodies.
14735 The metric is computed and reported for whole set of processed Ada sources
14736 only.
14737
14738 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14739 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14740 bodies, task bodies, entry bodies and statement sequences in package bodies
14741
14742 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14743 @item ^-ne^/NO_EXITS_AS_GOTOS^
14744 Do not consider @code{exit} statements as @code{goto}s when
14745 computing Essential Complexity
14746
14747 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14748 @item ^--no-static-loop^/NO_STATIC_LOOP^
14749 Do not consider static loops when computing cyclomatic complexity
14750
14751 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14752 Report the extra exit points for subprogram bodies. As an exit point, this
14753 metric counts @code{return} statements and raise statements in case when the
14754 raised exception is not handled in the same body. In case of a function this
14755 metric subtracts 1 from the number of exit points, because a function body
14756 must contain at least one @code{return} statement.
14757
14758 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14759 Do not report the extra exit points for subprogram bodies
14760 @end table
14761
14762
14763 @node Coupling Metrics Control
14764 @subsubsection Coupling Metrics Control
14765 @cindex Coupling metrics control in @command{gnatmetric}
14766
14767 @noindent
14768 @cindex Coupling metrics (in in @command{gnatmetric})
14769 Coupling metrics measure the dependencies between a given entity and other
14770 entities the program consists of. The goal of these metrics is to estimate the
14771 stability of the whole program considered as the collection of entities
14772 (modules, classes etc.).
14773
14774 Gnatmetric computes the following coupling metrics:
14775
14776 @itemize @bullet
14777
14778 @item
14779 @emph{object-oriented coupling} - for classes in traditional object-oriented
14780 sense;
14781
14782 @item
14783 @emph{unit coupling} - for all the program units making up a program;
14784
14785 @item
14786 @emph{control coupling} - this metric counts dependencies between a unit and
14787 only those units that define subprograms;
14788 @end itemize
14789
14790 @noindent
14791 Two kinds of coupling metrics are computed:
14792
14793 @table @asis
14794 @item fan-out coupling (efferent coupling)
14795 @cindex fan-out coupling
14796 @cindex efferent coupling
14797 the number of entities the given entity depends upon. It
14798 estimates in what extent the given entity depends on the changes in
14799 ``external world''
14800
14801 @item fan-in coupling (afferent coupling)
14802 @cindex fan-in coupling
14803 @cindex afferent coupling
14804 the number of entities that depend on a given entity.
14805 It estimates in what extent the ``external world'' depends on the changes in a
14806 given entity
14807 @end table
14808
14809 @noindent
14810
14811 Object-oriented coupling metrics are metrics that measure the dependencies
14812 between a given class (or a group of classes) and the other classes in the
14813 program. In this subsection the term ``class'' is used in its traditional
14814 object-oriented programming sense (an instantiable module that contains data
14815 and/or method members). A @emph{category} (of classes) is a group of closely
14816 related classes that are reused and/or modified together.
14817
14818 A class @code{K}'s fan-out coupling is the number of classes
14819 that @code{K} depends upon.
14820 A category's fan-out coupling is the number of classes outside the
14821 category that the classes inside the category depend upon.
14822
14823 A class @code{K}'s fan-in coupling is the number of classes
14824 that depend upon @code{K}.
14825 A category's fan-in coupling is the number of classes outside the
14826 category that depend on classes belonging to the category.
14827
14828 Ada's implementation of the object-oriented paradigm does not use the
14829 traditional class notion, so the definition of the coupling
14830 metrics for Ada maps the class and class category notions
14831 onto Ada constructs.
14832
14833 For the coupling metrics, several kinds of modules -- a library package,
14834 a library generic package, and a library generic package instantiation --
14835 that define a tagged type or an interface type are
14836 considered to be a class. A category consists of a library package (or
14837 a library generic package) that defines a tagged or an interface type,
14838 together with all its descendant (generic) packages that define tagged
14839 or interface types. That is a
14840 category is an Ada hierarchy of library-level program units. So class coupling
14841 in case of Ada is called as tagged coupling, and category coupling - as
14842 hierarchy coupling.
14843
14844 For any package counted as a class, its body and subunits (if any) are
14845 considered together with its spec when counting the dependencies, and coupling
14846 metrics are reported for spec units only. For dependencies between classes,
14847 the Ada semantic dependencies are considered. For object-oriented coupling
14848 metrics, only dependencies on units that are considered as classes, are
14849 considered.
14850
14851 For unit and control coupling also not compilation units but program units are
14852 counted. That is, for a package, its spec, its body and its subunits (if any)
14853 are considered as making up one unit, and the dependencies that are counted
14854 are the dependencies of all these compilation units collected together as
14855 the dependencies as a (whole) unit. And metrics are reported for spec
14856 compilation units only (or for a subprogram body unit in case if there is no
14857 separate spec for the given subprogram).
14858
14859 For unit coupling, dependencies between all kinds of program units are
14860 considered. For control coupling, for each unit the dependencies of this unit
14861 upon units that define subprograms are counted, so control fan-out coupling
14862 is reported for all units, but control fan-in coupling - only for the units
14863 that define subprograms.
14864
14865
14866
14867
14868
14869
14870 When computing coupling metrics, @command{gnatmetric} counts only
14871 dependencies between units that are arguments of the gnatmetric call.
14872 Coupling metrics are program-wide (or project-wide) metrics, so to
14873 get a valid result, you should call @command{gnatmetric} for
14874 the whole set of sources that make up your program. It can be done
14875 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14876 option (see @ref{The GNAT Driver and Project Files} for details).
14877
14878 By default, all the coupling metrics are disabled. You can use the following
14879 switches to specify the coupling metrics to be computed and reported:
14880
14881 @table @option
14882
14883 @ifclear vms
14884 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14885 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14886 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14887 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14888 @end ifclear
14889
14890 @ifset vms
14891 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14892 @end ifset
14893
14894 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14895 Report all the coupling metrics
14896
14897 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14898 Report tagged (class) fan-out coupling
14899
14900 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14901 Report tagged (class) fan-in coupling
14902
14903 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14904 Report hierarchy (category) fan-out coupling
14905
14906 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14907 Report hierarchy (category) fan-in coupling
14908
14909 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14910 Report unit fan-out coupling
14911
14912 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14913 Report unit fan-in coupling
14914
14915 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14916 Report control fan-out coupling
14917
14918 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14919 Report control fan-in coupling
14920 @end table
14921
14922 @node Other gnatmetric Switches
14923 @subsection Other @code{gnatmetric} Switches
14924
14925 @noindent
14926 Additional @command{gnatmetric} switches are as follows:
14927
14928 @table @option
14929 @item ^-files @var{filename}^/FILES=@var{filename}^
14930 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14931 Take the argument source files from the specified file. This file should be an
14932 ordinary text file containing file names separated by spaces or
14933 line breaks. You can use this switch more than once in the same call to
14934 @command{gnatmetric}. You also can combine this switch with
14935 an explicit list of files.
14936
14937 @item ^-v^/VERBOSE^
14938 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14939 Verbose mode;
14940 @command{gnatmetric} generates version information and then
14941 a trace of sources being processed.
14942
14943 @item ^-q^/QUIET^
14944 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14945 Quiet mode.
14946 @end table
14947
14948 @node Generate project-wide metrics
14949 @subsection Generate project-wide metrics
14950
14951 In order to compute metrics on all units of a given project, you can use
14952 the @command{gnat} driver along with the @option{-P} option:
14953 @smallexample
14954    gnat metric -Pproj
14955 @end smallexample
14956
14957 @noindent
14958 If the project @code{proj} depends upon other projects, you can compute
14959 the metrics on the project closure using the @option{-U} option:
14960 @smallexample
14961    gnat metric -Pproj -U
14962 @end smallexample
14963
14964 @noindent
14965 Finally, if not all the units are relevant to a particular main
14966 program in the project closure, you can generate metrics for the set
14967 of units needed to create a given main program (unit closure) using
14968 the @option{-U} option followed by the name of the main unit:
14969 @smallexample
14970    gnat metric -Pproj -U main
14971 @end smallexample
14972
14973
14974 @c ***********************************
14975 @node File Name Krunching Using gnatkr
14976 @chapter File Name Krunching Using @code{gnatkr}
14977 @findex gnatkr
14978
14979 @noindent
14980 This chapter discusses the method used by the compiler to shorten
14981 the default file names chosen for Ada units so that they do not
14982 exceed the maximum length permitted. It also describes the
14983 @code{gnatkr} utility that can be used to determine the result of
14984 applying this shortening.
14985 @menu
14986 * About gnatkr::
14987 * Using gnatkr::
14988 * Krunching Method::
14989 * Examples of gnatkr Usage::
14990 @end menu
14991
14992 @node About gnatkr
14993 @section About @code{gnatkr}
14994
14995 @noindent
14996 The default file naming rule in GNAT
14997 is that the file name must be derived from
14998 the unit name. The exact default rule is as follows:
14999 @itemize @bullet
15000 @item
15001 Take the unit name and replace all dots by hyphens.
15002 @item
15003 If such a replacement occurs in the
15004 second character position of a name, and the first character is
15005 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15006 then replace the dot by the character
15007 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15008 instead of a minus.
15009 @end itemize
15010 The reason for this exception is to avoid clashes
15011 with the standard names for children of System, Ada, Interfaces,
15012 and GNAT, which use the prefixes
15013 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15014 respectively.
15015
15016 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15017 switch of the compiler activates a ``krunching''
15018 circuit that limits file names to nn characters (where nn is a decimal
15019 integer). For example, using OpenVMS,
15020 where the maximum file name length is
15021 39, the value of nn is usually set to 39, but if you want to generate
15022 a set of files that would be usable if ported to a system with some
15023 different maximum file length, then a different value can be specified.
15024 The default value of 39 for OpenVMS need not be specified.
15025
15026 The @code{gnatkr} utility can be used to determine the krunched name for
15027 a given file, when krunched to a specified maximum length.
15028
15029 @node Using gnatkr
15030 @section Using @code{gnatkr}
15031
15032 @noindent
15033 The @code{gnatkr} command has the form
15034
15035 @ifclear vms
15036 @smallexample
15037 @c $ gnatkr @var{name} @ovar{length}
15038 @c Expanding @ovar macro inline (explanation in macro def comments)
15039 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15040 @end smallexample
15041 @end ifclear
15042
15043 @ifset vms
15044 @smallexample
15045 $ gnatkr @var{name} /COUNT=nn
15046 @end smallexample
15047 @end ifset
15048
15049 @noindent
15050 @var{name} is the uncrunched file name, derived from the name of the unit
15051 in the standard manner described in the previous section (i.e., in particular
15052 all dots are replaced by hyphens). The file name may or may not have an
15053 extension (defined as a suffix of the form period followed by arbitrary
15054 characters other than period). If an extension is present then it will
15055 be preserved in the output. For example, when krunching @file{hellofile.ads}
15056 to eight characters, the result will be hellofil.ads.
15057
15058 Note: for compatibility with previous versions of @code{gnatkr} dots may
15059 appear in the name instead of hyphens, but the last dot will always be
15060 taken as the start of an extension. So if @code{gnatkr} is given an argument
15061 such as @file{Hello.World.adb} it will be treated exactly as if the first
15062 period had been a hyphen, and for example krunching to eight characters
15063 gives the result @file{hellworl.adb}.
15064
15065 Note that the result is always all lower case (except on OpenVMS where it is
15066 all upper case). Characters of the other case are folded as required.
15067
15068 @var{length} represents the length of the krunched name. The default
15069 when no argument is given is ^8^39^ characters. A length of zero stands for
15070 unlimited, in other words do not chop except for system files where the
15071 implied crunching length is always eight characters.
15072
15073 @noindent
15074 The output is the krunched name. The output has an extension only if the
15075 original argument was a file name with an extension.
15076
15077 @node Krunching Method
15078 @section Krunching Method
15079
15080 @noindent
15081 The initial file name is determined by the name of the unit that the file
15082 contains. The name is formed by taking the full expanded name of the
15083 unit and replacing the separating dots with hyphens and
15084 using ^lowercase^uppercase^
15085 for all letters, except that a hyphen in the second character position is
15086 replaced by a ^tilde^dollar sign^ if the first character is
15087 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15088 The extension is @code{.ads} for a
15089 spec and @code{.adb} for a body.
15090 Krunching does not affect the extension, but the file name is shortened to
15091 the specified length by following these rules:
15092
15093 @itemize @bullet
15094 @item
15095 The name is divided into segments separated by hyphens, tildes or
15096 underscores and all hyphens, tildes, and underscores are
15097 eliminated. If this leaves the name short enough, we are done.
15098
15099 @item
15100 If the name is too long, the longest segment is located (left-most
15101 if there are two of equal length), and shortened by dropping
15102 its last character. This is repeated until the name is short enough.
15103
15104 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15105 to fit the name into 8 characters as required by some operating systems.
15106
15107 @smallexample
15108 our-strings-wide_fixed 22
15109 our strings wide fixed 19
15110 our string  wide fixed 18
15111 our strin   wide fixed 17
15112 our stri    wide fixed 16
15113 our stri    wide fixe  15
15114 our str     wide fixe  14
15115 our str     wid  fixe  13
15116 our str     wid  fix   12
15117 ou  str     wid  fix   11
15118 ou  st      wid  fix   10
15119 ou  st      wi   fix   9
15120 ou  st      wi   fi    8
15121 Final file name: oustwifi.adb
15122 @end smallexample
15123
15124 @item
15125 The file names for all predefined units are always krunched to eight
15126 characters. The krunching of these predefined units uses the following
15127 special prefix replacements:
15128
15129 @table @file
15130 @item ada-
15131 replaced by @file{^a^A^-}
15132
15133 @item gnat-
15134 replaced by @file{^g^G^-}
15135
15136 @item interfaces-
15137 replaced by @file{^i^I^-}
15138
15139 @item system-
15140 replaced by @file{^s^S^-}
15141 @end table
15142
15143 These system files have a hyphen in the second character position. That
15144 is why normal user files replace such a character with a
15145 ^tilde^dollar sign^, to
15146 avoid confusion with system file names.
15147
15148 As an example of this special rule, consider
15149 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15150
15151 @smallexample
15152 ada-strings-wide_fixed 22
15153 a-  strings wide fixed 18
15154 a-  string  wide fixed 17
15155 a-  strin   wide fixed 16
15156 a-  stri    wide fixed 15
15157 a-  stri    wide fixe  14
15158 a-  str     wide fixe  13
15159 a-  str     wid  fixe  12
15160 a-  str     wid  fix   11
15161 a-  st      wid  fix   10
15162 a-  st      wi   fix   9
15163 a-  st      wi   fi    8
15164 Final file name: a-stwifi.adb
15165 @end smallexample
15166 @end itemize
15167
15168 Of course no file shortening algorithm can guarantee uniqueness over all
15169 possible unit names, and if file name krunching is used then it is your
15170 responsibility to ensure that no name clashes occur. The utility
15171 program @code{gnatkr} is supplied for conveniently determining the
15172 krunched name of a file.
15173
15174 @node Examples of gnatkr Usage
15175 @section Examples of @code{gnatkr} Usage
15176
15177 @smallexample
15178 @iftex
15179 @leftskip=0cm
15180 @end iftex
15181 @ifclear vms
15182 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15183 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15184 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15185 $ gnatkr grandparent-parent-child     --> grparchi
15186 @end ifclear
15187 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15188 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15189 @end smallexample
15190
15191 @node Preprocessing Using gnatprep
15192 @chapter Preprocessing Using @code{gnatprep}
15193 @findex gnatprep
15194
15195 @noindent
15196 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15197 preprocessing.
15198 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15199 special GNAT features.
15200 For further discussion of conditional compilation in general, see
15201 @ref{Conditional Compilation}.
15202
15203 @menu
15204 * Preprocessing Symbols::
15205 * Using gnatprep::
15206 * Switches for gnatprep::
15207 * Form of Definitions File::
15208 * Form of Input Text for gnatprep::
15209 @end menu
15210
15211 @node Preprocessing Symbols
15212 @section Preprocessing Symbols
15213
15214 @noindent
15215 Preprocessing symbols are defined in definition files and referred to in
15216 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15217 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15218 all characters need to be in the ASCII set (no accented letters).
15219
15220 @node Using gnatprep
15221 @section Using @code{gnatprep}
15222
15223 @noindent
15224 To call @code{gnatprep} use
15225
15226 @smallexample
15227 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15228 @c Expanding @ovar macro inline (explanation in macro def comments)
15229 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15230 @end smallexample
15231
15232 @noindent
15233 where
15234 @table @var
15235 @item switches
15236 is an optional sequence of switches as described in the next section.
15237
15238 @item infile
15239 is the full name of the input file, which is an Ada source
15240 file containing preprocessor directives.
15241
15242 @item outfile
15243 is the full name of the output file, which is an Ada source
15244 in standard Ada form. When used with GNAT, this file name will
15245 normally have an ads or adb suffix.
15246
15247 @item deffile
15248 is the full name of a text file containing definitions of
15249 preprocessing symbols to be referenced by the preprocessor. This argument is
15250 optional, and can be replaced by the use of the @option{-D} switch.
15251
15252 @end table
15253
15254 @node Switches for gnatprep
15255 @section Switches for @code{gnatprep}
15256
15257 @table @option
15258 @c !sort!
15259
15260 @item ^-b^/BLANK_LINES^
15261 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15262 Causes both preprocessor lines and the lines deleted by
15263 preprocessing to be replaced by blank lines in the output source file,
15264 preserving line numbers in the output file.
15265
15266 @item ^-c^/COMMENTS^
15267 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15268 Causes both preprocessor lines and the lines deleted
15269 by preprocessing to be retained in the output source as comments marked
15270 with the special string @code{"--! "}. This option will result in line numbers
15271 being preserved in the output file.
15272
15273 @item ^-C^/REPLACE_IN_COMMENTS^
15274 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15275 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15276 If this option is specified, then comments are scanned and any $symbol
15277 substitutions performed as in program text. This is particularly useful
15278 when structured comments are used (e.g., when writing programs in the
15279 SPARK dialect of Ada). Note that this switch is not available when
15280 doing integrated preprocessing (it would be useless in this context
15281 since comments are ignored by the compiler in any case).
15282
15283 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15284 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15285 Defines a new preprocessing symbol, associated with value. If no value is given
15286 on the command line, then symbol is considered to be @code{True}. This switch
15287 can be used in place of a definition file.
15288
15289 @ifset vms
15290 @item /REMOVE
15291 @cindex @option{/REMOVE} (@command{gnatprep})
15292 This is the default setting which causes lines deleted by preprocessing
15293 to be entirely removed from the output file.
15294 @end ifset
15295
15296 @item ^-r^/REFERENCE^
15297 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15298 Causes a @code{Source_Reference} pragma to be generated that
15299 references the original input file, so that error messages will use
15300 the file name of this original file. The use of this switch implies
15301 that preprocessor lines are not to be removed from the file, so its
15302 use will force @option{^-b^/BLANK_LINES^} mode if
15303 @option{^-c^/COMMENTS^}
15304 has not been specified explicitly.
15305
15306 Note that if the file to be preprocessed contains multiple units, then
15307 it will be necessary to @code{gnatchop} the output file from
15308 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15309 in the preprocessed file, it will be respected by
15310 @code{gnatchop ^-r^/REFERENCE^}
15311 so that the final chopped files will correctly refer to the original
15312 input source file for @code{gnatprep}.
15313
15314 @item ^-s^/SYMBOLS^
15315 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15316 Causes a sorted list of symbol names and values to be
15317 listed on the standard output file.
15318
15319 @item ^-u^/UNDEFINED^
15320 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15321 Causes undefined symbols to be treated as having the value FALSE in the context
15322 of a preprocessor test. In the absence of this option, an undefined symbol in
15323 a @code{#if} or @code{#elsif} test will be treated as an error.
15324
15325 @end table
15326
15327 @ifclear vms
15328 @noindent
15329 Note: if neither @option{-b} nor @option{-c} is present,
15330 then preprocessor lines and
15331 deleted lines are completely removed from the output, unless -r is
15332 specified, in which case -b is assumed.
15333 @end ifclear
15334
15335 @node Form of Definitions File
15336 @section Form of Definitions File
15337
15338 @noindent
15339 The definitions file contains lines of the form
15340
15341 @smallexample
15342 symbol := value
15343 @end smallexample
15344
15345 @noindent
15346 where symbol is a preprocessing symbol, and value is one of the following:
15347
15348 @itemize @bullet
15349 @item
15350 Empty, corresponding to a null substitution
15351 @item
15352 A string literal using normal Ada syntax
15353 @item
15354 Any sequence of characters from the set
15355 (letters, digits, period, underline).
15356 @end itemize
15357
15358 @noindent
15359 Comment lines may also appear in the definitions file, starting with
15360 the usual @code{--},
15361 and comments may be added to the definitions lines.
15362
15363 @node Form of Input Text for gnatprep
15364 @section Form of Input Text for @code{gnatprep}
15365
15366 @noindent
15367 The input text may contain preprocessor conditional inclusion lines,
15368 as well as general symbol substitution sequences.
15369
15370 The preprocessor conditional inclusion commands have the form
15371
15372 @smallexample
15373 @group
15374 @cartouche
15375 #if @i{expression} @r{[}then@r{]}
15376    lines
15377 #elsif @i{expression} @r{[}then@r{]}
15378    lines
15379 #elsif @i{expression} @r{[}then@r{]}
15380    lines
15381 @dots{}
15382 #else
15383    lines
15384 #end if;
15385 @end cartouche
15386 @end group
15387 @end smallexample
15388
15389 @noindent
15390 In this example, @i{expression} is defined by the following grammar:
15391 @smallexample
15392 @i{expression} ::=  <symbol>
15393 @i{expression} ::=  <symbol> = "<value>"
15394 @i{expression} ::=  <symbol> = <symbol>
15395 @i{expression} ::=  <symbol> 'Defined
15396 @i{expression} ::=  not @i{expression}
15397 @i{expression} ::=  @i{expression} and @i{expression}
15398 @i{expression} ::=  @i{expression} or @i{expression}
15399 @i{expression} ::=  @i{expression} and then @i{expression}
15400 @i{expression} ::=  @i{expression} or else @i{expression}
15401 @i{expression} ::=  ( @i{expression} )
15402 @end smallexample
15403
15404 The following restriction exists: it is not allowed to have "and" or "or"
15405 following "not" in the same expression without parentheses. For example, this
15406 is not allowed:
15407
15408 @smallexample
15409    not X or Y
15410 @end smallexample
15411
15412 This should be one of the following:
15413
15414 @smallexample
15415    (not X) or Y
15416    not (X or Y)
15417 @end smallexample
15418
15419 @noindent
15420 For the first test (@i{expression} ::= <symbol>) the symbol must have
15421 either the value true or false, that is to say the right-hand of the
15422 symbol definition must be one of the (case-insensitive) literals
15423 @code{True} or @code{False}. If the value is true, then the
15424 corresponding lines are included, and if the value is false, they are
15425 excluded.
15426
15427 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15428 the symbol has been defined in the definition file or by a @option{-D}
15429 switch on the command line. Otherwise, the test is false.
15430
15431 The equality tests are case insensitive, as are all the preprocessor lines.
15432
15433 If the symbol referenced is not defined in the symbol definitions file,
15434 then the effect depends on whether or not switch @option{-u}
15435 is specified. If so, then the symbol is treated as if it had the value
15436 false and the test fails. If this switch is not specified, then
15437 it is an error to reference an undefined symbol. It is also an error to
15438 reference a symbol that is defined with a value other than @code{True}
15439 or @code{False}.
15440
15441 The use of the @code{not} operator inverts the sense of this logical test.
15442 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15443 operators, without parentheses. For example, "if not X or Y then" is not
15444 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15445
15446 The @code{then} keyword is optional as shown
15447
15448 The @code{#} must be the first non-blank character on a line, but
15449 otherwise the format is free form. Spaces or tabs may appear between
15450 the @code{#} and the keyword. The keywords and the symbols are case
15451 insensitive as in normal Ada code. Comments may be used on a
15452 preprocessor line, but other than that, no other tokens may appear on a
15453 preprocessor line. Any number of @code{elsif} clauses can be present,
15454 including none at all. The @code{else} is optional, as in Ada.
15455
15456 The @code{#} marking the start of a preprocessor line must be the first
15457 non-blank character on the line, i.e., it must be preceded only by
15458 spaces or horizontal tabs.
15459
15460 Symbol substitution outside of preprocessor lines is obtained by using
15461 the sequence
15462
15463 @smallexample
15464 $symbol
15465 @end smallexample
15466
15467 @noindent
15468 anywhere within a source line, except in a comment or within a
15469 string literal. The identifier
15470 following the @code{$} must match one of the symbols defined in the symbol
15471 definition file, and the result is to substitute the value of the
15472 symbol in place of @code{$symbol} in the output file.
15473
15474 Note that although the substitution of strings within a string literal
15475 is not possible, it is possible to have a symbol whose defined value is
15476 a string literal. So instead of setting XYZ to @code{hello} and writing:
15477
15478 @smallexample
15479 Header : String := "$XYZ";
15480 @end smallexample
15481
15482 @noindent
15483 you should set XYZ to @code{"hello"} and write:
15484
15485 @smallexample
15486 Header : String := $XYZ;
15487 @end smallexample
15488
15489 @noindent
15490 and then the substitution will occur as desired.
15491
15492 @node The GNAT Library Browser gnatls
15493 @chapter The GNAT Library Browser @code{gnatls}
15494 @findex gnatls
15495 @cindex Library browser
15496
15497 @noindent
15498 @code{gnatls} is a tool that outputs information about compiled
15499 units. It gives the relationship between objects, unit names and source
15500 files. It can also be used to check the source dependencies of a unit
15501 as well as various characteristics.
15502
15503 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15504 driver (see @ref{The GNAT Driver and Project Files}).
15505
15506 @menu
15507 * Running gnatls::
15508 * Switches for gnatls::
15509 * Examples of gnatls Usage::
15510 @end menu
15511
15512 @node Running gnatls
15513 @section Running @code{gnatls}
15514
15515 @noindent
15516 The @code{gnatls} command has the form
15517
15518 @smallexample
15519 $ gnatls switches @var{object_or_ali_file}
15520 @end smallexample
15521
15522 @noindent
15523 The main argument is the list of object or @file{ali} files
15524 (@pxref{The Ada Library Information Files})
15525 for which information is requested.
15526
15527 In normal mode, without additional option, @code{gnatls} produces a
15528 four-column listing. Each line represents information for a specific
15529 object. The first column gives the full path of the object, the second
15530 column gives the name of the principal unit in this object, the third
15531 column gives the status of the source and the fourth column gives the
15532 full path of the source representing this unit.
15533 Here is a simple example of use:
15534
15535 @smallexample
15536 $ gnatls *.o
15537 ^./^[]^demo1.o            demo1            DIF demo1.adb
15538 ^./^[]^demo2.o            demo2             OK demo2.adb
15539 ^./^[]^hello.o            h1                OK hello.adb
15540 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15541 ^./^[]^instr.o            instr             OK instr.adb
15542 ^./^[]^tef.o              tef              DIF tef.adb
15543 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15544 ^./^[]^tgef.o             tgef             DIF tgef.adb
15545 @end smallexample
15546
15547 @noindent
15548 The first line can be interpreted as follows: the main unit which is
15549 contained in
15550 object file @file{demo1.o} is demo1, whose main source is in
15551 @file{demo1.adb}. Furthermore, the version of the source used for the
15552 compilation of demo1 has been modified (DIF). Each source file has a status
15553 qualifier which can be:
15554
15555 @table @code
15556 @item OK (unchanged)
15557 The version of the source file used for the compilation of the
15558 specified unit corresponds exactly to the actual source file.
15559
15560 @item MOK (slightly modified)
15561 The version of the source file used for the compilation of the
15562 specified unit differs from the actual source file but not enough to
15563 require recompilation. If you use gnatmake with the qualifier
15564 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15565 MOK will not be recompiled.
15566
15567 @item DIF (modified)
15568 No version of the source found on the path corresponds to the source
15569 used to build this object.
15570
15571 @item ??? (file not found)
15572 No source file was found for this unit.
15573
15574 @item HID (hidden,  unchanged version not first on PATH)
15575 The version of the source that corresponds exactly to the source used
15576 for compilation has been found on the path but it is hidden by another
15577 version of the same source that has been modified.
15578
15579 @end table
15580
15581 @node Switches for gnatls
15582 @section Switches for @code{gnatls}
15583
15584 @noindent
15585 @code{gnatls} recognizes the following switches:
15586
15587 @table @option
15588 @c !sort!
15589 @cindex @option{--version} @command{gnatls}
15590 Display Copyright and version, then exit disregarding all other options.
15591
15592 @item --help
15593 @cindex @option{--help} @command{gnatls}
15594 If @option{--version} was not used, display usage, then exit disregarding
15595 all other options.
15596
15597 @item ^-a^/ALL_UNITS^
15598 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15599 Consider all units, including those of the predefined Ada library.
15600 Especially useful with @option{^-d^/DEPENDENCIES^}.
15601
15602 @item ^-d^/DEPENDENCIES^
15603 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15604 List sources from which specified units depend on.
15605
15606 @item ^-h^/OUTPUT=OPTIONS^
15607 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15608 Output the list of options.
15609
15610 @item ^-o^/OUTPUT=OBJECTS^
15611 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15612 Only output information about object files.
15613
15614 @item ^-s^/OUTPUT=SOURCES^
15615 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15616 Only output information about source files.
15617
15618 @item ^-u^/OUTPUT=UNITS^
15619 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15620 Only output information about compilation units.
15621
15622 @item ^-files^/FILES^=@var{file}
15623 @cindex @option{^-files^/FILES^} (@code{gnatls})
15624 Take as arguments the files listed in text file @var{file}.
15625 Text file @var{file} may contain empty lines that are ignored.
15626 Each nonempty line should contain the name of an existing file.
15627 Several such switches may be specified simultaneously.
15628
15629 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15630 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15631 @itemx ^-I^/SEARCH=^@var{dir}
15632 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15633 @itemx -nostdinc
15634 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15635 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15636 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15637 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15638 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15639 flags (@pxref{Switches for gnatmake}).
15640
15641 @item --RTS=@var{rts-path}
15642 @cindex @option{--RTS} (@code{gnatls})
15643 Specifies the default location of the runtime library. Same meaning as the
15644 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15645
15646 @item ^-v^/OUTPUT=VERBOSE^
15647 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15648 Verbose mode. Output the complete source, object and project paths. Do not use
15649 the default column layout but instead use long format giving as much as
15650 information possible on each requested units, including special
15651 characteristics such as:
15652
15653 @table @code
15654 @item  Preelaborable
15655 The unit is preelaborable in the Ada sense.
15656
15657 @item No_Elab_Code
15658 No elaboration code has been produced by the compiler for this unit.
15659
15660 @item Pure
15661 The unit is pure in the Ada sense.
15662
15663 @item Elaborate_Body
15664 The unit contains a pragma Elaborate_Body.
15665
15666 @item Remote_Types
15667 The unit contains a pragma Remote_Types.
15668
15669 @item Shared_Passive
15670 The unit contains a pragma Shared_Passive.
15671
15672 @item Predefined
15673 This unit is part of the predefined environment and cannot be modified
15674 by the user.
15675
15676 @item Remote_Call_Interface
15677 The unit contains a pragma Remote_Call_Interface.
15678
15679 @end table
15680
15681 @end table
15682
15683 @node Examples of gnatls Usage
15684 @section Example of @code{gnatls} Usage
15685 @ifclear vms
15686
15687 @noindent
15688 Example of using the verbose switch. Note how the source and
15689 object paths are affected by the -I switch.
15690
15691 @smallexample
15692 $ gnatls -v -I.. demo1.o
15693
15694 GNATLS 5.03w (20041123-34)
15695 Copyright 1997-2004 Free Software Foundation, Inc.
15696
15697 Source Search Path:
15698    <Current_Directory>
15699    ../
15700    /home/comar/local/adainclude/
15701
15702 Object Search Path:
15703    <Current_Directory>
15704    ../
15705    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15706
15707 Project Search Path:
15708    <Current_Directory>
15709    /home/comar/local/lib/gnat/
15710
15711 ./demo1.o
15712    Unit =>
15713      Name   => demo1
15714      Kind   => subprogram body
15715      Flags  => No_Elab_Code
15716      Source => demo1.adb    modified
15717 @end smallexample
15718
15719 @noindent
15720 The following is an example of use of the dependency list.
15721 Note the use of the -s switch
15722 which gives a straight list of source files. This can be useful for
15723 building specialized scripts.
15724
15725 @smallexample
15726 $ gnatls -d demo2.o
15727 ./demo2.o   demo2        OK demo2.adb
15728                          OK gen_list.ads
15729                          OK gen_list.adb
15730                          OK instr.ads
15731                          OK instr-child.ads
15732
15733 $ gnatls -d -s -a demo1.o
15734 demo1.adb
15735 /home/comar/local/adainclude/ada.ads
15736 /home/comar/local/adainclude/a-finali.ads
15737 /home/comar/local/adainclude/a-filico.ads
15738 /home/comar/local/adainclude/a-stream.ads
15739 /home/comar/local/adainclude/a-tags.ads
15740 gen_list.ads
15741 gen_list.adb
15742 /home/comar/local/adainclude/gnat.ads
15743 /home/comar/local/adainclude/g-io.ads
15744 instr.ads
15745 /home/comar/local/adainclude/system.ads
15746 /home/comar/local/adainclude/s-exctab.ads
15747 /home/comar/local/adainclude/s-finimp.ads
15748 /home/comar/local/adainclude/s-finroo.ads
15749 /home/comar/local/adainclude/s-secsta.ads
15750 /home/comar/local/adainclude/s-stalib.ads
15751 /home/comar/local/adainclude/s-stoele.ads
15752 /home/comar/local/adainclude/s-stratt.ads
15753 /home/comar/local/adainclude/s-tasoli.ads
15754 /home/comar/local/adainclude/s-unstyp.ads
15755 /home/comar/local/adainclude/unchconv.ads
15756 @end smallexample
15757 @end ifclear
15758
15759 @ifset vms
15760 @smallexample
15761 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15762
15763 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15764 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15765 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15766 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15767 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15768 demo1.adb
15769 gen_list.ads
15770 gen_list.adb
15771 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15772 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15773 instr.ads
15774 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15775 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15776 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15777 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15778 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15779 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15780 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15781 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15782 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15783 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15784 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15785 @end smallexample
15786 @end ifset
15787
15788 @node Cleaning Up Using gnatclean
15789 @chapter Cleaning Up Using @code{gnatclean}
15790 @findex gnatclean
15791 @cindex Cleaning tool
15792
15793 @noindent
15794 @code{gnatclean} is a tool that allows the deletion of files produced by the
15795 compiler, binder and linker, including ALI files, object files, tree files,
15796 expanded source files, library files, interface copy source files, binder
15797 generated files and executable files.
15798
15799 @menu
15800 * Running gnatclean::
15801 * Switches for gnatclean::
15802 @c * Examples of gnatclean Usage::
15803 @end menu
15804
15805 @node Running gnatclean
15806 @section Running @code{gnatclean}
15807
15808 @noindent
15809 The @code{gnatclean} command has the form:
15810
15811 @smallexample
15812 $ gnatclean switches @var{names}
15813 @end smallexample
15814
15815 @noindent
15816 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15817 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15818 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15819
15820 @noindent
15821 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15822 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15823 the linker. In informative-only mode, specified by switch
15824 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15825 normal mode is listed, but no file is actually deleted.
15826
15827 @node Switches for gnatclean
15828 @section Switches for @code{gnatclean}
15829
15830 @noindent
15831 @code{gnatclean} recognizes the following switches:
15832
15833 @table @option
15834 @c !sort!
15835 @cindex @option{--version} @command{gnatclean}
15836 Display Copyright and version, then exit disregarding all other options.
15837
15838 @item --help
15839 @cindex @option{--help} @command{gnatclean}
15840 If @option{--version} was not used, display usage, then exit disregarding
15841 all other options.
15842
15843 @item ^--subdirs^/SUBDIRS^=subdir
15844 Actual object directory of each project file is the subdirectory subdir of the
15845 object directory specified or defaulted in the project file.
15846
15847 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15848 By default, shared library projects are not allowed to import static library
15849 projects. When this switch is used on the command line, this restriction is
15850 relaxed.
15851
15852 @item ^-c^/COMPILER_FILES_ONLY^
15853 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15854 Only attempt to delete the files produced by the compiler, not those produced
15855 by the binder or the linker. The files that are not to be deleted are library
15856 files, interface copy files, binder generated files and executable files.
15857
15858 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15859 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15860 Indicate that ALI and object files should normally be found in directory
15861 @var{dir}.
15862
15863 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15864 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15865 When using project files, if some errors or warnings are detected during
15866 parsing and verbose mode is not in effect (no use of switch
15867 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15868 file, rather than its simple file name.
15869
15870 @item ^-h^/HELP^
15871 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15872 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15873
15874 @item ^-n^/NODELETE^
15875 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15876 Informative-only mode. Do not delete any files. Output the list of the files
15877 that would have been deleted if this switch was not specified.
15878
15879 @item ^-P^/PROJECT_FILE=^@var{project}
15880 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15881 Use project file @var{project}. Only one such switch can be used.
15882 When cleaning a project file, the files produced by the compilation of the
15883 immediate sources or inherited sources of the project files are to be
15884 deleted. This is not depending on the presence or not of executable names
15885 on the command line.
15886
15887 @item ^-q^/QUIET^
15888 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15889 Quiet output. If there are no errors, do not output anything, except in
15890 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15891 (switch ^-n^/NODELETE^).
15892
15893 @item ^-r^/RECURSIVE^
15894 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15895 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15896 clean all imported and extended project files, recursively. If this switch
15897 is not specified, only the files related to the main project file are to be
15898 deleted. This switch has no effect if no project file is specified.
15899
15900 @item ^-v^/VERBOSE^
15901 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15902 Verbose mode.
15903
15904 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15905 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15906 Indicates the verbosity of the parsing of GNAT project files.
15907 @xref{Switches Related to Project Files}.
15908
15909 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15910 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15911 Indicates that external variable @var{name} has the value @var{value}.
15912 The Project Manager will use this value for occurrences of
15913 @code{external(name)} when parsing the project file.
15914 @xref{Switches Related to Project Files}.
15915
15916 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15917 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15918 When searching for ALI and object files, look in directory
15919 @var{dir}.
15920
15921 @item ^-I^/SEARCH=^@var{dir}
15922 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15923 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15924
15925 @item ^-I-^/NOCURRENT_DIRECTORY^
15926 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15927 @cindex Source files, suppressing search
15928 Do not look for ALI or object files in the directory
15929 where @code{gnatclean} was invoked.
15930
15931 @end table
15932
15933 @c @node Examples of gnatclean Usage
15934 @c @section Examples of @code{gnatclean} Usage
15935
15936 @ifclear vms
15937 @node GNAT and Libraries
15938 @chapter GNAT and Libraries
15939 @cindex Library, building, installing, using
15940
15941 @noindent
15942 This chapter describes how to build and use libraries with GNAT, and also shows
15943 how to recompile the GNAT run-time library. You should be familiar with the
15944 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15945 chapter.
15946
15947 @menu
15948 * Introduction to Libraries in GNAT::
15949 * General Ada Libraries::
15950 * Stand-alone Ada Libraries::
15951 * Rebuilding the GNAT Run-Time Library::
15952 @end menu
15953
15954 @node Introduction to Libraries in GNAT
15955 @section Introduction to Libraries in GNAT
15956
15957 @noindent
15958 A library is, conceptually, a collection of objects which does not have its
15959 own main thread of execution, but rather provides certain services to the
15960 applications that use it. A library can be either statically linked with the
15961 application, in which case its code is directly included in the application,
15962 or, on platforms that support it, be dynamically linked, in which case
15963 its code is shared by all applications making use of this library.
15964
15965 GNAT supports both types of libraries.
15966 In the static case, the compiled code can be provided in different ways. The
15967 simplest approach is to provide directly the set of objects resulting from
15968 compilation of the library source files. Alternatively, you can group the
15969 objects into an archive using whatever commands are provided by the operating
15970 system. For the latter case, the objects are grouped into a shared library.
15971
15972 In the GNAT environment, a library has three types of components:
15973 @itemize @bullet
15974 @item
15975 Source files.
15976 @item
15977 @file{ALI} files.
15978 @xref{The Ada Library Information Files}.
15979 @item
15980 Object files, an archive or a shared library.
15981 @end itemize
15982
15983 @noindent
15984 A GNAT library may expose all its source files, which is useful for
15985 documentation purposes. Alternatively, it may expose only the units needed by
15986 an external user to make use of the library. That is to say, the specs
15987 reflecting the library services along with all the units needed to compile
15988 those specs, which can include generic bodies or any body implementing an
15989 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15990 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15991
15992 All compilation units comprising an application, including those in a library,
15993 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15994 computes the elaboration order from the @file{ALI} files and this is why they
15995 constitute a mandatory part of GNAT libraries.
15996 @emph{Stand-alone libraries} are the exception to this rule because a specific
15997 library elaboration routine is produced independently of the application(s)
15998 using the library.
15999
16000 @node General Ada Libraries
16001 @section General Ada Libraries
16002
16003 @menu
16004 * Building a library::
16005 * Installing a library::
16006 * Using a library::
16007 @end menu
16008
16009 @node Building a library
16010 @subsection Building a library
16011
16012 @noindent
16013 The easiest way to build a library is to use the Project Manager,
16014 which supports a special type of project called a @emph{Library Project}
16015 (@pxref{Library Projects}).
16016
16017 A project is considered a library project, when two project-level attributes
16018 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16019 control different aspects of library configuration, additional optional
16020 project-level attributes can be specified:
16021 @table @code
16022 @item Library_Kind
16023 This attribute controls whether the library is to be static or dynamic
16024
16025 @item Library_Version
16026 This attribute specifies the library version; this value is used
16027 during dynamic linking of shared libraries to determine if the currently
16028 installed versions of the binaries are compatible.
16029
16030 @item Library_Options
16031 @item Library_GCC
16032 These attributes specify additional low-level options to be used during
16033 library generation, and redefine the actual application used to generate
16034 library.
16035 @end table
16036
16037 @noindent
16038 The GNAT Project Manager takes full care of the library maintenance task,
16039 including recompilation of the source files for which objects do not exist
16040 or are not up to date, assembly of the library archive, and installation of
16041 the library (i.e., copying associated source, object and @file{ALI} files
16042 to the specified location).
16043
16044 Here is a simple library project file:
16045 @smallexample @c ada
16046 project My_Lib is
16047    for Source_Dirs use ("src1", "src2");
16048    for Object_Dir use "obj";
16049    for Library_Name use "mylib";
16050    for Library_Dir use "lib";
16051    for Library_Kind use "dynamic";
16052 end My_lib;
16053 @end smallexample
16054
16055 @noindent
16056 and the compilation command to build and install the library:
16057
16058 @smallexample @c ada
16059   $ gnatmake -Pmy_lib
16060 @end smallexample
16061
16062 @noindent
16063 It is not entirely trivial to perform manually all the steps required to
16064 produce a library. We recommend that you use the GNAT Project Manager
16065 for this task. In special cases where this is not desired, the necessary
16066 steps are discussed below.
16067
16068 There are various possibilities for compiling the units that make up the
16069 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16070 with a conventional script. For simple libraries, it is also possible to create
16071 a dummy main program which depends upon all the packages that comprise the
16072 interface of the library. This dummy main program can then be given to
16073 @command{gnatmake}, which will ensure that all necessary objects are built.
16074
16075 After this task is accomplished, you should follow the standard procedure
16076 of the underlying operating system to produce the static or shared library.
16077
16078 Here is an example of such a dummy program:
16079 @smallexample @c ada
16080 @group
16081 with My_Lib.Service1;
16082 with My_Lib.Service2;
16083 with My_Lib.Service3;
16084 procedure My_Lib_Dummy is
16085 begin
16086    null;
16087 end;
16088 @end group
16089 @end smallexample
16090
16091 @noindent
16092 Here are the generic commands that will build an archive or a shared library.
16093
16094 @smallexample
16095 # compiling the library
16096 $ gnatmake -c my_lib_dummy.adb
16097
16098 # we don't need the dummy object itself
16099 $ rm my_lib_dummy.o my_lib_dummy.ali
16100
16101 # create an archive with the remaining objects
16102 $ ar rc libmy_lib.a *.o
16103 # some systems may require "ranlib" to be run as well
16104
16105 # or create a shared library
16106 $ gcc -shared -o libmy_lib.so *.o
16107 # some systems may require the code to have been compiled with -fPIC
16108
16109 # remove the object files that are now in the library
16110 $ rm *.o
16111
16112 # Make the ALI files read-only so that gnatmake will not try to
16113 # regenerate the objects that are in the library
16114 $ chmod -w *.ali
16115 @end smallexample
16116
16117 @noindent
16118 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16119 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16120 be accessed by the directive @option{-l@var{xxx}} at link time.
16121
16122 @node Installing a library
16123 @subsection Installing a library
16124 @cindex @code{ADA_PROJECT_PATH}
16125 @cindex @code{GPR_PROJECT_PATH}
16126
16127 @noindent
16128 If you use project files, library installation is part of the library build
16129 process (@pxref{Installing a library with project files}).
16130
16131 When project files are not an option, it is also possible, but not recommended,
16132 to install the library so that the sources needed to use the library are on the
16133 Ada source path and the ALI files & libraries be on the Ada Object path (see
16134 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16135 administrator can place general-purpose libraries in the default compiler
16136 paths, by specifying the libraries' location in the configuration files
16137 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16138 must be located in the GNAT installation tree at the same place as the gcc spec
16139 file. The location of the gcc spec file can be determined as follows:
16140 @smallexample
16141 $ gcc -v
16142 @end smallexample
16143
16144 @noindent
16145 The configuration files mentioned above have a simple format: each line
16146 must contain one unique directory name.
16147 Those names are added to the corresponding path
16148 in their order of appearance in the file. The names can be either absolute
16149 or relative; in the latter case, they are relative to where theses files
16150 are located.
16151
16152 The files @file{ada_source_path} and @file{ada_object_path} might not be
16153 present in a
16154 GNAT installation, in which case, GNAT will look for its run-time library in
16155 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16156 objects and @file{ALI} files). When the files exist, the compiler does not
16157 look in @file{adainclude} and @file{adalib}, and thus the
16158 @file{ada_source_path} file
16159 must contain the location for the GNAT run-time sources (which can simply
16160 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16161 contain the location for the GNAT run-time objects (which can simply
16162 be @file{adalib}).
16163
16164 You can also specify a new default path to the run-time library at compilation
16165 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16166 the run-time library you want your program to be compiled with. This switch is
16167 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16168 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16169
16170 It is possible to install a library before or after the standard GNAT
16171 library, by reordering the lines in the configuration files. In general, a
16172 library must be installed before the GNAT library if it redefines
16173 any part of it.
16174
16175 @node Using a library
16176 @subsection Using a library
16177
16178 @noindent Once again, the project facility greatly simplifies the use of
16179 libraries. In this context, using a library is just a matter of adding a
16180 @code{with} clause in the user project. For instance, to make use of the
16181 library @code{My_Lib} shown in examples in earlier sections, you can
16182 write:
16183
16184 @smallexample @c projectfile
16185 with "my_lib";
16186 project My_Proj is
16187   @dots{}
16188 end My_Proj;
16189 @end smallexample
16190
16191 Even if you have a third-party, non-Ada library, you can still use GNAT's
16192 Project Manager facility to provide a wrapper for it. For example, the
16193 following project, when @code{with}ed by your main project, will link with the
16194 third-party library @file{liba.a}:
16195
16196 @smallexample @c projectfile
16197 @group
16198 project Liba is
16199    for Externally_Built use "true";
16200    for Source_Files use ();
16201    for Library_Dir use "lib";
16202    for Library_Name use "a";
16203    for Library_Kind use "static";
16204 end Liba;
16205 @end group
16206 @end smallexample
16207 This is an alternative to the use of @code{pragma Linker_Options}. It is
16208 especially interesting in the context of systems with several interdependent
16209 static libraries where finding a proper linker order is not easy and best be
16210 left to the tools having visibility over project dependence information.
16211
16212 @noindent
16213 In order to use an Ada library manually, you need to make sure that this
16214 library is on both your source and object path
16215 (see @ref{Search Paths and the Run-Time Library (RTL)}
16216 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16217 in an archive or a shared library, you need to specify the desired
16218 library at link time.
16219
16220 For example, you can use the library @file{mylib} installed in
16221 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16222
16223 @smallexample
16224 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16225   -largs -lmy_lib
16226 @end smallexample
16227
16228 @noindent
16229 This can be expressed more simply:
16230 @smallexample
16231 $ gnatmake my_appl
16232 @end smallexample
16233 @noindent
16234 when the following conditions are met:
16235 @itemize @bullet
16236 @item
16237 @file{/dir/my_lib_src} has been added by the user to the environment
16238 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16239 @file{ada_source_path}
16240 @item
16241 @file{/dir/my_lib_obj} has been added by the user to the environment
16242 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16243 @file{ada_object_path}
16244 @item
16245 a pragma @code{Linker_Options} has been added to one of the sources.
16246 For example:
16247
16248 @smallexample @c ada
16249 pragma Linker_Options ("-lmy_lib");
16250 @end smallexample
16251 @end itemize
16252
16253 @node Stand-alone Ada Libraries
16254 @section Stand-alone Ada Libraries
16255 @cindex Stand-alone library, building, using
16256
16257 @menu
16258 * Introduction to Stand-alone Libraries::
16259 * Building a Stand-alone Library::
16260 * Creating a Stand-alone Library to be used in a non-Ada context::
16261 * Restrictions in Stand-alone Libraries::
16262 @end menu
16263
16264 @node Introduction to Stand-alone Libraries
16265 @subsection Introduction to Stand-alone Libraries
16266
16267 @noindent
16268 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16269 necessary code to
16270 elaborate the Ada units that are included in the library. In contrast with
16271 an ordinary library, which consists of all sources, objects and @file{ALI}
16272 files of the
16273 library, a SAL may specify a restricted subset of compilation units
16274 to serve as a library interface. In this case, the fully
16275 self-sufficient set of files will normally consist of an objects
16276 archive, the sources of interface units' specs, and the @file{ALI}
16277 files of interface units.
16278 If an interface spec contains a generic unit or an inlined subprogram,
16279 the body's
16280 source must also be provided; if the units that must be provided in the source
16281 form depend on other units, the source and @file{ALI} files of those must
16282 also be provided.
16283
16284 The main purpose of a SAL is to minimize the recompilation overhead of client
16285 applications when a new version of the library is installed. Specifically,
16286 if the interface sources have not changed, client applications do not need to
16287 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16288 version, controlled by @code{Library_Version} attribute, is not changed,
16289 then the clients do not need to be relinked.
16290
16291 SALs also allow the library providers to minimize the amount of library source
16292 text exposed to the clients.  Such ``information hiding'' might be useful or
16293 necessary for various reasons.
16294
16295 Stand-alone libraries are also well suited to be used in an executable whose
16296 main routine is not written in Ada.
16297
16298 @node Building a Stand-alone Library
16299 @subsection Building a Stand-alone Library
16300
16301 @noindent
16302 GNAT's Project facility provides a simple way of building and installing
16303 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16304 To be a Stand-alone Library Project, in addition to the two attributes
16305 that make a project a Library Project (@code{Library_Name} and
16306 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16307 @code{Library_Interface} must be defined.  For example:
16308
16309 @smallexample @c projectfile
16310 @group
16311    for Library_Dir use "lib_dir";
16312    for Library_Name use "dummy";
16313    for Library_Interface use ("int1", "int1.child");
16314 @end group
16315 @end smallexample
16316
16317 @noindent
16318 Attribute @code{Library_Interface} has a non-empty string list value,
16319 each string in the list designating a unit contained in an immediate source
16320 of the project file.
16321
16322 When a Stand-alone Library is built, first the binder is invoked to build
16323 a package whose name depends on the library name
16324 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16325 This binder-generated package includes initialization and
16326 finalization procedures whose
16327 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16328 in the example
16329 above). The object corresponding to this package is included in the library.
16330
16331 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16332 calling of these procedures if a static SAL is built, or if a shared SAL
16333 is built
16334 with the project-level attribute @code{Library_Auto_Init} set to
16335 @code{"false"}.
16336
16337 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16338 (those that are listed in attribute @code{Library_Interface}) are copied to
16339 the Library Directory. As a consequence, only the Interface Units may be
16340 imported from Ada units outside of the library. If other units are imported,
16341 the binding phase will fail.
16342
16343 The attribute @code{Library_Src_Dir} may be specified for a
16344 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16345 single string value. Its value must be the path (absolute or relative to the
16346 project directory) of an existing directory. This directory cannot be the
16347 object directory or one of the source directories, but it can be the same as
16348 the library directory. The sources of the Interface
16349 Units of the library that are needed by an Ada client of the library will be
16350 copied to the designated directory, called the Interface Copy directory.
16351 These sources include the specs of the Interface Units, but they may also
16352 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16353 are used, or when there is a generic unit in the spec. Before the sources
16354 are copied to the Interface Copy directory, an attempt is made to delete all
16355 files in the Interface Copy directory.
16356
16357 Building stand-alone libraries by hand is somewhat tedious, but for those
16358 occasions when it is necessary here are the steps that you need to perform:
16359 @itemize @bullet
16360 @item
16361 Compile all library sources.
16362
16363 @item
16364 Invoke the binder with the switch @option{-n} (No Ada main program),
16365 with all the @file{ALI} files of the interfaces, and
16366 with the switch @option{-L} to give specific names to the @code{init}
16367 and @code{final} procedures.  For example:
16368 @smallexample
16369   gnatbind -n int1.ali int2.ali -Lsal1
16370 @end smallexample
16371
16372 @item
16373 Compile the binder generated file:
16374 @smallexample
16375   gcc -c b~int2.adb
16376 @end smallexample
16377
16378 @item
16379 Link the dynamic library with all the necessary object files,
16380 indicating to the linker the names of the @code{init} (and possibly
16381 @code{final}) procedures for automatic initialization (and finalization).
16382 The built library should be placed in a directory different from
16383 the object directory.
16384
16385 @item
16386 Copy the @code{ALI} files of the interface to the library directory,
16387 add in this copy an indication that it is an interface to a SAL
16388 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16389 with letter ``P'') and make the modified copy of the @file{ALI} file
16390 read-only.
16391 @end itemize
16392
16393 @noindent
16394 Using SALs is not different from using other libraries
16395 (see @ref{Using a library}).
16396
16397 @node Creating a Stand-alone Library to be used in a non-Ada context
16398 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16399
16400 @noindent
16401 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16402 a non-Ada context.
16403
16404 The only extra step required is to ensure that library interface subprograms
16405 are compatible with the main program, by means of @code{pragma Export}
16406 or @code{pragma Convention}.
16407
16408 Here is an example of simple library interface for use with C main program:
16409
16410 @smallexample @c ada
16411 package My_Package is
16412
16413    procedure Do_Something;
16414    pragma Export (C, Do_Something, "do_something");
16415
16416    procedure Do_Something_Else;
16417    pragma Export (C, Do_Something_Else, "do_something_else");
16418
16419 end My_Package;
16420 @end smallexample
16421
16422 @noindent
16423 On the foreign language side, you must provide a ``foreign'' view of the
16424 library interface; remember that it should contain elaboration routines in
16425 addition to interface subprograms.
16426
16427 The example below shows the content of @code{mylib_interface.h} (note
16428 that there is no rule for the naming of this file, any name can be used)
16429 @smallexample
16430 /* the library elaboration procedure */
16431 extern void mylibinit (void);
16432
16433 /* the library finalization procedure */
16434 extern void mylibfinal (void);
16435
16436 /* the interface exported by the library */
16437 extern void do_something (void);
16438 extern void do_something_else (void);
16439 @end smallexample
16440
16441 @noindent
16442 Libraries built as explained above can be used from any program, provided
16443 that the elaboration procedures (named @code{mylibinit} in the previous
16444 example) are called before the library services are used. Any number of
16445 libraries can be used simultaneously, as long as the elaboration
16446 procedure of each library is called.
16447
16448 Below is an example of a C program that uses the @code{mylib} library.
16449
16450 @smallexample
16451 #include "mylib_interface.h"
16452
16453 int
16454 main (void)
16455 @{
16456    /* First, elaborate the library before using it */
16457    mylibinit ();
16458
16459    /* Main program, using the library exported entities */
16460    do_something ();
16461    do_something_else ();
16462
16463    /* Library finalization at the end of the program */
16464    mylibfinal ();
16465    return 0;
16466 @}
16467 @end smallexample
16468
16469 @noindent
16470 Note that invoking any library finalization procedure generated by
16471 @code{gnatbind} shuts down the Ada run-time environment.
16472 Consequently, the
16473 finalization of all Ada libraries must be performed at the end of the program.
16474 No call to these libraries or to the Ada run-time library should be made
16475 after the finalization phase.
16476
16477 @node Restrictions in Stand-alone Libraries
16478 @subsection Restrictions in Stand-alone Libraries
16479
16480 @noindent
16481 The pragmas listed below should be used with caution inside libraries,
16482 as they can create incompatibilities with other Ada libraries:
16483 @itemize @bullet
16484 @item pragma @code{Locking_Policy}
16485 @item pragma @code{Queuing_Policy}
16486 @item pragma @code{Task_Dispatching_Policy}
16487 @item pragma @code{Unreserve_All_Interrupts}
16488 @end itemize
16489
16490 @noindent
16491 When using a library that contains such pragmas, the user must make sure
16492 that all libraries use the same pragmas with the same values. Otherwise,
16493 @code{Program_Error} will
16494 be raised during the elaboration of the conflicting
16495 libraries. The usage of these pragmas and its consequences for the user
16496 should therefore be well documented.
16497
16498 Similarly, the traceback in the exception occurrence mechanism should be
16499 enabled or disabled in a consistent manner across all libraries.
16500 Otherwise, Program_Error will be raised during the elaboration of the
16501 conflicting libraries.
16502
16503 If the @code{Version} or @code{Body_Version}
16504 attributes are used inside a library, then you need to
16505 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16506 libraries, so that version identifiers can be properly computed.
16507 In practice these attributes are rarely used, so this is unlikely
16508 to be a consideration.
16509
16510 @node  Rebuilding the GNAT Run-Time Library
16511 @section Rebuilding the GNAT Run-Time Library
16512 @cindex GNAT Run-Time Library, rebuilding
16513 @cindex Building the GNAT Run-Time Library
16514 @cindex Rebuilding the GNAT Run-Time Library
16515 @cindex Run-Time Library, rebuilding
16516
16517 @noindent
16518 It may be useful to recompile the GNAT library in various contexts, the
16519 most important one being the use of partition-wide configuration pragmas
16520 such as @code{Normalize_Scalars}. A special Makefile called
16521 @code{Makefile.adalib} is provided to that effect and can be found in
16522 the directory containing the GNAT library. The location of this
16523 directory depends on the way the GNAT environment has been installed and can
16524 be determined by means of the command:
16525
16526 @smallexample
16527 $ gnatls -v
16528 @end smallexample
16529
16530 @noindent
16531 The last entry in the object search path usually contains the
16532 gnat library. This Makefile contains its own documentation and in
16533 particular the set of instructions needed to rebuild a new library and
16534 to use it.
16535
16536 @node Using the GNU make Utility
16537 @chapter Using the GNU @code{make} Utility
16538 @findex make
16539
16540 @noindent
16541 This chapter offers some examples of makefiles that solve specific
16542 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16543 make, make, GNU @code{make}}), nor does it try to replace the
16544 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16545
16546 All the examples in this section are specific to the GNU version of
16547 make. Although @command{make} is a standard utility, and the basic language
16548 is the same, these examples use some advanced features found only in
16549 @code{GNU make}.
16550
16551 @menu
16552 * Using gnatmake in a Makefile::
16553 * Automatically Creating a List of Directories::
16554 * Generating the Command Line Switches::
16555 * Overcoming Command Line Length Limits::
16556 @end menu
16557
16558 @node Using gnatmake in a Makefile
16559 @section Using gnatmake in a Makefile
16560 @findex makefile
16561 @cindex GNU make
16562
16563 @noindent
16564 Complex project organizations can be handled in a very powerful way by
16565 using GNU make combined with gnatmake. For instance, here is a Makefile
16566 which allows you to build each subsystem of a big project into a separate
16567 shared library. Such a makefile allows you to significantly reduce the link
16568 time of very big applications while maintaining full coherence at
16569 each step of the build process.
16570
16571 The list of dependencies are handled automatically by
16572 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16573 the appropriate directories.
16574
16575 Note that you should also read the example on how to automatically
16576 create the list of directories
16577 (@pxref{Automatically Creating a List of Directories})
16578 which might help you in case your project has a lot of subdirectories.
16579
16580 @smallexample
16581 @iftex
16582 @leftskip=0cm
16583 @font@heightrm=cmr8
16584 @heightrm
16585 @end iftex
16586 ## This Makefile is intended to be used with the following directory
16587 ## configuration:
16588 ##  - The sources are split into a series of csc (computer software components)
16589 ##    Each of these csc is put in its own directory.
16590 ##    Their name are referenced by the directory names.
16591 ##    They will be compiled into shared library (although this would also work
16592 ##    with static libraries
16593 ##  - The main program (and possibly other packages that do not belong to any
16594 ##    csc is put in the top level directory (where the Makefile is).
16595 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16596 ##                    \_ second_csc (sources) __ lib (will contain the library)
16597 ##                    \_ @dots{}
16598 ## Although this Makefile is build for shared library, it is easy to modify
16599 ## to build partial link objects instead (modify the lines with -shared and
16600 ## gnatlink below)
16601 ##
16602 ## With this makefile, you can change any file in the system or add any new
16603 ## file, and everything will be recompiled correctly (only the relevant shared
16604 ## objects will be recompiled, and the main program will be re-linked).
16605
16606 # The list of computer software component for your project. This might be
16607 # generated automatically.
16608 CSC_LIST=aa bb cc
16609
16610 # Name of the main program (no extension)
16611 MAIN=main
16612
16613 # If we need to build objects with -fPIC, uncomment the following line
16614 #NEED_FPIC=-fPIC
16615
16616 # The following variable should give the directory containing libgnat.so
16617 # You can get this directory through 'gnatls -v'. This is usually the last
16618 # directory in the Object_Path.
16619 GLIB=@dots{}
16620
16621 # The directories for the libraries
16622 # (This macro expands the list of CSC to the list of shared libraries, you
16623 # could simply use the expanded form:
16624 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16625 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16626
16627 $@{MAIN@}: objects $@{LIB_DIR@}
16628     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16629     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16630
16631 objects::
16632     # recompile the sources
16633     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16634
16635 # Note: In a future version of GNAT, the following commands will be simplified
16636 # by a new tool, gnatmlib
16637 $@{LIB_DIR@}:
16638     mkdir -p $@{dir $@@ @}
16639     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16640     cd $@{dir $@@ @} && cp -f ../*.ali .
16641
16642 # The dependencies for the modules
16643 # Note that we have to force the expansion of *.o, since in some cases
16644 # make won't be able to do it itself.
16645 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16646 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16647 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16648
16649 # Make sure all of the shared libraries are in the path before starting the
16650 # program
16651 run::
16652     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16653
16654 clean::
16655     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16656     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16657     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16658     $@{RM@} *.o *.ali $@{MAIN@}
16659 @end smallexample
16660
16661 @node Automatically Creating a List of Directories
16662 @section Automatically Creating a List of Directories
16663
16664 @noindent
16665 In most makefiles, you will have to specify a list of directories, and
16666 store it in a variable. For small projects, it is often easier to
16667 specify each of them by hand, since you then have full control over what
16668 is the proper order for these directories, which ones should be
16669 included.
16670
16671 However, in larger projects, which might involve hundreds of
16672 subdirectories, it might be more convenient to generate this list
16673 automatically.
16674
16675 The example below presents two methods. The first one, although less
16676 general, gives you more control over the list. It involves wildcard
16677 characters, that are automatically expanded by @command{make}. Its
16678 shortcoming is that you need to explicitly specify some of the
16679 organization of your project, such as for instance the directory tree
16680 depth, whether some directories are found in a separate tree, @enddots{}
16681
16682 The second method is the most general one. It requires an external
16683 program, called @command{find}, which is standard on all Unix systems. All
16684 the directories found under a given root directory will be added to the
16685 list.
16686
16687 @smallexample
16688 @iftex
16689 @leftskip=0cm
16690 @font@heightrm=cmr8
16691 @heightrm
16692 @end iftex
16693 # The examples below are based on the following directory hierarchy:
16694 # All the directories can contain any number of files
16695 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16696 #                       ->  ab
16697 #                       ->  ac
16698 #                ->  b  ->  ba  ->  baa
16699 #                       ->  bb
16700 #                       ->  bc
16701 # This Makefile creates a variable called DIRS, that can be reused any time
16702 # you need this list (see the other examples in this section)
16703
16704 # The root of your project's directory hierarchy
16705 ROOT_DIRECTORY=.
16706
16707 ####
16708 # First method: specify explicitly the list of directories
16709 # This allows you to specify any subset of all the directories you need.
16710 ####
16711
16712 DIRS := a/aa/ a/ab/ b/ba/
16713
16714 ####
16715 # Second method: use wildcards
16716 # Note that the argument(s) to wildcard below should end with a '/'.
16717 # Since wildcards also return file names, we have to filter them out
16718 # to avoid duplicate directory names.
16719 # We thus use make's @code{dir} and @code{sort} functions.
16720 # It sets DIRs to the following value (note that the directories aaa and baa
16721 # are not given, unless you change the arguments to wildcard).
16722 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16723 ####
16724
16725 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16726                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16727
16728 ####
16729 # Third method: use an external program
16730 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16731 # This is the most complete command: it sets DIRs to the following value:
16732 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16733 ####
16734
16735 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16736
16737 @end smallexample
16738
16739 @node Generating the Command Line Switches
16740 @section Generating the Command Line Switches
16741
16742 @noindent
16743 Once you have created the list of directories as explained in the
16744 previous section (@pxref{Automatically Creating a List of Directories}),
16745 you can easily generate the command line arguments to pass to gnatmake.
16746
16747 For the sake of completeness, this example assumes that the source path
16748 is not the same as the object path, and that you have two separate lists
16749 of directories.
16750
16751 @smallexample
16752 # see "Automatically creating a list of directories" to create
16753 # these variables
16754 SOURCE_DIRS=
16755 OBJECT_DIRS=
16756
16757 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16758 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16759
16760 all:
16761         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16762 @end smallexample
16763
16764 @node Overcoming Command Line Length Limits
16765 @section Overcoming Command Line Length Limits
16766
16767 @noindent
16768 One problem that might be encountered on big projects is that many
16769 operating systems limit the length of the command line. It is thus hard to give
16770 gnatmake the list of source and object directories.
16771
16772 This example shows how you can set up environment variables, which will
16773 make @command{gnatmake} behave exactly as if the directories had been
16774 specified on the command line, but have a much higher length limit (or
16775 even none on most systems).
16776
16777 It assumes that you have created a list of directories in your Makefile,
16778 using one of the methods presented in
16779 @ref{Automatically Creating a List of Directories}.
16780 For the sake of completeness, we assume that the object
16781 path (where the ALI files are found) is different from the sources patch.
16782
16783 Note a small trick in the Makefile below: for efficiency reasons, we
16784 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16785 expanded immediately by @code{make}. This way we overcome the standard
16786 make behavior which is to expand the variables only when they are
16787 actually used.
16788
16789 On Windows, if you are using the standard Windows command shell, you must
16790 replace colons with semicolons in the assignments to these variables.
16791
16792 @smallexample
16793 @iftex
16794 @leftskip=0cm
16795 @font@heightrm=cmr8
16796 @heightrm
16797 @end iftex
16798 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16799 # This is the same thing as putting the -I arguments on the command line.
16800 # (the equivalent of using -aI on the command line would be to define
16801 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16802 # You can of course have different values for these variables.
16803 #
16804 # Note also that we need to keep the previous values of these variables, since
16805 # they might have been set before running 'make' to specify where the GNAT
16806 # library is installed.
16807
16808 # see "Automatically creating a list of directories" to create these
16809 # variables
16810 SOURCE_DIRS=
16811 OBJECT_DIRS=
16812
16813 empty:=
16814 space:=$@{empty@} $@{empty@}
16815 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16816 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16817 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16818 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16819 export ADA_INCLUDE_PATH
16820 export ADA_OBJECTS_PATH
16821
16822 all:
16823         gnatmake main_unit
16824 @end smallexample
16825 @end ifclear
16826
16827 @node Memory Management Issues
16828 @chapter Memory Management Issues
16829
16830 @noindent
16831 This chapter describes some useful memory pools provided in the GNAT library
16832 and in particular the GNAT Debug Pool facility, which can be used to detect
16833 incorrect uses of access values (including ``dangling references'').
16834 @ifclear vms
16835 It also describes the @command{gnatmem} tool, which can be used to track down
16836 ``memory leaks''.
16837 @end ifclear
16838
16839 @menu
16840 * Some Useful Memory Pools::
16841 * The GNAT Debug Pool Facility::
16842 @ifclear vms
16843 * The gnatmem Tool::
16844 @end ifclear
16845 @end menu
16846
16847 @node Some Useful Memory Pools
16848 @section Some Useful Memory Pools
16849 @findex Memory Pool
16850 @cindex storage, pool
16851
16852 @noindent
16853 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16854 storage pool. Allocations use the standard system call @code{malloc} while
16855 deallocations use the standard system call @code{free}. No reclamation is
16856 performed when the pool goes out of scope. For performance reasons, the
16857 standard default Ada allocators/deallocators do not use any explicit storage
16858 pools but if they did, they could use this storage pool without any change in
16859 behavior. That is why this storage pool is used  when the user
16860 manages to make the default implicit allocator explicit as in this example:
16861 @smallexample @c ada
16862    type T1 is access Something;
16863     -- no Storage pool is defined for T2
16864    type T2 is access Something_Else;
16865    for T2'Storage_Pool use T1'Storage_Pool;
16866    -- the above is equivalent to
16867    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16868 @end smallexample
16869
16870 @noindent
16871 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16872 pool. The allocation strategy is similar to @code{Pool_Local}'s
16873 except that the all
16874 storage allocated with this pool is reclaimed when the pool object goes out of
16875 scope. This pool provides a explicit mechanism similar to the implicit one
16876 provided by several Ada 83 compilers for allocations performed through a local
16877 access type and whose purpose was to reclaim memory when exiting the
16878 scope of a given local access. As an example, the following program does not
16879 leak memory even though it does not perform explicit deallocation:
16880
16881 @smallexample @c ada
16882 with System.Pool_Local;
16883 procedure Pooloc1 is
16884    procedure Internal is
16885       type A is access Integer;
16886       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16887       for A'Storage_Pool use X;
16888       v : A;
16889    begin
16890       for I in  1 .. 50 loop
16891          v := new Integer;
16892       end loop;
16893    end Internal;
16894 begin
16895    for I in  1 .. 100 loop
16896       Internal;
16897    end loop;
16898 end Pooloc1;
16899 @end smallexample
16900
16901 @noindent
16902 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16903 @code{Storage_Size} is specified for an access type.
16904 The whole storage for the pool is
16905 allocated at once, usually on the stack at the point where the access type is
16906 elaborated. It is automatically reclaimed when exiting the scope where the
16907 access type is defined. This package is not intended to be used directly by the
16908 user and it is implicitly used for each such declaration:
16909
16910 @smallexample @c ada
16911    type T1 is access Something;
16912    for T1'Storage_Size use 10_000;
16913 @end smallexample
16914
16915 @node The GNAT Debug Pool Facility
16916 @section The GNAT Debug Pool Facility
16917 @findex Debug Pool
16918 @cindex storage, pool, memory corruption
16919
16920 @noindent
16921 The use of unchecked deallocation and unchecked conversion can easily
16922 lead to incorrect memory references. The problems generated by such
16923 references are usually difficult to tackle because the symptoms can be
16924 very remote from the origin of the problem. In such cases, it is
16925 very helpful to detect the problem as early as possible. This is the
16926 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16927
16928 In order to use the GNAT specific debugging pool, the user must
16929 associate a debug pool object with each of the access types that may be
16930 related to suspected memory problems. See Ada Reference Manual 13.11.
16931 @smallexample @c ada
16932 type Ptr is access Some_Type;
16933 Pool : GNAT.Debug_Pools.Debug_Pool;
16934 for Ptr'Storage_Pool use Pool;
16935 @end smallexample
16936
16937 @noindent
16938 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16939 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16940 allow the user to redefine allocation and deallocation strategies. They
16941 also provide a checkpoint for each dereference, through the use of
16942 the primitive operation @code{Dereference} which is implicitly called at
16943 each dereference of an access value.
16944
16945 Once an access type has been associated with a debug pool, operations on
16946 values of the type may raise four distinct exceptions,
16947 which correspond to four potential kinds of memory corruption:
16948 @itemize @bullet
16949 @item
16950 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16951 @item
16952 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16953 @item
16954 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16955 @item
16956 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16957 @end itemize
16958
16959 @noindent
16960 For types associated with a Debug_Pool, dynamic allocation is performed using
16961 the standard GNAT allocation routine. References to all allocated chunks of
16962 memory are kept in an internal dictionary. Several deallocation strategies are
16963 provided, whereupon the user can choose to release the memory to the system,
16964 keep it allocated for further invalid access checks, or fill it with an easily
16965 recognizable pattern for debug sessions. The memory pattern is the old IBM
16966 hexadecimal convention: @code{16#DEADBEEF#}.
16967
16968 See the documentation in the file g-debpoo.ads for more information on the
16969 various strategies.
16970
16971 Upon each dereference, a check is made that the access value denotes a
16972 properly allocated memory location. Here is a complete example of use of
16973 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16974 @smallexample @c ada
16975 @iftex
16976 @leftskip=0cm
16977 @end iftex
16978 with Gnat.Io; use Gnat.Io;
16979 with Unchecked_Deallocation;
16980 with Unchecked_Conversion;
16981 with GNAT.Debug_Pools;
16982 with System.Storage_Elements;
16983 with Ada.Exceptions; use Ada.Exceptions;
16984 procedure Debug_Pool_Test is
16985
16986    type T is access Integer;
16987    type U is access all T;
16988
16989    P : GNAT.Debug_Pools.Debug_Pool;
16990    for T'Storage_Pool use P;
16991
16992    procedure Free is new Unchecked_Deallocation (Integer, T);
16993    function UC is new Unchecked_Conversion (U, T);
16994    A, B : aliased T;
16995
16996    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16997
16998 begin
16999    Info (P);
17000    A := new Integer;
17001    B := new Integer;
17002    B := A;
17003    Info (P);
17004    Free (A);
17005    begin
17006       Put_Line (Integer'Image(B.all));
17007    exception
17008       when E : others => Put_Line ("raised: " & Exception_Name (E));
17009    end;
17010    begin
17011       Free (B);
17012    exception
17013       when E : others => Put_Line ("raised: " & Exception_Name (E));
17014    end;
17015    B := UC(A'Access);
17016    begin
17017       Put_Line (Integer'Image(B.all));
17018    exception
17019       when E : others => Put_Line ("raised: " & Exception_Name (E));
17020    end;
17021    begin
17022       Free (B);
17023    exception
17024       when E : others => Put_Line ("raised: " & Exception_Name (E));
17025    end;
17026    Info (P);
17027 end Debug_Pool_Test;
17028 @end smallexample
17029
17030 @noindent
17031 The debug pool mechanism provides the following precise diagnostics on the
17032 execution of this erroneous program:
17033 @smallexample
17034 Debug Pool info:
17035   Total allocated bytes :  0
17036   Total deallocated bytes :  0
17037   Current Water Mark:  0
17038   High Water Mark:  0
17039
17040 Debug Pool info:
17041   Total allocated bytes :  8
17042   Total deallocated bytes :  0
17043   Current Water Mark:  8
17044   High Water Mark:  8
17045
17046 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17047 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17048 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17049 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17050 Debug Pool info:
17051   Total allocated bytes :  8
17052   Total deallocated bytes :  4
17053   Current Water Mark:  4
17054   High Water Mark:  8
17055 @end smallexample
17056
17057 @ifclear vms
17058 @node The gnatmem Tool
17059 @section The @command{gnatmem} Tool
17060 @findex gnatmem
17061
17062 @noindent
17063 The @code{gnatmem} utility monitors dynamic allocation and
17064 deallocation activity in a program, and displays information about
17065 incorrect deallocations and possible sources of memory leaks.
17066 It is designed to work in association with a static runtime library
17067 only and in this context provides three types of information:
17068 @itemize @bullet
17069 @item
17070 General information concerning memory management, such as the total
17071 number of allocations and deallocations, the amount of allocated
17072 memory and the high water mark, i.e.@: the largest amount of allocated
17073 memory in the course of program execution.
17074
17075 @item
17076 Backtraces for all incorrect deallocations, that is to say deallocations
17077 which do not correspond to a valid allocation.
17078
17079 @item
17080 Information on each allocation that is potentially the origin of a memory
17081 leak.
17082 @end itemize
17083
17084 @menu
17085 * Running gnatmem::
17086 * Switches for gnatmem::
17087 * Example of gnatmem Usage::
17088 @end menu
17089
17090 @node Running gnatmem
17091 @subsection Running @code{gnatmem}
17092
17093 @noindent
17094 @code{gnatmem} makes use of the output created by the special version of
17095 allocation and deallocation routines that record call information. This
17096 allows to obtain accurate dynamic memory usage history at a minimal cost to
17097 the execution speed. Note however, that @code{gnatmem} is not supported on
17098 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17099 Solaris and Windows NT/2000/XP (x86).
17100
17101 @noindent
17102 The @code{gnatmem} command has the form
17103
17104 @smallexample
17105 @c    $ gnatmem @ovar{switches} user_program
17106 @c Expanding @ovar macro inline (explanation in macro def comments)
17107       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17108 @end smallexample
17109
17110 @noindent
17111 The program must have been linked with the instrumented version of the
17112 allocation and deallocation routines. This is done by linking with the
17113 @file{libgmem.a} library. For correct symbolic backtrace information,
17114 the user program should be compiled with debugging options
17115 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17116
17117 @smallexample
17118 $ gnatmake -g my_program -largs -lgmem
17119 @end smallexample
17120
17121 @noindent
17122 As library @file{libgmem.a} contains an alternate body for package
17123 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17124 when an executable is linked with library @file{libgmem.a}. It is then not
17125 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17126
17127 @noindent
17128 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17129 This file contains information about all allocations and deallocations
17130 performed by the program. It is produced by the instrumented allocations and
17131 deallocations routines and will be used by @code{gnatmem}.
17132
17133 In order to produce symbolic backtrace information for allocations and
17134 deallocations performed by the GNAT run-time library, you need to use a
17135 version of that library that has been compiled with the @option{-g} switch
17136 (see @ref{Rebuilding the GNAT Run-Time Library}).
17137
17138 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17139 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17140 @option{-i} switch, gnatmem will assume that this file can be found in the
17141 current directory. For example, after you have executed @file{my_program},
17142 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17143
17144 @smallexample
17145 $ gnatmem my_program
17146 @end smallexample
17147
17148 @noindent
17149 This will produce the output with the following format:
17150
17151 *************** debut cc
17152 @smallexample
17153 $ gnatmem my_program
17154
17155 Global information
17156 ------------------
17157    Total number of allocations        :  45
17158    Total number of deallocations      :   6
17159    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17160    High Water Mark                    :  11.40 Kilobytes
17161
17162 .
17163 .
17164 .
17165 Allocation Root # 2
17166 -------------------
17167  Number of non freed allocations    :  11
17168  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17169  High Water Mark                    :   1.27 Kilobytes
17170  Backtrace                          :
17171    my_program.adb:23 my_program.alloc
17172 .
17173 .
17174 .
17175 @end smallexample
17176
17177 The first block of output gives general information. In this case, the
17178 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17179 Unchecked_Deallocation routine occurred.
17180
17181 @noindent
17182 Subsequent paragraphs display  information on all allocation roots.
17183 An allocation root is a specific point in the execution of the program
17184 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17185 construct. This root is represented by an execution backtrace (or subprogram
17186 call stack). By default the backtrace depth for allocations roots is 1, so
17187 that a root corresponds exactly to a source location. The backtrace can
17188 be made deeper, to make the root more specific.
17189
17190 @node Switches for gnatmem
17191 @subsection Switches for @code{gnatmem}
17192
17193 @noindent
17194 @code{gnatmem} recognizes the following switches:
17195
17196 @table @option
17197
17198 @item -q
17199 @cindex @option{-q} (@code{gnatmem})
17200 Quiet. Gives the minimum output needed to identify the origin of the
17201 memory leaks. Omits statistical information.
17202
17203 @item @var{N}
17204 @cindex @var{N} (@code{gnatmem})
17205 N is an integer literal (usually between 1 and 10) which controls the
17206 depth of the backtraces defining allocation root. The default value for
17207 N is 1. The deeper the backtrace, the more precise the localization of
17208 the root. Note that the total number of roots can depend on this
17209 parameter. This parameter must be specified @emph{before} the name of the
17210 executable to be analyzed, to avoid ambiguity.
17211
17212 @item -b n
17213 @cindex @option{-b} (@code{gnatmem})
17214 This switch has the same effect as just depth parameter.
17215
17216 @item -i @var{file}
17217 @cindex @option{-i} (@code{gnatmem})
17218 Do the @code{gnatmem} processing starting from @file{file}, rather than
17219 @file{gmem.out} in the current directory.
17220
17221 @item -m n
17222 @cindex @option{-m} (@code{gnatmem})
17223 This switch causes @code{gnatmem} to mask the allocation roots that have less
17224 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17225 examine even the roots that didn't result in leaks.
17226
17227 @item -s order
17228 @cindex @option{-s} (@code{gnatmem})
17229 This switch causes @code{gnatmem} to sort the allocation roots according to the
17230 specified order of sort criteria, each identified by a single letter. The
17231 currently supported criteria are @code{n, h, w} standing respectively for
17232 number of unfreed allocations, high watermark, and final watermark
17233 corresponding to a specific root. The default order is @code{nwh}.
17234
17235 @end table
17236
17237 @node Example of gnatmem Usage
17238 @subsection Example of @code{gnatmem} Usage
17239
17240 @noindent
17241 The following example shows the use of @code{gnatmem}
17242 on a simple memory-leaking program.
17243 Suppose that we have the following Ada program:
17244
17245 @smallexample @c ada
17246 @group
17247 @cartouche
17248 with Unchecked_Deallocation;
17249 procedure Test_Gm is
17250
17251    type T is array (1..1000) of Integer;
17252    type Ptr is access T;
17253    procedure Free is new Unchecked_Deallocation (T, Ptr);
17254    A : Ptr;
17255
17256    procedure My_Alloc is
17257    begin
17258       A := new T;
17259    end My_Alloc;
17260
17261    procedure My_DeAlloc is
17262       B : Ptr := A;
17263    begin
17264       Free (B);
17265    end My_DeAlloc;
17266
17267 begin
17268    My_Alloc;
17269    for I in 1 .. 5 loop
17270       for J in I .. 5 loop
17271          My_Alloc;
17272       end loop;
17273       My_Dealloc;
17274    end loop;
17275 end;
17276 @end cartouche
17277 @end group
17278 @end smallexample
17279
17280 @noindent
17281 The program needs to be compiled with debugging option and linked with
17282 @code{gmem} library:
17283
17284 @smallexample
17285 $ gnatmake -g test_gm -largs -lgmem
17286 @end smallexample
17287
17288 @noindent
17289 Then we execute the program as usual:
17290
17291 @smallexample
17292 $ test_gm
17293 @end smallexample
17294
17295 @noindent
17296 Then @code{gnatmem} is invoked simply with
17297 @smallexample
17298 $ gnatmem test_gm
17299 @end smallexample
17300
17301 @noindent
17302 which produces the following output (result may vary on different platforms):
17303
17304 @smallexample
17305 Global information
17306 ------------------
17307    Total number of allocations        :  18
17308    Total number of deallocations      :   5
17309    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17310    High Water Mark                    :  56.90 Kilobytes
17311
17312 Allocation Root # 1
17313 -------------------
17314  Number of non freed allocations    :  11
17315  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17316  High Water Mark                    :  46.88 Kilobytes
17317  Backtrace                          :
17318    test_gm.adb:11 test_gm.my_alloc
17319
17320 Allocation Root # 2
17321 -------------------
17322  Number of non freed allocations    :   1
17323  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17324  High Water Mark                    :  10.02 Kilobytes
17325  Backtrace                          :
17326    s-secsta.adb:81 system.secondary_stack.ss_init
17327
17328 Allocation Root # 3
17329 -------------------
17330  Number of non freed allocations    :   1
17331  Final Water Mark (non freed mem)   :  12 Bytes
17332  High Water Mark                    :  12 Bytes
17333  Backtrace                          :
17334    s-secsta.adb:181 system.secondary_stack.ss_init
17335 @end smallexample
17336
17337 @noindent
17338 Note that the GNAT run time contains itself a certain number of
17339 allocations that have no  corresponding deallocation,
17340 as shown here for root #2 and root
17341 #3. This is a normal behavior when the number of non-freed allocations
17342 is one, it allocates dynamic data structures that the run time needs for
17343 the complete lifetime of the program. Note also that there is only one
17344 allocation root in the user program with a single line back trace:
17345 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17346 program shows that 'My_Alloc' is called at 2 different points in the
17347 source (line 21 and line 24). If those two allocation roots need to be
17348 distinguished, the backtrace depth parameter can be used:
17349
17350 @smallexample
17351 $ gnatmem 3 test_gm
17352 @end smallexample
17353
17354 @noindent
17355 which will give the following output:
17356
17357 @smallexample
17358 Global information
17359 ------------------
17360    Total number of allocations        :  18
17361    Total number of deallocations      :   5
17362    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17363    High Water Mark                    :  56.90 Kilobytes
17364
17365 Allocation Root # 1
17366 -------------------
17367  Number of non freed allocations    :  10
17368  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17369  High Water Mark                    :  42.97 Kilobytes
17370  Backtrace                          :
17371    test_gm.adb:11 test_gm.my_alloc
17372    test_gm.adb:24 test_gm
17373    b_test_gm.c:52 main
17374
17375 Allocation Root # 2
17376 -------------------
17377  Number of non freed allocations    :   1
17378  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17379  High Water Mark                    :  10.02 Kilobytes
17380  Backtrace                          :
17381    s-secsta.adb:81  system.secondary_stack.ss_init
17382    s-secsta.adb:283 <system__secondary_stack___elabb>
17383    b_test_gm.c:33   adainit
17384
17385 Allocation Root # 3
17386 -------------------
17387  Number of non freed allocations    :   1
17388  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17389  High Water Mark                    :   3.91 Kilobytes
17390  Backtrace                          :
17391    test_gm.adb:11 test_gm.my_alloc
17392    test_gm.adb:21 test_gm
17393    b_test_gm.c:52 main
17394
17395 Allocation Root # 4
17396 -------------------
17397  Number of non freed allocations    :   1
17398  Final Water Mark (non freed mem)   :  12 Bytes
17399  High Water Mark                    :  12 Bytes
17400  Backtrace                          :
17401    s-secsta.adb:181 system.secondary_stack.ss_init
17402    s-secsta.adb:283 <system__secondary_stack___elabb>
17403    b_test_gm.c:33   adainit
17404 @end smallexample
17405
17406 @noindent
17407 The allocation root #1 of the first example has been split in 2 roots #1
17408 and #3 thanks to the more precise associated backtrace.
17409
17410 @end ifclear
17411
17412 @node Stack Related Facilities
17413 @chapter Stack Related Facilities
17414
17415 @noindent
17416 This chapter describes some useful tools associated with stack
17417 checking and analysis. In
17418 particular, it deals with dynamic and static stack usage measurements.
17419
17420 @menu
17421 * Stack Overflow Checking::
17422 * Static Stack Usage Analysis::
17423 * Dynamic Stack Usage Analysis::
17424 @end menu
17425
17426 @node Stack Overflow Checking
17427 @section Stack Overflow Checking
17428 @cindex Stack Overflow Checking
17429 @cindex -fstack-check
17430
17431 @noindent
17432 For most operating systems, @command{gcc} does not perform stack overflow
17433 checking by default. This means that if the main environment task or
17434 some other task exceeds the available stack space, then unpredictable
17435 behavior will occur. Most native systems offer some level of protection by
17436 adding a guard page at the end of each task stack. This mechanism is usually
17437 not enough for dealing properly with stack overflow situations because
17438 a large local variable could ``jump'' above the guard page.
17439 Furthermore, when the
17440 guard page is hit, there may not be any space left on the stack for executing
17441 the exception propagation code. Enabling stack checking avoids
17442 such situations.
17443
17444 To activate stack checking, compile all units with the gcc option
17445 @option{-fstack-check}. For example:
17446
17447 @smallexample
17448 gcc -c -fstack-check package1.adb
17449 @end smallexample
17450
17451 @noindent
17452 Units compiled with this option will generate extra instructions to check
17453 that any use of the stack (for procedure calls or for declaring local
17454 variables in declare blocks) does not exceed the available stack space.
17455 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17456
17457 For declared tasks, the stack size is controlled by the size
17458 given in an applicable @code{Storage_Size} pragma or by the value specified
17459 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17460 the default size as defined in the GNAT runtime otherwise.
17461
17462 For the environment task, the stack size depends on
17463 system defaults and is unknown to the compiler. Stack checking
17464 may still work correctly if a fixed
17465 size stack is allocated, but this cannot be guaranteed.
17466 @ifclear vms
17467 To ensure that a clean exception is signalled for stack
17468 overflow, set the environment variable
17469 @env{GNAT_STACK_LIMIT} to indicate the maximum
17470 stack area that can be used, as in:
17471 @cindex GNAT_STACK_LIMIT
17472
17473 @smallexample
17474 SET GNAT_STACK_LIMIT 1600
17475 @end smallexample
17476
17477 @noindent
17478 The limit is given in kilobytes, so the above declaration would
17479 set the stack limit of the environment task to 1.6 megabytes.
17480 Note that the only purpose of this usage is to limit the amount
17481 of stack used by the environment task. If it is necessary to
17482 increase the amount of stack for the environment task, then this
17483 is an operating systems issue, and must be addressed with the
17484 appropriate operating systems commands.
17485 @end ifclear
17486 @ifset vms
17487 To have a fixed size stack in the environment task, the stack must be put
17488 in the P0 address space and its size specified.  Use these switches to
17489 create a p0 image:
17490
17491 @smallexample
17492 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17493 @end smallexample
17494
17495 @noindent
17496 The quotes are required to keep case.  The number after @samp{STACK=} is the
17497 size of the environmental task stack in pagelets (512 bytes).  In this example
17498 the stack size is about 2 megabytes.
17499
17500 @noindent
17501 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17502 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17503 more details about the @option{/p0image} qualifier and the @option{stack}
17504 option.
17505
17506 @noindent
17507 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17508 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17509 stack in kilobytes.  For example:
17510
17511 @smallexample
17512 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17513 @end smallexample
17514 @end ifset
17515
17516 @node Static Stack Usage Analysis
17517 @section Static Stack Usage Analysis
17518 @cindex Static Stack Usage Analysis
17519 @cindex -fstack-usage
17520
17521 @noindent
17522 A unit compiled with @option{-fstack-usage} will generate an extra file
17523 that specifies
17524 the maximum amount of stack used, on a per-function basis.
17525 The file has the same
17526 basename as the target object file with a @file{.su} extension.
17527 Each line of this file is made up of three fields:
17528
17529 @itemize
17530 @item
17531 The name of the function.
17532 @item
17533 A number of bytes.
17534 @item
17535 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17536 @end itemize
17537
17538 The second field corresponds to the size of the known part of the function
17539 frame.
17540
17541 The qualifier @code{static} means that the function frame size
17542 is purely static.
17543 It usually means that all local variables have a static size.
17544 In this case, the second field is a reliable measure of the function stack
17545 utilization.
17546
17547 The qualifier @code{dynamic} means that the function frame size is not static.
17548 It happens mainly when some local variables have a dynamic size. When this
17549 qualifier appears alone, the second field is not a reliable measure
17550 of the function stack analysis. When it is qualified with  @code{bounded}, it
17551 means that the second field is a reliable maximum of the function stack
17552 utilization.
17553
17554 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17555 subprogram whose stack usage might be larger than the specified amount of
17556 bytes.  The wording is in keeping with the qualifier documented above.
17557
17558 @node Dynamic Stack Usage Analysis
17559 @section Dynamic Stack Usage Analysis
17560
17561 @noindent
17562 It is possible to measure the maximum amount of stack used by a task, by
17563 adding a switch to @command{gnatbind}, as:
17564
17565 @smallexample
17566 $ gnatbind -u0 file
17567 @end smallexample
17568
17569 @noindent
17570 With this option, at each task termination, its stack usage is  output on
17571 @file{stderr}.
17572 It is not always convenient to output the stack usage when the program
17573 is still running. Hence, it is possible to delay this output until program
17574 termination. for a given number of tasks specified as the argument of the
17575 @option{-u} option. For instance:
17576
17577 @smallexample
17578 $ gnatbind -u100 file
17579 @end smallexample
17580
17581 @noindent
17582 will buffer the stack usage information of the first 100 tasks to terminate and
17583 output this info at program termination. Results are displayed in four
17584 columns:
17585
17586 @noindent
17587 Index | Task Name | Stack Size | Stack Usage
17588
17589 @noindent
17590 where:
17591
17592 @table @emph
17593 @item Index
17594 is a number associated with each task.
17595
17596 @item Task Name
17597 is the name of the task analyzed.
17598
17599 @item Stack Size
17600 is the maximum size for the stack.
17601
17602 @item Stack Usage
17603 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17604 is not entirely analyzed, and it's not possible to know exactly how
17605 much has actually been used.
17606
17607 @end table
17608
17609 @noindent
17610 The environment task stack, e.g., the stack that contains the main unit, is
17611 only processed when the environment variable GNAT_STACK_LIMIT is set.
17612
17613 @noindent
17614 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17615 stack usage reports at run-time. See its body for the details.
17616
17617 @c *********************************
17618 @c *            GNATCHECK          *
17619 @c *********************************
17620 @node Verifying Properties Using gnatcheck
17621 @chapter Verifying Properties Using @command{gnatcheck}
17622 @findex gnatcheck
17623 @cindex @command{gnatcheck}
17624
17625 @noindent
17626 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17627 of Ada source files according to a given set of semantic rules.
17628 @cindex ASIS
17629
17630 In order to check compliance with a given rule, @command{gnatcheck} has to
17631 semantically analyze the Ada sources.
17632 Therefore, checks can only be performed on
17633 legal Ada units. Moreover, when a unit depends semantically upon units located
17634 outside the current directory, the source search path has to be provided when
17635 calling @command{gnatcheck}, either through a specified project file or
17636 through @command{gnatcheck} switches.
17637
17638 For full details, refer to @cite{GNATcheck Reference Manual} document.
17639
17640
17641 @c *********************************
17642 @node Creating Sample Bodies Using gnatstub
17643 @chapter Creating Sample Bodies Using @command{gnatstub}
17644 @findex gnatstub
17645
17646 @noindent
17647 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17648 for library unit declarations.
17649
17650 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17651 driver (see @ref{The GNAT Driver and Project Files}).
17652
17653 To create a body stub, @command{gnatstub} has to compile the library
17654 unit declaration. Therefore, bodies can be created only for legal
17655 library units. Moreover, if a library unit depends semantically upon
17656 units located outside the current directory, you have to provide
17657 the source search path when calling @command{gnatstub}, see the description
17658 of @command{gnatstub} switches below.
17659
17660 By default, all the program unit body stubs generated by @code{gnatstub}
17661 raise the predefined @code{Program_Error} exception, which will catch
17662 accidental calls of generated stubs. This behavior can be changed with
17663 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17664
17665 @menu
17666 * Running gnatstub::
17667 * Switches for gnatstub::
17668 @end menu
17669
17670 @node Running gnatstub
17671 @section Running @command{gnatstub}
17672
17673 @noindent
17674 @command{gnatstub} has a command-line interface of the form:
17675
17676 @smallexample
17677 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17678 @c Expanding @ovar macro inline (explanation in macro def comments)
17679 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17680 @end smallexample
17681
17682 @noindent
17683 where
17684 @table @var
17685 @item filename
17686 is the name of the source file that contains a library unit declaration
17687 for which a body must be created. The file name may contain the path
17688 information.
17689 The file name does not have to follow the GNAT file name conventions. If the
17690 name
17691 does not follow GNAT file naming conventions, the name of the body file must
17692 be provided
17693 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17694 If the file name follows the GNAT file naming
17695 conventions and the name of the body file is not provided,
17696 @command{gnatstub}
17697 creates the name
17698 of the body file from the argument file name by replacing the @file{.ads}
17699 suffix
17700 with the @file{.adb} suffix.
17701
17702 @item directory
17703 indicates the directory in which the body stub is to be placed (the default
17704 is the
17705 current directory)
17706
17707 @item @samp{@var{gcc_switches}} is a list of switches for
17708 @command{gcc}. They will be passed on to all compiler invocations made by
17709 @command{gnatstub} to generate the ASIS trees. Here you can provide
17710 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17711 use the @option{-gnatec} switch to set the configuration file,
17712 use the @option{-gnat05} switch if sources should be compiled in
17713 Ada 2005 mode etc.
17714
17715 @item switches
17716 is an optional sequence of switches as described in the next section
17717 @end table
17718
17719 @node Switches for gnatstub
17720 @section Switches for @command{gnatstub}
17721
17722 @table @option
17723 @c !sort!
17724
17725 @item ^-f^/FULL^
17726 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17727 If the destination directory already contains a file with the name of the
17728 body file
17729 for the argument spec file, replace it with the generated body stub.
17730
17731 @item ^-hs^/HEADER=SPEC^
17732 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17733 Put the comment header (i.e., all the comments preceding the
17734 compilation unit) from the source of the library unit declaration
17735 into the body stub.
17736
17737 @item ^-hg^/HEADER=GENERAL^
17738 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17739 Put a sample comment header into the body stub.
17740
17741 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17742 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17743 Use the content of the file as the comment header for a generated body stub.
17744
17745 @ifclear vms
17746 @item -IDIR
17747 @cindex @option{-IDIR} (@command{gnatstub})
17748 @itemx -I-
17749 @cindex @option{-I-} (@command{gnatstub})
17750 @end ifclear
17751 @ifset vms
17752 @item /NOCURRENT_DIRECTORY
17753 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17754 @end ifset
17755 ^These switches have ^This switch has^ the same meaning as in calls to
17756 @command{gcc}.
17757 ^They define ^It defines ^ the source search path in the call to
17758 @command{gcc} issued
17759 by @command{gnatstub} to compile an argument source file.
17760
17761 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17762 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17763 This switch has the same meaning as in calls to @command{gcc}.
17764 It defines the additional configuration file to be passed to the call to
17765 @command{gcc} issued
17766 by @command{gnatstub} to compile an argument source file.
17767
17768 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17769 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17770 (@var{n} is a non-negative integer). Set the maximum line length in the
17771 body stub to @var{n}; the default is 79. The maximum value that can be
17772 specified is 32767. Note that in the special case of configuration
17773 pragma files, the maximum is always 32767 regardless of whether or
17774 not this switch appears.
17775
17776 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17777 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17778 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17779 the generated body sample to @var{n}.
17780 The default indentation is 3.
17781
17782 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17783 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17784 Order local bodies alphabetically. (By default local bodies are ordered
17785 in the same way as the corresponding local specs in the argument spec file.)
17786
17787 @item ^-i^/INDENTATION=^@var{n}
17788 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17789 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17790
17791 @item ^-k^/TREE_FILE=SAVE^
17792 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17793 Do not remove the tree file (i.e., the snapshot of the compiler internal
17794 structures used by @command{gnatstub}) after creating the body stub.
17795
17796 @item ^-l^/LINE_LENGTH=^@var{n}
17797 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17798 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17799
17800 @item ^--no-exception^/NO_EXCEPTION^
17801 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17802 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17803 This is not always possible for function stubs.
17804
17805 @item ^--no-local-header^/NO_LOCAL_HEADER^
17806 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17807 Do not place local comment header with unit name before body stub for a
17808 unit.
17809
17810 @item ^-o ^/BODY=^@var{body-name}
17811 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17812 Body file name.  This should be set if the argument file name does not
17813 follow
17814 the GNAT file naming
17815 conventions. If this switch is omitted the default name for the body will be
17816 obtained
17817 from the argument file name according to the GNAT file naming conventions.
17818
17819 @item ^-q^/QUIET^
17820 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17821 Quiet mode: do not generate a confirmation when a body is
17822 successfully created, and do not generate a message when a body is not
17823 required for an
17824 argument unit.
17825
17826 @item ^-r^/TREE_FILE=REUSE^
17827 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17828 Reuse the tree file (if it exists) instead of creating it.  Instead of
17829 creating the tree file for the library unit declaration, @command{gnatstub}
17830 tries to find it in the current directory and use it for creating
17831 a body. If the tree file is not found, no body is created. This option
17832 also implies @option{^-k^/SAVE^}, whether or not
17833 the latter is set explicitly.
17834
17835 @item ^-t^/TREE_FILE=OVERWRITE^
17836 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17837 Overwrite the existing tree file.  If the current directory already
17838 contains the file which, according to the GNAT file naming rules should
17839 be considered as a tree file for the argument source file,
17840 @command{gnatstub}
17841 will refuse to create the tree file needed to create a sample body
17842 unless this option is set.
17843
17844 @item ^-v^/VERBOSE^
17845 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17846 Verbose mode: generate version information.
17847
17848 @end table
17849
17850 @c *********************************
17851 @node Creating Unit Tests Using gnattest
17852 @chapter Creating Unit Tests Using @command{gnattest}
17853 @findex gnattest
17854
17855 @noindent
17856 @command{gnattest} is an ASIS-based utility that creates unit-test stubs
17857 as well as a test driver infrastructure (harness). @command{gnattest} creates
17858 a stub for each visible subprogram in the packages under consideration when
17859 they do not exist already.
17860
17861 In order to process source files from a project, @command{gnattest} has to
17862 semantically analyze the sources. Therefore, test stubs can only be
17863 generated for legal Ada units. If a unit is dependent on other units,
17864 those units should be among the source files of the project or of other projects
17865 imported by this one.
17866
17867 Generated stubs and harnesses are based on the AUnit testing framework. AUnit is
17868 an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit for Java
17869 or CppUnit for C++. While it is advised that gnattest users read the AUnit
17870 manual, deep knowledge of AUnit is not necessary for using gnattest. For correct
17871 operation of @command{gnattest}, AUnit should be installed and aunit.gpr must be
17872 on the project path. This happens automatically when Aunit is installed at its
17873 default location.
17874 @menu
17875 * Running gnattest::
17876 * Switches for gnattest::
17877 * Project Attributes for gnattest::
17878 * Simple Example::
17879 * Setting Up and Tearing Down the Testing Environment::
17880 * Regenerating Tests::
17881 * Default Test Behavior::
17882 * Testing Primitive Operations of Tagged Types::
17883 * Testing Inheritance::
17884 * Tagged Types Substitutability Testing::
17885 * Testing with Contracts::
17886 * Additional Tests::
17887 * Current Limitations::
17888 @end menu
17889
17890 @node Running gnattest
17891 @section Running @command{gnattest}
17892
17893 @noindent
17894 @command{gnattest} has a command-line interface of the form
17895
17896 @smallexample
17897 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17898 @c Expanding @ovar macro inline (explanation in macro def comments)
17899 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17900 @end smallexample
17901
17902 @noindent
17903 where
17904 @table @var
17905
17906 @item -Pprojname
17907 specifies the project defining the location of source files. When no
17908 file names are provided on the command line, all sources in the project
17909 are used as input. This switch is required.
17910
17911 @item --harness-dir=dirname
17912 specifies the directory that will hold the harness packages and project file
17913 for the test driver. The harness directory should be specified either by that
17914 switch or by the corresponding attribute in the project file.
17915
17916 @item filename
17917 is the name of the source file containing the library unit package declaration
17918 for which a test package will be created. The file name may given with a path.
17919
17920 @item @samp{@var{gcc_switches}} is a list of switches for
17921 @command{gcc}. These switches will be passed on to all compiler invocations
17922 made by @command{gnatstub} to generate a set of ASIS trees. Here you can provide
17923 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17924 use the @option{-gnatec} switch to set the configuration file,
17925 use the @option{-gnat05} switch if sources should be compiled in
17926 Ada 2005 mode, etc.
17927
17928 @item switches
17929 is an optional sequence of switches as described in the next section.
17930
17931 @end table
17932
17933 @command{gnattest} results can be found in two different places.
17934
17935 @itemize @bullet
17936 @item automatic harness
17937 the harness code, which is located either in the harness-dir as specified on
17938 the command line or in the project file. All of this code is generated
17939 completely automatically and can be destroyed and regenerated at will. It is not
17940 recommended to modify this code manually, since it could easily be overridden
17941 by mistake. The entry point in the harness code is the project file named
17942 @command{test_driver.gpr}. Tests can be compiled and run using a command
17943 such as:
17944
17945 @smallexample
17946 gnatmake -P<harness-dir>/test_driver
17947 test_runner
17948 @end smallexample
17949
17950 Note that you might need to specify the necessary values of scenario variables
17951 when you are not using the AUnit defaults.
17952
17953 @item actual unit test stubs
17954 a test stub for each visible subprogram is created in a separate file, if it
17955 doesn't exist already. By default, those separate test files are located in a
17956 "tests" directory that is created in the directory containing the source file
17957 itself. If it is not appropriate to create the tests in subdirectories of the
17958 source, option @option{--separate-root} can be used. For example, if a source
17959 file my_unit.ads in directory src contains a visible subprogram Proc, then
17960 the corresponding unit test will be found in file
17961 src/tests/my_unit-tests-proc_<code>.adb. <code> is a signature encoding used to
17962 differentiate test names in cases of overloading.
17963
17964 Note that if the project already has both my_unit.ads and my_unit-tests.ads this
17965 will cause name a conflict with generated test package.
17966 @end itemize
17967
17968 @node Switches for gnattest
17969 @section Switches for @command{gnattest}
17970
17971 @table @option
17972 @c !sort!
17973
17974 @item --harness-only
17975 @cindex @option{--harness-only} (@command{gnattest})
17976 When this option is given, @command{gnattest} creates a harness for all
17977 sources, treating them as test packages.
17978
17979 @item --additional-tests=@var{projname}
17980 @cindex @option{--additional-tests} (@command{gnattest})
17981 Sources described in @var{projname} are considered potential additional
17982 manual tests to be added to the test suite.
17983
17984 @item -r
17985 @cindex @option{-r} (@command{gnattest})
17986 Recursively consider all sources from all projects.
17987
17988 @item -X@var{name=value}
17989 @cindex @option{-X} (@command{gnattest})
17990 Indicate that external variable @var{name} has the value @var{value}.
17991
17992 @item -q
17993 @cindex @option{-q} (@command{gnattest})
17994 Suppresses noncritical output messages.
17995
17996 @item -v
17997 @cindex @option{-v} (@command{gnattest})
17998 Verbose mode: generates version information.
17999
18000 @item --liskov
18001 @cindex @option{--liskov} (@command{gnattest})
18002 Enables Liskov verification: run all tests from all parents in order
18003 to check substitutability.
18004
18005 @item --stub-default=@var{val}
18006 @cindex @option{--stub-default} (@command{gnattest})
18007 Specifies the default behavior of generated stubs. @var{val} can be either
18008 "fail" or "pass", "fail" being the default.
18009
18010 @item --separate-root=@var{dirname}
18011 @cindex @option{--separate-root} (@command{gnattest})
18012 The directory hierarchy of tested sources is recreated in the @var{dirname}
18013 directory, and test packages are placed in corresponding directories.
18014
18015 @item --subdir=@var{dirname}
18016 @cindex @option{--subdir} (@command{gnattest})
18017 Test packages are placed in subdirectories. This is the default output mode
18018 since it does not require any additional input from the user. Subdirectories
18019 named "tests" will be created by default.
18020
18021 @end table
18022
18023 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
18024
18025 @node Project Attributes for gnattest
18026 @section Project Attributes for @command{gnattest}
18027
18028 @noindent
18029
18030 Most of the command-line options can also be passed to the tool by adding
18031 special attributes to the project file. Those attributes should be put in
18032 package gnattest. Here is the list of attributes:
18033
18034 @itemize @bullet
18035
18036 @item Separate_Stub_Root
18037 is used to select the same output mode as with the --separate-root option.
18038 This attribute cannot be used together with Stub_Subdir.
18039
18040 @item Stub_Subdir
18041 is used to select the same output mode as with the --subdir option.
18042 This attribute cannot be used together with Separate_Stub_Root.
18043
18044 @item Harness_Dir
18045 is used to specify the directory in which to place harness packages and project
18046 file for the test driver, otherwise specified by --harness-dir.
18047
18048 @item Additional_Tests
18049 is used to specify the project file, otherwise given by
18050 --additional-tests switch.
18051
18052 @item Stubs_Default
18053 is used to specify the default behaviour of test stubs, otherwise
18054 specified by --stub-default option. The value of this attribute
18055 should be either "pass" or "fail".
18056
18057 @end itemize
18058
18059 Each of those attributes can be overridden from the command line if needed.
18060 Other @command{gnattest} switches can also be passed via the project
18061 file as an attribute list called GNATtest_Switches.
18062
18063 @node Simple Example
18064 @section Simple Example
18065
18066 @noindent
18067
18068 Let's take a very simple example using the first @command{gnattest} example
18069 located in:
18070
18071 @smallexample
18072 <install_prefix>/share/examples/gnattest/simple
18073 @end smallexample
18074
18075 This project contains a simple package containing one subprogram. By running gnattest:
18076
18077 @smallexample
18078 $ gnattest --harness-dir=driver -Psimple.gpr
18079 @end smallexample
18080
18081 a test driver is created in directory "driver". It can be compiled and run:
18082
18083 @smallexample
18084 $ cd driver
18085 $ gprbuild -Ptest_driver
18086 $ test_runner
18087 @end smallexample
18088
18089 One failed test with diagnosis "test not implemented" is reported.
18090 Since no special output option was specified, the test package Simple.Tests
18091 is located in:
18092
18093 @smallexample
18094 <install_prefix>/share/examples/gnattest/simple/src/tests
18095 @end smallexample
18096
18097 For each package containing visible subprograms, a child test package is
18098 generated. It contains one test routine per tested subprogram. Each
18099 declaration of a test subprogram has a comment specifying which tested
18100 subprogram it corresponds to. All of the test routines have separate bodies.
18101 The test routine located at simple-tests-test_inc_5eaee3.adb contains a single
18102 statement: a call to procedure Assert. It has two arguments: the Boolean
18103 expression we want to check and the diagnosis message to display if
18104 the condition is false.
18105
18106 That is where actual testing code should be written after a proper setup.
18107 An actual check can be performed by replacing the Assert call with:
18108
18109 @smallexample @c ada
18110 Assert (Inc (1) = 2, "wrong incrementation");
18111 @end smallexample
18112
18113 After recompiling and running the test driver, one successfully passed test
18114 is reported.
18115
18116 @node Setting Up and Tearing Down the Testing Environment
18117 @section Setting Up and Tearing Down the Testing Environment
18118
18119 @noindent
18120
18121 Besides test routines themselves, each test package has an inner package
18122 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
18123 User_Set_Up is called before each test routine of the package and
18124 User_Tear_Down is called after each test routine. Those two procedures can
18125 be used to perform necessary initialization and finalization,
18126 memory allocation, etc.
18127
18128 @node Regenerating Tests
18129 @section Regenerating Tests
18130
18131 @noindent
18132
18133 Bodies of test routines and env_mgmt packages are never overridden after they
18134 have been created once. As long as the name of the subprogram, full expanded Ada
18135 names, and the order of its parameters is the same, the old test routine will
18136 fit in its place and no test stub will be generated for the subprogram.
18137
18138 This can be demonstrated with the previous example. By uncommenting declaration
18139 and body of function Dec in simple.ads and simple.adb, running
18140 @command{gnattest} on the project, and then running the test driver:
18141
18142 @smallexample
18143 gnattest --harness-dir=driver -Psimple.gpr
18144 cd driver
18145 gprbuild -Ptest_driver
18146 test_runner
18147 @end smallexample
18148
18149 the old test is not replaced with a stub, nor is it lost, but a new test stub is
18150 created for function Dec.
18151
18152 The only way of regenerating tests stubs is to remove the previously created
18153 tests.
18154
18155 @node Default Test Behavior
18156 @section Default Test Behavior
18157
18158 @noindent
18159
18160 The generated test driver can treat unimplemented tests in two ways:
18161 either count them all as failed (this is useful to see which tests are still
18162 left to implement) or as passed (to sort out unimplemented ones from those
18163 actually failing).
18164
18165 The test driver accepts a switch to specify this behavior: --stub-default=val,
18166 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
18167
18168 The default behavior of the test driver is set with the same switch
18169 as passed to gnattest when generating the test driver.
18170
18171 Passing it to the driver generated on the first example:
18172
18173 @smallexample
18174 test_runner --stub-default=pass
18175 @end smallexample
18176
18177 makes both tests pass, even the unimplemented one.
18178
18179 @node Testing Primitive Operations of Tagged Types
18180 @section Testing Primitive Operations of Tagged Types
18181
18182 @noindent
18183
18184 Creation of test stubs for primitive operations of tagged types entails a number
18185 of features. Test routines for all primitives of a given tagged type are
18186 placed in a separate child package named according to the tagged type. For
18187 example, if you have tagged type T in package P, all tests for primitives
18188 of T will be in P.T_Tests.
18189
18190 Consider running gnattest on the second example (note: actual tests for this
18191 example already exist, so there's no need to worry if the tool reports that
18192 no new stubs were generated):
18193
18194 @smallexample
18195 cd <install_prefix>/share/examples/gnattest/tagged_rec
18196 gnattest --harness-dir=driver -Ptagged_rec.gpr
18197 @end smallexample
18198
18199 Taking a closer look at the test type declared in the test package
18200 Speed1.Controller_Tests is necessary. It is declared in:
18201
18202 @smallexample
18203 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18204 @end smallexample
18205
18206 Test types are direct or indirect descendants of
18207 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18208 subprograms, the user doesn't need to be concerned with them. However,
18209 when generating test packages for primitive operations, there are some things
18210 the user needs to know.
18211
18212 Type Test_Controller has components that allow assignment of various
18213 derivations of type Controller. And if you look at the specification of
18214 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18215 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18216 Thus, test types mirror the hierarchy of tested types.
18217
18218 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18219 of primitive operations of type T assigns to Fixture a reference to an
18220 object of that exact type T. Notice, however, that if the tagged type has
18221 discriminants, the User_Set_Up only has a commented template for setting
18222 up the fixture, since filling the discriminant with actual value is up
18223 to the user.
18224
18225 The knowledge of the structure of test types allows additional testing
18226 without additional effort. Those possibilities are described below.
18227
18228 @node Testing Inheritance
18229 @section Testing Inheritance
18230
18231 @noindent
18232
18233 Since the test type hierarchy mimics the hierarchy of tested types, the
18234 inheritance of tests takes place. An example of such inheritance can be
18235 seen by running the test driver generated for the second example. As previously
18236 mentioned, actual tests are already written for this example.
18237
18238 @smallexample
18239 cd driver
18240 gprbuild -Ptest_driver
18241 test_runner
18242 @end smallexample
18243
18244 There are 6 passed tests while there are only 5 testable subprograms. The test
18245 routine for function Speed has been inherited and run against objects of the
18246 derived type.
18247
18248 @node Tagged Types Substitutability Testing
18249 @section Tagged Types Substitutability Testing
18250
18251 @noindent
18252
18253 Tagged Types Substitutability Testing is a way of verifying the Liskov
18254 substitution principle (LSP) by testing. LSP is a principle stating that if
18255 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18256 then objects of type T may be replaced with objects of type S (that is,
18257 objects of type S may be substituted for objects of type T), without
18258 altering any of the desirable properties of the program. When the properties
18259 of the program are expressed in the form of subprogram preconditions and
18260 postconditions (let's call them pre and post), LSP is formulated as relations
18261 between the pre and post of primitive operations and the pre and post of their
18262 derived operations. The pre of a derived operation should not be stronger than
18263 the original pre, and the post of the derived operation should not be weaker
18264 than the original post. Those relations ensure that verifying if a dispatching
18265 call is safe can be done just by using the pre and post of the root operation.
18266
18267 Verifying LSP by testing consists of running all the unit tests associated with
18268 the primitives of a given tagged type with objects of its derived types.
18269
18270 In the example used in the previous section, there was clearly a violation of
18271 LSP. The overriding primitive Adjust_Speed in package Speed2 removes the
18272 functionality of the overridden primitive and thus doesn't respect LSP.
18273 Gnattest has a special option to run overridden parent tests against objects
18274 of the type which have overriding primitives:
18275
18276 @smallexample
18277 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18278 cd driver
18279 gprbuild -Ptest_driver
18280 test_runner
18281 @end smallexample
18282
18283 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18284 against objects of the derived type.
18285
18286 @node Testing with Contracts
18287 @section Testing with Contracts
18288
18289 @noindent
18290
18291 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case.
18292 Test routines are generated, one per each Test_Case associated with a tested
18293 subprogram. Those test routines have special wrappers for tested functions
18294 that have composition of pre- and postcondition of the subprogram with
18295 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18296 either count for Nominal mode or do not count for Robustness mode).
18297
18298 The third example demonstrates how this works:
18299
18300 @smallexample
18301 cd <install_prefix>/share/examples/gnattest/contracts
18302 gnattest --harness-dir=driver -Pcontracts.gpr
18303 @end smallexample
18304
18305 Putting actual checks within the range of the contract does not cause any
18306 error reports. For example, for the test routine which corresponds to
18307 test case 1:
18308
18309 @smallexample @c ada
18310 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18311 @end smallexample
18312
18313 and for the test routine corresponding to test case 2:
18314
18315 @smallexample @c ada
18316 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18317 @end smallexample
18318
18319 are acceptable:
18320
18321 @smallexample
18322 cd driver
18323 gprbuild -Ptest_driver
18324 test_runner
18325 @end smallexample
18326
18327 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18328 a precondition violation for test case one. Also, by using any otherwise
18329 correct but positive pair of numbers in the second test routine, you can also
18330 get a precondition violation. Postconditions are checked and reported
18331 the same way.
18332
18333 @node Additional Tests
18334 @section Additional Tests
18335
18336 @noindent
18337 @command{gnattest} can add user-written tests to the main suite of the test
18338 driver. @command{gnattest} traverses the given packages and searches for test
18339 routines. All procedures with a single in out parameter of a type which is
18340 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18341 specifications are added to the suites and are then executed by the test driver.
18342 (Set_Up and Tear_Down are filtered out.)
18343
18344 An example illustrates two ways of creating test harnesses for user-written
18345 tests. Directory additional_tests contains an AUnit-based test driver written
18346 by hand.
18347
18348 @smallexample
18349 <install_prefix>/share/examples/gnattest/additional_tests/
18350 @end smallexample
18351
18352 To create a test driver for already-written tests, use the --harness-only
18353 option:
18354
18355 @smallexample
18356 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18357   --harness-only
18358 gnatmake -Pharness_only/test_driver.gpr
18359 harness_only/test_runner
18360 @end smallexample
18361
18362 Additional tests can also be executed together with generated tests:
18363
18364 @smallexample
18365 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18366   --harness-dir=mixing
18367 gnatmake -Pmixing/test_driver.gpr
18368 mixing/test_runner
18369 @end smallexample
18370
18371 @node Current Limitations
18372 @section Current Limitations
18373
18374 @noindent
18375
18376 The tool currently does not support following features:
18377
18378 @itemize @bullet
18379 @item generic tests for generic packages and package instantiations
18380 @item tests for protected subprograms and entries
18381 @item aspects Precondition, Postcondition, and Test_Case
18382 @item generating test packages for code that is not conformant with ada 2005
18383
18384 @end itemize
18385
18386 @c *********************************
18387 @node Generating Ada Bindings for C and C++ headers
18388 @chapter Generating Ada Bindings for C and C++ headers
18389 @findex binding
18390
18391 @noindent
18392 GNAT now comes with a binding generator for C and C++ headers which is
18393 intended to do 95% of the tedious work of generating Ada specs from C
18394 or C++ header files.
18395
18396 Note that this capability is not intended to generate 100% correct Ada specs,
18397 and will is some cases require manual adjustments, although it can often
18398 be used out of the box in practice.
18399
18400 Some of the known limitations include:
18401
18402 @itemize @bullet
18403 @item only very simple character constant macros are translated into Ada
18404 constants. Function macros (macros with arguments) are partially translated
18405 as comments, to be completed manually if needed.
18406 @item some extensions (e.g. vector types) are not supported
18407 @item pointers to pointers or complex structures are mapped to System.Address
18408 @item identifiers with identical name (except casing) will generate compilation
18409       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18410 @end itemize
18411
18412 The code generated is using the Ada 2005 syntax, which makes it
18413 easier to interface with other languages than previous versions of Ada.
18414
18415 @menu
18416 * Running the binding generator::
18417 * Generating bindings for C++ headers::
18418 * Switches::
18419 @end menu
18420
18421 @node Running the binding generator
18422 @section Running the binding generator
18423
18424 @noindent
18425 The binding generator is part of the @command{gcc} compiler and can be
18426 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18427 spec files for the header files specified on the command line, and all
18428 header files needed by these files transitively. For example:
18429
18430 @smallexample
18431 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18432 $ gcc -c -gnat05 *.ads
18433 @end smallexample
18434
18435 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18436 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18437 correspond to the files @file{/usr/include/time.h},
18438 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18439 mode these Ada specs.
18440
18441 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18442 and will attempt to generate corresponding Ada comments.
18443
18444 If you want to generate a single Ada file and not the transitive closure, you
18445 can use instead the @option{-fdump-ada-spec-slim} switch.
18446
18447 Note that we recommend when possible to use the @command{g++} driver to
18448 generate bindings, even for most C headers, since this will in general
18449 generate better Ada specs. For generating bindings for C++ headers, it is
18450 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18451 is equivalent in this case. If @command{g++} cannot work on your C headers
18452 because of incompatibilities between C and C++, then you can fallback to
18453 @command{gcc} instead.
18454
18455 For an example of better bindings generated from the C++ front-end,
18456 the name of the parameters (when available) are actually ignored by the C
18457 front-end. Consider the following C header:
18458
18459 @smallexample
18460 extern void foo (int variable);
18461 @end smallexample
18462
18463 with the C front-end, @code{variable} is ignored, and the above is handled as:
18464
18465 @smallexample
18466 extern void foo (int);
18467 @end smallexample
18468
18469 generating a generic:
18470
18471 @smallexample
18472 procedure foo (param1 : int);
18473 @end smallexample
18474
18475 with the C++ front-end, the name is available, and we generate:
18476
18477 @smallexample
18478 procedure foo (variable : int);
18479 @end smallexample
18480
18481 In some cases, the generated bindings will be more complete or more meaningful
18482 when defining some macros, which you can do via the @option{-D} switch. This
18483 is for example the case with @file{Xlib.h} under GNU/Linux:
18484
18485 @smallexample
18486 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18487 @end smallexample
18488
18489 The above will generate more complete bindings than a straight call without
18490 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18491
18492 In other cases, it is not possible to parse a header file in a stand alone
18493 manner, because other include files need to be included first. In this
18494 case, the solution is to create a small header file including the needed
18495 @code{#include} and possible @code{#define} directives. For example, to
18496 generate Ada bindings for @file{readline/readline.h}, you need to first
18497 include @file{stdio.h}, so you can create a file with the following two
18498 lines in e.g. @file{readline1.h}:
18499
18500 @smallexample
18501 #include <stdio.h>
18502 #include <readline/readline.h>
18503 @end smallexample
18504
18505 and then generate Ada bindings from this file:
18506
18507 @smallexample
18508 $ g++ -c -fdump-ada-spec readline1.h
18509 @end smallexample
18510
18511 @node Generating bindings for C++ headers
18512 @section Generating bindings for C++ headers
18513
18514 @noindent
18515 Generating bindings for C++ headers is done using the same options, always
18516 with the @command{g++} compiler.
18517
18518 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18519 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18520 multiple inheritance of abstract classes will be mapped to Ada interfaces
18521 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18522 information on interfacing to C++).
18523
18524 For example, given the following C++ header file:
18525
18526 @smallexample
18527 @group
18528 @cartouche
18529 class Carnivore @{
18530 public:
18531    virtual int Number_Of_Teeth () = 0;
18532 @};
18533
18534 class Domestic @{
18535 public:
18536    virtual void Set_Owner (char* Name) = 0;
18537 @};
18538
18539 class Animal @{
18540 public:
18541   int Age_Count;
18542   virtual void Set_Age (int New_Age);
18543 @};
18544
18545 class Dog : Animal, Carnivore, Domestic @{
18546  public:
18547   int  Tooth_Count;
18548   char *Owner;
18549
18550   virtual int  Number_Of_Teeth ();
18551   virtual void Set_Owner (char* Name);
18552
18553   Dog();
18554 @};
18555 @end cartouche
18556 @end group
18557 @end smallexample
18558
18559 The corresponding Ada code is generated:
18560
18561 @smallexample @c ada
18562 @group
18563 @cartouche
18564   package Class_Carnivore is
18565     type Carnivore is limited interface;
18566     pragma Import (CPP, Carnivore);
18567
18568     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18569   end;
18570   use Class_Carnivore;
18571
18572   package Class_Domestic is
18573     type Domestic is limited interface;
18574     pragma Import (CPP, Domestic);
18575
18576     procedure Set_Owner
18577       (this : access Domestic;
18578        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18579   end;
18580   use Class_Domestic;
18581
18582   package Class_Animal is
18583     type Animal is tagged limited record
18584       Age_Count : aliased int;
18585     end record;
18586     pragma Import (CPP, Animal);
18587
18588     procedure Set_Age (this : access Animal; New_Age : int);
18589     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18590   end;
18591   use Class_Animal;
18592
18593   package Class_Dog is
18594     type Dog is new Animal and Carnivore and Domestic with record
18595       Tooth_Count : aliased int;
18596       Owner : Interfaces.C.Strings.chars_ptr;
18597     end record;
18598     pragma Import (CPP, Dog);
18599
18600     function Number_Of_Teeth (this : access Dog) return int;
18601     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18602
18603     procedure Set_Owner
18604       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18605     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18606
18607     function New_Dog return Dog;
18608     pragma CPP_Constructor (New_Dog);
18609     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18610   end;
18611   use Class_Dog;
18612 @end cartouche
18613 @end group
18614 @end smallexample
18615
18616 @node Switches
18617 @section Switches
18618
18619 @table @option
18620 @item -fdump-ada-spec
18621 @cindex @option{-fdump-ada-spec} (@command{gcc})
18622 Generate Ada spec files for the given header files transitively (including
18623 all header files that these headers depend upon).
18624
18625 @item -fdump-ada-spec-slim
18626 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18627 Generate Ada spec files for the header files specified on the command line
18628 only.
18629
18630 @item -C
18631 @cindex @option{-C} (@command{gcc})
18632 Extract comments from headers and generate Ada comments in the Ada spec files.
18633 @end table
18634
18635 @node Other Utility Programs
18636 @chapter Other Utility Programs
18637
18638 @noindent
18639 This chapter discusses some other utility programs available in the Ada
18640 environment.
18641
18642 @menu
18643 * Using Other Utility Programs with GNAT::
18644 * The External Symbol Naming Scheme of GNAT::
18645 * Converting Ada Files to html with gnathtml::
18646 * Installing gnathtml::
18647 @ifset vms
18648 * LSE::
18649 * Profiling::
18650 @end ifset
18651 @end menu
18652
18653 @node Using Other Utility Programs with GNAT
18654 @section Using Other Utility Programs with GNAT
18655
18656 @noindent
18657 The object files generated by GNAT are in standard system format and in
18658 particular the debugging information uses this format. This means
18659 programs generated by GNAT can be used with existing utilities that
18660 depend on these formats.
18661
18662 @ifclear vms
18663 In general, any utility program that works with C will also often work with
18664 Ada programs generated by GNAT. This includes software utilities such as
18665 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18666 as Purify.
18667 @end ifclear
18668
18669 @node The External Symbol Naming Scheme of GNAT
18670 @section The External Symbol Naming Scheme of GNAT
18671
18672 @noindent
18673 In order to interpret the output from GNAT, when using tools that are
18674 originally intended for use with other languages, it is useful to
18675 understand the conventions used to generate link names from the Ada
18676 entity names.
18677
18678 All link names are in all lowercase letters. With the exception of library
18679 procedure names, the mechanism used is simply to use the full expanded
18680 Ada name with dots replaced by double underscores. For example, suppose
18681 we have the following package spec:
18682
18683 @smallexample @c ada
18684 @group
18685 @cartouche
18686 package QRS is
18687    MN : Integer;
18688 end QRS;
18689 @end cartouche
18690 @end group
18691 @end smallexample
18692
18693 @noindent
18694 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18695 the corresponding link name is @code{qrs__mn}.
18696 @findex Export
18697 Of course if a @code{pragma Export} is used this may be overridden:
18698
18699 @smallexample @c ada
18700 @group
18701 @cartouche
18702 package Exports is
18703    Var1 : Integer;
18704    pragma Export (Var1, C, External_Name => "var1_name");
18705    Var2 : Integer;
18706    pragma Export (Var2, C, Link_Name => "var2_link_name");
18707 end Exports;
18708 @end cartouche
18709 @end group
18710 @end smallexample
18711
18712 @noindent
18713 In this case, the link name for @var{Var1} is whatever link name the
18714 C compiler would assign for the C function @var{var1_name}. This typically
18715 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18716 system conventions, but other possibilities exist. The link name for
18717 @var{Var2} is @var{var2_link_name}, and this is not operating system
18718 dependent.
18719
18720 @findex _main
18721 One exception occurs for library level procedures. A potential ambiguity
18722 arises between the required name @code{_main} for the C main program,
18723 and the name we would otherwise assign to an Ada library level procedure
18724 called @code{Main} (which might well not be the main program).
18725
18726 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18727 names. So if we have a library level procedure such as
18728
18729 @smallexample @c ada
18730 @group
18731 @cartouche
18732 procedure Hello (S : String);
18733 @end cartouche
18734 @end group
18735 @end smallexample
18736
18737 @noindent
18738 the external name of this procedure will be @var{_ada_hello}.
18739
18740
18741 @node Converting Ada Files to html with gnathtml
18742 @section Converting Ada Files to HTML with @code{gnathtml}
18743
18744 @noindent
18745 This @code{Perl} script allows Ada source files to be browsed using
18746 standard Web browsers. For installation procedure, see the section
18747 @xref{Installing gnathtml}.
18748
18749 Ada reserved keywords are highlighted in a bold font and Ada comments in
18750 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18751 switch to suppress the generation of cross-referencing information, user
18752 defined variables and types will appear in a different color; you will
18753 be able to click on any identifier and go to its declaration.
18754
18755 The command line is as follow:
18756 @smallexample
18757 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18758 @c Expanding @ovar macro inline (explanation in macro def comments)
18759 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18760 @end smallexample
18761
18762 @noindent
18763 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18764 an html file for every ada file, and a global file called @file{index.htm}.
18765 This file is an index of every identifier defined in the files.
18766
18767 The available ^switches^options^ are the following ones:
18768
18769 @table @option
18770 @item -83
18771 @cindex @option{-83} (@code{gnathtml})
18772 Only the Ada 83 subset of keywords will be highlighted.
18773
18774 @item -cc @var{color}
18775 @cindex @option{-cc} (@code{gnathtml})
18776 This option allows you to change the color used for comments. The default
18777 value is green. The color argument can be any name accepted by html.
18778
18779 @item -d
18780 @cindex @option{-d} (@code{gnathtml})
18781 If the Ada files depend on some other files (for instance through
18782 @code{with} clauses, the latter files will also be converted to html.
18783 Only the files in the user project will be converted to html, not the files
18784 in the run-time library itself.
18785
18786 @item -D
18787 @cindex @option{-D} (@code{gnathtml})
18788 This command is the same as @option{-d} above, but @command{gnathtml} will
18789 also look for files in the run-time library, and generate html files for them.
18790
18791 @item -ext @var{extension}
18792 @cindex @option{-ext} (@code{gnathtml})
18793 This option allows you to change the extension of the generated HTML files.
18794 If you do not specify an extension, it will default to @file{htm}.
18795
18796 @item -f
18797 @cindex @option{-f} (@code{gnathtml})
18798 By default, gnathtml will generate html links only for global entities
18799 ('with'ed units, global variables and types,@dots{}).  If you specify
18800 @option{-f} on the command line, then links will be generated for local
18801 entities too.
18802
18803 @item -l @var{number}
18804 @cindex @option{-l} (@code{gnathtml})
18805 If this ^switch^option^ is provided and @var{number} is not 0, then
18806 @code{gnathtml} will number the html files every @var{number} line.
18807
18808 @item -I @var{dir}
18809 @cindex @option{-I} (@code{gnathtml})
18810 Specify a directory to search for library files (@file{.ALI} files) and
18811 source files. You can provide several -I switches on the command line,
18812 and the directories will be parsed in the order of the command line.
18813
18814 @item -o @var{dir}
18815 @cindex @option{-o} (@code{gnathtml})
18816 Specify the output directory for html files. By default, gnathtml will
18817 saved the generated html files in a subdirectory named @file{html/}.
18818
18819 @item -p @var{file}
18820 @cindex @option{-p} (@code{gnathtml})
18821 If you are using Emacs and the most recent Emacs Ada mode, which provides
18822 a full Integrated Development Environment for compiling, checking,
18823 running and debugging applications, you may use @file{.gpr} files
18824 to give the directories where Emacs can find sources and object files.
18825
18826 Using this ^switch^option^, you can tell gnathtml to use these files.
18827 This allows you to get an html version of your application, even if it
18828 is spread over multiple directories.
18829
18830 @item -sc @var{color}
18831 @cindex @option{-sc} (@code{gnathtml})
18832 This ^switch^option^ allows you to change the color used for symbol
18833 definitions.
18834 The default value is red. The color argument can be any name accepted by html.
18835
18836 @item -t @var{file}
18837 @cindex @option{-t} (@code{gnathtml})
18838 This ^switch^option^ provides the name of a file. This file contains a list of
18839 file names to be converted, and the effect is exactly as though they had
18840 appeared explicitly on the command line. This
18841 is the recommended way to work around the command line length limit on some
18842 systems.
18843
18844 @end table
18845
18846 @node Installing gnathtml
18847 @section Installing @code{gnathtml}
18848
18849 @noindent
18850 @code{Perl} needs to be installed on your machine to run this script.
18851 @code{Perl} is freely available for almost every architecture and
18852 Operating System via the Internet.
18853
18854 On Unix systems, you  may want to modify  the  first line of  the script
18855 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18856 is. The syntax of this line is:
18857 @smallexample
18858 #!full_path_name_to_perl
18859 @end smallexample
18860
18861 @noindent
18862 Alternatively, you may run the script using the following command line:
18863
18864 @smallexample
18865 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18866 @c Expanding @ovar macro inline (explanation in macro def comments)
18867 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18868 @end smallexample
18869
18870 @ifset vms
18871 @node LSE
18872 @section LSE
18873 @findex LSE
18874
18875 @noindent
18876 The GNAT distribution provides an Ada 95 template for the HP Language
18877 Sensitive Editor (LSE), a component of DECset. In order to
18878 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18879
18880 @node Profiling
18881 @section Profiling
18882 @findex PCA
18883
18884 @noindent
18885 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18886 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18887 the collection phase with the /DEBUG qualifier.
18888
18889 @smallexample
18890 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18891 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18892 $ RUN/DEBUG <PROGRAM_NAME>
18893 @end smallexample
18894 @noindent
18895 @end ifset
18896
18897 @ifclear vms
18898 @c ******************************
18899 @node Code Coverage and Profiling
18900 @chapter Code Coverage and Profiling
18901 @cindex Code Coverage
18902 @cindex Profiling
18903
18904 @noindent
18905 This chapter describes how to use @code{gcov} - coverage testing tool - and
18906 @code{gprof} - profiler tool - on your Ada programs.
18907
18908 @menu
18909 * Code Coverage of Ada Programs using gcov::
18910 * Profiling an Ada Program using gprof::
18911 @end menu
18912
18913 @node Code Coverage of Ada Programs using gcov
18914 @section Code Coverage of Ada Programs using gcov
18915 @cindex gcov
18916 @cindex -fprofile-arcs
18917 @cindex -ftest-coverage
18918 @cindex -coverage
18919 @cindex Code Coverage
18920
18921 @noindent
18922 @code{gcov} is a test coverage program: it analyzes the execution of a given
18923 program on selected tests, to help you determine the portions of the program
18924 that are still untested.
18925
18926 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18927 User's Guide. You can refer to this documentation for a more complete
18928 description.
18929
18930 This chapter provides a quick startup guide, and
18931 details some Gnat-specific features.
18932
18933 @menu
18934 * Quick startup guide::
18935 * Gnat specifics::
18936 @end menu
18937
18938 @node Quick startup guide
18939 @subsection Quick startup guide
18940
18941 In order to perform coverage analysis of a program using @code{gcov}, 3
18942 steps are needed:
18943
18944 @itemize @bullet
18945 @item
18946 Code instrumentation during the compilation process
18947 @item
18948 Execution of the instrumented program
18949 @item
18950 Execution of the @code{gcov} tool to generate the result.
18951 @end itemize
18952
18953 The code instrumentation needed by gcov is created at the object level:
18954 The source code is not modified in any way, because the instrumentation code is
18955 inserted by gcc during the compilation process. To compile your code with code
18956 coverage activated, you need to recompile your whole project using the
18957 switches
18958 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18959 @code{-fprofile-arcs}.
18960
18961 @smallexample
18962 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18963    -largs -fprofile-arcs
18964 @end smallexample
18965
18966 This compilation process will create @file{.gcno} files together with
18967 the usual object files.
18968
18969 Once the program is compiled with coverage instrumentation, you can
18970 run it as many times as needed - on portions of a test suite for
18971 example. The first execution will produce @file{.gcda} files at the
18972 same location as the @file{.gcno} files.  The following executions
18973 will update those files, so that a cumulative result of the covered
18974 portions of the program is generated.
18975
18976 Finally, you need to call the @code{gcov} tool. The different options of
18977 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18978
18979 This will create annotated source files with a @file{.gcov} extension:
18980 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18981
18982 @node Gnat specifics
18983 @subsection Gnat specifics
18984
18985 Because Ada semantics, portions of the source code may be shared among
18986 several object files. This is the case for example when generics are
18987 involved, when inlining is active  or when declarations generate  initialisation
18988 calls. In order to take
18989 into account this shared code, you need to call @code{gcov} on all
18990 source files of the tested program at once.
18991
18992 The list of source files might exceed the system's maximum command line
18993 length. In order to bypass this limitation, a new mechanism has been
18994 implemented in @code{gcov}: you can now list all your project's files into a
18995 text file, and provide this file to gcov as a parameter,  preceded by a @@
18996 (e.g. @samp{gcov @@mysrclist.txt}).
18997
18998 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18999 not supported as there can be unresolved symbols during the final link.
19000
19001 @node Profiling an Ada Program using gprof
19002 @section Profiling an Ada Program using gprof
19003 @cindex gprof
19004 @cindex -pg
19005 @cindex Profiling
19006
19007 @noindent
19008 This section is not meant to be an exhaustive documentation of @code{gprof}.
19009 Full documentation for it can be found in the GNU Profiler User's Guide
19010 documentation that is part of this GNAT distribution.
19011
19012 Profiling a program helps determine the parts of a program that are executed
19013 most often, and are therefore the most time-consuming.
19014
19015 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19016 better handle Ada programs and multitasking.
19017 It is currently supported on the following platforms
19018 @itemize @bullet
19019 @item
19020 linux x86/x86_64
19021 @item
19022 solaris sparc/sparc64/x86
19023 @item
19024 windows x86
19025 @end itemize
19026
19027 @noindent
19028 In order to profile a program using @code{gprof}, 3 steps are needed:
19029
19030 @itemize @bullet
19031 @item
19032 Code instrumentation, requiring a full recompilation of the project with the
19033 proper switches.
19034 @item
19035 Execution of the program under the analysis conditions, i.e. with the desired
19036 input.
19037 @item
19038 Analysis of the results using the @code{gprof} tool.
19039 @end itemize
19040
19041 @noindent
19042 The following sections detail the different steps, and indicate how
19043 to interpret the results:
19044 @menu
19045 * Compilation for profiling::
19046 * Program execution::
19047 * Running gprof::
19048 * Interpretation of profiling results::
19049 @end menu
19050
19051 @node Compilation for profiling
19052 @subsection Compilation for profiling
19053 @cindex -pg
19054 @cindex Profiling
19055
19056 In order to profile a program the first step is to tell the compiler
19057 to generate the necessary profiling information. The compiler switch to be used
19058 is @code{-pg}, which must be added to other compilation switches. This
19059 switch needs to be specified both during compilation and link stages, and can
19060 be specified once when using gnatmake:
19061
19062 @smallexample
19063 gnatmake -f -pg -P my_project
19064 @end smallexample
19065
19066 @noindent
19067 Note that only the objects that were compiled with the @samp{-pg} switch will
19068 be profiled; if you need to profile your whole project, use the @samp{-f}
19069 gnatmake switch to force full recompilation.
19070
19071 @node Program execution
19072 @subsection Program execution
19073
19074 @noindent
19075 Once the program has been compiled for profiling, you can run it as usual.
19076
19077 The only constraint imposed by profiling is that the program must terminate
19078 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19079 properly analyzed.
19080
19081 Once the program completes execution, a data file called @file{gmon.out} is
19082 generated in the directory where the program was launched from. If this file
19083 already exists, it will be overwritten.
19084
19085 @node Running gprof
19086 @subsection Running gprof
19087
19088 @noindent
19089 The @code{gprof} tool is called as follow:
19090
19091 @smallexample
19092 gprof my_prog gmon.out
19093 @end smallexample
19094
19095 @noindent
19096 or simpler:
19097
19098 @smallexample
19099 gprof my_prog
19100 @end smallexample
19101
19102 @noindent
19103 The complete form of the gprof command line is the following:
19104
19105 @smallexample
19106 gprof [^switches^options^] [executable [data-file]]
19107 @end smallexample
19108
19109 @noindent
19110 @code{gprof} supports numerous ^switch^options^. The order of these
19111 ^switch^options^ does not matter. The full list of options can be found in
19112 the GNU Profiler User's Guide documentation that comes with this documentation.
19113
19114 The following is the subset of those switches that is most relevant:
19115
19116 @table @option
19117
19118 @item --demangle[=@var{style}]
19119 @itemx --no-demangle
19120 @cindex @option{--demangle} (@code{gprof})
19121 These options control whether symbol names should be demangled when
19122 printing output.  The default is to demangle C++ symbols.  The
19123 @code{--no-demangle} option may be used to turn off demangling. Different
19124 compilers have different mangling styles.  The optional demangling style
19125 argument can be used to choose an appropriate demangling style for your
19126 compiler, in particular Ada symbols generated by GNAT can be demangled using
19127 @code{--demangle=gnat}.
19128
19129 @item -e @var{function_name}
19130 @cindex @option{-e} (@code{gprof})
19131 The @samp{-e @var{function}} option tells @code{gprof} not to print
19132 information about the function @var{function_name} (and its
19133 children@dots{}) in the call graph.  The function will still be listed
19134 as a child of any functions that call it, but its index number will be
19135 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19136 given; only one @var{function_name} may be indicated with each @samp{-e}
19137 option.
19138
19139 @item -E @var{function_name}
19140 @cindex @option{-E} (@code{gprof})
19141 The @code{-E @var{function}} option works like the @code{-e} option, but
19142 execution time spent in the function (and children who were not called from
19143 anywhere else), will not be used to compute the percentages-of-time for
19144 the call graph.  More than one @samp{-E} option may be given; only one
19145 @var{function_name} may be indicated with each @samp{-E} option.
19146
19147 @item -f @var{function_name}
19148 @cindex @option{-f} (@code{gprof})
19149 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19150 call graph to the function @var{function_name} and its children (and
19151 their children@dots{}).  More than one @samp{-f} option may be given;
19152 only one @var{function_name} may be indicated with each @samp{-f}
19153 option.
19154
19155 @item -F @var{function_name}
19156 @cindex @option{-F} (@code{gprof})
19157 The @samp{-F @var{function}} option works like the @code{-f} option, but
19158 only time spent in the function and its children (and their
19159 children@dots{}) will be used to determine total-time and
19160 percentages-of-time for the call graph.  More than one @samp{-F} option
19161 may be given; only one @var{function_name} may be indicated with each
19162 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19163
19164 @end table
19165
19166 @node Interpretation of profiling results
19167 @subsection Interpretation of profiling results
19168
19169 @noindent
19170
19171 The results of the profiling analysis are represented by two arrays: the
19172 'flat profile' and the 'call graph'. Full documentation of those outputs
19173 can be found in the GNU Profiler User's Guide.
19174
19175 The flat profile shows the time spent in each function of the program, and how
19176 many time it has been called. This allows you to locate easily the most
19177 time-consuming functions.
19178
19179 The call graph shows, for each subprogram, the subprograms that call it,
19180 and the subprograms that it calls. It also provides an estimate of the time
19181 spent in each of those callers/called subprograms.
19182 @end ifclear
19183
19184 @c ******************************
19185 @node Running and Debugging Ada Programs
19186 @chapter Running and Debugging Ada Programs
19187 @cindex Debugging
19188
19189 @noindent
19190 This chapter discusses how to debug Ada programs.
19191 @ifset vms
19192 It applies to GNAT on the Alpha OpenVMS platform;
19193 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19194 since HP has implemented Ada support in the OpenVMS debugger on I64.
19195 @end ifset
19196
19197 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19198
19199 @enumerate
19200 @item
19201 The illegality may be a violation of the static semantics of Ada. In
19202 that case GNAT diagnoses the constructs in the program that are illegal.
19203 It is then a straightforward matter for the user to modify those parts of
19204 the program.
19205
19206 @item
19207 The illegality may be a violation of the dynamic semantics of Ada. In
19208 that case the program compiles and executes, but may generate incorrect
19209 results, or may terminate abnormally with some exception.
19210
19211 @item
19212 When presented with a program that contains convoluted errors, GNAT
19213 itself may terminate abnormally without providing full diagnostics on
19214 the incorrect user program.
19215 @end enumerate
19216
19217 @menu
19218 * The GNAT Debugger GDB::
19219 * Running GDB::
19220 * Introduction to GDB Commands::
19221 * Using Ada Expressions::
19222 * Calling User-Defined Subprograms::
19223 * Using the Next Command in a Function::
19224 * Ada Exceptions::
19225 * Ada Tasks::
19226 * Debugging Generic Units::
19227 * Remote Debugging using gdbserver::
19228 * GNAT Abnormal Termination or Failure to Terminate::
19229 * Naming Conventions for GNAT Source Files::
19230 * Getting Internal Debugging Information::
19231 * Stack Traceback::
19232 @end menu
19233
19234 @cindex Debugger
19235 @findex gdb
19236
19237 @node The GNAT Debugger GDB
19238 @section The GNAT Debugger GDB
19239
19240 @noindent
19241 @code{GDB} is a general purpose, platform-independent debugger that
19242 can be used to debug mixed-language programs compiled with @command{gcc},
19243 and in particular is capable of debugging Ada programs compiled with
19244 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19245 complex Ada data structures.
19246
19247 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19248 @ifset vms
19249 located in the GNU:[DOCS] directory,
19250 @end ifset
19251 for full details on the usage of @code{GDB}, including a section on
19252 its usage on programs. This manual should be consulted for full
19253 details. The section that follows is a brief introduction to the
19254 philosophy and use of @code{GDB}.
19255
19256 When GNAT programs are compiled, the compiler optionally writes debugging
19257 information into the generated object file, including information on
19258 line numbers, and on declared types and variables. This information is
19259 separate from the generated code. It makes the object files considerably
19260 larger, but it does not add to the size of the actual executable that
19261 will be loaded into memory, and has no impact on run-time performance. The
19262 generation of debug information is triggered by the use of the
19263 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19264 used to carry out the compilations. It is important to emphasize that
19265 the use of these options does not change the generated code.
19266
19267 The debugging information is written in standard system formats that
19268 are used by many tools, including debuggers and profilers. The format
19269 of the information is typically designed to describe C types and
19270 semantics, but GNAT implements a translation scheme which allows full
19271 details about Ada types and variables to be encoded into these
19272 standard C formats. Details of this encoding scheme may be found in
19273 the file exp_dbug.ads in the GNAT source distribution. However, the
19274 details of this encoding are, in general, of no interest to a user,
19275 since @code{GDB} automatically performs the necessary decoding.
19276
19277 When a program is bound and linked, the debugging information is
19278 collected from the object files, and stored in the executable image of
19279 the program. Again, this process significantly increases the size of
19280 the generated executable file, but it does not increase the size of
19281 the executable program itself. Furthermore, if this program is run in
19282 the normal manner, it runs exactly as if the debug information were
19283 not present, and takes no more actual memory.
19284
19285 However, if the program is run under control of @code{GDB}, the
19286 debugger is activated.  The image of the program is loaded, at which
19287 point it is ready to run.  If a run command is given, then the program
19288 will run exactly as it would have if @code{GDB} were not present. This
19289 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19290 entirely non-intrusive until a breakpoint is encountered.  If no
19291 breakpoint is ever hit, the program will run exactly as it would if no
19292 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19293 the debugging information and can respond to user commands to inspect
19294 variables, and more generally to report on the state of execution.
19295
19296 @c **************
19297 @node Running GDB
19298 @section Running GDB
19299
19300 @noindent
19301 This section describes how to initiate the debugger.
19302 @c The above sentence is really just filler, but it was otherwise
19303 @c clumsy to get the first paragraph nonindented given the conditional
19304 @c nature of the description
19305
19306 @ifclear vms
19307 The debugger can be launched from a @code{GPS} menu or
19308 directly from the command line. The description below covers the latter use.
19309 All the commands shown can be used in the @code{GPS} debug console window,
19310 but there are usually more GUI-based ways to achieve the same effect.
19311 @end ifclear
19312
19313 The command to run @code{GDB} is
19314
19315 @smallexample
19316 $ ^gdb program^GDB PROGRAM^
19317 @end smallexample
19318
19319 @noindent
19320 where @code{^program^PROGRAM^} is the name of the executable file. This
19321 activates the debugger and results in a prompt for debugger commands.
19322 The simplest command is simply @code{run}, which causes the program to run
19323 exactly as if the debugger were not present. The following section
19324 describes some of the additional commands that can be given to @code{GDB}.
19325
19326 @c *******************************
19327 @node Introduction to GDB Commands
19328 @section Introduction to GDB Commands
19329
19330 @noindent
19331 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19332 Debugging with GDB, gdb, Debugging with GDB},
19333 @ifset vms
19334 located in the GNU:[DOCS] directory,
19335 @end ifset
19336 for extensive documentation on the use
19337 of these commands, together with examples of their use. Furthermore,
19338 the command @command{help} invoked from within GDB activates a simple help
19339 facility which summarizes the available commands and their options.
19340 In this section we summarize a few of the most commonly
19341 used commands to give an idea of what @code{GDB} is about. You should create
19342 a simple program with debugging information and experiment with the use of
19343 these @code{GDB} commands on the program as you read through the
19344 following section.
19345
19346 @table @code
19347 @item set args @var{arguments}
19348 The @var{arguments} list above is a list of arguments to be passed to
19349 the program on a subsequent run command, just as though the arguments
19350 had been entered on a normal invocation of the program. The @code{set args}
19351 command is not needed if the program does not require arguments.
19352
19353 @item run
19354 The @code{run} command causes execution of the program to start from
19355 the beginning. If the program is already running, that is to say if
19356 you are currently positioned at a breakpoint, then a prompt will ask
19357 for confirmation that you want to abandon the current execution and
19358 restart.
19359
19360 @item breakpoint @var{location}
19361 The breakpoint command sets a breakpoint, that is to say a point at which
19362 execution will halt and @code{GDB} will await further
19363 commands. @var{location} is
19364 either a line number within a file, given in the format @code{file:linenumber},
19365 or it is the name of a subprogram. If you request that a breakpoint be set on
19366 a subprogram that is overloaded, a prompt will ask you to specify on which of
19367 those subprograms you want to breakpoint. You can also
19368 specify that all of them should be breakpointed. If the program is run
19369 and execution encounters the breakpoint, then the program
19370 stops and @code{GDB} signals that the breakpoint was encountered by
19371 printing the line of code before which the program is halted.
19372
19373 @item catch exception @var{name}
19374 This command causes the program execution to stop whenever exception
19375 @var{name} is raised.  If @var{name} is omitted, then the execution is
19376 suspended when any exception is raised.
19377
19378 @item print @var{expression}
19379 This will print the value of the given expression. Most simple
19380 Ada expression formats are properly handled by @code{GDB}, so the expression
19381 can contain function calls, variables, operators, and attribute references.
19382
19383 @item continue
19384 Continues execution following a breakpoint, until the next breakpoint or the
19385 termination of the program.
19386
19387 @item step
19388 Executes a single line after a breakpoint. If the next statement
19389 is a subprogram call, execution continues into (the first statement of)
19390 the called subprogram.
19391
19392 @item next
19393 Executes a single line. If this line is a subprogram call, executes and
19394 returns from the call.
19395
19396 @item list
19397 Lists a few lines around the current source location. In practice, it
19398 is usually more convenient to have a separate edit window open with the
19399 relevant source file displayed. Successive applications of this command
19400 print subsequent lines. The command can be given an argument which is a
19401 line number, in which case it displays a few lines around the specified one.
19402
19403 @item backtrace
19404 Displays a backtrace of the call chain. This command is typically
19405 used after a breakpoint has occurred, to examine the sequence of calls that
19406 leads to the current breakpoint. The display includes one line for each
19407 activation record (frame) corresponding to an active subprogram.
19408
19409 @item up
19410 At a breakpoint, @code{GDB} can display the values of variables local
19411 to the current frame. The command @code{up} can be used to
19412 examine the contents of other active frames, by moving the focus up
19413 the stack, that is to say from callee to caller, one frame at a time.
19414
19415 @item down
19416 Moves the focus of @code{GDB} down from the frame currently being
19417 examined to the frame of its callee (the reverse of the previous command),
19418
19419 @item frame @var{n}
19420 Inspect the frame with the given number. The value 0 denotes the frame
19421 of the current breakpoint, that is to say the top of the call stack.
19422
19423 @end table
19424
19425 @noindent
19426 The above list is a very short introduction to the commands that
19427 @code{GDB} provides. Important additional capabilities, including conditional
19428 breakpoints, the ability to execute command sequences on a breakpoint,
19429 the ability to debug at the machine instruction level and many other
19430 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19431 Debugging with GDB}.  Note that most commands can be abbreviated
19432 (for example, c for continue, bt for backtrace).
19433
19434 @node Using Ada Expressions
19435 @section Using Ada Expressions
19436 @cindex Ada expressions
19437
19438 @noindent
19439 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19440 extensions. The philosophy behind the design of this subset is
19441
19442 @itemize @bullet
19443 @item
19444 That @code{GDB} should provide basic literals and access to operations for
19445 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19446 leaving more sophisticated computations to subprograms written into the
19447 program (which therefore may be called from @code{GDB}).
19448
19449 @item
19450 That type safety and strict adherence to Ada language restrictions
19451 are not particularly important to the @code{GDB} user.
19452
19453 @item
19454 That brevity is important to the @code{GDB} user.
19455 @end itemize
19456
19457 @noindent
19458 Thus, for brevity, the debugger acts as if there were
19459 implicit @code{with} and @code{use} clauses in effect for all user-written
19460 packages, thus making it unnecessary to fully qualify most names with
19461 their packages, regardless of context. Where this causes ambiguity,
19462 @code{GDB} asks the user's intent.
19463
19464 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19465 GDB, gdb, Debugging with GDB}.
19466
19467 @node Calling User-Defined Subprograms
19468 @section Calling User-Defined Subprograms
19469
19470 @noindent
19471 An important capability of @code{GDB} is the ability to call user-defined
19472 subprograms while debugging. This is achieved simply by entering
19473 a subprogram call statement in the form:
19474
19475 @smallexample
19476 call subprogram-name (parameters)
19477 @end smallexample
19478
19479 @noindent
19480 The keyword @code{call} can be omitted in the normal case where the
19481 @code{subprogram-name} does not coincide with any of the predefined
19482 @code{GDB} commands.
19483
19484 The effect is to invoke the given subprogram, passing it the
19485 list of parameters that is supplied. The parameters can be expressions and
19486 can include variables from the program being debugged. The
19487 subprogram must be defined
19488 at the library level within your program, and @code{GDB} will call the
19489 subprogram within the environment of your program execution (which
19490 means that the subprogram is free to access or even modify variables
19491 within your program).
19492
19493 The most important use of this facility is in allowing the inclusion of
19494 debugging routines that are tailored to particular data structures
19495 in your program. Such debugging routines can be written to provide a suitably
19496 high-level description of an abstract type, rather than a low-level dump
19497 of its physical layout. After all, the standard
19498 @code{GDB print} command only knows the physical layout of your
19499 types, not their abstract meaning. Debugging routines can provide information
19500 at the desired semantic level and are thus enormously useful.
19501
19502 For example, when debugging GNAT itself, it is crucial to have access to
19503 the contents of the tree nodes used to represent the program internally.
19504 But tree nodes are represented simply by an integer value (which in turn
19505 is an index into a table of nodes).
19506 Using the @code{print} command on a tree node would simply print this integer
19507 value, which is not very useful. But the PN routine (defined in file
19508 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19509 a useful high level representation of the tree node, which includes the
19510 syntactic category of the node, its position in the source, the integers
19511 that denote descendant nodes and parent node, as well as varied
19512 semantic information. To study this example in more detail, you might want to
19513 look at the body of the PN procedure in the stated file.
19514
19515 @node Using the Next Command in a Function
19516 @section Using the Next Command in a Function
19517
19518 @noindent
19519 When you use the @code{next} command in a function, the current source
19520 location will advance to the next statement as usual. A special case
19521 arises in the case of a @code{return} statement.
19522
19523 Part of the code for a return statement is the ``epilog'' of the function.
19524 This is the code that returns to the caller. There is only one copy of
19525 this epilog code, and it is typically associated with the last return
19526 statement in the function if there is more than one return. In some
19527 implementations, this epilog is associated with the first statement
19528 of the function.
19529
19530 The result is that if you use the @code{next} command from a return
19531 statement that is not the last return statement of the function you
19532 may see a strange apparent jump to the last return statement or to
19533 the start of the function. You should simply ignore this odd jump.
19534 The value returned is always that from the first return statement
19535 that was stepped through.
19536
19537 @node Ada Exceptions
19538 @section Stopping when Ada Exceptions are Raised
19539 @cindex Exceptions
19540
19541 @noindent
19542 You can set catchpoints that stop the program execution when your program
19543 raises selected exceptions.
19544
19545 @table @code
19546 @item catch exception
19547 Set a catchpoint that stops execution whenever (any task in the) program
19548 raises any exception.
19549
19550 @item catch exception @var{name}
19551 Set a catchpoint that stops execution whenever (any task in the) program
19552 raises the exception @var{name}.
19553
19554 @item catch exception unhandled
19555 Set a catchpoint that stops executing whenever (any task in the) program
19556 raises an exception for which there is no handler.
19557
19558 @item info exceptions
19559 @itemx info exceptions @var{regexp}
19560 The @code{info exceptions} command permits the user to examine all defined
19561 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19562 argument, prints out only those exceptions whose name matches @var{regexp}.
19563 @end table
19564
19565 @node Ada Tasks
19566 @section Ada Tasks
19567 @cindex Tasks
19568
19569 @noindent
19570 @code{GDB} allows the following task-related commands:
19571
19572 @table @code
19573 @item info tasks
19574 This command shows a list of current Ada tasks, as in the following example:
19575
19576 @smallexample
19577 @iftex
19578 @leftskip=0cm
19579 @end iftex
19580 (gdb) info tasks
19581   ID       TID P-ID   Thread Pri State                 Name
19582    1   8088000   0   807e000  15 Child Activation Wait main_task
19583    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19584    3   809a800   1   80a4800  15 Child Activation Wait a
19585 *  4   80ae800   3   80b8000  15 Running               c
19586 @end smallexample
19587
19588 @noindent
19589 In this listing, the asterisk before the first task indicates it to be the
19590 currently running task. The first column lists the task ID that is used
19591 to refer to tasks in the following commands.
19592
19593 @item break @var{linespec} task @var{taskid}
19594 @itemx break @var{linespec} task @var{taskid} if @dots{}
19595 @cindex Breakpoints and tasks
19596 These commands are like the @code{break @dots{} thread @dots{}}.
19597 @var{linespec} specifies source lines.
19598
19599 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19600 to specify that you only want @code{GDB} to stop the program when a
19601 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19602 numeric task identifiers assigned by @code{GDB}, shown in the first
19603 column of the @samp{info tasks} display.
19604
19605 If you do not specify @samp{task @var{taskid}} when you set a
19606 breakpoint, the breakpoint applies to @emph{all} tasks of your
19607 program.
19608
19609 You can use the @code{task} qualifier on conditional breakpoints as
19610 well; in this case, place @samp{task @var{taskid}} before the
19611 breakpoint condition (before the @code{if}).
19612
19613 @item task @var{taskno}
19614 @cindex Task switching
19615
19616 This command allows to switch to the task referred by @var{taskno}. In
19617 particular, This allows to browse the backtrace of the specified
19618 task. It is advised to switch back to the original task before
19619 continuing execution otherwise the scheduling of the program may be
19620 perturbed.
19621 @end table
19622
19623 @noindent
19624 For more detailed information on the tasking support,
19625 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19626
19627 @node Debugging Generic Units
19628 @section Debugging Generic Units
19629 @cindex Debugging Generic Units
19630 @cindex Generics
19631
19632 @noindent
19633 GNAT always uses code expansion for generic instantiation. This means that
19634 each time an instantiation occurs, a complete copy of the original code is
19635 made, with appropriate substitutions of formals by actuals.
19636
19637 It is not possible to refer to the original generic entities in
19638 @code{GDB}, but it is always possible to debug a particular instance of
19639 a generic, by using the appropriate expanded names. For example, if we have
19640
19641 @smallexample @c ada
19642 @group
19643 @cartouche
19644 procedure g is
19645
19646    generic package k is
19647       procedure kp (v1 : in out integer);
19648    end k;
19649
19650    package body k is
19651       procedure kp (v1 : in out integer) is
19652       begin
19653          v1 := v1 + 1;
19654       end kp;
19655    end k;
19656
19657    package k1 is new k;
19658    package k2 is new k;
19659
19660    var : integer := 1;
19661
19662 begin
19663    k1.kp (var);
19664    k2.kp (var);
19665    k1.kp (var);
19666    k2.kp (var);
19667 end;
19668 @end cartouche
19669 @end group
19670 @end smallexample
19671
19672 @noindent
19673 Then to break on a call to procedure kp in the k2 instance, simply
19674 use the command:
19675
19676 @smallexample
19677 (gdb) break g.k2.kp
19678 @end smallexample
19679
19680 @noindent
19681 When the breakpoint occurs, you can step through the code of the
19682 instance in the normal manner and examine the values of local variables, as for
19683 other units.
19684
19685 @node Remote Debugging using gdbserver
19686 @section Remote Debugging using gdbserver
19687 @cindex Remote Debugging using gdbserver
19688
19689 @noindent
19690 On platforms where gdbserver is supported, it is possible to use this tool
19691 to debug your application remotely.  This can be useful in situations
19692 where the program needs to be run on a target host that is different
19693 from the host used for development, particularly when the target has
19694 a limited amount of resources (either CPU and/or memory).
19695
19696 To do so, start your program using gdbserver on the target machine.
19697 gdbserver then automatically suspends the execution of your program
19698 at its entry point, waiting for a debugger to connect to it.  The
19699 following commands starts an application and tells gdbserver to
19700 wait for a connection with the debugger on localhost port 4444.
19701
19702 @smallexample
19703 $ gdbserver localhost:4444 program
19704 Process program created; pid = 5685
19705 Listening on port 4444
19706 @end smallexample
19707
19708 Once gdbserver has started listening, we can tell the debugger to establish
19709 a connection with this gdbserver, and then start the same debugging session
19710 as if the program was being debugged on the same host, directly under
19711 the control of GDB.
19712
19713 @smallexample
19714 $ gdb program
19715 (gdb) target remote targethost:4444
19716 Remote debugging using targethost:4444
19717 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19718 (gdb) b foo.adb:3
19719 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19720 (gdb) continue
19721 Continuing.
19722
19723 Breakpoint 1, foo () at foo.adb:4
19724 4       end foo;
19725 @end smallexample
19726
19727 It is also possible to use gdbserver to attach to an already running
19728 program, in which case the execution of that program is simply suspended
19729 until the connection between the debugger and gdbserver is established.
19730
19731 For more information on how to use gdbserver, @ref{Top, Server, Using
19732 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
19733 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19734
19735 @node GNAT Abnormal Termination or Failure to Terminate
19736 @section GNAT Abnormal Termination or Failure to Terminate
19737 @cindex GNAT Abnormal Termination or Failure to Terminate
19738
19739 @noindent
19740 When presented with programs that contain serious errors in syntax
19741 or semantics,
19742 GNAT may on rare occasions  experience problems in operation, such
19743 as aborting with a
19744 segmentation fault or illegal memory access, raising an internal
19745 exception, terminating abnormally, or failing to terminate at all.
19746 In such cases, you can activate
19747 various features of GNAT that can help you pinpoint the construct in your
19748 program that is the likely source of the problem.
19749
19750 The following strategies are presented in increasing order of
19751 difficulty, corresponding to your experience in using GNAT and your
19752 familiarity with compiler internals.
19753
19754 @enumerate
19755 @item
19756 Run @command{gcc} with the @option{-gnatf}. This first
19757 switch causes all errors on a given line to be reported. In its absence,
19758 only the first error on a line is displayed.
19759
19760 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19761 are encountered, rather than after compilation is terminated. If GNAT
19762 terminates prematurely or goes into an infinite loop, the last error
19763 message displayed may help to pinpoint the culprit.
19764
19765 @item
19766 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19767 mode, @command{gcc} produces ongoing information about the progress of the
19768 compilation and provides the name of each procedure as code is
19769 generated. This switch allows you to find which Ada procedure was being
19770 compiled when it encountered a code generation problem.
19771
19772 @item
19773 @cindex @option{-gnatdc} switch
19774 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19775 switch that does for the front-end what @option{^-v^VERBOSE^} does
19776 for the back end. The system prints the name of each unit,
19777 either a compilation unit or nested unit, as it is being analyzed.
19778 @item
19779 Finally, you can start
19780 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19781 front-end of GNAT, and can be run independently (normally it is just
19782 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19783 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19784 @code{where} command is the first line of attack; the variable
19785 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19786 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19787 which the execution stopped, and @code{input_file name} indicates the name of
19788 the source file.
19789 @end enumerate
19790
19791 @node Naming Conventions for GNAT Source Files
19792 @section Naming Conventions for GNAT Source Files
19793
19794 @noindent
19795 In order to examine the workings of the GNAT system, the following
19796 brief description of its organization may be helpful:
19797
19798 @itemize @bullet
19799 @item
19800 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19801
19802 @item
19803 All files prefixed with @file{^par^PAR^} are components of the parser. The
19804 numbers correspond to chapters of the Ada Reference Manual. For example,
19805 parsing of select statements can be found in @file{par-ch9.adb}.
19806
19807 @item
19808 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19809 numbers correspond to chapters of the Ada standard. For example, all
19810 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19811 addition, some features of the language require sufficient special processing
19812 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19813 dynamic dispatching, etc.
19814
19815 @item
19816 All files prefixed with @file{^exp^EXP^} perform normalization and
19817 expansion of the intermediate representation (abstract syntax tree, or AST).
19818 these files use the same numbering scheme as the parser and semantics files.
19819 For example, the construction of record initialization procedures is done in
19820 @file{exp_ch3.adb}.
19821
19822 @item
19823 The files prefixed with @file{^bind^BIND^} implement the binder, which
19824 verifies the consistency of the compilation, determines an order of
19825 elaboration, and generates the bind file.
19826
19827 @item
19828 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19829 data structures used by the front-end.
19830
19831 @item
19832 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19833 the abstract syntax tree as produced by the parser.
19834
19835 @item
19836 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19837 all entities, computed during semantic analysis.
19838
19839 @item
19840 Library management issues are dealt with in files with prefix
19841 @file{^lib^LIB^}.
19842
19843 @item
19844 @findex Ada
19845 @cindex Annex A
19846 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19847 defined in Annex A.
19848
19849 @item
19850 @findex Interfaces
19851 @cindex Annex B
19852 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19853 defined in Annex B.
19854
19855 @item
19856 @findex System
19857 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19858 both language-defined children and GNAT run-time routines.
19859
19860 @item
19861 @findex GNAT
19862 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19863 general-purpose packages, fully documented in their specs. All
19864 the other @file{.c} files are modifications of common @command{gcc} files.
19865 @end itemize
19866
19867 @node Getting Internal Debugging Information
19868 @section Getting Internal Debugging Information
19869
19870 @noindent
19871 Most compilers have internal debugging switches and modes. GNAT
19872 does also, except GNAT internal debugging switches and modes are not
19873 secret. A summary and full description of all the compiler and binder
19874 debug flags are in the file @file{debug.adb}. You must obtain the
19875 sources of the compiler to see the full detailed effects of these flags.
19876
19877 The switches that print the source of the program (reconstructed from
19878 the internal tree) are of general interest for user programs, as are the
19879 options to print
19880 the full internal tree, and the entity table (the symbol table
19881 information). The reconstructed source provides a readable version of the
19882 program after the front-end has completed analysis and  expansion,
19883 and is useful when studying the performance of specific constructs.
19884 For example, constraint checks are indicated, complex aggregates
19885 are replaced with loops and assignments, and tasking primitives
19886 are replaced with run-time calls.
19887
19888 @node Stack Traceback
19889 @section Stack Traceback
19890 @cindex traceback
19891 @cindex stack traceback
19892 @cindex stack unwinding
19893
19894 @noindent
19895 Traceback is a mechanism to display the sequence of subprogram calls that
19896 leads to a specified execution point in a program. Often (but not always)
19897 the execution point is an instruction at which an exception has been raised.
19898 This mechanism is also known as @i{stack unwinding} because it obtains
19899 its information by scanning the run-time stack and recovering the activation
19900 records of all active subprograms. Stack unwinding is one of the most
19901 important tools for program debugging.
19902
19903 The first entry stored in traceback corresponds to the deepest calling level,
19904 that is to say the subprogram currently executing the instruction
19905 from which we want to obtain the traceback.
19906
19907 Note that there is no runtime performance penalty when stack traceback
19908 is enabled, and no exception is raised during program execution.
19909
19910 @menu
19911 * Non-Symbolic Traceback::
19912 * Symbolic Traceback::
19913 @end menu
19914
19915 @node Non-Symbolic Traceback
19916 @subsection Non-Symbolic Traceback
19917 @cindex traceback, non-symbolic
19918
19919 @noindent
19920 Note: this feature is not supported on all platforms. See
19921 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19922 platforms.
19923
19924 @menu
19925 * Tracebacks From an Unhandled Exception::
19926 * Tracebacks From Exception Occurrences (non-symbolic)::
19927 * Tracebacks From Anywhere in a Program (non-symbolic)::
19928 @end menu
19929
19930 @node Tracebacks From an Unhandled Exception
19931 @subsubsection Tracebacks From an Unhandled Exception
19932
19933 @noindent
19934 A runtime non-symbolic traceback is a list of addresses of call instructions.
19935 To enable this feature you must use the @option{-E}
19936 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19937 of exception information. You can retrieve this information using the
19938 @code{addr2line} tool.
19939
19940 Here is a simple example:
19941
19942 @smallexample @c ada
19943 @cartouche
19944 procedure STB is
19945
19946    procedure P1 is
19947    begin
19948       raise Constraint_Error;
19949    end P1;
19950
19951    procedure P2 is
19952    begin
19953       P1;
19954    end P2;
19955
19956 begin
19957    P2;
19958 end STB;
19959 @end cartouche
19960 @end smallexample
19961
19962 @smallexample
19963 $ gnatmake stb -bargs -E
19964 $ stb
19965
19966 Execution terminated by unhandled exception
19967 Exception name: CONSTRAINT_ERROR
19968 Message: stb.adb:5
19969 Call stack traceback locations:
19970 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19971 @end smallexample
19972
19973 @noindent
19974 As we see the traceback lists a sequence of addresses for the unhandled
19975 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19976 guess that this exception come from procedure P1. To translate these
19977 addresses into the source lines where the calls appear, the
19978 @code{addr2line} tool, described below, is invaluable. The use of this tool
19979 requires the program to be compiled with debug information.
19980
19981 @smallexample
19982 $ gnatmake -g stb -bargs -E
19983 $ stb
19984
19985 Execution terminated by unhandled exception
19986 Exception name: CONSTRAINT_ERROR
19987 Message: stb.adb:5
19988 Call stack traceback locations:
19989 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19990
19991 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19992    0x4011f1 0x77e892a4
19993
19994 00401373 at d:/stb/stb.adb:5
19995 0040138B at d:/stb/stb.adb:10
19996 0040139C at d:/stb/stb.adb:14
19997 00401335 at d:/stb/b~stb.adb:104
19998 004011C4 at /build/@dots{}/crt1.c:200
19999 004011F1 at /build/@dots{}/crt1.c:222
20000 77E892A4 in ?? at ??:0
20001 @end smallexample
20002
20003 @noindent
20004 The @code{addr2line} tool has several other useful options:
20005
20006 @table @code
20007 @item --functions
20008 to get the function name corresponding to any location
20009
20010 @item --demangle=gnat
20011 to use the gnat decoding mode for the function names. Note that
20012 for binutils version 2.9.x the option is simply @option{--demangle}.
20013 @end table
20014
20015 @smallexample
20016 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20017    0x40139c 0x401335 0x4011c4 0x4011f1
20018
20019 00401373 in stb.p1 at d:/stb/stb.adb:5
20020 0040138B in stb.p2 at d:/stb/stb.adb:10
20021 0040139C in stb at d:/stb/stb.adb:14
20022 00401335 in main at d:/stb/b~stb.adb:104
20023 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20024 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20025 @end smallexample
20026
20027 @noindent
20028 From this traceback we can see that the exception was raised in
20029 @file{stb.adb} at line 5, which was reached from a procedure call in
20030 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20031 which contains the call to the main program.
20032 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20033 and the output will vary from platform to platform.
20034
20035 It is also possible to use @code{GDB} with these traceback addresses to debug
20036 the program. For example, we can break at a given code location, as reported
20037 in the stack traceback:
20038
20039 @smallexample
20040 $ gdb -nw stb
20041 @ifclear vms
20042 @noindent
20043 Furthermore, this feature is not implemented inside Windows DLL. Only
20044 the non-symbolic traceback is reported in this case.
20045 @end ifclear
20046
20047 (gdb) break *0x401373
20048 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20049 @end smallexample
20050
20051 @noindent
20052 It is important to note that the stack traceback addresses
20053 do not change when debug information is included. This is particularly useful
20054 because it makes it possible to release software without debug information (to
20055 minimize object size), get a field report that includes a stack traceback
20056 whenever an internal bug occurs, and then be able to retrieve the sequence
20057 of calls with the same program compiled with debug information.
20058
20059 @node Tracebacks From Exception Occurrences (non-symbolic)
20060 @subsubsection Tracebacks From Exception Occurrences
20061
20062 @noindent
20063 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20064 The stack traceback is attached to the exception information string, and can
20065 be retrieved in an exception handler within the Ada program, by means of the
20066 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20067
20068 @smallexample @c ada
20069 with Ada.Text_IO;
20070 with Ada.Exceptions;
20071
20072 procedure STB is
20073
20074    use Ada;
20075    use Ada.Exceptions;
20076
20077    procedure P1 is
20078       K : Positive := 1;
20079    begin
20080       K := K - 1;
20081    exception
20082       when E : others =>
20083          Text_IO.Put_Line (Exception_Information (E));
20084    end P1;
20085
20086    procedure P2 is
20087    begin
20088       P1;
20089    end P2;
20090
20091 begin
20092    P2;
20093 end STB;
20094 @end smallexample
20095
20096 @noindent
20097 This program will output:
20098
20099 @smallexample
20100 $ stb
20101
20102 Exception name: CONSTRAINT_ERROR
20103 Message: stb.adb:12
20104 Call stack traceback locations:
20105 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20106 @end smallexample
20107
20108 @node Tracebacks From Anywhere in a Program (non-symbolic)
20109 @subsubsection Tracebacks From Anywhere in a Program
20110
20111 @noindent
20112 It is also possible to retrieve a stack traceback from anywhere in a
20113 program. For this you need to
20114 use the @code{GNAT.Traceback} API. This package includes a procedure called
20115 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20116 display procedures described below. It is not necessary to use the
20117 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20118 is invoked explicitly.
20119
20120 @noindent
20121 In the following example we compute a traceback at a specific location in
20122 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20123 convert addresses to strings:
20124
20125 @smallexample @c ada
20126 with Ada.Text_IO;
20127 with GNAT.Traceback;
20128 with GNAT.Debug_Utilities;
20129
20130 procedure STB is
20131
20132    use Ada;
20133    use GNAT;
20134    use GNAT.Traceback;
20135
20136    procedure P1 is
20137       TB  : Tracebacks_Array (1 .. 10);
20138       --  We are asking for a maximum of 10 stack frames.
20139       Len : Natural;
20140       --  Len will receive the actual number of stack frames returned.
20141    begin
20142       Call_Chain (TB, Len);
20143
20144       Text_IO.Put ("In STB.P1 : ");
20145
20146       for K in 1 .. Len loop
20147          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20148          Text_IO.Put (' ');
20149       end loop;
20150
20151       Text_IO.New_Line;
20152    end P1;
20153
20154    procedure P2 is
20155    begin
20156       P1;
20157    end P2;
20158
20159 begin
20160    P2;
20161 end STB;
20162 @end smallexample
20163
20164 @smallexample
20165 $ gnatmake -g stb
20166 $ stb
20167
20168 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20169 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20170 @end smallexample
20171
20172 @noindent
20173 You can then get further information by invoking the @code{addr2line}
20174 tool as described earlier (note that the hexadecimal addresses
20175 need to be specified in C format, with a leading ``0x'').
20176
20177 @node Symbolic Traceback
20178 @subsection Symbolic Traceback
20179 @cindex traceback, symbolic
20180
20181 @noindent
20182 A symbolic traceback is a stack traceback in which procedure names are
20183 associated with each code location.
20184
20185 @noindent
20186 Note that this feature is not supported on all platforms. See
20187 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20188 list of currently supported platforms.
20189
20190 @noindent
20191 Note that the symbolic traceback requires that the program be compiled
20192 with debug information. If it is not compiled with debug information
20193 only the non-symbolic information will be valid.
20194
20195 @menu
20196 * Tracebacks From Exception Occurrences (symbolic)::
20197 * Tracebacks From Anywhere in a Program (symbolic)::
20198 @end menu
20199
20200 @node Tracebacks From Exception Occurrences (symbolic)
20201 @subsubsection Tracebacks From Exception Occurrences
20202
20203 @smallexample @c ada
20204 with Ada.Text_IO;
20205 with GNAT.Traceback.Symbolic;
20206
20207 procedure STB is
20208
20209    procedure P1 is
20210    begin
20211       raise Constraint_Error;
20212    end P1;
20213
20214    procedure P2 is
20215    begin
20216       P1;
20217    end P2;
20218
20219    procedure P3 is
20220    begin
20221       P2;
20222    end P3;
20223
20224 begin
20225    P3;
20226 exception
20227    when E : others =>
20228       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20229 end STB;
20230 @end smallexample
20231
20232 @smallexample
20233 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20234 $ stb
20235
20236 0040149F in stb.p1 at stb.adb:8
20237 004014B7 in stb.p2 at stb.adb:13
20238 004014CF in stb.p3 at stb.adb:18
20239 004015DD in ada.stb at stb.adb:22
20240 00401461 in main at b~stb.adb:168
20241 004011C4 in __mingw_CRTStartup at crt1.c:200
20242 004011F1 in mainCRTStartup at crt1.c:222
20243 77E892A4 in ?? at ??:0
20244 @end smallexample
20245
20246 @noindent
20247 In the above example the ``.\'' syntax in the @command{gnatmake} command
20248 is currently required by @command{addr2line} for files that are in
20249 the current working directory.
20250 Moreover, the exact sequence of linker options may vary from platform
20251 to platform.
20252 The above @option{-largs} section is for Windows platforms. By contrast,
20253 under Unix there is no need for the @option{-largs} section.
20254 Differences across platforms are due to details of linker implementation.
20255
20256 @node Tracebacks From Anywhere in a Program (symbolic)
20257 @subsubsection Tracebacks From Anywhere in a Program
20258
20259 @noindent
20260 It is possible to get a symbolic stack traceback
20261 from anywhere in a program, just as for non-symbolic tracebacks.
20262 The first step is to obtain a non-symbolic
20263 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20264 information. Here is an example:
20265
20266 @smallexample @c ada
20267 with Ada.Text_IO;
20268 with GNAT.Traceback;
20269 with GNAT.Traceback.Symbolic;
20270
20271 procedure STB is
20272
20273    use Ada;
20274    use GNAT.Traceback;
20275    use GNAT.Traceback.Symbolic;
20276
20277    procedure P1 is
20278       TB  : Tracebacks_Array (1 .. 10);
20279       --  We are asking for a maximum of 10 stack frames.
20280       Len : Natural;
20281       --  Len will receive the actual number of stack frames returned.
20282    begin
20283       Call_Chain (TB, Len);
20284       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20285    end P1;
20286
20287    procedure P2 is
20288    begin
20289       P1;
20290    end P2;
20291
20292 begin
20293    P2;
20294 end STB;
20295 @end smallexample
20296
20297 @c ******************************
20298 @ifset vms
20299 @node Compatibility with HP Ada
20300 @chapter Compatibility with HP Ada
20301 @cindex Compatibility
20302
20303 @noindent
20304 @cindex DEC Ada
20305 @cindex HP Ada
20306 @cindex Compatibility between GNAT and HP Ada
20307 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20308 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20309 GNAT is highly compatible
20310 with HP Ada, and it should generally be straightforward to port code
20311 from the HP Ada environment to GNAT. However, there are a few language
20312 and implementation differences of which the user must be aware. These
20313 differences are discussed in this chapter. In
20314 addition, the operating environment and command structure for the
20315 compiler are different, and these differences are also discussed.
20316
20317 For further details on these and other compatibility issues,
20318 see Appendix E of the HP publication
20319 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20320
20321 Except where otherwise indicated, the description of GNAT for OpenVMS
20322 applies to both the Alpha and I64 platforms.
20323
20324 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20325 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20326
20327 The discussion in this chapter addresses specifically the implementation
20328 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20329 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20330 GNAT always follows the Alpha implementation.
20331
20332 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20333 attributes are recognized, although only a subset of them can sensibly
20334 be implemented.  The description of pragmas in
20335 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20336 indicates whether or not they are applicable to non-VMS systems.
20337
20338 @menu
20339 * Ada Language Compatibility::
20340 * Differences in the Definition of Package System::
20341 * Language-Related Features::
20342 * The Package STANDARD::
20343 * The Package SYSTEM::
20344 * Tasking and Task-Related Features::
20345 * Pragmas and Pragma-Related Features::
20346 * Library of Predefined Units::
20347 * Bindings::
20348 * Main Program Definition::
20349 * Implementation-Defined Attributes::
20350 * Compiler and Run-Time Interfacing::
20351 * Program Compilation and Library Management::
20352 * Input-Output::
20353 * Implementation Limits::
20354 * Tools and Utilities::
20355 @end menu
20356
20357 @node Ada Language Compatibility
20358 @section Ada Language Compatibility
20359
20360 @noindent
20361 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20362 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20363 with Ada 83, and therefore Ada 83 programs will compile
20364 and run under GNAT with
20365 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20366 provides details on specific incompatibilities.
20367
20368 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20369 as well as the pragma @code{ADA_83}, to force the compiler to
20370 operate in Ada 83 mode. This mode does not guarantee complete
20371 conformance to Ada 83, but in practice is sufficient to
20372 eliminate most sources of incompatibilities.
20373 In particular, it eliminates the recognition of the
20374 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20375 in Ada 83 programs is legal, and handles the cases of packages
20376 with optional bodies, and generics that instantiate unconstrained
20377 types without the use of @code{(<>)}.
20378
20379 @node Differences in the Definition of Package System
20380 @section Differences in the Definition of Package @code{System}
20381
20382 @noindent
20383 An Ada compiler is allowed to add
20384 implementation-dependent declarations to package @code{System}.
20385 In normal mode,
20386 GNAT does not take advantage of this permission, and the version of
20387 @code{System} provided by GNAT exactly matches that defined in the Ada
20388 Reference Manual.
20389
20390 However, HP Ada adds an extensive set of declarations to package
20391 @code{System},
20392 as fully documented in the HP Ada manuals. To minimize changes required
20393 for programs that make use of these extensions, GNAT provides the pragma
20394 @code{Extend_System} for extending the definition of package System. By using:
20395 @cindex pragma @code{Extend_System}
20396 @cindex @code{Extend_System} pragma
20397
20398 @smallexample @c ada
20399 @group
20400 @cartouche
20401 pragma Extend_System (Aux_DEC);
20402 @end cartouche
20403 @end group
20404 @end smallexample
20405
20406 @noindent
20407 the set of definitions in @code{System} is extended to include those in
20408 package @code{System.Aux_DEC}.
20409 @cindex @code{System.Aux_DEC} package
20410 @cindex @code{Aux_DEC} package (child of @code{System})
20411 These definitions are incorporated directly into package @code{System},
20412 as though they had been declared there. For a
20413 list of the declarations added, see the spec of this package,
20414 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20415 @cindex @file{s-auxdec.ads} file
20416 The pragma @code{Extend_System} is a configuration pragma, which means that
20417 it can be placed in the file @file{gnat.adc}, so that it will automatically
20418 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20419 for further details.
20420
20421 An alternative approach that avoids the use of the non-standard
20422 @code{Extend_System} pragma is to add a context clause to the unit that
20423 references these facilities:
20424
20425 @smallexample @c ada
20426 @cartouche
20427 with System.Aux_DEC;
20428 use  System.Aux_DEC;
20429 @end cartouche
20430 @end smallexample
20431
20432 @noindent
20433 The effect is not quite semantically identical to incorporating
20434 the declarations directly into package @code{System},
20435 but most programs will not notice a difference
20436 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20437 to reference the entities directly in package @code{System}.
20438 For units containing such references,
20439 the prefixes must either be removed, or the pragma @code{Extend_System}
20440 must be used.
20441
20442 @node Language-Related Features
20443 @section Language-Related Features
20444
20445 @noindent
20446 The following sections highlight differences in types,
20447 representations of types, operations, alignment, and
20448 related topics.
20449
20450 @menu
20451 * Integer Types and Representations::
20452 * Floating-Point Types and Representations::
20453 * Pragmas Float_Representation and Long_Float::
20454 * Fixed-Point Types and Representations::
20455 * Record and Array Component Alignment::
20456 * Address Clauses::
20457 * Other Representation Clauses::
20458 @end menu
20459
20460 @node Integer Types and Representations
20461 @subsection Integer Types and Representations
20462
20463 @noindent
20464 The set of predefined integer types is identical in HP Ada and GNAT.
20465 Furthermore the representation of these integer types is also identical,
20466 including the capability of size clauses forcing biased representation.
20467
20468 In addition,
20469 HP Ada for OpenVMS Alpha systems has defined the
20470 following additional integer types in package @code{System}:
20471
20472 @itemize @bullet
20473
20474 @item
20475 @code{INTEGER_8}
20476
20477 @item
20478 @code{INTEGER_16}
20479
20480 @item
20481 @code{INTEGER_32}
20482
20483 @item
20484 @code{INTEGER_64}
20485
20486 @item
20487 @code{LARGEST_INTEGER}
20488 @end itemize
20489
20490 @noindent
20491 In GNAT, the first four of these types may be obtained from the
20492 standard Ada package @code{Interfaces}.
20493 Alternatively, by use of the pragma @code{Extend_System}, identical
20494 declarations can be referenced directly in package @code{System}.
20495 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20496
20497 @node Floating-Point Types and Representations
20498 @subsection Floating-Point Types and Representations
20499 @cindex Floating-Point types
20500
20501 @noindent
20502 The set of predefined floating-point types is identical in HP Ada and GNAT.
20503 Furthermore the representation of these floating-point
20504 types is also identical. One important difference is that the default
20505 representation for HP Ada is @code{VAX_Float}, but the default representation
20506 for GNAT is IEEE.
20507
20508 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20509 pragma @code{Float_Representation} as described in the HP Ada
20510 documentation.
20511 For example, the declarations:
20512
20513 @smallexample @c ada
20514 @cartouche
20515 type F_Float is digits 6;
20516 pragma Float_Representation (VAX_Float, F_Float);
20517 @end cartouche
20518 @end smallexample
20519
20520 @noindent
20521 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20522 format.
20523 This set of declarations actually appears in @code{System.Aux_DEC},
20524 which contains
20525 the full set of additional floating-point declarations provided in
20526 the HP Ada version of package @code{System}.
20527 This and similar declarations may be accessed in a user program
20528 by using pragma @code{Extend_System}. The use of this
20529 pragma, and the related pragma @code{Long_Float} is described in further
20530 detail in the following section.
20531
20532 @node Pragmas Float_Representation and Long_Float
20533 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20534
20535 @noindent
20536 HP Ada provides the pragma @code{Float_Representation}, which
20537 acts as a program library switch to allow control over
20538 the internal representation chosen for the predefined
20539 floating-point types declared in the package @code{Standard}.
20540 The format of this pragma is as follows:
20541
20542 @smallexample @c ada
20543 @cartouche
20544 pragma Float_Representation(VAX_Float | IEEE_Float);
20545 @end cartouche
20546 @end smallexample
20547
20548 @noindent
20549 This pragma controls the representation of floating-point
20550 types as follows:
20551
20552 @itemize @bullet
20553 @item
20554 @code{VAX_Float} specifies that floating-point
20555 types are represented by default with the VAX system hardware types
20556 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20557 Note that the @code{H-floating}
20558 type was available only on VAX systems, and is not available
20559 in either HP Ada or GNAT.
20560
20561 @item
20562 @code{IEEE_Float} specifies that floating-point
20563 types are represented by default with the IEEE single and
20564 double floating-point types.
20565 @end itemize
20566
20567 @noindent
20568 GNAT provides an identical implementation of the pragma
20569 @code{Float_Representation}, except that it functions as a
20570 configuration pragma. Note that the
20571 notion of configuration pragma corresponds closely to the
20572 HP Ada notion of a program library switch.
20573
20574 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20575 which is different
20576 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20577 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20578 advisable to change the format of numbers passed to standard library
20579 routines, and if necessary explicit type conversions may be needed.
20580
20581 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20582 efficient, and (given that it conforms to an international standard)
20583 potentially more portable.
20584 The situation in which @code{VAX_Float} may be useful is in interfacing
20585 to existing code and data that expect the use of @code{VAX_Float}.
20586 In such a situation use the predefined @code{VAX_Float}
20587 types in package @code{System}, as extended by
20588 @code{Extend_System}. For example, use @code{System.F_Float}
20589 to specify the 32-bit @code{F-Float} format.
20590
20591 @noindent
20592 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20593 to allow control over the internal representation chosen
20594 for the predefined type @code{Long_Float} and for floating-point
20595 type declarations with digits specified in the range 7 .. 15.
20596 The format of this pragma is as follows:
20597
20598 @smallexample @c ada
20599 @cartouche
20600 pragma Long_Float (D_FLOAT | G_FLOAT);
20601 @end cartouche
20602 @end smallexample
20603
20604 @node Fixed-Point Types and Representations
20605 @subsection Fixed-Point Types and Representations
20606
20607 @noindent
20608 On HP Ada for OpenVMS Alpha systems, rounding is
20609 away from zero for both positive and negative numbers.
20610 Therefore, @code{+0.5} rounds to @code{1},
20611 and @code{-0.5} rounds to @code{-1}.
20612
20613 On GNAT the results of operations
20614 on fixed-point types are in accordance with the Ada
20615 rules. In particular, results of operations on decimal
20616 fixed-point types are truncated.
20617
20618 @node Record and Array Component Alignment
20619 @subsection Record and Array Component Alignment
20620
20621 @noindent
20622 On HP Ada for OpenVMS Alpha, all non-composite components
20623 are aligned on natural boundaries. For example, 1-byte
20624 components are aligned on byte boundaries, 2-byte
20625 components on 2-byte boundaries, 4-byte components on 4-byte
20626 byte boundaries, and so on. The OpenVMS Alpha hardware
20627 runs more efficiently with naturally aligned data.
20628
20629 On GNAT, alignment rules are compatible
20630 with HP Ada for OpenVMS Alpha.
20631
20632 @node Address Clauses
20633 @subsection Address Clauses
20634
20635 @noindent
20636 In HP Ada and GNAT, address clauses are supported for
20637 objects and imported subprograms.
20638 The predefined type @code{System.Address} is a private type
20639 in both compilers on Alpha OpenVMS, with the same representation
20640 (it is simply a machine pointer). Addition, subtraction, and comparison
20641 operations are available in the standard Ada package
20642 @code{System.Storage_Elements}, or in package @code{System}
20643 if it is extended to include @code{System.Aux_DEC} using a
20644 pragma @code{Extend_System} as previously described.
20645
20646 Note that code that @code{with}'s both this extended package @code{System}
20647 and the package @code{System.Storage_Elements} should not @code{use}
20648 both packages, or ambiguities will result. In general it is better
20649 not to mix these two sets of facilities. The Ada package was
20650 designed specifically to provide the kind of features that HP Ada
20651 adds directly to package @code{System}.
20652
20653 The type @code{System.Address} is a 64-bit integer type in GNAT for
20654 I64 OpenVMS.  For more information,
20655 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20656
20657 GNAT is compatible with HP Ada in its handling of address
20658 clauses, except for some limitations in
20659 the form of address clauses for composite objects with
20660 initialization. Such address clauses are easily replaced
20661 by the use of an explicitly-defined constant as described
20662 in the Ada Reference Manual (13.1(22)). For example, the sequence
20663 of declarations:
20664
20665 @smallexample @c ada
20666 @cartouche
20667 X, Y : Integer := Init_Func;
20668 Q : String (X .. Y) := "abc";
20669 @dots{}
20670 for Q'Address use Compute_Address;
20671 @end cartouche
20672 @end smallexample
20673
20674 @noindent
20675 will be rejected by GNAT, since the address cannot be computed at the time
20676 that @code{Q} is declared. To achieve the intended effect, write instead:
20677
20678 @smallexample @c ada
20679 @group
20680 @cartouche
20681 X, Y : Integer := Init_Func;
20682 Q_Address : constant Address := Compute_Address;
20683 Q : String (X .. Y) := "abc";
20684 @dots{}
20685 for Q'Address use Q_Address;
20686 @end cartouche
20687 @end group
20688 @end smallexample
20689
20690 @noindent
20691 which will be accepted by GNAT (and other Ada compilers), and is also
20692 compatible with Ada 83. A fuller description of the restrictions
20693 on address specifications is found in @ref{Top, GNAT Reference Manual,
20694 About This Guide, gnat_rm, GNAT Reference Manual}.
20695
20696 @node Other Representation Clauses
20697 @subsection Other Representation Clauses
20698
20699 @noindent
20700 GNAT implements in a compatible manner all the representation
20701 clauses supported by HP Ada. In addition, GNAT
20702 implements the representation clause forms that were introduced in Ada 95,
20703 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20704
20705 @node The Package STANDARD
20706 @section The Package @code{STANDARD}
20707
20708 @noindent
20709 The package @code{STANDARD}, as implemented by HP Ada, is fully
20710 described in the @cite{Ada Reference Manual} and in the
20711 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20712 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20713
20714 In addition, HP Ada supports the Latin-1 character set in
20715 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20716 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20717 the type @code{WIDE_CHARACTER}.
20718
20719 The floating-point types supported by GNAT are those
20720 supported by HP Ada, but the defaults are different, and are controlled by
20721 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20722
20723 @node The Package SYSTEM
20724 @section The Package @code{SYSTEM}
20725
20726 @noindent
20727 HP Ada provides a specific version of the package
20728 @code{SYSTEM} for each platform on which the language is implemented.
20729 For the complete spec of the package @code{SYSTEM}, see
20730 Appendix F of the @cite{HP Ada Language Reference Manual}.
20731
20732 On HP Ada, the package @code{SYSTEM} includes the following conversion
20733 functions:
20734 @itemize @bullet
20735 @item @code{TO_ADDRESS(INTEGER)}
20736
20737 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20738
20739 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20740
20741 @item @code{TO_INTEGER(ADDRESS)}
20742
20743 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20744
20745 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20746 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20747 @end itemize
20748
20749 @noindent
20750 By default, GNAT supplies a version of @code{SYSTEM} that matches
20751 the definition given in the @cite{Ada Reference Manual}.
20752 This
20753 is a subset of the HP system definitions, which is as
20754 close as possible to the original definitions. The only difference
20755 is that the definition of @code{SYSTEM_NAME} is different:
20756
20757 @smallexample @c ada
20758 @cartouche
20759 type Name is (SYSTEM_NAME_GNAT);
20760 System_Name : constant Name := SYSTEM_NAME_GNAT;
20761 @end cartouche
20762 @end smallexample
20763
20764 @noindent
20765 Also, GNAT adds the Ada declarations for
20766 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20767
20768 However, the use of the following pragma causes GNAT
20769 to extend the definition of package @code{SYSTEM} so that it
20770 encompasses the full set of HP-specific extensions,
20771 including the functions listed above:
20772
20773 @smallexample @c ada
20774 @cartouche
20775 pragma Extend_System (Aux_DEC);
20776 @end cartouche
20777 @end smallexample
20778
20779 @noindent
20780 The pragma @code{Extend_System} is a configuration pragma that
20781 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20782 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20783
20784 HP Ada does not allow the recompilation of the package
20785 @code{SYSTEM}. Instead HP Ada provides several pragmas
20786 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20787 to modify values in the package @code{SYSTEM}.
20788 On OpenVMS Alpha systems, the pragma
20789 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20790 its single argument.
20791
20792 GNAT does permit the recompilation of package @code{SYSTEM} using
20793 the special switch @option{-gnatg}, and this switch can be used if
20794 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20795 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20796 or @code{MEMORY_SIZE} by any other means.
20797
20798 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20799 enumeration literal @code{SYSTEM_NAME_GNAT}.
20800
20801 The definitions provided by the use of
20802
20803 @smallexample @c ada
20804 pragma Extend_System (AUX_Dec);
20805 @end smallexample
20806
20807 @noindent
20808 are virtually identical to those provided by the HP Ada 83 package
20809 @code{SYSTEM}. One important difference is that the name of the
20810 @code{TO_ADDRESS}
20811 function for type @code{UNSIGNED_LONGWORD} is changed to
20812 @code{TO_ADDRESS_LONG}.
20813 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20814 discussion of why this change was necessary.
20815
20816 @noindent
20817 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20818 is in fact
20819 an extension to Ada 83 not strictly compatible with the reference manual.
20820 GNAT, in order to be exactly compatible with the standard,
20821 does not provide this capability. In HP Ada 83, the
20822 point of this definition is to deal with a call like:
20823
20824 @smallexample @c ada
20825 TO_ADDRESS (16#12777#);
20826 @end smallexample
20827
20828 @noindent
20829 Normally, according to Ada 83 semantics, one would expect this to be
20830 ambiguous, since it matches both the @code{INTEGER} and
20831 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20832 However, in HP Ada 83, there is no ambiguity, since the
20833 definition using @i{universal_integer} takes precedence.
20834
20835 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20836 it is
20837 not possible to be 100% compatible. Since there are many programs using
20838 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20839 GNAT was
20840 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20841 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20842
20843 @smallexample @c ada
20844 function To_Address (X : Integer) return Address;
20845 pragma Pure_Function (To_Address);
20846
20847 function To_Address_Long (X : Unsigned_Longword) return Address;
20848 pragma Pure_Function (To_Address_Long);
20849 @end smallexample
20850
20851 @noindent
20852 This means that programs using @code{TO_ADDRESS} for
20853 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20854
20855 @node Tasking and Task-Related Features
20856 @section Tasking and Task-Related Features
20857
20858 @noindent
20859 This section compares the treatment of tasking in GNAT
20860 and in HP Ada for OpenVMS Alpha.
20861 The GNAT description applies to both Alpha and I64 OpenVMS.
20862 For detailed information on tasking in
20863 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20864 relevant run-time reference manual.
20865
20866 @menu
20867 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20868 * Assigning Task IDs::
20869 * Task IDs and Delays::
20870 * Task-Related Pragmas::
20871 * Scheduling and Task Priority::
20872 * The Task Stack::
20873 * External Interrupts::
20874 @end menu
20875
20876 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20877 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20878
20879 @noindent
20880 On OpenVMS Alpha systems, each Ada task (except a passive
20881 task) is implemented as a single stream of execution
20882 that is created and managed by the kernel. On these
20883 systems, HP Ada tasking support is based on DECthreads,
20884 an implementation of the POSIX standard for threads.
20885
20886 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20887 code that calls DECthreads routines can be used together.
20888 The interaction between Ada tasks and DECthreads routines
20889 can have some benefits. For example when on OpenVMS Alpha,
20890 HP Ada can call C code that is already threaded.
20891
20892 GNAT uses the facilities of DECthreads,
20893 and Ada tasks are mapped to threads.
20894
20895 @node Assigning Task IDs
20896 @subsection Assigning Task IDs
20897
20898 @noindent
20899 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20900 the environment task that executes the main program. On
20901 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20902 that have been created but are not yet activated.
20903
20904 On OpenVMS Alpha systems, task IDs are assigned at
20905 activation. On GNAT systems, task IDs are also assigned at
20906 task creation but do not have the same form or values as
20907 task ID values in HP Ada. There is no null task, and the
20908 environment task does not have a specific task ID value.
20909
20910 @node Task IDs and Delays
20911 @subsection Task IDs and Delays
20912
20913 @noindent
20914 On OpenVMS Alpha systems, tasking delays are implemented
20915 using Timer System Services. The Task ID is used for the
20916 identification of the timer request (the @code{REQIDT} parameter).
20917 If Timers are used in the application take care not to use
20918 @code{0} for the identification, because cancelling such a timer
20919 will cancel all timers and may lead to unpredictable results.
20920
20921 @node Task-Related Pragmas
20922 @subsection Task-Related Pragmas
20923
20924 @noindent
20925 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20926 specification of the size of the guard area for a task
20927 stack. (The guard area forms an area of memory that has no
20928 read or write access and thus helps in the detection of
20929 stack overflow.) On OpenVMS Alpha systems, if the pragma
20930 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20931 area is created. In the absence of a pragma @code{TASK_STORAGE},
20932 a default guard area is created.
20933
20934 GNAT supplies the following task-related pragmas:
20935
20936 @itemize @bullet
20937 @item  @code{TASK_INFO}
20938
20939 This pragma appears within a task definition and
20940 applies to the task in which it appears. The argument
20941 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20942
20943 @item  @code{TASK_STORAGE}
20944
20945 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20946 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20947 @code{SUPPRESS}, and @code{VOLATILE}.
20948 @end itemize
20949 @node Scheduling and Task Priority
20950 @subsection Scheduling and Task Priority
20951
20952 @noindent
20953 HP Ada implements the Ada language requirement that
20954 when two tasks are eligible for execution and they have
20955 different priorities, the lower priority task does not
20956 execute while the higher priority task is waiting. The HP
20957 Ada Run-Time Library keeps a task running until either the
20958 task is suspended or a higher priority task becomes ready.
20959
20960 On OpenVMS Alpha systems, the default strategy is round-
20961 robin with preemption. Tasks of equal priority take turns
20962 at the processor. A task is run for a certain period of
20963 time and then placed at the tail of the ready queue for
20964 its priority level.
20965
20966 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20967 which can be used to enable or disable round-robin
20968 scheduling of tasks with the same priority.
20969 See the relevant HP Ada run-time reference manual for
20970 information on using the pragmas to control HP Ada task
20971 scheduling.
20972
20973 GNAT follows the scheduling rules of Annex D (Real-Time
20974 Annex) of the @cite{Ada Reference Manual}. In general, this
20975 scheduling strategy is fully compatible with HP Ada
20976 although it provides some additional constraints (as
20977 fully documented in Annex D).
20978 GNAT implements time slicing control in a manner compatible with
20979 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20980 are identical to the HP Ada 83 pragma of the same name.
20981 Note that it is not possible to mix GNAT tasking and
20982 HP Ada 83 tasking in the same program, since the two run-time
20983 libraries are not compatible.
20984
20985 @node The Task Stack
20986 @subsection The Task Stack
20987
20988 @noindent
20989 In HP Ada, a task stack is allocated each time a
20990 non-passive task is activated. As soon as the task is
20991 terminated, the storage for the task stack is deallocated.
20992 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20993 a default stack size is used. Also, regardless of the size
20994 specified, some additional space is allocated for task
20995 management purposes. On OpenVMS Alpha systems, at least
20996 one page is allocated.
20997
20998 GNAT handles task stacks in a similar manner. In accordance with
20999 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21000 an alternative method for controlling the task stack size.
21001 The specification of the attribute @code{T'STORAGE_SIZE} is also
21002 supported in a manner compatible with HP Ada.
21003
21004 @node External Interrupts
21005 @subsection External Interrupts
21006
21007 @noindent
21008 On HP Ada, external interrupts can be associated with task entries.
21009 GNAT is compatible with HP Ada in its handling of external interrupts.
21010
21011 @node Pragmas and Pragma-Related Features
21012 @section Pragmas and Pragma-Related Features
21013
21014 @noindent
21015 Both HP Ada and GNAT supply all language-defined pragmas
21016 as specified by the Ada 83 standard. GNAT also supplies all
21017 language-defined pragmas introduced by Ada 95 and Ada 2005.
21018 In addition, GNAT implements the implementation-defined pragmas
21019 from HP Ada 83.
21020
21021 @itemize @bullet
21022 @item  @code{AST_ENTRY}
21023
21024 @item  @code{COMMON_OBJECT}
21025
21026 @item  @code{COMPONENT_ALIGNMENT}
21027
21028 @item  @code{EXPORT_EXCEPTION}
21029
21030 @item  @code{EXPORT_FUNCTION}
21031
21032 @item  @code{EXPORT_OBJECT}
21033
21034 @item  @code{EXPORT_PROCEDURE}
21035
21036 @item  @code{EXPORT_VALUED_PROCEDURE}
21037
21038 @item  @code{FLOAT_REPRESENTATION}
21039
21040 @item  @code{IDENT}
21041
21042 @item  @code{IMPORT_EXCEPTION}
21043
21044 @item  @code{IMPORT_FUNCTION}
21045
21046 @item  @code{IMPORT_OBJECT}
21047
21048 @item  @code{IMPORT_PROCEDURE}
21049
21050 @item  @code{IMPORT_VALUED_PROCEDURE}
21051
21052 @item  @code{INLINE_GENERIC}
21053
21054 @item  @code{INTERFACE_NAME}
21055
21056 @item  @code{LONG_FLOAT}
21057
21058 @item  @code{MAIN_STORAGE}
21059
21060 @item  @code{PASSIVE}
21061
21062 @item  @code{PSECT_OBJECT}
21063
21064 @item  @code{SHARE_GENERIC}
21065
21066 @item  @code{SUPPRESS_ALL}
21067
21068 @item  @code{TASK_STORAGE}
21069
21070 @item  @code{TIME_SLICE}
21071
21072 @item  @code{TITLE}
21073 @end itemize
21074
21075 @noindent
21076 These pragmas are all fully implemented, with the exception of @code{TITLE},
21077 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21078 recognized, but which have no
21079 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21080 use of Ada protected objects. In GNAT, all generics are inlined.
21081
21082 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21083 a separate subprogram specification which must appear before the
21084 subprogram body.
21085
21086 GNAT also supplies a number of implementation-defined pragmas including the
21087 following:
21088
21089 @itemize @bullet
21090 @item  @code{ABORT_DEFER}
21091
21092 @item  @code{ADA_83}
21093
21094 @item  @code{ADA_95}
21095
21096 @item  @code{ADA_05}
21097
21098 @item  @code{Ada_2005}
21099
21100 @item  @code{Ada_12}
21101
21102 @item  @code{Ada_2012}
21103
21104 @item  @code{ANNOTATE}
21105
21106 @item  @code{ASSERT}
21107
21108 @item  @code{C_PASS_BY_COPY}
21109
21110 @item  @code{CPP_CLASS}
21111
21112 @item  @code{CPP_CONSTRUCTOR}
21113
21114 @item  @code{CPP_DESTRUCTOR}
21115
21116 @item  @code{DEBUG}
21117
21118 @item  @code{EXTEND_SYSTEM}
21119
21120 @item  @code{LINKER_ALIAS}
21121
21122 @item  @code{LINKER_SECTION}
21123
21124 @item  @code{MACHINE_ATTRIBUTE}
21125
21126 @item  @code{NO_RETURN}
21127
21128 @item  @code{PURE_FUNCTION}
21129
21130 @item  @code{SOURCE_FILE_NAME}
21131
21132 @item  @code{SOURCE_REFERENCE}
21133
21134 @item  @code{TASK_INFO}
21135
21136 @item  @code{UNCHECKED_UNION}
21137
21138 @item  @code{UNIMPLEMENTED_UNIT}
21139
21140 @item  @code{UNIVERSAL_DATA}
21141
21142 @item  @code{UNSUPPRESS}
21143
21144 @item  @code{WARNINGS}
21145
21146 @item  @code{WEAK_EXTERNAL}
21147 @end itemize
21148
21149 @noindent
21150 For full details on these and other GNAT implementation-defined pragmas,
21151 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21152 Manual}.
21153
21154 @menu
21155 * Restrictions on the Pragma INLINE::
21156 * Restrictions on the Pragma INTERFACE::
21157 * Restrictions on the Pragma SYSTEM_NAME::
21158 @end menu
21159
21160 @node Restrictions on the Pragma INLINE
21161 @subsection Restrictions on Pragma @code{INLINE}
21162
21163 @noindent
21164 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21165 @itemize @bullet
21166 @item  Parameters cannot have a task type.
21167
21168 @item  Function results cannot be task types, unconstrained
21169 array types, or unconstrained types with discriminants.
21170
21171 @item  Bodies cannot declare the following:
21172 @itemize @bullet
21173 @item  Subprogram body or stub (imported subprogram is allowed)
21174
21175 @item  Tasks
21176
21177 @item  Generic declarations
21178
21179 @item  Instantiations
21180
21181 @item  Exceptions
21182
21183 @item  Access types (types derived from access types allowed)
21184
21185 @item  Array or record types
21186
21187 @item  Dependent tasks
21188
21189 @item  Direct recursive calls of subprogram or containing
21190 subprogram, directly or via a renaming
21191
21192 @end itemize
21193 @end itemize
21194
21195 @noindent
21196 In GNAT, the only restriction on pragma @code{INLINE} is that the
21197 body must occur before the call if both are in the same
21198 unit, and the size must be appropriately small. There are
21199 no other specific restrictions which cause subprograms to
21200 be incapable of being inlined.
21201
21202 @node  Restrictions on the Pragma INTERFACE
21203 @subsection  Restrictions on Pragma @code{INTERFACE}
21204
21205 @noindent
21206 The following restrictions on pragma @code{INTERFACE}
21207 are enforced by both HP Ada and GNAT:
21208 @itemize @bullet
21209 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21210 Default is the default on OpenVMS Alpha systems.
21211
21212 @item  Parameter passing: Language specifies default
21213 mechanisms but can be overridden with an @code{EXPORT} pragma.
21214
21215 @itemize @bullet
21216 @item  Ada: Use internal Ada rules.
21217
21218 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21219 record or task type. Result cannot be a string, an
21220 array, or a record.
21221
21222 @item  Fortran: Parameters cannot have a task type. Result cannot
21223 be a string, an array, or a record.
21224 @end itemize
21225 @end itemize
21226
21227 @noindent
21228 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21229 record parameters for all languages.
21230
21231 @node  Restrictions on the Pragma SYSTEM_NAME
21232 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21233
21234 @noindent
21235 For HP Ada for OpenVMS Alpha, the enumeration literal
21236 for the type @code{NAME} is @code{OPENVMS_AXP}.
21237 In GNAT, the enumeration
21238 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21239
21240 @node  Library of Predefined Units
21241 @section  Library of Predefined Units
21242
21243 @noindent
21244 A library of predefined units is provided as part of the
21245 HP Ada and GNAT implementations. HP Ada does not provide
21246 the package @code{MACHINE_CODE} but instead recommends importing
21247 assembler code.
21248
21249 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21250 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21251 version.
21252 The HP Ada Predefined Library units are modified to remove post-Ada 83
21253 incompatibilities and to make them interoperable with GNAT
21254 (@pxref{Changes to DECLIB}, for details).
21255 The units are located in the @file{DECLIB} directory.
21256
21257 The GNAT RTL is contained in
21258 the @file{ADALIB} directory, and
21259 the default search path is set up to find @code{DECLIB} units in preference
21260 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21261 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21262
21263 @menu
21264 * Changes to DECLIB::
21265 @end menu
21266
21267 @node Changes to DECLIB
21268 @subsection Changes to @code{DECLIB}
21269
21270 @noindent
21271 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21272 compatibility are minor and include the following:
21273
21274 @itemize @bullet
21275 @item  Adjusting the location of pragmas and record representation
21276 clauses to obey Ada 95 (and thus Ada 2005) rules
21277
21278 @item  Adding the proper notation to generic formal parameters
21279 that take unconstrained types in instantiation
21280
21281 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21282 that have package bodies not otherwise allowed
21283
21284 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21285 ``@code{PROTECTD}''.
21286 Currently these are found only in the @code{STARLET} package spec.
21287
21288 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21289 where the address size is constrained to 32 bits.
21290 @end itemize
21291
21292 @noindent
21293 None of the above changes is visible to users.
21294
21295 @node Bindings
21296 @section Bindings
21297
21298 @noindent
21299 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21300 @itemize @bullet
21301
21302 @item  Command Language Interpreter (CLI interface)
21303
21304 @item  DECtalk Run-Time Library (DTK interface)
21305
21306 @item  Librarian utility routines (LBR interface)
21307
21308 @item  General Purpose Run-Time Library (LIB interface)
21309
21310 @item  Math Run-Time Library (MTH interface)
21311
21312 @item  National Character Set Run-Time Library (NCS interface)
21313
21314 @item  Compiled Code Support Run-Time Library (OTS interface)
21315
21316 @item  Parallel Processing Run-Time Library (PPL interface)
21317
21318 @item  Screen Management Run-Time Library (SMG interface)
21319
21320 @item  Sort Run-Time Library (SOR interface)
21321
21322 @item  String Run-Time Library (STR interface)
21323
21324 @item STARLET System Library
21325 @findex Starlet
21326
21327 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21328
21329 @item  X Windows Toolkit (XT interface)
21330
21331 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21332 @end itemize
21333
21334 @noindent
21335 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21336 directory, on both the Alpha and I64 OpenVMS platforms.
21337
21338 The X components of DECLIB compatibility package are located in a separate
21339 library, called XDECGNAT, which is not linked with by default; this library
21340 must be explicitly linked with any application that makes use of any X facilities,
21341 with a command similar to
21342
21343 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21344
21345 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21346 in the
21347 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21348 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21349 @code{Xt}, and @code{X_Lib}
21350 causing the default X/Motif sharable image libraries to be linked in. This
21351 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21352 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21353
21354 It may be necessary to edit these options files to update or correct the
21355 library names if, for example, the newer X/Motif bindings from
21356 @file{ADA$EXAMPLES}
21357 had been (previous to installing GNAT) copied and renamed to supersede the
21358 default @file{ADA$PREDEFINED} versions.
21359
21360 @menu
21361 * Shared Libraries and Options Files::
21362 * Interfaces to C::
21363 @end menu
21364
21365 @node Shared Libraries and Options Files
21366 @subsection Shared Libraries and Options Files
21367
21368 @noindent
21369 When using the HP Ada
21370 predefined X and Motif bindings, the linking with their sharable images is
21371 done automatically by @command{GNAT LINK}.
21372 When using other X and Motif bindings, you need
21373 to add the corresponding sharable images to the command line for
21374 @code{GNAT LINK}. When linking with shared libraries, or with
21375 @file{.OPT} files, you must
21376 also add them to the command line for @command{GNAT LINK}.
21377
21378 A shared library to be used with GNAT is built in the same way as other
21379 libraries under VMS. The VMS Link command can be used in standard fashion.
21380
21381 @node Interfaces to C
21382 @subsection Interfaces to C
21383
21384 @noindent
21385 HP Ada
21386 provides the following Ada types and operations:
21387
21388 @itemize @bullet
21389 @item C types package (@code{C_TYPES})
21390
21391 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21392
21393 @item Other_types (@code{SHORT_INT})
21394 @end itemize
21395
21396 @noindent
21397 Interfacing to C with GNAT, you can use the above approach
21398 described for HP Ada or the facilities of Annex B of
21399 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21400 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21401 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21402
21403 The @option{-gnatF} qualifier forces default and explicit
21404 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21405 to be uppercased for compatibility with the default behavior
21406 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21407
21408 @node Main Program Definition
21409 @section Main Program Definition
21410
21411 @noindent
21412 The following section discusses differences in the
21413 definition of main programs on HP Ada and GNAT.
21414 On HP Ada, main programs are defined to meet the
21415 following conditions:
21416 @itemize @bullet
21417 @item  Procedure with no formal parameters (returns @code{0} upon
21418 normal completion)
21419
21420 @item  Procedure with no formal parameters (returns @code{42} when
21421 an unhandled exception is raised)
21422
21423 @item  Function with no formal parameters whose returned value
21424 is of a discrete type
21425
21426 @item  Procedure with one @code{out} formal of a discrete type for
21427 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21428
21429 @end itemize
21430
21431 @noindent
21432 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21433 a main function or main procedure returns a discrete
21434 value whose size is less than 64 bits (32 on VAX systems),
21435 the value is zero- or sign-extended as appropriate.
21436 On GNAT, main programs are defined as follows:
21437 @itemize @bullet
21438 @item  Must be a non-generic, parameterless subprogram that
21439 is either a procedure or function returning an Ada
21440 @code{STANDARD.INTEGER} (the predefined type)
21441
21442 @item  Cannot be a generic subprogram or an instantiation of a
21443 generic subprogram
21444 @end itemize
21445
21446 @node Implementation-Defined Attributes
21447 @section Implementation-Defined Attributes
21448
21449 @noindent
21450 GNAT provides all HP Ada implementation-defined
21451 attributes.
21452
21453 @node Compiler and Run-Time Interfacing
21454 @section Compiler and Run-Time Interfacing
21455
21456 @noindent
21457 HP Ada provides the following qualifiers to pass options to the linker
21458 (ACS LINK):
21459 @itemize @bullet
21460 @item  @option{/WAIT} and @option{/SUBMIT}
21461
21462 @item  @option{/COMMAND}
21463
21464 @item  @option{/@r{[}NO@r{]}MAP}
21465
21466 @item  @option{/OUTPUT=@var{file-spec}}
21467
21468 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21469 @end itemize
21470
21471 @noindent
21472 To pass options to the linker, GNAT provides the following
21473 switches:
21474
21475 @itemize @bullet
21476 @item   @option{/EXECUTABLE=@var{exec-name}}
21477
21478 @item   @option{/VERBOSE}
21479
21480 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21481 @end itemize
21482
21483 @noindent
21484 For more information on these switches, see
21485 @ref{Switches for gnatlink}.
21486 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21487 to control optimization. HP Ada also supplies the
21488 following pragmas:
21489 @itemize @bullet
21490 @item  @code{OPTIMIZE}
21491
21492 @item  @code{INLINE}
21493
21494 @item  @code{INLINE_GENERIC}
21495
21496 @item  @code{SUPPRESS_ALL}
21497
21498 @item  @code{PASSIVE}
21499 @end itemize
21500
21501 @noindent
21502 In GNAT, optimization is controlled strictly by command
21503 line parameters, as described in the corresponding section of this guide.
21504 The HP pragmas for control of optimization are
21505 recognized but ignored.
21506
21507 Note that in GNAT, the default is optimization off, whereas in HP Ada
21508 the default is that optimization is turned on.
21509
21510 @node Program Compilation and Library Management
21511 @section Program Compilation and Library Management
21512
21513 @noindent
21514 HP Ada and GNAT provide a comparable set of commands to
21515 build programs. HP Ada also provides a program library,
21516 which is a concept that does not exist on GNAT. Instead,
21517 GNAT provides directories of sources that are compiled as
21518 needed.
21519
21520 The following table summarizes
21521 the HP Ada commands and provides
21522 equivalent GNAT commands. In this table, some GNAT
21523 equivalents reflect the fact that GNAT does not use the
21524 concept of a program library. Instead, it uses a model
21525 in which collections of source and object files are used
21526 in a manner consistent with other languages like C and
21527 Fortran. Therefore, standard system file commands are used
21528 to manipulate these elements. Those GNAT commands are marked with
21529 an asterisk.
21530 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21531
21532 @need 1500
21533 @multitable @columnfractions .35 .65
21534
21535 @item @emph{HP Ada Command}
21536 @tab @emph{GNAT Equivalent / Description}
21537
21538 @item @command{ADA}
21539 @tab @command{GNAT COMPILE}@*
21540 Invokes the compiler to compile one or more Ada source files.
21541
21542 @item @command{ACS ATTACH}@*
21543 @tab [No equivalent]@*
21544 Switches control of terminal from current process running the program
21545 library manager.
21546
21547 @item @command{ACS CHECK}
21548 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21549 Forms the execution closure of one
21550 or more compiled units and checks completeness and currency.
21551
21552 @item @command{ACS COMPILE}
21553 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21554 Forms the execution closure of one or
21555 more specified units, checks completeness and currency,
21556 identifies units that have revised source files, compiles same,
21557 and recompiles units that are or will become obsolete.
21558 Also completes incomplete generic instantiations.
21559
21560 @item @command{ACS COPY FOREIGN}
21561 @tab Copy (*)@*
21562 Copies a foreign object file into the program library as a
21563 library unit body.
21564
21565 @item @command{ACS COPY UNIT}
21566 @tab Copy (*)@*
21567 Copies a compiled unit from one program library to another.
21568
21569 @item @command{ACS CREATE LIBRARY}
21570 @tab Create /directory (*)@*
21571 Creates a program library.
21572
21573 @item @command{ACS CREATE SUBLIBRARY}
21574 @tab Create /directory (*)@*
21575 Creates a program sublibrary.
21576
21577 @item @command{ACS DELETE LIBRARY}
21578 @tab @*
21579 Deletes a program library and its contents.
21580
21581 @item @command{ACS DELETE SUBLIBRARY}
21582 @tab @*
21583 Deletes a program sublibrary and its contents.
21584
21585 @item @command{ACS DELETE UNIT}
21586 @tab Delete file (*)@*
21587 On OpenVMS systems, deletes one or more compiled units from
21588 the current program library.
21589
21590 @item @command{ACS DIRECTORY}
21591 @tab Directory (*)@*
21592 On OpenVMS systems, lists units contained in the current
21593 program library.
21594
21595 @item @command{ACS ENTER FOREIGN}
21596 @tab Copy (*)@*
21597 Allows the import of a foreign body as an Ada library
21598 spec and enters a reference to a pointer.
21599
21600 @item @command{ACS ENTER UNIT}
21601 @tab Copy (*)@*
21602 Enters a reference (pointer) from the current program library to
21603 a unit compiled into another program library.
21604
21605 @item @command{ACS EXIT}
21606 @tab [No equivalent]@*
21607 Exits from the program library manager.
21608
21609 @item @command{ACS EXPORT}
21610 @tab Copy (*)@*
21611 Creates an object file that contains system-specific object code
21612 for one or more units. With GNAT, object files can simply be copied
21613 into the desired directory.
21614
21615 @item @command{ACS EXTRACT SOURCE}
21616 @tab Copy (*)@*
21617 Allows access to the copied source file for each Ada compilation unit
21618
21619 @item @command{ACS HELP}
21620 @tab @command{HELP GNAT}@*
21621 Provides online help.
21622
21623 @item @command{ACS LINK}
21624 @tab @command{GNAT LINK}@*
21625 Links an object file containing Ada units into an executable file.
21626
21627 @item @command{ACS LOAD}
21628 @tab Copy (*)@*
21629 Loads (partially compiles) Ada units into the program library.
21630 Allows loading a program from a collection of files into a library
21631 without knowing the relationship among units.
21632
21633 @item @command{ACS MERGE}
21634 @tab Copy (*)@*
21635 Merges into the current program library, one or more units from
21636 another library where they were modified.
21637
21638 @item @command{ACS RECOMPILE}
21639 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21640 Recompiles from   external or copied source files any obsolete
21641 unit in the closure. Also, completes any incomplete generic
21642 instantiations.
21643
21644 @item @command{ACS REENTER}
21645 @tab @command{GNAT MAKE}@*
21646 Reenters current references to units compiled after last entered
21647 with the @command{ACS ENTER UNIT} command.
21648
21649 @item @command{ACS SET LIBRARY}
21650 @tab Set default (*)@*
21651 Defines a program library to be the compilation context as well
21652 as the target library for compiler output and commands in general.
21653
21654 @item @command{ACS SET PRAGMA}
21655 @tab Edit @file{gnat.adc} (*)@*
21656 Redefines specified  values of the library characteristics
21657 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21658 and @code{Float_Representation}.
21659
21660 @item @command{ACS SET SOURCE}
21661 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21662 Defines the source file search list for the @command{ACS COMPILE} command.
21663
21664 @item @command{ACS SHOW LIBRARY}
21665 @tab Directory (*)@*
21666 Lists information about one or more program libraries.
21667
21668 @item @command{ACS SHOW PROGRAM}
21669 @tab [No equivalent]@*
21670 Lists information about the execution closure of one or
21671 more units in the program library.
21672
21673 @item @command{ACS SHOW SOURCE}
21674 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21675 Shows the source file search used when compiling units.
21676
21677 @item @command{ACS SHOW VERSION}
21678 @tab Compile with @option{VERBOSE} option
21679 Displays the version number of the compiler and program library
21680 manager used.
21681
21682 @item @command{ACS SPAWN}
21683 @tab [No equivalent]@*
21684 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21685 command).
21686
21687 @item @command{ACS VERIFY}
21688 @tab [No equivalent]@*
21689 Performs a series of consistency checks on a program library to
21690 determine whether the library structure and library files are in
21691 valid form.
21692 @end multitable
21693
21694 @noindent
21695
21696 @node Input-Output
21697 @section Input-Output
21698
21699 @noindent
21700 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21701 Management Services (RMS) to perform operations on
21702 external files.
21703
21704 @noindent
21705 HP Ada and GNAT predefine an identical set of input-
21706 output packages. To make the use of the
21707 generic @code{TEXT_IO} operations more convenient, HP Ada
21708 provides predefined library packages that instantiate the
21709 integer and floating-point operations for the predefined
21710 integer and floating-point types as shown in the following table.
21711
21712 @multitable @columnfractions .45 .55
21713 @item @emph{Package Name} @tab Instantiation
21714
21715 @item @code{INTEGER_TEXT_IO}
21716 @tab @code{INTEGER_IO(INTEGER)}
21717
21718 @item @code{SHORT_INTEGER_TEXT_IO}
21719 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21720
21721 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21722 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21723
21724 @item @code{FLOAT_TEXT_IO}
21725 @tab @code{FLOAT_IO(FLOAT)}
21726
21727 @item @code{LONG_FLOAT_TEXT_IO}
21728 @tab @code{FLOAT_IO(LONG_FLOAT)}
21729 @end multitable
21730
21731 @noindent
21732 The HP Ada predefined packages and their operations
21733 are implemented using OpenVMS Alpha files and input-output
21734 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21735 Familiarity with the following is recommended:
21736 @itemize @bullet
21737 @item  RMS file organizations and access methods
21738
21739 @item  OpenVMS file specifications and directories
21740
21741 @item  OpenVMS File Definition Language (FDL)
21742 @end itemize
21743
21744 @noindent
21745 GNAT provides I/O facilities that are completely
21746 compatible with HP Ada. The distribution includes the
21747 standard HP Ada versions of all I/O packages, operating
21748 in a manner compatible with HP Ada. In particular, the
21749 following packages are by default the HP Ada (Ada 83)
21750 versions of these packages rather than the renamings
21751 suggested in Annex J of the Ada Reference Manual:
21752 @itemize @bullet
21753 @item  @code{TEXT_IO}
21754
21755 @item  @code{SEQUENTIAL_IO}
21756
21757 @item  @code{DIRECT_IO}
21758 @end itemize
21759
21760 @noindent
21761 The use of the standard child package syntax (for
21762 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21763 packages.
21764 GNAT provides HP-compatible predefined instantiations
21765 of the @code{TEXT_IO} packages, and also
21766 provides the standard predefined instantiations required
21767 by the @cite{Ada Reference Manual}.
21768
21769 For further information on how GNAT interfaces to the file
21770 system or how I/O is implemented in programs written in
21771 mixed languages, see @ref{Implementation of the Standard I/O,,,
21772 gnat_rm, GNAT Reference Manual}.
21773 This chapter covers the following:
21774 @itemize @bullet
21775 @item  Standard I/O packages
21776
21777 @item  @code{FORM} strings
21778
21779 @item  @code{ADA.DIRECT_IO}
21780
21781 @item  @code{ADA.SEQUENTIAL_IO}
21782
21783 @item  @code{ADA.TEXT_IO}
21784
21785 @item  Stream pointer positioning
21786
21787 @item  Reading and writing non-regular files
21788
21789 @item  @code{GET_IMMEDIATE}
21790
21791 @item  Treating @code{TEXT_IO} files as streams
21792
21793 @item  Shared files
21794
21795 @item  Open modes
21796 @end itemize
21797
21798 @node Implementation Limits
21799 @section Implementation Limits
21800
21801 @noindent
21802 The following table lists implementation limits for HP Ada
21803 and GNAT systems.
21804 @multitable @columnfractions .60 .20 .20
21805 @sp 1
21806 @item  @emph{Compilation Parameter}
21807 @tab   @emph{HP Ada}
21808 @tab   @emph{GNAT}
21809 @sp 1
21810
21811 @item  In a subprogram or entry  declaration, maximum number of
21812 formal parameters that are of an unconstrained record type
21813 @tab   32
21814 @tab   No set limit
21815 @sp 1
21816
21817 @item  Maximum identifier length (number of characters)
21818 @tab   255
21819 @tab   32766
21820 @sp 1
21821
21822 @item  Maximum number of characters in a source line
21823 @tab   255
21824 @tab   32766
21825 @sp 1
21826
21827 @item  Maximum collection size   (number of bytes)
21828 @tab   2**31-1
21829 @tab   2**31-1
21830 @sp 1
21831
21832 @item  Maximum number of discriminants for a record type
21833 @tab   245
21834 @tab   No set limit
21835 @sp 1
21836
21837 @item  Maximum number of formal parameters in an entry or
21838 subprogram declaration
21839 @tab   246
21840 @tab    No set limit
21841 @sp 1
21842
21843 @item  Maximum number of dimensions in an array type
21844 @tab   255
21845 @tab   No set limit
21846 @sp 1
21847
21848 @item  Maximum number of library  units and subunits in a compilation.
21849 @tab   4095
21850 @tab   No set limit
21851 @sp 1
21852
21853 @item  Maximum number of library units and subunits in an execution.
21854 @tab   16383
21855 @tab   No set limit
21856 @sp 1
21857
21858 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21859 or @code{PSECT_OBJECT}
21860 @tab   32757
21861 @tab   No set limit
21862 @sp 1
21863
21864 @item  Maximum number of enumeration literals in an enumeration type
21865 definition
21866 @tab   65535
21867 @tab   No set limit
21868 @sp 1
21869
21870 @item  Maximum number of lines in a source file
21871 @tab   65534
21872 @tab   No set limit
21873 @sp 1
21874
21875 @item  Maximum number of bits in any object
21876 @tab   2**31-1
21877 @tab   2**31-1
21878 @sp 1
21879
21880 @item  Maximum size of the static portion of a stack frame (approximate)
21881 @tab   2**31-1
21882 @tab   2**31-1
21883 @end multitable
21884
21885 @node Tools and Utilities
21886 @section Tools and Utilities
21887
21888 @noindent
21889 The following table lists some of the OpenVMS development tools
21890 available for HP Ada, and the corresponding tools for
21891 use with @value{EDITION} on Alpha and I64 platforms.
21892 Aside from the debugger, all the OpenVMS tools identified are part
21893 of the DECset package.
21894
21895 @iftex
21896 @c Specify table in TeX since Texinfo does a poor job
21897 @tex
21898 \smallskip
21899 \smallskip
21900 \settabs\+Language-Sensitive Editor\quad
21901    &Product with HP Ada\quad
21902    &\cr
21903 \+\it Tool
21904    &\it Product with HP Ada
21905    & \it Product with @value{EDITION}\cr
21906 \smallskip
21907 \+Code Management System
21908    &HP CMS
21909    & HP CMS\cr
21910 \smallskip
21911 \+Language-Sensitive Editor
21912    &HP LSE
21913    & emacs or HP LSE (Alpha)\cr
21914 \+
21915    &
21916    & HP LSE (I64)\cr
21917 \smallskip
21918 \+Debugger
21919    &OpenVMS Debug
21920    & gdb (Alpha),\cr
21921 \+
21922    &
21923    & OpenVMS Debug (I64)\cr
21924 \smallskip
21925 \+Source Code Analyzer /
21926    &HP SCA
21927    & GNAT XREF\cr
21928 \+Cross Referencer
21929    &
21930    &\cr
21931 \smallskip
21932 \+Test Manager
21933    &HP Digital Test
21934    & HP DTM\cr
21935 \+
21936    &Manager (DTM)
21937    &\cr
21938 \smallskip
21939 \+Performance and
21940    & HP PCA
21941    & HP PCA\cr
21942 \+Coverage Analyzer
21943    &
21944    &\cr
21945 \smallskip
21946 \+Module Management
21947    & HP MMS
21948    & Not applicable\cr
21949 \+ System
21950    &
21951    &\cr
21952 \smallskip
21953 \smallskip
21954 @end tex
21955 @end iftex
21956
21957 @ifnottex
21958 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21959 @c the TeX version above for the printed version
21960 @flushleft
21961 @c @multitable @columnfractions .3 .4 .4
21962 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
21963 @item @i{Tool}
21964 @tab @i{Tool with HP Ada}
21965 @tab @i{Tool with @value{EDITION}}
21966 @item Code Management@*System
21967 @tab HP CMS
21968 @tab HP CMS
21969 @item Language-Sensitive@*Editor
21970 @tab HP LSE
21971 @tab emacs or HP LSE (Alpha)
21972 @item
21973 @tab
21974 @tab HP LSE (I64)
21975 @item Debugger
21976 @tab OpenVMS Debug
21977 @tab gdb (Alpha),
21978 @item
21979 @tab
21980 @tab OpenVMS Debug (I64)
21981 @item Source Code Analyzer /@*Cross Referencer
21982 @tab HP SCA
21983 @tab GNAT XREF
21984 @item Test Manager
21985 @tab HP Digital Test@*Manager (DTM)
21986 @tab HP DTM
21987 @item Performance and@*Coverage Analyzer
21988 @tab HP PCA
21989 @tab HP PCA
21990 @item Module Management@*System
21991 @tab HP MMS
21992 @tab Not applicable
21993 @end multitable
21994 @end flushleft
21995 @end ifnottex
21996
21997 @end ifset
21998
21999 @c **************************************
22000 @node Platform-Specific Information for the Run-Time Libraries
22001 @appendix Platform-Specific Information for the Run-Time Libraries
22002 @cindex Tasking and threads libraries
22003 @cindex Threads libraries and tasking
22004 @cindex Run-time libraries (platform-specific information)
22005
22006 @noindent
22007 The GNAT run-time implementation may vary with respect to both the
22008 underlying threads library and the exception handling scheme.
22009 For threads support, one or more of the following are supplied:
22010 @itemize @bullet
22011 @item @b{native threads library}, a binding to the thread package from
22012 the underlying operating system
22013
22014 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22015 POSIX thread package
22016 @end itemize
22017
22018 @noindent
22019 For exception handling, either or both of two models are supplied:
22020 @itemize @bullet
22021 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22022 Most programs should experience a substantial speed improvement by
22023 being compiled with a ZCX run-time.
22024 This is especially true for
22025 tasking applications or applications with many exception handlers.}
22026 @cindex Zero-Cost Exceptions
22027 @cindex ZCX (Zero-Cost Exceptions)
22028 which uses binder-generated tables that
22029 are interrogated at run time to locate a handler
22030
22031 @item @b{setjmp / longjmp} (``SJLJ''),
22032 @cindex setjmp/longjmp Exception Model
22033 @cindex SJLJ (setjmp/longjmp Exception Model)
22034 which uses dynamically-set data to establish
22035 the set of handlers
22036 @end itemize
22037
22038 @noindent
22039 This appendix summarizes which combinations of threads and exception support
22040 are supplied on various GNAT platforms.
22041 It then shows how to select a particular library either
22042 permanently or temporarily,
22043 explains the properties of (and tradeoffs among) the various threads
22044 libraries, and provides some additional
22045 information about several specific platforms.
22046
22047 @menu
22048 * Summary of Run-Time Configurations::
22049 * Specifying a Run-Time Library::
22050 * Choosing the Scheduling Policy::
22051 * Solaris-Specific Considerations::
22052 * Linux-Specific Considerations::
22053 * AIX-Specific Considerations::
22054 * Irix-Specific Considerations::
22055 * RTX-Specific Considerations::
22056 * HP-UX-Specific Considerations::
22057 @end menu
22058
22059 @node Summary of Run-Time Configurations
22060 @section Summary of Run-Time Configurations
22061
22062 @multitable @columnfractions .30 .70
22063 @item @b{alpha-openvms}
22064 @item @code{@ @ }@i{rts-native (default)}
22065 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22066 @item @code{@ @ @ @ }Exceptions @tab ZCX
22067 @*
22068 @item @b{alpha-tru64}
22069 @item @code{@ @ }@i{rts-native (default)}
22070 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22071 @item @code{@ @ @ @ }Exceptions @tab ZCX
22072 @*
22073 @item @code{@ @ }@i{rts-sjlj}
22074 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22075 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22076 @*
22077 @item @b{ia64-hp_linux}
22078 @item @code{@ @ }@i{rts-native (default)}
22079 @item @code{@ @ @ @ }Tasking    @tab pthread library
22080 @item @code{@ @ @ @ }Exceptions @tab ZCX
22081 @*
22082 @item @b{ia64-hpux}
22083 @item @code{@ @ }@i{rts-native (default)}
22084 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22085 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22086 @*
22087 @item @b{ia64-openvms}
22088 @item @code{@ @ }@i{rts-native (default)}
22089 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22090 @item @code{@ @ @ @ }Exceptions @tab ZCX
22091 @*
22092 @item @b{ia64-sgi_linux}
22093 @item @code{@ @ }@i{rts-native (default)}
22094 @item @code{@ @ @ @ }Tasking    @tab pthread library
22095 @item @code{@ @ @ @ }Exceptions @tab ZCX
22096 @*
22097 @item @b{mips-irix}
22098 @item @code{@ @ }@i{rts-native (default)}
22099 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22100 @item @code{@ @ @ @ }Exceptions @tab ZCX
22101 @*
22102 @item @b{pa-hpux}
22103 @item @code{@ @ }@i{rts-native (default)}
22104 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22105 @item @code{@ @ @ @ }Exceptions @tab ZCX
22106 @*
22107 @item @code{@ @ }@i{rts-sjlj}
22108 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22109 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22110 @*
22111 @item @b{ppc-aix}
22112 @item @code{@ @ }@i{rts-native (default)}
22113 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22114 @item @code{@ @ @ @ }Exceptions @tab ZCX
22115 @*
22116 @item @code{@ @ }@i{rts-sjlj}
22117 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22118 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22119 @*
22120 @item @b{ppc-darwin}
22121 @item @code{@ @ }@i{rts-native (default)}
22122 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22123 @item @code{@ @ @ @ }Exceptions @tab ZCX
22124 @*
22125 @item @b{sparc-solaris}  @tab
22126 @item @code{@ @ }@i{rts-native (default)}
22127 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22128 @item @code{@ @ @ @ }Exceptions @tab ZCX
22129 @*
22130 @item @code{@ @ }@i{rts-pthread}
22131 @item @code{@ @ @ @ }Tasking    @tab pthread library
22132 @item @code{@ @ @ @ }Exceptions @tab ZCX
22133 @*
22134 @item @code{@ @ }@i{rts-sjlj}
22135 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22136 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22137 @*
22138 @item @b{sparc64-solaris}  @tab
22139 @item @code{@ @ }@i{rts-native (default)}
22140 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22141 @item @code{@ @ @ @ }Exceptions @tab ZCX
22142 @*
22143 @item @b{x86-linux}
22144 @item @code{@ @ }@i{rts-native (default)}
22145 @item @code{@ @ @ @ }Tasking    @tab pthread library
22146 @item @code{@ @ @ @ }Exceptions @tab ZCX
22147 @*
22148 @item @code{@ @ }@i{rts-sjlj}
22149 @item @code{@ @ @ @ }Tasking    @tab pthread library
22150 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22151 @*
22152 @item @b{x86-lynx}
22153 @item @code{@ @ }@i{rts-native (default)}
22154 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22155 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22156 @*
22157 @item @b{x86-solaris}
22158 @item @code{@ @ }@i{rts-native (default)}
22159 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22160 @item @code{@ @ @ @ }Exceptions @tab ZCX
22161 @*
22162 @item @code{@ @ }@i{rts-sjlj}
22163 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22164 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22165 @*
22166 @item @b{x86-windows}
22167 @item @code{@ @ }@i{rts-native (default)}
22168 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22169 @item @code{@ @ @ @ }Exceptions @tab ZCX
22170 @*
22171 @item @code{@ @ }@i{rts-sjlj}
22172 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22173 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22174 @*
22175 @item @b{x86-windows-rtx}
22176 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22177 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22178 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22179 @*
22180 @item @code{@ @ }@i{rts-rtx-w32}
22181 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22182 @item @code{@ @ @ @ }Exceptions @tab ZCX
22183 @*
22184 @item @b{x86_64-linux}
22185 @item @code{@ @ }@i{rts-native (default)}
22186 @item @code{@ @ @ @ }Tasking    @tab pthread library
22187 @item @code{@ @ @ @ }Exceptions @tab ZCX
22188 @*
22189 @item @code{@ @ }@i{rts-sjlj}
22190 @item @code{@ @ @ @ }Tasking    @tab pthread library
22191 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22192 @*
22193 @end multitable
22194
22195 @node Specifying a Run-Time Library
22196 @section Specifying a Run-Time Library
22197
22198 @noindent
22199 The @file{adainclude} subdirectory containing the sources of the GNAT
22200 run-time library, and the @file{adalib} subdirectory containing the
22201 @file{ALI} files and the static and/or shared GNAT library, are located
22202 in the gcc target-dependent area:
22203
22204 @smallexample
22205 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22206 @end smallexample
22207
22208 @noindent
22209 As indicated above, on some platforms several run-time libraries are supplied.
22210 These libraries are installed in the target dependent area and
22211 contain a complete source and binary subdirectory. The detailed description
22212 below explains the differences between the different libraries in terms of
22213 their thread support.
22214
22215 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22216 This default run time is selected by the means of soft links.
22217 For example on x86-linux:
22218
22219 @smallexample
22220 @group
22221  $(target-dir)
22222      |
22223      +--- adainclude----------+
22224      |                        |
22225      +--- adalib-----------+  |
22226      |                     |  |
22227      +--- rts-native       |  |
22228      |    |                |  |
22229      |    +--- adainclude <---+
22230      |    |                |
22231      |    +--- adalib <----+
22232      |
22233      +--- rts-sjlj
22234           |
22235           +--- adainclude
22236           |
22237           +--- adalib
22238 @end group
22239 @end smallexample
22240
22241 @noindent
22242 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22243 these soft links can be modified with the following commands:
22244
22245 @smallexample
22246 $ cd $target
22247 $ rm -f adainclude adalib
22248 $ ln -s rts-sjlj/adainclude adainclude
22249 $ ln -s rts-sjlj/adalib adalib
22250 @end smallexample
22251
22252 @noindent
22253 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22254 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22255 @file{$target/ada_object_path}.
22256
22257 Selecting another run-time library temporarily can be
22258 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22259 @cindex @option{--RTS} option
22260
22261 @node Choosing the Scheduling Policy
22262 @section Choosing the Scheduling Policy
22263
22264 @noindent
22265 When using a POSIX threads implementation, you have a choice of several
22266 scheduling policies: @code{SCHED_FIFO},
22267 @cindex @code{SCHED_FIFO} scheduling policy
22268 @code{SCHED_RR}
22269 @cindex @code{SCHED_RR} scheduling policy
22270 and @code{SCHED_OTHER}.
22271 @cindex @code{SCHED_OTHER} scheduling policy
22272 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22273 or @code{SCHED_RR} requires special (e.g., root) privileges.
22274
22275 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22276 @code{SCHED_FIFO},
22277 @cindex @code{SCHED_FIFO} scheduling policy
22278 you can use one of the following:
22279
22280 @itemize @bullet
22281 @item
22282 @code{pragma Time_Slice (0.0)}
22283 @cindex pragma Time_Slice
22284 @item
22285 the corresponding binder option @option{-T0}
22286 @cindex @option{-T0} option
22287 @item
22288 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22289 @cindex pragma Task_Dispatching_Policy
22290 @end itemize
22291
22292 @noindent
22293 To specify @code{SCHED_RR},
22294 @cindex @code{SCHED_RR} scheduling policy
22295 you should use @code{pragma Time_Slice} with a
22296 value greater than @code{0.0}, or else use the corresponding @option{-T}
22297 binder option.
22298
22299 @node Solaris-Specific Considerations
22300 @section Solaris-Specific Considerations
22301 @cindex Solaris Sparc threads libraries
22302
22303 @noindent
22304 This section addresses some topics related to the various threads libraries
22305 on Sparc Solaris.
22306
22307 @menu
22308 * Solaris Threads Issues::
22309 @end menu
22310
22311 @node Solaris Threads Issues
22312 @subsection Solaris Threads Issues
22313
22314 @noindent
22315 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22316 library based on POSIX threads --- @emph{rts-pthread}.
22317 @cindex rts-pthread threads library
22318 This run-time library has the advantage of being mostly shared across all
22319 POSIX-compliant thread implementations, and it also provides under
22320 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22321 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22322 and @code{PTHREAD_PRIO_PROTECT}
22323 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22324 semantics that can be selected using the predefined pragma
22325 @code{Locking_Policy}
22326 @cindex pragma Locking_Policy (under rts-pthread)
22327 with respectively
22328 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22329 @cindex @code{Inheritance_Locking} (under rts-pthread)
22330 @cindex @code{Ceiling_Locking} (under rts-pthread)
22331
22332 As explained above, the native run-time library is based on the Solaris thread
22333 library (@code{libthread}) and is the default library.
22334
22335 When the Solaris threads library is used (this is the default), programs
22336 compiled with GNAT can automatically take advantage of
22337 and can thus execute on multiple processors.
22338 The user can alternatively specify a processor on which the program should run
22339 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22340 is made by
22341 setting the environment variable @env{GNAT_PROCESSOR}
22342 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22343 to one of the following:
22344
22345 @table @code
22346 @item -2
22347 Use the default configuration (run the program on all
22348 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22349 unset
22350
22351 @item -1
22352 Let the run-time implementation choose one processor and run the program on
22353 that processor
22354
22355 @item 0 .. Last_Proc
22356 Run the program on the specified processor.
22357 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22358 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22359 @end table
22360
22361 @node Linux-Specific Considerations
22362 @section Linux-Specific Considerations
22363 @cindex Linux threads libraries
22364
22365 @noindent
22366 On GNU/Linux without NPTL support (usually system with GNU C Library
22367 older than 2.3), the signal model is not POSIX compliant, which means
22368 that to send a signal to the process, you need to send the signal to all
22369 threads, e.g.@: by using @code{killpg()}.
22370
22371 @node AIX-Specific Considerations
22372 @section AIX-Specific Considerations
22373 @cindex AIX resolver library
22374
22375 @noindent
22376 On AIX, the resolver library initializes some internal structure on
22377 the first call to @code{get*by*} functions, which are used to implement
22378 @code{GNAT.Sockets.Get_Host_By_Name} and
22379 @code{GNAT.Sockets.Get_Host_By_Address}.
22380 If such initialization occurs within an Ada task, and the stack size for
22381 the task is the default size, a stack overflow may occur.
22382
22383 To avoid this overflow, the user should either ensure that the first call
22384 to @code{GNAT.Sockets.Get_Host_By_Name} or
22385 @code{GNAT.Sockets.Get_Host_By_Addrss}
22386 occurs in the environment task, or use @code{pragma Storage_Size} to
22387 specify a sufficiently large size for the stack of the task that contains
22388 this call.
22389
22390 @node Irix-Specific Considerations
22391 @section Irix-Specific Considerations
22392 @cindex Irix libraries
22393
22394 @noindent
22395 The GCC support libraries coming with the Irix compiler have moved to
22396 their canonical place with respect to the general Irix ABI related
22397 conventions. Running applications built with the default shared GNAT
22398 run-time now requires the LD_LIBRARY_PATH environment variable to
22399 include this location. A possible way to achieve this is to issue the
22400 following command line on a bash prompt:
22401
22402 @smallexample
22403 @group
22404 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22405 @end group
22406 @end smallexample
22407
22408 @node RTX-Specific Considerations
22409 @section RTX-Specific Considerations
22410 @cindex RTX libraries
22411
22412 @noindent
22413 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22414 API. Applications can be built to work in two different modes:
22415
22416 @itemize @bullet
22417 @item
22418 Windows executables that run in Ring 3 to utilize memory protection
22419 (@emph{rts-rtx-w32}).
22420
22421 @item
22422 Real-time subsystem (RTSS) executables that run in Ring 0, where
22423 performance can be optimized with RTSS applications taking precedent
22424 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22425 the Microsoft linker to handle RTSS libraries.
22426
22427 @end itemize
22428
22429 @node HP-UX-Specific Considerations
22430 @section HP-UX-Specific Considerations
22431 @cindex HP-UX Scheduling
22432
22433 @noindent
22434 On HP-UX, appropriate privileges are required to change the scheduling
22435 parameters of a task. The calling process must have appropriate
22436 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22437 successfully change the scheduling parameters.
22438
22439 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22440 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22441 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22442
22443 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22444 one of the following:
22445
22446 @itemize @bullet
22447 @item
22448 @code{pragma Time_Slice (0.0)}
22449 @cindex pragma Time_Slice
22450 @item
22451 the corresponding binder option @option{-T0}
22452 @cindex @option{-T0} option
22453 @item
22454 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22455 @cindex pragma Task_Dispatching_Policy
22456 @end itemize
22457
22458 @noindent
22459 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22460 you should use @code{pragma Time_Slice} with a
22461 value greater than @code{0.0}, or use the corresponding @option{-T}
22462 binder option, or set the @code{pragma Task_Dispatching_Policy
22463 (Round_Robin_Within_Priorities)}.
22464
22465 @c *******************************
22466 @node Example of Binder Output File
22467 @appendix Example of Binder Output File
22468
22469 @noindent
22470 This Appendix displays the source code for @command{gnatbind}'s output
22471 file generated for a simple ``Hello World'' program.
22472 Comments have been added for clarification purposes.
22473
22474 @smallexample @c adanocomment
22475 @iftex
22476 @leftskip=0cm
22477 @end iftex
22478 --  The package is called Ada_Main unless this name is actually used
22479 --  as a unit name in the partition, in which case some other unique
22480 --  name is used.
22481
22482 with System;
22483 package ada_main is
22484
22485    Elab_Final_Code : Integer;
22486    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22487
22488    --  The main program saves the parameters (argument count,
22489    --  argument values, environment pointer) in global variables
22490    --  for later access by other units including
22491    --  Ada.Command_Line.
22492
22493    gnat_argc : Integer;
22494    gnat_argv : System.Address;
22495    gnat_envp : System.Address;
22496
22497    --  The actual variables are stored in a library routine. This
22498    --  is useful for some shared library situations, where there
22499    --  are problems if variables are not in the library.
22500
22501    pragma Import (C, gnat_argc);
22502    pragma Import (C, gnat_argv);
22503    pragma Import (C, gnat_envp);
22504
22505    --  The exit status is similarly an external location
22506
22507    gnat_exit_status : Integer;
22508    pragma Import (C, gnat_exit_status);
22509
22510    GNAT_Version : constant String :=
22511                     "GNAT Version: 6.0.0w (20061115)";
22512    pragma Export (C, GNAT_Version, "__gnat_version");
22513
22514    --  This is the generated adafinal routine that performs
22515    --  finalization at the end of execution. In the case where
22516    --  Ada is the main program, this main program makes a call
22517    --  to adafinal at program termination.
22518
22519    procedure adafinal;
22520    pragma Export (C, adafinal, "adafinal");
22521
22522    --  This is the generated adainit routine that performs
22523    --  initialization at the start of execution. In the case
22524    --  where Ada is the main program, this main program makes
22525    --  a call to adainit at program startup.
22526
22527    procedure adainit;
22528    pragma Export (C, adainit, "adainit");
22529
22530    --  This routine is called at the start of execution. It is
22531    --  a dummy routine that is used by the debugger to breakpoint
22532    --  at the start of execution.
22533
22534    procedure Break_Start;
22535    pragma Import (C, Break_Start, "__gnat_break_start");
22536
22537    --  This is the actual generated main program (it would be
22538    --  suppressed if the no main program switch were used). As
22539    --  required by standard system conventions, this program has
22540    --  the external name main.
22541
22542    function main
22543      (argc : Integer;
22544       argv : System.Address;
22545       envp : System.Address)
22546       return Integer;
22547    pragma Export (C, main, "main");
22548
22549    --  The following set of constants give the version
22550    --  identification values for every unit in the bound
22551    --  partition. This identification is computed from all
22552    --  dependent semantic units, and corresponds to the
22553    --  string that would be returned by use of the
22554    --  Body_Version or Version attributes.
22555
22556    type Version_32 is mod 2 ** 32;
22557    u00001 : constant Version_32 := 16#7880BEB3#;
22558    u00002 : constant Version_32 := 16#0D24CBD0#;
22559    u00003 : constant Version_32 := 16#3283DBEB#;
22560    u00004 : constant Version_32 := 16#2359F9ED#;
22561    u00005 : constant Version_32 := 16#664FB847#;
22562    u00006 : constant Version_32 := 16#68E803DF#;
22563    u00007 : constant Version_32 := 16#5572E604#;
22564    u00008 : constant Version_32 := 16#46B173D8#;
22565    u00009 : constant Version_32 := 16#156A40CF#;
22566    u00010 : constant Version_32 := 16#033DABE0#;
22567    u00011 : constant Version_32 := 16#6AB38FEA#;
22568    u00012 : constant Version_32 := 16#22B6217D#;
22569    u00013 : constant Version_32 := 16#68A22947#;
22570    u00014 : constant Version_32 := 16#18CC4A56#;
22571    u00015 : constant Version_32 := 16#08258E1B#;
22572    u00016 : constant Version_32 := 16#367D5222#;
22573    u00017 : constant Version_32 := 16#20C9ECA4#;
22574    u00018 : constant Version_32 := 16#50D32CB6#;
22575    u00019 : constant Version_32 := 16#39A8BB77#;
22576    u00020 : constant Version_32 := 16#5CF8FA2B#;
22577    u00021 : constant Version_32 := 16#2F1EB794#;
22578    u00022 : constant Version_32 := 16#31AB6444#;
22579    u00023 : constant Version_32 := 16#1574B6E9#;
22580    u00024 : constant Version_32 := 16#5109C189#;
22581    u00025 : constant Version_32 := 16#56D770CD#;
22582    u00026 : constant Version_32 := 16#02F9DE3D#;
22583    u00027 : constant Version_32 := 16#08AB6B2C#;
22584    u00028 : constant Version_32 := 16#3FA37670#;
22585    u00029 : constant Version_32 := 16#476457A0#;
22586    u00030 : constant Version_32 := 16#731E1B6E#;
22587    u00031 : constant Version_32 := 16#23C2E789#;
22588    u00032 : constant Version_32 := 16#0F1BD6A1#;
22589    u00033 : constant Version_32 := 16#7C25DE96#;
22590    u00034 : constant Version_32 := 16#39ADFFA2#;
22591    u00035 : constant Version_32 := 16#571DE3E7#;
22592    u00036 : constant Version_32 := 16#5EB646AB#;
22593    u00037 : constant Version_32 := 16#4249379B#;
22594    u00038 : constant Version_32 := 16#0357E00A#;
22595    u00039 : constant Version_32 := 16#3784FB72#;
22596    u00040 : constant Version_32 := 16#2E723019#;
22597    u00041 : constant Version_32 := 16#623358EA#;
22598    u00042 : constant Version_32 := 16#107F9465#;
22599    u00043 : constant Version_32 := 16#6843F68A#;
22600    u00044 : constant Version_32 := 16#63305874#;
22601    u00045 : constant Version_32 := 16#31E56CE1#;
22602    u00046 : constant Version_32 := 16#02917970#;
22603    u00047 : constant Version_32 := 16#6CCBA70E#;
22604    u00048 : constant Version_32 := 16#41CD4204#;
22605    u00049 : constant Version_32 := 16#572E3F58#;
22606    u00050 : constant Version_32 := 16#20729FF5#;
22607    u00051 : constant Version_32 := 16#1D4F93E8#;
22608    u00052 : constant Version_32 := 16#30B2EC3D#;
22609    u00053 : constant Version_32 := 16#34054F96#;
22610    u00054 : constant Version_32 := 16#5A199860#;
22611    u00055 : constant Version_32 := 16#0E7F912B#;
22612    u00056 : constant Version_32 := 16#5760634A#;
22613    u00057 : constant Version_32 := 16#5D851835#;
22614
22615    --  The following Export pragmas export the version numbers
22616    --  with symbolic names ending in B (for body) or S
22617    --  (for spec) so that they can be located in a link. The
22618    --  information provided here is sufficient to track down
22619    --  the exact versions of units used in a given build.
22620
22621    pragma Export (C, u00001, "helloB");
22622    pragma Export (C, u00002, "system__standard_libraryB");
22623    pragma Export (C, u00003, "system__standard_libraryS");
22624    pragma Export (C, u00004, "adaS");
22625    pragma Export (C, u00005, "ada__text_ioB");
22626    pragma Export (C, u00006, "ada__text_ioS");
22627    pragma Export (C, u00007, "ada__exceptionsB");
22628    pragma Export (C, u00008, "ada__exceptionsS");
22629    pragma Export (C, u00009, "gnatS");
22630    pragma Export (C, u00010, "gnat__heap_sort_aB");
22631    pragma Export (C, u00011, "gnat__heap_sort_aS");
22632    pragma Export (C, u00012, "systemS");
22633    pragma Export (C, u00013, "system__exception_tableB");
22634    pragma Export (C, u00014, "system__exception_tableS");
22635    pragma Export (C, u00015, "gnat__htableB");
22636    pragma Export (C, u00016, "gnat__htableS");
22637    pragma Export (C, u00017, "system__exceptionsS");
22638    pragma Export (C, u00018, "system__machine_state_operationsB");
22639    pragma Export (C, u00019, "system__machine_state_operationsS");
22640    pragma Export (C, u00020, "system__machine_codeS");
22641    pragma Export (C, u00021, "system__storage_elementsB");
22642    pragma Export (C, u00022, "system__storage_elementsS");
22643    pragma Export (C, u00023, "system__secondary_stackB");
22644    pragma Export (C, u00024, "system__secondary_stackS");
22645    pragma Export (C, u00025, "system__parametersB");
22646    pragma Export (C, u00026, "system__parametersS");
22647    pragma Export (C, u00027, "system__soft_linksB");
22648    pragma Export (C, u00028, "system__soft_linksS");
22649    pragma Export (C, u00029, "system__stack_checkingB");
22650    pragma Export (C, u00030, "system__stack_checkingS");
22651    pragma Export (C, u00031, "system__tracebackB");
22652    pragma Export (C, u00032, "system__tracebackS");
22653    pragma Export (C, u00033, "ada__streamsS");
22654    pragma Export (C, u00034, "ada__tagsB");
22655    pragma Export (C, u00035, "ada__tagsS");
22656    pragma Export (C, u00036, "system__string_opsB");
22657    pragma Export (C, u00037, "system__string_opsS");
22658    pragma Export (C, u00038, "interfacesS");
22659    pragma Export (C, u00039, "interfaces__c_streamsB");
22660    pragma Export (C, u00040, "interfaces__c_streamsS");
22661    pragma Export (C, u00041, "system__file_ioB");
22662    pragma Export (C, u00042, "system__file_ioS");
22663    pragma Export (C, u00043, "ada__finalizationB");
22664    pragma Export (C, u00044, "ada__finalizationS");
22665    pragma Export (C, u00045, "system__finalization_rootB");
22666    pragma Export (C, u00046, "system__finalization_rootS");
22667    pragma Export (C, u00047, "system__finalization_implementationB");
22668    pragma Export (C, u00048, "system__finalization_implementationS");
22669    pragma Export (C, u00049, "system__string_ops_concat_3B");
22670    pragma Export (C, u00050, "system__string_ops_concat_3S");
22671    pragma Export (C, u00051, "system__stream_attributesB");
22672    pragma Export (C, u00052, "system__stream_attributesS");
22673    pragma Export (C, u00053, "ada__io_exceptionsS");
22674    pragma Export (C, u00054, "system__unsigned_typesS");
22675    pragma Export (C, u00055, "system__file_control_blockS");
22676    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22677    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22678
22679    -- BEGIN ELABORATION ORDER
22680    -- ada (spec)
22681    -- gnat (spec)
22682    -- gnat.heap_sort_a (spec)
22683    -- gnat.heap_sort_a (body)
22684    -- gnat.htable (spec)
22685    -- gnat.htable (body)
22686    -- interfaces (spec)
22687    -- system (spec)
22688    -- system.machine_code (spec)
22689    -- system.parameters (spec)
22690    -- system.parameters (body)
22691    -- interfaces.c_streams (spec)
22692    -- interfaces.c_streams (body)
22693    -- system.standard_library (spec)
22694    -- ada.exceptions (spec)
22695    -- system.exception_table (spec)
22696    -- system.exception_table (body)
22697    -- ada.io_exceptions (spec)
22698    -- system.exceptions (spec)
22699    -- system.storage_elements (spec)
22700    -- system.storage_elements (body)
22701    -- system.machine_state_operations (spec)
22702    -- system.machine_state_operations (body)
22703    -- system.secondary_stack (spec)
22704    -- system.stack_checking (spec)
22705    -- system.soft_links (spec)
22706    -- system.soft_links (body)
22707    -- system.stack_checking (body)
22708    -- system.secondary_stack (body)
22709    -- system.standard_library (body)
22710    -- system.string_ops (spec)
22711    -- system.string_ops (body)
22712    -- ada.tags (spec)
22713    -- ada.tags (body)
22714    -- ada.streams (spec)
22715    -- system.finalization_root (spec)
22716    -- system.finalization_root (body)
22717    -- system.string_ops_concat_3 (spec)
22718    -- system.string_ops_concat_3 (body)
22719    -- system.traceback (spec)
22720    -- system.traceback (body)
22721    -- ada.exceptions (body)
22722    -- system.unsigned_types (spec)
22723    -- system.stream_attributes (spec)
22724    -- system.stream_attributes (body)
22725    -- system.finalization_implementation (spec)
22726    -- system.finalization_implementation (body)
22727    -- ada.finalization (spec)
22728    -- ada.finalization (body)
22729    -- ada.finalization.list_controller (spec)
22730    -- ada.finalization.list_controller (body)
22731    -- system.file_control_block (spec)
22732    -- system.file_io (spec)
22733    -- system.file_io (body)
22734    -- ada.text_io (spec)
22735    -- ada.text_io (body)
22736    -- hello (body)
22737    -- END ELABORATION ORDER
22738
22739 end ada_main;
22740
22741 --  The following source file name pragmas allow the generated file
22742 --  names to be unique for different main programs. They are needed
22743 --  since the package name will always be Ada_Main.
22744
22745 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22746 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22747
22748 --  Generated package body for Ada_Main starts here
22749
22750 package body ada_main is
22751
22752    --  The actual finalization is performed by calling the
22753    --  library routine in System.Standard_Library.Adafinal
22754
22755    procedure Do_Finalize;
22756    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22757
22758    -------------
22759    -- adainit --
22760    -------------
22761
22762 @findex adainit
22763    procedure adainit is
22764
22765       --  These booleans are set to True once the associated unit has
22766       --  been elaborated. It is also used to avoid elaborating the
22767       --  same unit twice.
22768
22769       E040 : Boolean;
22770       pragma Import (Ada, E040, "interfaces__c_streams_E");
22771
22772       E008 : Boolean;
22773       pragma Import (Ada, E008, "ada__exceptions_E");
22774
22775       E014 : Boolean;
22776       pragma Import (Ada, E014, "system__exception_table_E");
22777
22778       E053 : Boolean;
22779       pragma Import (Ada, E053, "ada__io_exceptions_E");
22780
22781       E017 : Boolean;
22782       pragma Import (Ada, E017, "system__exceptions_E");
22783
22784       E024 : Boolean;
22785       pragma Import (Ada, E024, "system__secondary_stack_E");
22786
22787       E030 : Boolean;
22788       pragma Import (Ada, E030, "system__stack_checking_E");
22789
22790       E028 : Boolean;
22791       pragma Import (Ada, E028, "system__soft_links_E");
22792
22793       E035 : Boolean;
22794       pragma Import (Ada, E035, "ada__tags_E");
22795
22796       E033 : Boolean;
22797       pragma Import (Ada, E033, "ada__streams_E");
22798
22799       E046 : Boolean;
22800       pragma Import (Ada, E046, "system__finalization_root_E");
22801
22802       E048 : Boolean;
22803       pragma Import (Ada, E048, "system__finalization_implementation_E");
22804
22805       E044 : Boolean;
22806       pragma Import (Ada, E044, "ada__finalization_E");
22807
22808       E057 : Boolean;
22809       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22810
22811       E055 : Boolean;
22812       pragma Import (Ada, E055, "system__file_control_block_E");
22813
22814       E042 : Boolean;
22815       pragma Import (Ada, E042, "system__file_io_E");
22816
22817       E006 : Boolean;
22818       pragma Import (Ada, E006, "ada__text_io_E");
22819
22820       --  Set_Globals is a library routine that stores away the
22821       --  value of the indicated set of global values in global
22822       --  variables within the library.
22823
22824       procedure Set_Globals
22825         (Main_Priority            : Integer;
22826          Time_Slice_Value         : Integer;
22827          WC_Encoding              : Character;
22828          Locking_Policy           : Character;
22829          Queuing_Policy           : Character;
22830          Task_Dispatching_Policy  : Character;
22831          Adafinal                 : System.Address;
22832          Unreserve_All_Interrupts : Integer;
22833          Exception_Tracebacks     : Integer);
22834 @findex __gnat_set_globals
22835       pragma Import (C, Set_Globals, "__gnat_set_globals");
22836
22837       --  SDP_Table_Build is a library routine used to build the
22838       --  exception tables. See unit Ada.Exceptions in files
22839       --  a-except.ads/adb for full details of how zero cost
22840       --  exception handling works. This procedure, the call to
22841       --  it, and the two following tables are all omitted if the
22842       --  build is in longjmp/setjmp exception mode.
22843
22844 @findex SDP_Table_Build
22845 @findex Zero Cost Exceptions
22846       procedure SDP_Table_Build
22847         (SDP_Addresses   : System.Address;
22848          SDP_Count       : Natural;
22849          Elab_Addresses  : System.Address;
22850          Elab_Addr_Count : Natural);
22851       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22852
22853       --  Table of Unit_Exception_Table addresses. Used for zero
22854       --  cost exception handling to build the top level table.
22855
22856       ST : aliased constant array (1 .. 23) of System.Address := (
22857         Hello'UET_Address,
22858         Ada.Text_Io'UET_Address,
22859         Ada.Exceptions'UET_Address,
22860         Gnat.Heap_Sort_A'UET_Address,
22861         System.Exception_Table'UET_Address,
22862         System.Machine_State_Operations'UET_Address,
22863         System.Secondary_Stack'UET_Address,
22864         System.Parameters'UET_Address,
22865         System.Soft_Links'UET_Address,
22866         System.Stack_Checking'UET_Address,
22867         System.Traceback'UET_Address,
22868         Ada.Streams'UET_Address,
22869         Ada.Tags'UET_Address,
22870         System.String_Ops'UET_Address,
22871         Interfaces.C_Streams'UET_Address,
22872         System.File_Io'UET_Address,
22873         Ada.Finalization'UET_Address,
22874         System.Finalization_Root'UET_Address,
22875         System.Finalization_Implementation'UET_Address,
22876         System.String_Ops_Concat_3'UET_Address,
22877         System.Stream_Attributes'UET_Address,
22878         System.File_Control_Block'UET_Address,
22879         Ada.Finalization.List_Controller'UET_Address);
22880
22881       --  Table of addresses of elaboration routines. Used for
22882       --  zero cost exception handling to make sure these
22883       --  addresses are included in the top level procedure
22884       --  address table.
22885
22886       EA : aliased constant array (1 .. 23) of System.Address := (
22887         adainit'Code_Address,
22888         Do_Finalize'Code_Address,
22889         Ada.Exceptions'Elab_Spec'Address,
22890         System.Exceptions'Elab_Spec'Address,
22891         Interfaces.C_Streams'Elab_Spec'Address,
22892         System.Exception_Table'Elab_Body'Address,
22893         Ada.Io_Exceptions'Elab_Spec'Address,
22894         System.Stack_Checking'Elab_Spec'Address,
22895         System.Soft_Links'Elab_Body'Address,
22896         System.Secondary_Stack'Elab_Body'Address,
22897         Ada.Tags'Elab_Spec'Address,
22898         Ada.Tags'Elab_Body'Address,
22899         Ada.Streams'Elab_Spec'Address,
22900         System.Finalization_Root'Elab_Spec'Address,
22901         Ada.Exceptions'Elab_Body'Address,
22902         System.Finalization_Implementation'Elab_Spec'Address,
22903         System.Finalization_Implementation'Elab_Body'Address,
22904         Ada.Finalization'Elab_Spec'Address,
22905         Ada.Finalization.List_Controller'Elab_Spec'Address,
22906         System.File_Control_Block'Elab_Spec'Address,
22907         System.File_Io'Elab_Body'Address,
22908         Ada.Text_Io'Elab_Spec'Address,
22909         Ada.Text_Io'Elab_Body'Address);
22910
22911    --  Start of processing for adainit
22912
22913    begin
22914
22915       --  Call SDP_Table_Build to build the top level procedure
22916       --  table for zero cost exception handling (omitted in
22917       --  longjmp/setjmp mode).
22918
22919       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22920
22921       --  Call Set_Globals to record various information for
22922       --  this partition.  The values are derived by the binder
22923       --  from information stored in the ali files by the compiler.
22924
22925 @findex __gnat_set_globals
22926       Set_Globals
22927         (Main_Priority            => -1,
22928          --  Priority of main program, -1 if no pragma Priority used
22929
22930          Time_Slice_Value         => -1,
22931          --  Time slice from Time_Slice pragma, -1 if none used
22932
22933          WC_Encoding              => 'b',
22934          --  Wide_Character encoding used, default is brackets
22935
22936          Locking_Policy           => ' ',
22937          --  Locking_Policy used, default of space means not
22938          --  specified, otherwise it is the first character of
22939          --  the policy name.
22940
22941          Queuing_Policy           => ' ',
22942          --  Queuing_Policy used, default of space means not
22943          --  specified, otherwise it is the first character of
22944          --  the policy name.
22945
22946          Task_Dispatching_Policy  => ' ',
22947          --  Task_Dispatching_Policy used, default of space means
22948          --  not specified, otherwise first character of the
22949          --  policy name.
22950
22951          Adafinal                 => System.Null_Address,
22952          --  Address of Adafinal routine, not used anymore
22953
22954          Unreserve_All_Interrupts => 0,
22955          --  Set true if pragma Unreserve_All_Interrupts was used
22956
22957          Exception_Tracebacks     => 0);
22958          --  Indicates if exception tracebacks are enabled
22959
22960       Elab_Final_Code := 1;
22961
22962       --  Now we have the elaboration calls for all units in the partition.
22963       --  The Elab_Spec and Elab_Body attributes generate references to the
22964       --  implicit elaboration procedures generated by the compiler for
22965       --  each unit that requires elaboration.
22966
22967       if not E040 then
22968          Interfaces.C_Streams'Elab_Spec;
22969       end if;
22970       E040 := True;
22971       if not E008 then
22972          Ada.Exceptions'Elab_Spec;
22973       end if;
22974       if not E014 then
22975          System.Exception_Table'Elab_Body;
22976          E014 := True;
22977       end if;
22978       if not E053 then
22979          Ada.Io_Exceptions'Elab_Spec;
22980          E053 := True;
22981       end if;
22982       if not E017 then
22983          System.Exceptions'Elab_Spec;
22984          E017 := True;
22985       end if;
22986       if not E030 then
22987          System.Stack_Checking'Elab_Spec;
22988       end if;
22989       if not E028 then
22990          System.Soft_Links'Elab_Body;
22991          E028 := True;
22992       end if;
22993       E030 := True;
22994       if not E024 then
22995          System.Secondary_Stack'Elab_Body;
22996          E024 := True;
22997       end if;
22998       if not E035 then
22999          Ada.Tags'Elab_Spec;
23000       end if;
23001       if not E035 then
23002          Ada.Tags'Elab_Body;
23003          E035 := True;
23004       end if;
23005       if not E033 then
23006          Ada.Streams'Elab_Spec;
23007          E033 := True;
23008       end if;
23009       if not E046 then
23010          System.Finalization_Root'Elab_Spec;
23011       end if;
23012       E046 := True;
23013       if not E008 then
23014          Ada.Exceptions'Elab_Body;
23015          E008 := True;
23016       end if;
23017       if not E048 then
23018          System.Finalization_Implementation'Elab_Spec;
23019       end if;
23020       if not E048 then
23021          System.Finalization_Implementation'Elab_Body;
23022          E048 := True;
23023       end if;
23024       if not E044 then
23025          Ada.Finalization'Elab_Spec;
23026       end if;
23027       E044 := True;
23028       if not E057 then
23029          Ada.Finalization.List_Controller'Elab_Spec;
23030       end if;
23031       E057 := True;
23032       if not E055 then
23033          System.File_Control_Block'Elab_Spec;
23034          E055 := True;
23035       end if;
23036       if not E042 then
23037          System.File_Io'Elab_Body;
23038          E042 := True;
23039       end if;
23040       if not E006 then
23041          Ada.Text_Io'Elab_Spec;
23042       end if;
23043       if not E006 then
23044          Ada.Text_Io'Elab_Body;
23045          E006 := True;
23046       end if;
23047
23048       Elab_Final_Code := 0;
23049    end adainit;
23050
23051    --------------
23052    -- adafinal --
23053    --------------
23054
23055 @findex adafinal
23056    procedure adafinal is
23057    begin
23058       Do_Finalize;
23059    end adafinal;
23060
23061    ----------
23062    -- main --
23063    ----------
23064
23065    --  main is actually a function, as in the ANSI C standard,
23066    --  defined to return the exit status. The three parameters
23067    --  are the argument count, argument values and environment
23068    --  pointer.
23069
23070 @findex Main Program
23071    function main
23072      (argc : Integer;
23073       argv : System.Address;
23074       envp : System.Address)
23075       return Integer
23076    is
23077       --  The initialize routine performs low level system
23078       --  initialization using a standard library routine which
23079       --  sets up signal handling and performs any other
23080       --  required setup. The routine can be found in file
23081       --  a-init.c.
23082
23083 @findex __gnat_initialize
23084       procedure initialize;
23085       pragma Import (C, initialize, "__gnat_initialize");
23086
23087       --  The finalize routine performs low level system
23088       --  finalization using a standard library routine. The
23089       --  routine is found in file a-final.c and in the standard
23090       --  distribution is a dummy routine that does nothing, so
23091       --  really this is a hook for special user finalization.
23092
23093 @findex __gnat_finalize
23094       procedure finalize;
23095       pragma Import (C, finalize, "__gnat_finalize");
23096
23097       --  We get to the main program of the partition by using
23098       --  pragma Import because if we try to with the unit and
23099       --  call it Ada style, then not only do we waste time
23100       --  recompiling it, but also, we don't really know the right
23101       --  switches (e.g.@: identifier character set) to be used
23102       --  to compile it.
23103
23104       procedure Ada_Main_Program;
23105       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23106
23107    --  Start of processing for main
23108
23109    begin
23110       --  Save global variables
23111
23112       gnat_argc := argc;
23113       gnat_argv := argv;
23114       gnat_envp := envp;
23115
23116       --  Call low level system initialization
23117
23118       Initialize;
23119
23120       --  Call our generated Ada initialization routine
23121
23122       adainit;
23123
23124       --  This is the point at which we want the debugger to get
23125       --  control
23126
23127       Break_Start;
23128
23129       --  Now we call the main program of the partition
23130
23131       Ada_Main_Program;
23132
23133       --  Perform Ada finalization
23134
23135       adafinal;
23136
23137       --  Perform low level system finalization
23138
23139       Finalize;
23140
23141       --  Return the proper exit status
23142       return (gnat_exit_status);
23143    end;
23144
23145 --  This section is entirely comments, so it has no effect on the
23146 --  compilation of the Ada_Main package. It provides the list of
23147 --  object files and linker options, as well as some standard
23148 --  libraries needed for the link. The gnatlink utility parses
23149 --  this b~hello.adb file to read these comment lines to generate
23150 --  the appropriate command line arguments for the call to the
23151 --  system linker. The BEGIN/END lines are used for sentinels for
23152 --  this parsing operation.
23153
23154 --  The exact file names will of course depend on the environment,
23155 --  host/target and location of files on the host system.
23156
23157 @findex Object file list
23158 -- BEGIN Object file/option list
23159    --   ./hello.o
23160    --   -L./
23161    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23162    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23163 -- END Object file/option list
23164
23165 end ada_main;
23166 @end smallexample
23167
23168 @noindent
23169 The Ada code in the above example is exactly what is generated by the
23170 binder. We have added comments to more clearly indicate the function
23171 of each part of the generated @code{Ada_Main} package.
23172
23173 The code is standard Ada in all respects, and can be processed by any
23174 tools that handle Ada. In particular, it is possible to use the debugger
23175 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23176 suppose that for reasons that you do not understand, your program is crashing
23177 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23178 you can place a breakpoint on the call:
23179
23180 @smallexample @c ada
23181 Ada.Text_Io'Elab_Body;
23182 @end smallexample
23183
23184 @noindent
23185 and trace the elaboration routine for this package to find out where
23186 the problem might be (more usually of course you would be debugging
23187 elaboration code in your own application).
23188
23189 @node Elaboration Order Handling in GNAT
23190 @appendix Elaboration Order Handling in GNAT
23191 @cindex Order of elaboration
23192 @cindex Elaboration control
23193
23194 @menu
23195 * Elaboration Code::
23196 * Checking the Elaboration Order::
23197 * Controlling the Elaboration Order::
23198 * Controlling Elaboration in GNAT - Internal Calls::
23199 * Controlling Elaboration in GNAT - External Calls::
23200 * Default Behavior in GNAT - Ensuring Safety::
23201 * Treatment of Pragma Elaborate::
23202 * Elaboration Issues for Library Tasks::
23203 * Mixing Elaboration Models::
23204 * What to Do If the Default Elaboration Behavior Fails::
23205 * Elaboration for Access-to-Subprogram Values::
23206 * Summary of Procedures for Elaboration Control::
23207 * Other Elaboration Order Considerations::
23208 @end menu
23209
23210 @noindent
23211 This chapter describes the handling of elaboration code in Ada and
23212 in GNAT, and discusses how the order of elaboration of program units can
23213 be controlled in GNAT, either automatically or with explicit programming
23214 features.
23215
23216 @node Elaboration Code
23217 @section Elaboration Code
23218
23219 @noindent
23220 Ada provides rather general mechanisms for executing code at elaboration
23221 time, that is to say before the main program starts executing. Such code arises
23222 in three contexts:
23223
23224 @table @asis
23225 @item Initializers for variables.
23226 Variables declared at the library level, in package specs or bodies, can
23227 require initialization that is performed at elaboration time, as in:
23228 @smallexample @c ada
23229 @cartouche
23230 Sqrt_Half : Float := Sqrt (0.5);
23231 @end cartouche
23232 @end smallexample
23233
23234 @item Package initialization code
23235 Code in a @code{BEGIN-END} section at the outer level of a package body is
23236 executed as part of the package body elaboration code.
23237
23238 @item Library level task allocators
23239 Tasks that are declared using task allocators at the library level
23240 start executing immediately and hence can execute at elaboration time.
23241 @end table
23242
23243 @noindent
23244 Subprogram calls are possible in any of these contexts, which means that
23245 any arbitrary part of the program may be executed as part of the elaboration
23246 code. It is even possible to write a program which does all its work at
23247 elaboration time, with a null main program, although stylistically this
23248 would usually be considered an inappropriate way to structure
23249 a program.
23250
23251 An important concern arises in the context of elaboration code:
23252 we have to be sure that it is executed in an appropriate order. What we
23253 have is a series of elaboration code sections, potentially one section
23254 for each unit in the program. It is important that these execute
23255 in the correct order. Correctness here means that, taking the above
23256 example of the declaration of @code{Sqrt_Half},
23257 if some other piece of
23258 elaboration code references @code{Sqrt_Half},
23259 then it must run after the
23260 section of elaboration code that contains the declaration of
23261 @code{Sqrt_Half}.
23262
23263 There would never be any order of elaboration problem if we made a rule
23264 that whenever you @code{with} a unit, you must elaborate both the spec and body
23265 of that unit before elaborating the unit doing the @code{with}'ing:
23266
23267 @smallexample @c ada
23268 @group
23269 @cartouche
23270 with Unit_1;
23271 package Unit_2 is @dots{}
23272 @end cartouche
23273 @end group
23274 @end smallexample
23275
23276 @noindent
23277 would require that both the body and spec of @code{Unit_1} be elaborated
23278 before the spec of @code{Unit_2}. However, a rule like that would be far too
23279 restrictive. In particular, it would make it impossible to have routines
23280 in separate packages that were mutually recursive.
23281
23282 You might think that a clever enough compiler could look at the actual
23283 elaboration code and determine an appropriate correct order of elaboration,
23284 but in the general case, this is not possible. Consider the following
23285 example.
23286
23287 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23288 that references
23289 the variable @code{Sqrt_1}, which is declared in the elaboration code
23290 of the body of @code{Unit_1}:
23291
23292 @smallexample @c ada
23293 @cartouche
23294 Sqrt_1 : Float := Sqrt (0.1);
23295 @end cartouche
23296 @end smallexample
23297
23298 @noindent
23299 The elaboration code of the body of @code{Unit_1} also contains:
23300
23301 @smallexample @c ada
23302 @group
23303 @cartouche
23304 if expression_1 = 1 then
23305    Q := Unit_2.Func_2;
23306 end if;
23307 @end cartouche
23308 @end group
23309 @end smallexample
23310
23311 @noindent
23312 @code{Unit_2} is exactly parallel,
23313 it has a procedure @code{Func_2} that references
23314 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23315 the body @code{Unit_2}:
23316
23317 @smallexample @c ada
23318 @cartouche
23319 Sqrt_2 : Float := Sqrt (0.1);
23320 @end cartouche
23321 @end smallexample
23322
23323 @noindent
23324 The elaboration code of the body of @code{Unit_2} also contains:
23325
23326 @smallexample @c ada
23327 @group
23328 @cartouche
23329 if expression_2 = 2 then
23330    Q := Unit_1.Func_1;
23331 end if;
23332 @end cartouche
23333 @end group
23334 @end smallexample
23335
23336 @noindent
23337 Now the question is, which of the following orders of elaboration is
23338 acceptable:
23339
23340 @smallexample
23341 @group
23342 Spec of Unit_1
23343 Spec of Unit_2
23344 Body of Unit_1
23345 Body of Unit_2
23346 @end group
23347 @end smallexample
23348
23349 @noindent
23350 or
23351
23352 @smallexample
23353 @group
23354 Spec of Unit_2
23355 Spec of Unit_1
23356 Body of Unit_2
23357 Body of Unit_1
23358 @end group
23359 @end smallexample
23360
23361 @noindent
23362 If you carefully analyze the flow here, you will see that you cannot tell
23363 at compile time the answer to this question.
23364 If @code{expression_1} is not equal to 1,
23365 and @code{expression_2} is not equal to 2,
23366 then either order is acceptable, because neither of the function calls is
23367 executed. If both tests evaluate to true, then neither order is acceptable
23368 and in fact there is no correct order.
23369
23370 If one of the two expressions is true, and the other is false, then one
23371 of the above orders is correct, and the other is incorrect. For example,
23372 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23373 then the call to @code{Func_1}
23374 will occur, but not the call to @code{Func_2.}
23375 This means that it is essential
23376 to elaborate the body of @code{Unit_1} before
23377 the body of @code{Unit_2}, so the first
23378 order of elaboration is correct and the second is wrong.
23379
23380 By making @code{expression_1} and @code{expression_2}
23381 depend on input data, or perhaps
23382 the time of day, we can make it impossible for the compiler or binder
23383 to figure out which of these expressions will be true, and hence it
23384 is impossible to guarantee a safe order of elaboration at run time.
23385
23386 @node Checking the Elaboration Order
23387 @section Checking the Elaboration Order
23388
23389 @noindent
23390 In some languages that involve the same kind of elaboration problems,
23391 e.g.@: Java and C++, the programmer is expected to worry about these
23392 ordering problems himself, and it is common to
23393 write a program in which an incorrect elaboration order  gives
23394 surprising results, because it references variables before they
23395 are initialized.
23396 Ada is designed to be a safe language, and a programmer-beware approach is
23397 clearly not sufficient. Consequently, the language provides three lines
23398 of defense:
23399
23400 @table @asis
23401 @item Standard rules
23402 Some standard rules restrict the possible choice of elaboration
23403 order. In particular, if you @code{with} a unit, then its spec is always
23404 elaborated before the unit doing the @code{with}. Similarly, a parent
23405 spec is always elaborated before the child spec, and finally
23406 a spec is always elaborated before its corresponding body.
23407
23408 @item Dynamic elaboration checks
23409 @cindex Elaboration checks
23410 @cindex Checks, elaboration
23411 Dynamic checks are made at run time, so that if some entity is accessed
23412 before it is elaborated (typically  by means of a subprogram call)
23413 then the exception (@code{Program_Error}) is raised.
23414
23415 @item Elaboration control
23416 Facilities are provided for the programmer to specify the desired order
23417 of elaboration.
23418 @end table
23419
23420 Let's look at these facilities in more detail. First, the rules for
23421 dynamic checking. One possible rule would be simply to say that the
23422 exception is raised if you access a variable which has not yet been
23423 elaborated. The trouble with this approach is that it could require
23424 expensive checks on every variable reference. Instead Ada has two
23425 rules which are a little more restrictive, but easier to check, and
23426 easier to state:
23427
23428 @table @asis
23429 @item Restrictions on calls
23430 A subprogram can only be called at elaboration time if its body
23431 has been elaborated. The rules for elaboration given above guarantee
23432 that the spec of the subprogram has been elaborated before the
23433 call, but not the body. If this rule is violated, then the
23434 exception @code{Program_Error} is raised.
23435
23436 @item Restrictions on instantiations
23437 A generic unit can only be instantiated if the body of the generic
23438 unit has been elaborated. Again, the rules for elaboration given above
23439 guarantee that the spec of the generic unit has been elaborated
23440 before the instantiation, but not the body. If this rule is
23441 violated, then the exception @code{Program_Error} is raised.
23442 @end table
23443
23444 @noindent
23445 The idea is that if the body has been elaborated, then any variables
23446 it references must have been elaborated; by checking for the body being
23447 elaborated we guarantee that none of its references causes any
23448 trouble. As we noted above, this is a little too restrictive, because a
23449 subprogram that has no non-local references in its body may in fact be safe
23450 to call. However, it really would be unsafe to rely on this, because
23451 it would mean that the caller was aware of details of the implementation
23452 in the body. This goes against the basic tenets of Ada.
23453
23454 A plausible implementation can be described as follows.
23455 A Boolean variable is associated with each subprogram
23456 and each generic unit. This variable is initialized to False, and is set to
23457 True at the point body is elaborated. Every call or instantiation checks the
23458 variable, and raises @code{Program_Error} if the variable is False.
23459
23460 Note that one might think that it would be good enough to have one Boolean
23461 variable for each package, but that would not deal with cases of trying
23462 to call a body in the same package as the call
23463 that has not been elaborated yet.
23464 Of course a compiler may be able to do enough analysis to optimize away
23465 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23466 does such optimizations, but still the easiest conceptual model is to
23467 think of there being one variable per subprogram.
23468
23469 @node Controlling the Elaboration Order
23470 @section Controlling the Elaboration Order
23471
23472 @noindent
23473 In the previous section we discussed the rules in Ada which ensure
23474 that @code{Program_Error} is raised if an incorrect elaboration order is
23475 chosen. This prevents erroneous executions, but we need mechanisms to
23476 specify a correct execution and avoid the exception altogether.
23477 To achieve this, Ada provides a number of features for controlling
23478 the order of elaboration. We discuss these features in this section.
23479
23480 First, there are several ways of indicating to the compiler that a given
23481 unit has no elaboration problems:
23482
23483 @table @asis
23484 @item packages that do not require a body
23485 A library package that does not require a body does not permit
23486 a body (this rule was introduced in Ada 95).
23487 Thus if we have a such a package, as in:
23488
23489 @smallexample @c ada
23490 @group
23491 @cartouche
23492 package Definitions is
23493    generic
23494       type m is new integer;
23495    package Subp is
23496       type a is array (1 .. 10) of m;
23497       type b is array (1 .. 20) of m;
23498    end Subp;
23499 end Definitions;
23500 @end cartouche
23501 @end group
23502 @end smallexample
23503
23504 @noindent
23505 A package that @code{with}'s @code{Definitions} may safely instantiate
23506 @code{Definitions.Subp} because the compiler can determine that there
23507 definitely is no package body to worry about in this case
23508
23509 @item pragma Pure
23510 @cindex pragma Pure
23511 @findex Pure
23512 Places sufficient restrictions on a unit to guarantee that
23513 no call to any subprogram in the unit can result in an
23514 elaboration problem. This means that the compiler does not need
23515 to worry about the point of elaboration of such units, and in
23516 particular, does not need to check any calls to any subprograms
23517 in this unit.
23518
23519 @item pragma Preelaborate
23520 @findex Preelaborate
23521 @cindex pragma Preelaborate
23522 This pragma places slightly less stringent restrictions on a unit than
23523 does pragma Pure,
23524 but these restrictions are still sufficient to ensure that there
23525 are no elaboration problems with any calls to the unit.
23526
23527 @item pragma Elaborate_Body
23528 @findex Elaborate_Body
23529 @cindex pragma Elaborate_Body
23530 This pragma requires that the body of a unit be elaborated immediately
23531 after its spec. Suppose a unit @code{A} has such a pragma,
23532 and unit @code{B} does
23533 a @code{with} of unit @code{A}. Recall that the standard rules require
23534 the spec of unit @code{A}
23535 to be elaborated before the @code{with}'ing unit; given the pragma in
23536 @code{A}, we also know that the body of @code{A}
23537 will be elaborated before @code{B}, so
23538 that calls to @code{A} are safe and do not need a check.
23539 @end table
23540
23541 @noindent
23542 Note that,
23543 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23544 the use of
23545 @code{Elaborate_Body} does not guarantee that the program is
23546 free of elaboration problems, because it may not be possible
23547 to satisfy the requested elaboration order.
23548 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23549 If a programmer
23550 marks @code{Unit_1} as @code{Elaborate_Body},
23551 and not @code{Unit_2,} then the order of
23552 elaboration will be:
23553
23554 @smallexample
23555 @group
23556 Spec of Unit_2
23557 Spec of Unit_1
23558 Body of Unit_1
23559 Body of Unit_2
23560 @end group
23561 @end smallexample
23562
23563 @noindent
23564 Now that means that the call to @code{Func_1} in @code{Unit_2}
23565 need not be checked,
23566 it must be safe. But the call to @code{Func_2} in
23567 @code{Unit_1} may still fail if
23568 @code{Expression_1} is equal to 1,
23569 and the programmer must still take
23570 responsibility for this not being the case.
23571
23572 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23573 eliminated, except for calls entirely within a body, which are
23574 in any case fully under programmer control. However, using the pragma
23575 everywhere is not always possible.
23576 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23577 we marked both of them as having pragma @code{Elaborate_Body}, then
23578 clearly there would be no possible elaboration order.
23579
23580 The above pragmas allow a server to guarantee safe use by clients, and
23581 clearly this is the preferable approach. Consequently a good rule
23582 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23583 and if this is not possible,
23584 mark them as @code{Elaborate_Body} if possible.
23585 As we have seen, there are situations where neither of these
23586 three pragmas can be used.
23587 So we also provide methods for clients to control the
23588 order of elaboration of the servers on which they depend:
23589
23590 @table @asis
23591 @item pragma Elaborate (unit)
23592 @findex Elaborate
23593 @cindex pragma Elaborate
23594 This pragma is placed in the context clause, after a @code{with} clause,
23595 and it requires that the body of the named unit be elaborated before
23596 the unit in which the pragma occurs. The idea is to use this pragma
23597 if the current unit calls at elaboration time, directly or indirectly,
23598 some subprogram in the named unit.
23599
23600 @item pragma Elaborate_All (unit)
23601 @findex Elaborate_All
23602 @cindex pragma Elaborate_All
23603 This is a stronger version of the Elaborate pragma. Consider the
23604 following example:
23605
23606 @smallexample
23607 Unit A @code{with}'s unit B and calls B.Func in elab code
23608 Unit B @code{with}'s unit C, and B.Func calls C.Func
23609 @end smallexample
23610
23611 @noindent
23612 Now if we put a pragma @code{Elaborate (B)}
23613 in unit @code{A}, this ensures that the
23614 body of @code{B} is elaborated before the call, but not the
23615 body of @code{C}, so
23616 the call to @code{C.Func} could still cause @code{Program_Error} to
23617 be raised.
23618
23619 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23620 not only that the body of the named unit be elaborated before the
23621 unit doing the @code{with}, but also the bodies of all units that the
23622 named unit uses, following @code{with} links transitively. For example,
23623 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23624 then it requires
23625 not only that the body of @code{B} be elaborated before @code{A},
23626 but also the
23627 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23628 @end table
23629
23630 @noindent
23631 We are now in a position to give a usage rule in Ada for avoiding
23632 elaboration problems, at least if dynamic dispatching and access to
23633 subprogram values are not used. We will handle these cases separately
23634 later.
23635
23636 The rule is simple. If a unit has elaboration code that can directly or
23637 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23638 a generic package in a @code{with}'ed unit,
23639 then if the @code{with}'ed unit does not have
23640 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23641 a pragma @code{Elaborate_All}
23642 for the @code{with}'ed unit. By following this rule a client is
23643 assured that calls can be made without risk of an exception.
23644
23645 For generic subprogram instantiations, the rule can be relaxed to
23646 require only a pragma @code{Elaborate} since elaborating the body
23647 of a subprogram cannot cause any transitive elaboration (we are
23648 not calling the subprogram in this case, just elaborating its
23649 declaration).
23650
23651 If this rule is not followed, then a program may be in one of four
23652 states:
23653
23654 @table @asis
23655 @item No order exists
23656 No order of elaboration exists which follows the rules, taking into
23657 account any @code{Elaborate}, @code{Elaborate_All},
23658 or @code{Elaborate_Body} pragmas. In
23659 this case, an Ada compiler must diagnose the situation at bind
23660 time, and refuse to build an executable program.
23661
23662 @item One or more orders exist, all incorrect
23663 One or more acceptable elaboration orders exist, and all of them
23664 generate an elaboration order problem. In this case, the binder
23665 can build an executable program, but @code{Program_Error} will be raised
23666 when the program is run.
23667
23668 @item Several orders exist, some right, some incorrect
23669 One or more acceptable elaboration orders exists, and some of them
23670 work, and some do not. The programmer has not controlled
23671 the order of elaboration, so the binder may or may not pick one of
23672 the correct orders, and the program may or may not raise an
23673 exception when it is run. This is the worst case, because it means
23674 that the program may fail when moved to another compiler, or even
23675 another version of the same compiler.
23676
23677 @item One or more orders exists, all correct
23678 One ore more acceptable elaboration orders exist, and all of them
23679 work. In this case the program runs successfully. This state of
23680 affairs can be guaranteed by following the rule we gave above, but
23681 may be true even if the rule is not followed.
23682 @end table
23683
23684 @noindent
23685 Note that one additional advantage of following our rules on the use
23686 of @code{Elaborate} and @code{Elaborate_All}
23687 is that the program continues to stay in the ideal (all orders OK) state
23688 even if maintenance
23689 changes some bodies of some units. Conversely, if a program that does
23690 not follow this rule happens to be safe at some point, this state of affairs
23691 may deteriorate silently as a result of maintenance changes.
23692
23693 You may have noticed that the above discussion did not mention
23694 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23695 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23696 code in the body makes calls to some other unit, so it is still necessary
23697 to use @code{Elaborate_All} on such units.
23698
23699 @node Controlling Elaboration in GNAT - Internal Calls
23700 @section Controlling Elaboration in GNAT - Internal Calls
23701
23702 @noindent
23703 In the case of internal calls, i.e., calls within a single package, the
23704 programmer has full control over the order of elaboration, and it is up
23705 to the programmer to elaborate declarations in an appropriate order. For
23706 example writing:
23707
23708 @smallexample @c ada
23709 @group
23710 @cartouche
23711 function One return Float;
23712
23713 Q : Float := One;
23714
23715 function One return Float is
23716 begin
23717      return 1.0;
23718 end One;
23719 @end cartouche
23720 @end group
23721 @end smallexample
23722
23723 @noindent
23724 will obviously raise @code{Program_Error} at run time, because function
23725 One will be called before its body is elaborated. In this case GNAT will
23726 generate a warning that the call will raise @code{Program_Error}:
23727
23728 @smallexample
23729 @group
23730 @cartouche
23731  1. procedure y is
23732  2.    function One return Float;
23733  3.
23734  4.    Q : Float := One;
23735                     |
23736     >>> warning: cannot call "One" before body is elaborated
23737     >>> warning: Program_Error will be raised at run time
23738
23739  5.
23740  6.    function One return Float is
23741  7.    begin
23742  8.         return 1.0;
23743  9.    end One;
23744 10.
23745 11. begin
23746 12.    null;
23747 13. end;
23748 @end cartouche
23749 @end group
23750 @end smallexample
23751
23752 @noindent
23753 Note that in this particular case, it is likely that the call is safe, because
23754 the function @code{One} does not access any global variables.
23755 Nevertheless in Ada, we do not want the validity of the check to depend on
23756 the contents of the body (think about the separate compilation case), so this
23757 is still wrong, as we discussed in the previous sections.
23758
23759 The error is easily corrected by rearranging the declarations so that the
23760 body of @code{One} appears before the declaration containing the call
23761 (note that in Ada 95 and Ada 2005,
23762 declarations can appear in any order, so there is no restriction that
23763 would prevent this reordering, and if we write:
23764
23765 @smallexample @c ada
23766 @group
23767 @cartouche
23768 function One return Float;
23769
23770 function One return Float is
23771 begin
23772      return 1.0;
23773 end One;
23774
23775 Q : Float := One;
23776 @end cartouche
23777 @end group
23778 @end smallexample
23779
23780 @noindent
23781 then all is well, no warning is generated, and no
23782 @code{Program_Error} exception
23783 will be raised.
23784 Things are more complicated when a chain of subprograms is executed:
23785
23786 @smallexample @c ada
23787 @group
23788 @cartouche
23789 function A return Integer;
23790 function B return Integer;
23791 function C return Integer;
23792
23793 function B return Integer is begin return A; end;
23794 function C return Integer is begin return B; end;
23795
23796 X : Integer := C;
23797
23798 function A return Integer is begin return 1; end;
23799 @end cartouche
23800 @end group
23801 @end smallexample
23802
23803 @noindent
23804 Now the call to @code{C}
23805 at elaboration time in the declaration of @code{X} is correct, because
23806 the body of @code{C} is already elaborated,
23807 and the call to @code{B} within the body of
23808 @code{C} is correct, but the call
23809 to @code{A} within the body of @code{B} is incorrect, because the body
23810 of @code{A} has not been elaborated, so @code{Program_Error}
23811 will be raised on the call to @code{A}.
23812 In this case GNAT will generate a
23813 warning that @code{Program_Error} may be
23814 raised at the point of the call. Let's look at the warning:
23815
23816 @smallexample
23817 @group
23818 @cartouche
23819  1. procedure x is
23820  2.    function A return Integer;
23821  3.    function B return Integer;
23822  4.    function C return Integer;
23823  5.
23824  6.    function B return Integer is begin return A; end;
23825                                                     |
23826     >>> warning: call to "A" before body is elaborated may
23827                  raise Program_Error
23828     >>> warning: "B" called at line 7
23829     >>> warning: "C" called at line 9
23830
23831  7.    function C return Integer is begin return B; end;
23832  8.
23833  9.    X : Integer := C;
23834 10.
23835 11.    function A return Integer is begin return 1; end;
23836 12.
23837 13. begin
23838 14.    null;
23839 15. end;
23840 @end cartouche
23841 @end group
23842 @end smallexample
23843
23844 @noindent
23845 Note that the message here says ``may raise'', instead of the direct case,
23846 where the message says ``will be raised''. That's because whether
23847 @code{A} is
23848 actually called depends in general on run-time flow of control.
23849 For example, if the body of @code{B} said
23850
23851 @smallexample @c ada
23852 @group
23853 @cartouche
23854 function B return Integer is
23855 begin
23856    if some-condition-depending-on-input-data then
23857       return A;
23858    else
23859       return 1;
23860    end if;
23861 end B;
23862 @end cartouche
23863 @end group
23864 @end smallexample
23865
23866 @noindent
23867 then we could not know until run time whether the incorrect call to A would
23868 actually occur, so @code{Program_Error} might
23869 or might not be raised. It is possible for a compiler to
23870 do a better job of analyzing bodies, to
23871 determine whether or not @code{Program_Error}
23872 might be raised, but it certainly
23873 couldn't do a perfect job (that would require solving the halting problem
23874 and is provably impossible), and because this is a warning anyway, it does
23875 not seem worth the effort to do the analysis. Cases in which it
23876 would be relevant are rare.
23877
23878 In practice, warnings of either of the forms given
23879 above will usually correspond to
23880 real errors, and should be examined carefully and eliminated.
23881 In the rare case where a warning is bogus, it can be suppressed by any of
23882 the following methods:
23883
23884 @itemize @bullet
23885 @item
23886 Compile with the @option{-gnatws} switch set
23887
23888 @item
23889 Suppress @code{Elaboration_Check} for the called subprogram
23890
23891 @item
23892 Use pragma @code{Warnings_Off} to turn warnings off for the call
23893 @end itemize
23894
23895 @noindent
23896 For the internal elaboration check case,
23897 GNAT by default generates the
23898 necessary run-time checks to ensure
23899 that @code{Program_Error} is raised if any
23900 call fails an elaboration check. Of course this can only happen if a
23901 warning has been issued as described above. The use of pragma
23902 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23903 some of these checks, meaning that it may be possible (but is not
23904 guaranteed) for a program to be able to call a subprogram whose body
23905 is not yet elaborated, without raising a @code{Program_Error} exception.
23906
23907 @node Controlling Elaboration in GNAT - External Calls
23908 @section Controlling Elaboration in GNAT - External Calls
23909
23910 @noindent
23911 The previous section discussed the case in which the execution of a
23912 particular thread of elaboration code occurred entirely within a
23913 single unit. This is the easy case to handle, because a programmer
23914 has direct and total control over the order of elaboration, and
23915 furthermore, checks need only be generated in cases which are rare
23916 and which the compiler can easily detect.
23917 The situation is more complex when separate compilation is taken into account.
23918 Consider the following:
23919
23920 @smallexample @c ada
23921 @cartouche
23922 @group
23923 package Math is
23924    function Sqrt (Arg : Float) return Float;
23925 end Math;
23926
23927 package body Math is
23928    function Sqrt (Arg : Float) return Float is
23929    begin
23930          @dots{}
23931    end Sqrt;
23932 end Math;
23933 @end group
23934 @group
23935 with Math;
23936 package Stuff is
23937    X : Float := Math.Sqrt (0.5);
23938 end Stuff;
23939
23940 with Stuff;
23941 procedure Main is
23942 begin
23943    @dots{}
23944 end Main;
23945 @end group
23946 @end cartouche
23947 @end smallexample
23948
23949 @noindent
23950 where @code{Main} is the main program. When this program is executed, the
23951 elaboration code must first be executed, and one of the jobs of the
23952 binder is to determine the order in which the units of a program are
23953 to be elaborated. In this case we have four units: the spec and body
23954 of @code{Math},
23955 the spec of @code{Stuff} and the body of @code{Main}).
23956 In what order should the four separate sections of elaboration code
23957 be executed?
23958
23959 There are some restrictions in the order of elaboration that the binder
23960 can choose. In particular, if unit U has a @code{with}
23961 for a package @code{X}, then you
23962 are assured that the spec of @code{X}
23963 is elaborated before U , but you are
23964 not assured that the body of @code{X}
23965 is elaborated before U.
23966 This means that in the above case, the binder is allowed to choose the
23967 order:
23968
23969 @smallexample
23970 spec of Math
23971 spec of Stuff
23972 body of Math
23973 body of Main
23974 @end smallexample
23975
23976 @noindent
23977 but that's not good, because now the call to @code{Math.Sqrt}
23978 that happens during
23979 the elaboration of the @code{Stuff}
23980 spec happens before the body of @code{Math.Sqrt} is
23981 elaborated, and hence causes @code{Program_Error} exception to be raised.
23982 At first glance, one might say that the binder is misbehaving, because
23983 obviously you want to elaborate the body of something you @code{with}
23984 first, but
23985 that is not a general rule that can be followed in all cases. Consider
23986
23987 @smallexample @c ada
23988 @group
23989 @cartouche
23990 package X is @dots{}
23991
23992 package Y is @dots{}
23993
23994 with X;
23995 package body Y is @dots{}
23996
23997 with Y;
23998 package body X is @dots{}
23999 @end cartouche
24000 @end group
24001 @end smallexample
24002
24003 @noindent
24004 This is a common arrangement, and, apart from the order of elaboration
24005 problems that might arise in connection with elaboration code, this works fine.
24006 A rule that says that you must first elaborate the body of anything you
24007 @code{with} cannot work in this case:
24008 the body of @code{X} @code{with}'s @code{Y},
24009 which means you would have to
24010 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24011 which means
24012 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24013 loop that cannot be broken.
24014
24015 It is true that the binder can in many cases guess an order of elaboration
24016 that is unlikely to cause a @code{Program_Error}
24017 exception to be raised, and it tries to do so (in the
24018 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24019 by default
24020 elaborate the body of @code{Math} right after its spec, so all will be well).
24021
24022 However, a program that blindly relies on the binder to be helpful can
24023 get into trouble, as we discussed in the previous sections, so
24024 GNAT
24025 provides a number of facilities for assisting the programmer in
24026 developing programs that are robust with respect to elaboration order.
24027
24028 @node Default Behavior in GNAT - Ensuring Safety
24029 @section Default Behavior in GNAT - Ensuring Safety
24030
24031 @noindent
24032 The default behavior in GNAT ensures elaboration safety. In its
24033 default mode GNAT implements the
24034 rule we previously described as the right approach. Let's restate it:
24035
24036 @itemize
24037 @item
24038 @emph{If a unit has elaboration code that can directly or indirectly make a
24039 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24040 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24041 does not have pragma @code{Pure} or
24042 @code{Preelaborate}, then the client should have an
24043 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24044
24045 @emph{In the case of instantiating a generic subprogram, it is always
24046 sufficient to have only an @code{Elaborate} pragma for the
24047 @code{with}'ed unit.}
24048 @end itemize
24049
24050 @noindent
24051 By following this rule a client is assured that calls and instantiations
24052 can be made without risk of an exception.
24053
24054 In this mode GNAT traces all calls that are potentially made from
24055 elaboration code, and puts in any missing implicit @code{Elaborate}
24056 and @code{Elaborate_All} pragmas.
24057 The advantage of this approach is that no elaboration problems
24058 are possible if the binder can find an elaboration order that is
24059 consistent with these implicit @code{Elaborate} and
24060 @code{Elaborate_All} pragmas. The
24061 disadvantage of this approach is that no such order may exist.
24062
24063 If the binder does not generate any diagnostics, then it means that it has
24064 found an elaboration order that is guaranteed to be safe. However, the binder
24065 may still be relying on implicitly generated @code{Elaborate} and
24066 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24067 guaranteed.
24068
24069 If it is important to guarantee portability, then the compilations should
24070 use the
24071 @option{-gnatwl}
24072 (warn on elaboration problems) switch. This will cause warning messages
24073 to be generated indicating the missing @code{Elaborate} and
24074 @code{Elaborate_All} pragmas.
24075 Consider the following source program:
24076
24077 @smallexample @c ada
24078 @group
24079 @cartouche
24080 with k;
24081 package j is
24082   m : integer := k.r;
24083 end;
24084 @end cartouche
24085 @end group
24086 @end smallexample
24087
24088 @noindent
24089 where it is clear that there
24090 should be a pragma @code{Elaborate_All}
24091 for unit @code{k}. An implicit pragma will be generated, and it is
24092 likely that the binder will be able to honor it. However, if you want
24093 to port this program to some other Ada compiler than GNAT.
24094 it is safer to include the pragma explicitly in the source. If this
24095 unit is compiled with the
24096 @option{-gnatwl}
24097 switch, then the compiler outputs a warning:
24098
24099 @smallexample
24100 @group
24101 @cartouche
24102 1. with k;
24103 2. package j is
24104 3.   m : integer := k.r;
24105                      |
24106    >>> warning: call to "r" may raise Program_Error
24107    >>> warning: missing pragma Elaborate_All for "k"
24108
24109 4. end;
24110 @end cartouche
24111 @end group
24112 @end smallexample
24113
24114 @noindent
24115 and these warnings can be used as a guide for supplying manually
24116 the missing pragmas. It is usually a bad idea to use this warning
24117 option during development. That's because it will warn you when
24118 you need to put in a pragma, but cannot warn you when it is time
24119 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24120 unnecessary dependencies and even false circularities.
24121
24122 This default mode is more restrictive than the Ada Reference
24123 Manual, and it is possible to construct programs which will compile
24124 using the dynamic model described there, but will run into a
24125 circularity using the safer static model we have described.
24126
24127 Of course any Ada compiler must be able to operate in a mode
24128 consistent with the requirements of the Ada Reference Manual,
24129 and in particular must have the capability of implementing the
24130 standard dynamic model of elaboration with run-time checks.
24131
24132 In GNAT, this standard mode can be achieved either by the use of
24133 the @option{-gnatE} switch on the compiler (@command{gcc} or
24134 @command{gnatmake}) command, or by the use of the configuration pragma:
24135
24136 @smallexample @c ada
24137 pragma Elaboration_Checks (DYNAMIC);
24138 @end smallexample
24139
24140 @noindent
24141 Either approach will cause the unit affected to be compiled using the
24142 standard dynamic run-time elaboration checks described in the Ada
24143 Reference Manual. The static model is generally preferable, since it
24144 is clearly safer to rely on compile and link time checks rather than
24145 run-time checks. However, in the case of legacy code, it may be
24146 difficult to meet the requirements of the static model. This
24147 issue is further discussed in
24148 @ref{What to Do If the Default Elaboration Behavior Fails}.
24149
24150 Note that the static model provides a strict subset of the allowed
24151 behavior and programs of the Ada Reference Manual, so if you do
24152 adhere to the static model and no circularities exist,
24153 then you are assured that your program will
24154 work using the dynamic model, providing that you remove any
24155 pragma Elaborate statements from the source.
24156
24157 @node Treatment of Pragma Elaborate
24158 @section Treatment of Pragma Elaborate
24159 @cindex Pragma Elaborate
24160
24161 @noindent
24162 The use of @code{pragma Elaborate}
24163 should generally be avoided in Ada 95 and Ada 2005 programs,
24164 since there is no guarantee that transitive calls
24165 will be properly handled. Indeed at one point, this pragma was placed
24166 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24167
24168 Now that's a bit restrictive. In practice, the case in which
24169 @code{pragma Elaborate} is useful is when the caller knows that there
24170 are no transitive calls, or that the called unit contains all necessary
24171 transitive @code{pragma Elaborate} statements, and legacy code often
24172 contains such uses.
24173
24174 Strictly speaking the static mode in GNAT should ignore such pragmas,
24175 since there is no assurance at compile time that the necessary safety
24176 conditions are met. In practice, this would cause GNAT to be incompatible
24177 with correctly written Ada 83 code that had all necessary
24178 @code{pragma Elaborate} statements in place. Consequently, we made the
24179 decision that GNAT in its default mode will believe that if it encounters
24180 a @code{pragma Elaborate} then the programmer knows what they are doing,
24181 and it will trust that no elaboration errors can occur.
24182
24183 The result of this decision is two-fold. First to be safe using the
24184 static mode, you should remove all @code{pragma Elaborate} statements.
24185 Second, when fixing circularities in existing code, you can selectively
24186 use @code{pragma Elaborate} statements to convince the static mode of
24187 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24188 statement.
24189
24190 When using the static mode with @option{-gnatwl}, any use of
24191 @code{pragma Elaborate} will generate a warning about possible
24192 problems.
24193
24194 @node Elaboration Issues for Library Tasks
24195 @section Elaboration Issues for Library Tasks
24196 @cindex Library tasks, elaboration issues
24197 @cindex Elaboration of library tasks
24198
24199 @noindent
24200 In this section we examine special elaboration issues that arise for
24201 programs that declare library level tasks.
24202
24203 Generally the model of execution of an Ada program is that all units are
24204 elaborated, and then execution of the program starts. However, the
24205 declaration of library tasks definitely does not fit this model. The
24206 reason for this is that library tasks start as soon as they are declared
24207 (more precisely, as soon as the statement part of the enclosing package
24208 body is reached), that is to say before elaboration
24209 of the program is complete. This means that if such a task calls a
24210 subprogram, or an entry in another task, the callee may or may not be
24211 elaborated yet, and in the standard
24212 Reference Manual model of dynamic elaboration checks, you can even
24213 get timing dependent Program_Error exceptions, since there can be
24214 a race between the elaboration code and the task code.
24215
24216 The static model of elaboration in GNAT seeks to avoid all such
24217 dynamic behavior, by being conservative, and the conservative
24218 approach in this particular case is to assume that all the code
24219 in a task body is potentially executed at elaboration time if
24220 a task is declared at the library level.
24221
24222 This can definitely result in unexpected circularities. Consider
24223 the following example
24224
24225 @smallexample @c ada
24226 package Decls is
24227   task Lib_Task is
24228      entry Start;
24229   end Lib_Task;
24230
24231   type My_Int is new Integer;
24232
24233   function Ident (M : My_Int) return My_Int;
24234 end Decls;
24235
24236 with Utils;
24237 package body Decls is
24238   task body Lib_Task is
24239   begin
24240      accept Start;
24241      Utils.Put_Val (2);
24242   end Lib_Task;
24243
24244   function Ident (M : My_Int) return My_Int is
24245   begin
24246      return M;
24247   end Ident;
24248 end Decls;
24249
24250 with Decls;
24251 package Utils is
24252   procedure Put_Val (Arg : Decls.My_Int);
24253 end Utils;
24254
24255 with Text_IO;
24256 package body Utils is
24257   procedure Put_Val (Arg : Decls.My_Int) is
24258   begin
24259      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24260   end Put_Val;
24261 end Utils;
24262
24263 with Decls;
24264 procedure Main is
24265 begin
24266    Decls.Lib_Task.Start;
24267 end;
24268 @end smallexample
24269
24270 @noindent
24271 If the above example is compiled in the default static elaboration
24272 mode, then a circularity occurs. The circularity comes from the call
24273 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24274 this call occurs in elaboration code, we need an implicit pragma
24275 @code{Elaborate_All} for @code{Utils}. This means that not only must
24276 the spec and body of @code{Utils} be elaborated before the body
24277 of @code{Decls}, but also the spec and body of any unit that is
24278 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24279 the body of @code{Decls}. This is the transitive implication of
24280 pragma @code{Elaborate_All} and it makes sense, because in general
24281 the body of @code{Put_Val} might have a call to something in a
24282 @code{with'ed} unit.
24283
24284 In this case, the body of Utils (actually its spec) @code{with's}
24285 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24286 must be elaborated before itself, in case there is a call from the
24287 body of @code{Utils}.
24288
24289 Here is the exact chain of events we are worrying about:
24290
24291 @enumerate
24292 @item
24293 In the body of @code{Decls} a call is made from within the body of a library
24294 task to a subprogram in the package @code{Utils}. Since this call may
24295 occur at elaboration time (given that the task is activated at elaboration
24296 time), we have to assume the worst, i.e., that the
24297 call does happen at elaboration time.
24298
24299 @item
24300 This means that the body and spec of @code{Util} must be elaborated before
24301 the body of @code{Decls} so that this call does not cause an access before
24302 elaboration.
24303
24304 @item
24305 Within the body of @code{Util}, specifically within the body of
24306 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24307 by this package.
24308
24309 @item
24310 One such @code{with}'ed package is package @code{Decls}, so there
24311 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24312 In fact there is such a call in this example, but we would have to
24313 assume that there was such a call even if it were not there, since
24314 we are not supposed to write the body of @code{Decls} knowing what
24315 is in the body of @code{Utils}; certainly in the case of the
24316 static elaboration model, the compiler does not know what is in
24317 other bodies and must assume the worst.
24318
24319 @item
24320 This means that the spec and body of @code{Decls} must also be
24321 elaborated before we elaborate the unit containing the call, but
24322 that unit is @code{Decls}! This means that the body of @code{Decls}
24323 must be elaborated before itself, and that's a circularity.
24324 @end enumerate
24325
24326 @noindent
24327 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24328 the body of @code{Decls} you will get a true Ada Reference Manual
24329 circularity that makes the program illegal.
24330
24331 In practice, we have found that problems with the static model of
24332 elaboration in existing code often arise from library tasks, so
24333 we must address this particular situation.
24334
24335 Note that if we compile and run the program above, using the dynamic model of
24336 elaboration (that is to say use the @option{-gnatE} switch),
24337 then it compiles, binds,
24338 links, and runs, printing the expected result of 2. Therefore in some sense
24339 the circularity here is only apparent, and we need to capture
24340 the properties of this program that  distinguish it from other library-level
24341 tasks that have real elaboration problems.
24342
24343 We have four possible answers to this question:
24344
24345 @itemize @bullet
24346
24347 @item
24348 Use the dynamic model of elaboration.
24349
24350 If we use the @option{-gnatE} switch, then as noted above, the program works.
24351 Why is this? If we examine the task body, it is apparent that the task cannot
24352 proceed past the
24353 @code{accept} statement until after elaboration has been completed, because
24354 the corresponding entry call comes from the main program, not earlier.
24355 This is why the dynamic model works here. But that's really giving
24356 up on a precise analysis, and we prefer to take this approach only if we cannot
24357 solve the
24358 problem in any other manner. So let us examine two ways to reorganize
24359 the program to avoid the potential elaboration problem.
24360
24361 @item
24362 Split library tasks into separate packages.
24363
24364 Write separate packages, so that library tasks are isolated from
24365 other declarations as much as possible. Let us look at a variation on
24366 the above program.
24367
24368 @smallexample @c ada
24369 package Decls1 is
24370   task Lib_Task is
24371      entry Start;
24372   end Lib_Task;
24373 end Decls1;
24374
24375 with Utils;
24376 package body Decls1 is
24377   task body Lib_Task is
24378   begin
24379      accept Start;
24380      Utils.Put_Val (2);
24381   end Lib_Task;
24382 end Decls1;
24383
24384 package Decls2 is
24385   type My_Int is new Integer;
24386   function Ident (M : My_Int) return My_Int;
24387 end Decls2;
24388
24389 with Utils;
24390 package body Decls2 is
24391   function Ident (M : My_Int) return My_Int is
24392   begin
24393      return M;
24394   end Ident;
24395 end Decls2;
24396
24397 with Decls2;
24398 package Utils is
24399   procedure Put_Val (Arg : Decls2.My_Int);
24400 end Utils;
24401
24402 with Text_IO;
24403 package body Utils is
24404   procedure Put_Val (Arg : Decls2.My_Int) is
24405   begin
24406      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24407   end Put_Val;
24408 end Utils;
24409
24410 with Decls1;
24411 procedure Main is
24412 begin
24413    Decls1.Lib_Task.Start;
24414 end;
24415 @end smallexample
24416
24417 @noindent
24418 All we have done is to split @code{Decls} into two packages, one
24419 containing the library task, and one containing everything else. Now
24420 there is no cycle, and the program compiles, binds, links and executes
24421 using the default static model of elaboration.
24422
24423 @item
24424 Declare separate task types.
24425
24426 A significant part of the problem arises because of the use of the
24427 single task declaration form. This means that the elaboration of
24428 the task type, and the elaboration of the task itself (i.e.@: the
24429 creation of the task) happen at the same time. A good rule
24430 of style in Ada is to always create explicit task types. By
24431 following the additional step of placing task objects in separate
24432 packages from the task type declaration, many elaboration problems
24433 are avoided. Here is another modified example of the example program:
24434
24435 @smallexample @c ada
24436 package Decls is
24437   task type Lib_Task_Type is
24438      entry Start;
24439   end Lib_Task_Type;
24440
24441   type My_Int is new Integer;
24442
24443   function Ident (M : My_Int) return My_Int;
24444 end Decls;
24445
24446 with Utils;
24447 package body Decls is
24448   task body Lib_Task_Type is
24449   begin
24450      accept Start;
24451      Utils.Put_Val (2);
24452   end Lib_Task_Type;
24453
24454   function Ident (M : My_Int) return My_Int is
24455   begin
24456      return M;
24457   end Ident;
24458 end Decls;
24459
24460 with Decls;
24461 package Utils is
24462   procedure Put_Val (Arg : Decls.My_Int);
24463 end Utils;
24464
24465 with Text_IO;
24466 package body Utils is
24467   procedure Put_Val (Arg : Decls.My_Int) is
24468   begin
24469      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24470   end Put_Val;
24471 end Utils;
24472
24473 with Decls;
24474 package Declst is
24475    Lib_Task : Decls.Lib_Task_Type;
24476 end Declst;
24477
24478 with Declst;
24479 procedure Main is
24480 begin
24481    Declst.Lib_Task.Start;
24482 end;
24483 @end smallexample
24484
24485 @noindent
24486 What we have done here is to replace the @code{task} declaration in
24487 package @code{Decls} with a @code{task type} declaration. Then we
24488 introduce a separate package @code{Declst} to contain the actual
24489 task object. This separates the elaboration issues for
24490 the @code{task type}
24491 declaration, which causes no trouble, from the elaboration issues
24492 of the task object, which is also unproblematic, since it is now independent
24493 of the elaboration of  @code{Utils}.
24494 This separation of concerns also corresponds to
24495 a generally sound engineering principle of separating declarations
24496 from instances. This version of the program also compiles, binds, links,
24497 and executes, generating the expected output.
24498
24499 @item
24500 Use No_Entry_Calls_In_Elaboration_Code restriction.
24501 @cindex No_Entry_Calls_In_Elaboration_Code
24502
24503 The previous two approaches described how a program can be restructured
24504 to avoid the special problems caused by library task bodies. in practice,
24505 however, such restructuring may be difficult to apply to existing legacy code,
24506 so we must consider solutions that do not require massive rewriting.
24507
24508 Let us consider more carefully why our original sample program works
24509 under the dynamic model of elaboration. The reason is that the code
24510 in the task body blocks immediately on the @code{accept}
24511 statement. Now of course there is nothing to prohibit elaboration
24512 code from making entry calls (for example from another library level task),
24513 so we cannot tell in isolation that
24514 the task will not execute the accept statement  during elaboration.
24515
24516 However, in practice it is very unusual to see elaboration code
24517 make any entry calls, and the pattern of tasks starting
24518 at elaboration time and then immediately blocking on @code{accept} or
24519 @code{select} statements is very common. What this means is that
24520 the compiler is being too pessimistic when it analyzes the
24521 whole package body as though it might be executed at elaboration
24522 time.
24523
24524 If we know that the elaboration code contains no entry calls, (a very safe
24525 assumption most of the time, that could almost be made the default
24526 behavior), then we can compile all units of the program under control
24527 of the following configuration pragma:
24528
24529 @smallexample
24530 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24531 @end smallexample
24532
24533 @noindent
24534 This pragma can be placed in the @file{gnat.adc} file in the usual
24535 manner. If we take our original unmodified program and compile it
24536 in the presence of a @file{gnat.adc} containing the above pragma,
24537 then once again, we can compile, bind, link, and execute, obtaining
24538 the expected result. In the presence of this pragma, the compiler does
24539 not trace calls in a task body, that appear after the first @code{accept}
24540 or @code{select} statement, and therefore does not report a potential
24541 circularity in the original program.
24542
24543 The compiler will check to the extent it can that the above
24544 restriction is not violated, but it is not always possible to do a
24545 complete check at compile time, so it is important to use this
24546 pragma only if the stated restriction is in fact met, that is to say
24547 no task receives an entry call before elaboration of all units is completed.
24548
24549 @end itemize
24550
24551 @node Mixing Elaboration Models
24552 @section Mixing Elaboration Models
24553 @noindent
24554 So far, we have assumed that the entire program is either compiled
24555 using the dynamic model or static model, ensuring consistency. It
24556 is possible to mix the two models, but rules have to be followed
24557 if this mixing is done to ensure that elaboration checks are not
24558 omitted.
24559
24560 The basic rule is that @emph{a unit compiled with the static model cannot
24561 be @code{with'ed} by a unit compiled with the dynamic model}. The
24562 reason for this is that in the static model, a unit assumes that
24563 its clients guarantee to use (the equivalent of) pragma
24564 @code{Elaborate_All} so that no elaboration checks are required
24565 in inner subprograms, and this assumption is violated if the
24566 client is compiled with dynamic checks.
24567
24568 The precise rule is as follows. A unit that is compiled with dynamic
24569 checks can only @code{with} a unit that meets at least one of the
24570 following criteria:
24571
24572 @itemize @bullet
24573
24574 @item
24575 The @code{with'ed} unit is itself compiled with dynamic elaboration
24576 checks (that is with the @option{-gnatE} switch.
24577
24578 @item
24579 The @code{with'ed} unit is an internal GNAT implementation unit from
24580 the System, Interfaces, Ada, or GNAT hierarchies.
24581
24582 @item
24583 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24584
24585 @item
24586 The @code{with'ing} unit (that is the client) has an explicit pragma
24587 @code{Elaborate_All} for the @code{with'ed} unit.
24588
24589 @end itemize
24590
24591 @noindent
24592 If this rule is violated, that is if a unit with dynamic elaboration
24593 checks @code{with's} a unit that does not meet one of the above four
24594 criteria, then the binder (@code{gnatbind}) will issue a warning
24595 similar to that in the following example:
24596
24597 @smallexample
24598 warning: "x.ads" has dynamic elaboration checks and with's
24599 warning:   "y.ads" which has static elaboration checks
24600 @end smallexample
24601
24602 @noindent
24603 These warnings indicate that the rule has been violated, and that as a result
24604 elaboration checks may be missed in the resulting executable file.
24605 This warning may be suppressed using the @option{-ws} binder switch
24606 in the usual manner.
24607
24608 One useful application of this mixing rule is in the case of a subsystem
24609 which does not itself @code{with} units from the remainder of the
24610 application. In this case, the entire subsystem can be compiled with
24611 dynamic checks to resolve a circularity in the subsystem, while
24612 allowing the main application that uses this subsystem to be compiled
24613 using the more reliable default static model.
24614
24615 @node What to Do If the Default Elaboration Behavior Fails
24616 @section What to Do If the Default Elaboration Behavior Fails
24617
24618 @noindent
24619 If the binder cannot find an acceptable order, it outputs detailed
24620 diagnostics. For example:
24621 @smallexample
24622 @group
24623 @iftex
24624 @leftskip=0cm
24625 @end iftex
24626 error: elaboration circularity detected
24627 info:   "proc (body)" must be elaborated before "pack (body)"
24628 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24629 info:     recompile "pack (body)" with -gnatwl
24630 info:                             for full details
24631 info:       "proc (body)"
24632 info:         is needed by its spec:
24633 info:       "proc (spec)"
24634 info:         which is withed by:
24635 info:       "pack (body)"
24636 info:  "pack (body)" must be elaborated before "proc (body)"
24637 info:     reason: pragma Elaborate in unit "proc (body)"
24638 @end group
24639
24640 @end smallexample
24641
24642 @noindent
24643 In this case we have a cycle that the binder cannot break. On the one
24644 hand, there is an explicit pragma Elaborate in @code{proc} for
24645 @code{pack}. This means that the body of @code{pack} must be elaborated
24646 before the body of @code{proc}. On the other hand, there is elaboration
24647 code in @code{pack} that calls a subprogram in @code{proc}. This means
24648 that for maximum safety, there should really be a pragma
24649 Elaborate_All in @code{pack} for @code{proc} which would require that
24650 the body of @code{proc} be elaborated before the body of
24651 @code{pack}. Clearly both requirements cannot be satisfied.
24652 Faced with a circularity of this kind, you have three different options.
24653
24654 @table @asis
24655 @item Fix the program
24656 The most desirable option from the point of view of long-term maintenance
24657 is to rearrange the program so that the elaboration problems are avoided.
24658 One useful technique is to place the elaboration code into separate
24659 child packages. Another is to move some of the initialization code to
24660 explicitly called subprograms, where the program controls the order
24661 of initialization explicitly. Although this is the most desirable option,
24662 it may be impractical and involve too much modification, especially in
24663 the case of complex legacy code.
24664
24665 @item Perform dynamic checks
24666 If the compilations are done using the
24667 @option{-gnatE}
24668 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24669 manner. Dynamic checks are generated for all calls that could possibly result
24670 in raising an exception. With this switch, the compiler does not generate
24671 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24672 exactly as specified in the @cite{Ada Reference Manual}.
24673 The binder will generate
24674 an executable program that may or may not raise @code{Program_Error}, and then
24675 it is the programmer's job to ensure that it does not raise an exception. Note
24676 that it is important to compile all units with the switch, it cannot be used
24677 selectively.
24678
24679 @item Suppress checks
24680 The drawback of dynamic checks is that they generate a
24681 significant overhead at run time, both in space and time. If you
24682 are absolutely sure that your program cannot raise any elaboration
24683 exceptions, and you still want to use the dynamic elaboration model,
24684 then you can use the configuration pragma
24685 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24686 example this pragma could be placed in the @file{gnat.adc} file.
24687
24688 @item Suppress checks selectively
24689 When you know that certain calls or instantiations in elaboration code cannot
24690 possibly lead to an elaboration error, and the binder nevertheless complains
24691 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24692 elaboration circularities, it is possible to remove those warnings locally and
24693 obtain a program that will bind. Clearly this can be unsafe, and it is the
24694 responsibility of the programmer to make sure that the resulting program has no
24695 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24696 used with different granularity to suppress warnings and break elaboration
24697 circularities:
24698
24699 @itemize @bullet
24700 @item
24701 Place the pragma that names the called subprogram in the declarative part
24702 that contains the call.
24703
24704 @item
24705 Place the pragma in the declarative part, without naming an entity. This
24706 disables warnings on all calls in the corresponding  declarative region.
24707
24708 @item
24709 Place the pragma in the package spec that declares the called subprogram,
24710 and name the subprogram. This disables warnings on all elaboration calls to
24711 that subprogram.
24712
24713 @item
24714 Place the pragma in the package spec that declares the called subprogram,
24715 without naming any entity. This disables warnings on all elaboration calls to
24716 all subprograms declared in this spec.
24717
24718 @item Use Pragma Elaborate
24719 As previously described in section @xref{Treatment of Pragma Elaborate},
24720 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24721 that no elaboration checks are required on calls to the designated unit.
24722 There may be cases in which the caller knows that no transitive calls
24723 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24724 case where @code{pragma Elaborate_All} would cause a circularity.
24725 @end itemize
24726
24727 @noindent
24728 These five cases are listed in order of decreasing safety, and therefore
24729 require increasing programmer care in their application. Consider the
24730 following program:
24731
24732 @smallexample @c adanocomment
24733 package Pack1 is
24734   function F1 return Integer;
24735   X1 : Integer;
24736 end Pack1;
24737
24738 package Pack2 is
24739   function F2 return Integer;
24740   function Pure (x : integer) return integer;
24741   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24742   --  pragma Suppress (Elaboration_Check);              -- (4)
24743 end Pack2;
24744
24745 with Pack2;
24746 package body Pack1 is
24747   function F1 return Integer is
24748   begin
24749     return 100;
24750   end F1;
24751   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24752 begin
24753   declare
24754     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24755     --  pragma Suppress(Elaboration_Check);             -- (2)
24756   begin
24757     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24758   end;
24759 end Pack1;
24760
24761 with Pack1;
24762 package body Pack2 is
24763   function F2 return Integer is
24764   begin
24765      return Pack1.F1;
24766   end F2;
24767   function Pure (x : integer) return integer is
24768   begin
24769      return x ** 3 - 3 * x;
24770   end;
24771 end Pack2;
24772
24773 with Pack1, Ada.Text_IO;
24774 procedure Proc3 is
24775 begin
24776   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24777 end Proc3;
24778 @end smallexample
24779 In the absence of any pragmas, an attempt to bind this program produces
24780 the following diagnostics:
24781 @smallexample
24782 @group
24783 @iftex
24784 @leftskip=.5cm
24785 @end iftex
24786 error: elaboration circularity detected
24787 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24788 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24789 info:       recompile "pack1 (body)" with -gnatwl for full details
24790 info:          "pack1 (body)"
24791 info:             must be elaborated along with its spec:
24792 info:          "pack1 (spec)"
24793 info:             which is withed by:
24794 info:          "pack2 (body)"
24795 info:             which must be elaborated along with its spec:
24796 info:          "pack2 (spec)"
24797 info:             which is withed by:
24798 info:          "pack1 (body)"
24799 @end group
24800 @end smallexample
24801 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24802 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24803 F2 is safe, even though F2 calls F1, because the call appears after the
24804 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24805 remove the warning on the call. It is also possible to use pragma (2)
24806 because there are no other potentially unsafe calls in the block.
24807
24808 @noindent
24809 The call to @code{Pure} is safe because this function does not depend on the
24810 state of @code{Pack2}. Therefore any call to this function is safe, and it
24811 is correct to place pragma (3) in the corresponding package spec.
24812
24813 @noindent
24814 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24815 warnings on all calls to functions declared therein. Note that this is not
24816 necessarily safe, and requires more detailed examination of the subprogram
24817 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24818 be already elaborated.
24819 @end table
24820
24821 @noindent
24822 It is hard to generalize on which of these four approaches should be
24823 taken. Obviously if it is possible to fix the program so that the default
24824 treatment works, this is preferable, but this may not always be practical.
24825 It is certainly simple enough to use
24826 @option{-gnatE}
24827 but the danger in this case is that, even if the GNAT binder
24828 finds a correct elaboration order, it may not always do so,
24829 and certainly a binder from another Ada compiler might not. A
24830 combination of testing and analysis (for which the warnings generated
24831 with the
24832 @option{-gnatwl}
24833 switch can be useful) must be used to ensure that the program is free
24834 of errors. One switch that is useful in this testing is the
24835 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24836 switch for
24837 @code{gnatbind}.
24838 Normally the binder tries to find an order that has the best chance
24839 of avoiding elaboration problems. However, if this switch is used, the binder
24840 plays a devil's advocate role, and tries to choose the order that
24841 has the best chance of failing. If your program works even with this
24842 switch, then it has a better chance of being error free, but this is still
24843 not a guarantee.
24844
24845 For an example of this approach in action, consider the C-tests (executable
24846 tests) from the ACVC suite. If these are compiled and run with the default
24847 treatment, then all but one of them succeed without generating any error
24848 diagnostics from the binder. However, there is one test that fails, and
24849 this is not surprising, because the whole point of this test is to ensure
24850 that the compiler can handle cases where it is impossible to determine
24851 a correct order statically, and it checks that an exception is indeed
24852 raised at run time.
24853
24854 This one test must be compiled and run using the
24855 @option{-gnatE}
24856 switch, and then it passes. Alternatively, the entire suite can
24857 be run using this switch. It is never wrong to run with the dynamic
24858 elaboration switch if your code is correct, and we assume that the
24859 C-tests are indeed correct (it is less efficient, but efficiency is
24860 not a factor in running the ACVC tests.)
24861
24862 @node Elaboration for Access-to-Subprogram Values
24863 @section Elaboration for Access-to-Subprogram Values
24864 @cindex Access-to-subprogram
24865
24866 @noindent
24867 Access-to-subprogram types (introduced in Ada 95) complicate
24868 the handling of elaboration. The trouble is that it becomes
24869 impossible to tell at compile time which procedure
24870 is being called. This means that it is not possible for the binder
24871 to analyze the elaboration requirements in this case.
24872
24873 If at the point at which the access value is created
24874 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24875 the body of the subprogram is
24876 known to have been elaborated, then the access value is safe, and its use
24877 does not require a check. This may be achieved by appropriate arrangement
24878 of the order of declarations if the subprogram is in the current unit,
24879 or, if the subprogram is in another unit, by using pragma
24880 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24881 on the referenced unit.
24882
24883 If the referenced body is not known to have been elaborated at the point
24884 the access value is created, then any use of the access value must do a
24885 dynamic check, and this dynamic check will fail and raise a
24886 @code{Program_Error} exception if the body has not been elaborated yet.
24887 GNAT will generate the necessary checks, and in addition, if the
24888 @option{-gnatwl}
24889 switch is set, will generate warnings that such checks are required.
24890
24891 The use of dynamic dispatching for tagged types similarly generates
24892 a requirement for dynamic checks, and premature calls to any primitive
24893 operation of a tagged type before the body of the operation has been
24894 elaborated, will result in the raising of @code{Program_Error}.
24895
24896 @node Summary of Procedures for Elaboration Control
24897 @section Summary of Procedures for Elaboration Control
24898 @cindex Elaboration control
24899
24900 @noindent
24901 First, compile your program with the default options, using none of
24902 the special elaboration control switches. If the binder successfully
24903 binds your program, then you can be confident that, apart from issues
24904 raised by the use of access-to-subprogram types and dynamic dispatching,
24905 the program is free of elaboration errors. If it is important that the
24906 program be portable, then use the
24907 @option{-gnatwl}
24908 switch to generate warnings about missing @code{Elaborate} or
24909 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24910
24911 If the program fails to bind using the default static elaboration
24912 handling, then you can fix the program to eliminate the binder
24913 message, or recompile the entire program with the
24914 @option{-gnatE} switch to generate dynamic elaboration checks,
24915 and, if you are sure there really are no elaboration problems,
24916 use a global pragma @code{Suppress (Elaboration_Check)}.
24917
24918 @node Other Elaboration Order Considerations
24919 @section Other Elaboration Order Considerations
24920 @noindent
24921 This section has been entirely concerned with the issue of finding a valid
24922 elaboration order, as defined by the Ada Reference Manual. In a case
24923 where several elaboration orders are valid, the task is to find one
24924 of the possible valid elaboration orders (and the static model in GNAT
24925 will ensure that this is achieved).
24926
24927 The purpose of the elaboration rules in the Ada Reference Manual is to
24928 make sure that no entity is accessed before it has been elaborated. For
24929 a subprogram, this means that the spec and body must have been elaborated
24930 before the subprogram is called. For an object, this means that the object
24931 must have been elaborated before its value is read or written. A violation
24932 of either of these two requirements is an access before elaboration order,
24933 and this section has been all about avoiding such errors.
24934
24935 In the case where more than one order of elaboration is possible, in the
24936 sense that access before elaboration errors are avoided, then any one of
24937 the orders is ``correct'' in the sense that it meets the requirements of
24938 the Ada Reference Manual, and no such error occurs.
24939
24940 However, it may be the case for a given program, that there are
24941 constraints on the order of elaboration that come not from consideration
24942 of avoiding elaboration errors, but rather from extra-lingual logic
24943 requirements. Consider this example:
24944
24945 @smallexample @c ada
24946 with Init_Constants;
24947 package Constants is
24948    X : Integer := 0;
24949    Y : Integer := 0;
24950 end Constants;
24951
24952 package Init_Constants is
24953    procedure P; -- require a body
24954 end Init_Constants;
24955
24956 with Constants;
24957 package body Init_Constants is
24958    procedure P is begin null; end;
24959 begin
24960    Constants.X := 3;
24961    Constants.Y := 4;
24962 end Init_Constants;
24963
24964 with Constants;
24965 package Calc is
24966    Z : Integer := Constants.X + Constants.Y;
24967 end Calc;
24968
24969 with Calc;
24970 with Text_IO; use Text_IO;
24971 procedure Main is
24972 begin
24973    Put_Line (Calc.Z'Img);
24974 end Main;
24975 @end smallexample
24976
24977 @noindent
24978 In this example, there is more than one valid order of elaboration. For
24979 example both the following are correct orders:
24980
24981 @smallexample
24982 Init_Constants spec
24983 Constants spec
24984 Calc spec
24985 Init_Constants body
24986 Main body
24987
24988   and
24989
24990 Init_Constants spec
24991 Init_Constants body
24992 Constants spec
24993 Calc spec
24994 Main body
24995 @end smallexample
24996
24997 @noindent
24998 There is no language rule to prefer one or the other, both are correct
24999 from an order of elaboration point of view. But the programmatic effects
25000 of the two orders are very different. In the first, the elaboration routine
25001 of @code{Calc} initializes @code{Z} to zero, and then the main program
25002 runs with this value of zero. But in the second order, the elaboration
25003 routine of @code{Calc} runs after the body of Init_Constants has set
25004 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25005 runs.
25006
25007 One could perhaps by applying pretty clever non-artificial intelligence
25008 to the situation guess that it is more likely that the second order of
25009 elaboration is the one desired, but there is no formal linguistic reason
25010 to prefer one over the other. In fact in this particular case, GNAT will
25011 prefer the second order, because of the rule that bodies are elaborated
25012 as soon as possible, but it's just luck that this is what was wanted
25013 (if indeed the second order was preferred).
25014
25015 If the program cares about the order of elaboration routines in a case like
25016 this, it is important to specify the order required. In this particular
25017 case, that could have been achieved by adding to the spec of Calc:
25018
25019 @smallexample @c ada
25020 pragma Elaborate_All (Constants);
25021 @end smallexample
25022
25023 @noindent
25024 which requires that the body (if any) and spec of @code{Constants},
25025 as well as the body and spec of any unit @code{with}'ed by
25026 @code{Constants} be elaborated before @code{Calc} is elaborated.
25027
25028 Clearly no automatic method can always guess which alternative you require,
25029 and if you are working with legacy code that had constraints of this kind
25030 which were not properly specified by adding @code{Elaborate} or
25031 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25032 compilers can choose different orders.
25033
25034 However, GNAT does attempt to diagnose the common situation where there
25035 are uninitialized variables in the visible part of a package spec, and the
25036 corresponding package body has an elaboration block that directly or
25037 indirectly initialized one or more of these variables. This is the situation
25038 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25039 a warning that suggests this addition if it detects this situation.
25040
25041 The @code{gnatbind}
25042 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25043 out problems. This switch causes bodies to be elaborated as late as possible
25044 instead of as early as possible. In the example above, it would have forced
25045 the choice of the first elaboration order. If you get different results
25046 when using this switch, and particularly if one set of results is right,
25047 and one is wrong as far as you are concerned, it shows that you have some
25048 missing @code{Elaborate} pragmas. For the example above, we have the
25049 following output:
25050
25051 @smallexample
25052 gnatmake -f -q main
25053 main
25054  7
25055 gnatmake -f -q main -bargs -p
25056 main
25057  0
25058 @end smallexample
25059
25060 @noindent
25061 It is of course quite unlikely that both these results are correct, so
25062 it is up to you in a case like this to investigate the source of the
25063 difference, by looking at the two elaboration orders that are chosen,
25064 and figuring out which is correct, and then adding the necessary
25065 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25066
25067
25068
25069 @c *******************************
25070 @node Conditional Compilation
25071 @appendix Conditional Compilation
25072 @c *******************************
25073 @cindex Conditional compilation
25074
25075 @noindent
25076 It is often necessary to arrange for a single source program
25077 to serve multiple purposes, where it is compiled in different
25078 ways to achieve these different goals. Some examples of the
25079 need for this feature are
25080
25081 @itemize @bullet
25082 @item  Adapting a program to a different hardware environment
25083 @item  Adapting a program to a different target architecture
25084 @item  Turning debugging features on and off
25085 @item  Arranging for a program to compile with different compilers
25086 @end itemize
25087
25088 @noindent
25089 In C, or C++, the typical approach would be to use the preprocessor
25090 that is defined as part of the language. The Ada language does not
25091 contain such a feature. This is not an oversight, but rather a very
25092 deliberate design decision, based on the experience that overuse of
25093 the preprocessing features in C and C++ can result in programs that
25094 are extremely difficult to maintain. For example, if we have ten
25095 switches that can be on or off, this means that there are a thousand
25096 separate programs, any one of which might not even be syntactically
25097 correct, and even if syntactically correct, the resulting program
25098 might not work correctly. Testing all combinations can quickly become
25099 impossible.
25100
25101 Nevertheless, the need to tailor programs certainly exists, and in
25102 this Appendix we will discuss how this can
25103 be achieved using Ada in general, and GNAT in particular.
25104
25105 @menu
25106 * Use of Boolean Constants::
25107 * Debugging - A Special Case::
25108 * Conditionalizing Declarations::
25109 * Use of Alternative Implementations::
25110 * Preprocessing::
25111 @end menu
25112
25113 @node Use of Boolean Constants
25114 @section Use of Boolean Constants
25115
25116 @noindent
25117 In the case where the difference is simply which code
25118 sequence is executed, the cleanest solution is to use Boolean
25119 constants to control which code is executed.
25120
25121 @smallexample @c ada
25122 @group
25123 FP_Initialize_Required : constant Boolean := True;
25124 @dots{}
25125 if FP_Initialize_Required then
25126 @dots{}
25127 end if;
25128 @end group
25129 @end smallexample
25130
25131 @noindent
25132 Not only will the code inside the @code{if} statement not be executed if
25133 the constant Boolean is @code{False}, but it will also be completely
25134 deleted from the program.
25135 However, the code is only deleted after the @code{if} statement
25136 has been checked for syntactic and semantic correctness.
25137 (In contrast, with preprocessors the code is deleted before the
25138 compiler ever gets to see it, so it is not checked until the switch
25139 is turned on.)
25140 @cindex Preprocessors (contrasted with conditional compilation)
25141
25142 Typically the Boolean constants will be in a separate package,
25143 something like:
25144
25145 @smallexample @c ada
25146 @group
25147 package Config is
25148    FP_Initialize_Required : constant Boolean := True;
25149    Reset_Available        : constant Boolean := False;
25150    @dots{}
25151 end Config;
25152 @end group
25153 @end smallexample
25154
25155 @noindent
25156 The @code{Config} package exists in multiple forms for the various targets,
25157 with an appropriate script selecting the version of @code{Config} needed.
25158 Then any other unit requiring conditional compilation can do a @code{with}
25159 of @code{Config} to make the constants visible.
25160
25161
25162 @node Debugging - A Special Case
25163 @section Debugging - A Special Case
25164
25165 @noindent
25166 A common use of conditional code is to execute statements (for example
25167 dynamic checks, or output of intermediate results) under control of a
25168 debug switch, so that the debugging behavior can be turned on and off.
25169 This can be done using a Boolean constant to control whether the code
25170 is active:
25171
25172 @smallexample @c ada
25173 @group
25174 if Debugging then
25175    Put_Line ("got to the first stage!");
25176 end if;
25177 @end group
25178 @end smallexample
25179
25180 @noindent
25181 or
25182
25183 @smallexample @c ada
25184 @group
25185 if Debugging and then Temperature > 999.0 then
25186    raise Temperature_Crazy;
25187 end if;
25188 @end group
25189 @end smallexample
25190
25191 @noindent
25192 Since this is a common case, there are special features to deal with
25193 this in a convenient manner. For the case of tests, Ada 2005 has added
25194 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25195 @cindex pragma @code{Assert}
25196 on the @code{Assert} pragma that has always been available in GNAT, so this
25197 feature may be used with GNAT even if you are not using Ada 2005 features.
25198 The use of pragma @code{Assert} is described in
25199 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25200 example, the last test could be written:
25201
25202 @smallexample @c ada
25203 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25204 @end smallexample
25205
25206 @noindent
25207 or simply
25208
25209 @smallexample @c ada
25210 pragma Assert (Temperature <= 999.0);
25211 @end smallexample
25212
25213 @noindent
25214 In both cases, if assertions are active and the temperature is excessive,
25215 the exception @code{Assert_Failure} will be raised, with the given string in
25216 the first case or a string indicating the location of the pragma in the second
25217 case used as the exception message.
25218
25219 You can turn assertions on and off by using the @code{Assertion_Policy}
25220 pragma.
25221 @cindex pragma @code{Assertion_Policy}
25222 This is an Ada 2005 pragma which is implemented in all modes by
25223 GNAT, but only in the latest versions of GNAT which include Ada 2005
25224 capability. Alternatively, you can use the @option{-gnata} switch
25225 @cindex @option{-gnata} switch
25226 to enable assertions from the command line (this is recognized by all versions
25227 of GNAT).
25228
25229 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25230 @code{Debug} can be used:
25231 @cindex pragma @code{Debug}
25232
25233 @smallexample @c ada
25234 pragma Debug (Put_Line ("got to the first stage!"));
25235 @end smallexample
25236
25237 @noindent
25238 If debug pragmas are enabled, the argument, which must be of the form of
25239 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25240 Only one call can be present, but of course a special debugging procedure
25241 containing any code you like can be included in the program and then
25242 called in a pragma @code{Debug} argument as needed.
25243
25244 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25245 construct is that pragma @code{Debug} can appear in declarative contexts,
25246 such as at the very beginning of a procedure, before local declarations have
25247 been elaborated.
25248
25249 Debug pragmas are enabled using either the @option{-gnata} switch that also
25250 controls assertions, or with a separate Debug_Policy pragma.
25251 @cindex pragma @code{Debug_Policy}
25252 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25253 in Ada 95 and Ada 83 programs as well), and is analogous to
25254 pragma @code{Assertion_Policy} to control assertions.
25255
25256 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25257 and thus they can appear in @file{gnat.adc} if you are not using a
25258 project file, or in the file designated to contain configuration pragmas
25259 in a project file.
25260 They then apply to all subsequent compilations. In practice the use of
25261 the @option{-gnata} switch is often the most convenient method of controlling
25262 the status of these pragmas.
25263
25264 Note that a pragma is not a statement, so in contexts where a statement
25265 sequence is required, you can't just write a pragma on its own. You have
25266 to add a @code{null} statement.
25267
25268 @smallexample @c ada
25269 @group
25270 if @dots{} then
25271    @dots{} -- some statements
25272 else
25273    pragma Assert (Num_Cases < 10);
25274    null;
25275 end if;
25276 @end group
25277 @end smallexample
25278
25279
25280 @node Conditionalizing Declarations
25281 @section Conditionalizing Declarations
25282
25283 @noindent
25284 In some cases, it may be necessary to conditionalize declarations to meet
25285 different requirements. For example we might want a bit string whose length
25286 is set to meet some hardware message requirement.
25287
25288 In some cases, it may be possible to do this using declare blocks controlled
25289 by conditional constants:
25290
25291 @smallexample @c ada
25292 @group
25293 if Small_Machine then
25294    declare
25295       X : Bit_String (1 .. 10);
25296    begin
25297       @dots{}
25298    end;
25299 else
25300    declare
25301       X : Large_Bit_String (1 .. 1000);
25302    begin
25303       @dots{}
25304    end;
25305 end if;
25306 @end group
25307 @end smallexample
25308
25309 @noindent
25310 Note that in this approach, both declarations are analyzed by the
25311 compiler so this can only be used where both declarations are legal,
25312 even though one of them will not be used.
25313
25314 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25315 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25316 that are parameterized by these constants. For example
25317
25318 @smallexample @c ada
25319 @group
25320 for Rec use
25321   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25322 end record;
25323 @end group
25324 @end smallexample
25325
25326 @noindent
25327 If @code{Bits_Per_Word} is set to 32, this generates either
25328
25329 @smallexample @c ada
25330 @group
25331 for Rec use
25332   Field1 at 0 range 0 .. 32;
25333 end record;
25334 @end group
25335 @end smallexample
25336
25337 @noindent
25338 for the big endian case, or
25339
25340 @smallexample @c ada
25341 @group
25342 for Rec use record
25343   Field1 at 0 range 10 .. 32;
25344 end record;
25345 @end group
25346 @end smallexample
25347
25348 @noindent
25349 for the little endian case. Since a powerful subset of Ada expression
25350 notation is usable for creating static constants, clever use of this
25351 feature can often solve quite difficult problems in conditionalizing
25352 compilation (note incidentally that in Ada 95, the little endian
25353 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25354 need to define this one yourself).
25355
25356
25357 @node Use of Alternative Implementations
25358 @section Use of Alternative Implementations
25359
25360 @noindent
25361 In some cases, none of the approaches described above are adequate. This
25362 can occur for example if the set of declarations required is radically
25363 different for two different configurations.
25364
25365 In this situation, the official Ada way of dealing with conditionalizing
25366 such code is to write separate units for the different cases. As long as
25367 this does not result in excessive duplication of code, this can be done
25368 without creating maintenance problems. The approach is to share common
25369 code as far as possible, and then isolate the code and declarations
25370 that are different. Subunits are often a convenient method for breaking
25371 out a piece of a unit that is to be conditionalized, with separate files
25372 for different versions of the subunit for different targets, where the
25373 build script selects the right one to give to the compiler.
25374 @cindex Subunits (and conditional compilation)
25375
25376 As an example, consider a situation where a new feature in Ada 2005
25377 allows something to be done in a really nice way. But your code must be able
25378 to compile with an Ada 95 compiler. Conceptually you want to say:
25379
25380 @smallexample @c ada
25381 @group
25382 if Ada_2005 then
25383    @dots{} neat Ada 2005 code
25384 else
25385    @dots{} not quite as neat Ada 95 code
25386 end if;
25387 @end group
25388 @end smallexample
25389
25390 @noindent
25391 where @code{Ada_2005} is a Boolean constant.
25392
25393 But this won't work when @code{Ada_2005} is set to @code{False},
25394 since the @code{then} clause will be illegal for an Ada 95 compiler.
25395 (Recall that although such unreachable code would eventually be deleted
25396 by the compiler, it still needs to be legal.  If it uses features
25397 introduced in Ada 2005, it will be illegal in Ada 95.)
25398
25399 So instead we write
25400
25401 @smallexample @c ada
25402 procedure Insert is separate;
25403 @end smallexample
25404
25405 @noindent
25406 Then we have two files for the subunit @code{Insert}, with the two sets of
25407 code.
25408 If the package containing this is called @code{File_Queries}, then we might
25409 have two files
25410
25411 @itemize @bullet
25412 @item    @file{file_queries-insert-2005.adb}
25413 @item    @file{file_queries-insert-95.adb}
25414 @end itemize
25415
25416 @noindent
25417 and the build script renames the appropriate file to
25418
25419 @smallexample
25420 file_queries-insert.adb
25421 @end smallexample
25422
25423 @noindent
25424 and then carries out the compilation.
25425
25426 This can also be done with project files' naming schemes. For example:
25427
25428 @smallexample @c project
25429 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25430 @end smallexample
25431
25432 @noindent
25433 Note also that with project files it is desirable to use a different extension
25434 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25435 conflict may arise through another commonly used feature: to declare as part
25436 of the project a set of directories containing all the sources obeying the
25437 default naming scheme.
25438
25439 The use of alternative units is certainly feasible in all situations,
25440 and for example the Ada part of the GNAT run-time is conditionalized
25441 based on the target architecture using this approach. As a specific example,
25442 consider the implementation of the AST feature in VMS. There is one
25443 spec:
25444
25445 @smallexample
25446 s-asthan.ads
25447 @end smallexample
25448
25449 @noindent
25450 which is the same for all architectures, and three bodies:
25451
25452 @table @file
25453 @item    s-asthan.adb
25454 used for all non-VMS operating systems
25455 @item    s-asthan-vms-alpha.adb
25456 used for VMS on the Alpha
25457 @item    s-asthan-vms-ia64.adb
25458 used for VMS on the ia64
25459 @end table
25460
25461 @noindent
25462 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25463 this operating system feature is not available, and the two remaining
25464 versions interface with the corresponding versions of VMS to provide
25465 VMS-compatible AST handling. The GNAT build script knows the architecture
25466 and operating system, and automatically selects the right version,
25467 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25468
25469 Another style for arranging alternative implementations is through Ada's
25470 access-to-subprogram facility.
25471 In case some functionality is to be conditionally included,
25472 you can declare an access-to-procedure variable @code{Ref} that is initialized
25473 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25474 when appropriate.
25475 In some library package, set @code{Ref} to @code{Proc'Access} for some
25476 procedure @code{Proc} that performs the relevant processing.
25477 The initialization only occurs if the library package is included in the
25478 program.
25479 The same idea can also be implemented using tagged types and dispatching
25480 calls.
25481
25482
25483 @node Preprocessing
25484 @section Preprocessing
25485 @cindex Preprocessing
25486
25487 @noindent
25488 Although it is quite possible to conditionalize code without the use of
25489 C-style preprocessing, as described earlier in this section, it is
25490 nevertheless convenient in some cases to use the C approach. Moreover,
25491 older Ada compilers have often provided some preprocessing capability,
25492 so legacy code may depend on this approach, even though it is not
25493 standard.
25494
25495 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25496 extent on the various preprocessors that have been used
25497 with legacy code on other compilers, to enable easier transition).
25498
25499 The preprocessor may be used in two separate modes. It can be used quite
25500 separately from the compiler, to generate a separate output source file
25501 that is then fed to the compiler as a separate step. This is the
25502 @code{gnatprep} utility, whose use is fully described in
25503 @ref{Preprocessing Using gnatprep}.
25504 @cindex @code{gnatprep}
25505
25506 The preprocessing language allows such constructs as
25507
25508 @smallexample
25509 @group
25510 #if DEBUG or PRIORITY > 4 then
25511    bunch of declarations
25512 #else
25513    completely different bunch of declarations
25514 #end if;
25515 @end group
25516 @end smallexample
25517
25518 @noindent
25519 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25520 defined either on the command line or in a separate file.
25521
25522 The other way of running the preprocessor is even closer to the C style and
25523 often more convenient. In this approach the preprocessing is integrated into
25524 the compilation process. The compiler is fed the preprocessor input which
25525 includes @code{#if} lines etc, and then the compiler carries out the
25526 preprocessing internally and processes the resulting output.
25527 For more details on this approach, see @ref{Integrated Preprocessing}.
25528
25529
25530 @c *******************************
25531 @node Inline Assembler
25532 @appendix Inline Assembler
25533 @c *******************************
25534
25535 @noindent
25536 If you need to write low-level software that interacts directly
25537 with the hardware, Ada provides two ways to incorporate assembly
25538 language code into your program.  First, you can import and invoke
25539 external routines written in assembly language, an Ada feature fully
25540 supported by GNAT@.  However, for small sections of code it may be simpler
25541 or more efficient to include assembly language statements directly
25542 in your Ada source program, using the facilities of the implementation-defined
25543 package @code{System.Machine_Code}, which incorporates the gcc
25544 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25545 including the following:
25546
25547 @itemize @bullet
25548 @item No need to use non-Ada tools
25549 @item Consistent interface over different targets
25550 @item Automatic usage of the proper calling conventions
25551 @item Access to Ada constants and variables
25552 @item Definition of intrinsic routines
25553 @item Possibility of inlining a subprogram comprising assembler code
25554 @item Code optimizer can take Inline Assembler code into account
25555 @end itemize
25556
25557 This chapter presents a series of examples to show you how to use
25558 the Inline Assembler.  Although it focuses on the Intel x86,
25559 the general approach applies also to other processors.
25560 It is assumed that you are familiar with Ada
25561 and with assembly language programming.
25562
25563 @menu
25564 * Basic Assembler Syntax::
25565 * A Simple Example of Inline Assembler::
25566 * Output Variables in Inline Assembler::
25567 * Input Variables in Inline Assembler::
25568 * Inlining Inline Assembler Code::
25569 * Other Asm Functionality::
25570 @end menu
25571
25572 @c ---------------------------------------------------------------------------
25573 @node Basic Assembler Syntax
25574 @section Basic Assembler Syntax
25575
25576 @noindent
25577 The assembler used by GNAT and gcc is based not on the Intel assembly
25578 language, but rather on a language that descends from the AT&T Unix
25579 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25580 The following table summarizes the main features of @emph{as} syntax
25581 and points out the differences from the Intel conventions.
25582 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25583 pre-processor) documentation for further information.
25584
25585 @table @asis
25586 @item Register names
25587 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25588 @*
25589 Intel: No extra punctuation; for example @code{eax}
25590
25591 @item Immediate operand
25592 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25593 @*
25594 Intel: No extra punctuation; for example @code{4}
25595
25596 @item Address
25597 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25598 @*
25599 Intel: No extra punctuation; for example @code{loc}
25600
25601 @item Memory contents
25602 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25603 @*
25604 Intel: Square brackets; for example @code{[loc]}
25605
25606 @item Register contents
25607 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25608 @*
25609 Intel: Square brackets; for example @code{[eax]}
25610
25611 @item Hexadecimal numbers
25612 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25613 @*
25614 Intel: Trailing ``h''; for example @code{A0h}
25615
25616 @item Operand size
25617 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25618 a 16-bit word
25619 @*
25620 Intel: Implicit, deduced by assembler; for example @code{mov}
25621
25622 @item Instruction repetition
25623 gcc / @emph{as}: Split into two lines; for example
25624 @*
25625 @code{rep}
25626 @*
25627 @code{stosl}
25628 @*
25629 Intel: Keep on one line; for example @code{rep stosl}
25630
25631 @item Order of operands
25632 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25633 @*
25634 Intel: Destination first; for example @code{mov eax, 4}
25635 @end table
25636
25637 @c ---------------------------------------------------------------------------
25638 @node A Simple Example of Inline Assembler
25639 @section A Simple Example of Inline Assembler
25640
25641 @noindent
25642 The following example will generate a single assembly language statement,
25643 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25644 the example will be useful in illustrating the basics of
25645 the Inline Assembler facility.
25646
25647 @smallexample @c ada
25648 @group
25649 with System.Machine_Code; use System.Machine_Code;
25650 procedure Nothing is
25651 begin
25652    Asm ("nop");
25653 end Nothing;
25654 @end group
25655 @end smallexample
25656
25657 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25658 here it takes one parameter, a @emph{template string} that must be a static
25659 expression and that will form the generated instruction.
25660 @code{Asm} may be regarded as a compile-time procedure that parses
25661 the template string and additional parameters (none here),
25662 from which it generates a sequence of assembly language instructions.
25663
25664 The examples in this chapter will illustrate several of the forms
25665 for invoking @code{Asm}; a complete specification of the syntax
25666 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25667 Manual}.
25668
25669 Under the standard GNAT conventions, the @code{Nothing} procedure
25670 should be in a file named @file{nothing.adb}.
25671 You can build the executable in the usual way:
25672 @smallexample
25673 gnatmake nothing
25674 @end smallexample
25675 However, the interesting aspect of this example is not its run-time behavior
25676 but rather the generated assembly code.
25677 To see this output, invoke the compiler as follows:
25678 @smallexample
25679    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25680 @end smallexample
25681 where the options are:
25682
25683 @table @code
25684 @item -c
25685 compile only (no bind or link)
25686 @item -S
25687 generate assembler listing
25688 @item -fomit-frame-pointer
25689 do not set up separate stack frames
25690 @item -gnatp
25691 do not add runtime checks
25692 @end table
25693
25694 This gives a human-readable assembler version of the code. The resulting
25695 file will have the same name as the Ada source file, but with a @code{.s}
25696 extension. In our example, the file @file{nothing.s} has the following
25697 contents:
25698
25699 @smallexample
25700 @group
25701 .file "nothing.adb"
25702 gcc2_compiled.:
25703 ___gnu_compiled_ada:
25704 .text
25705    .align 4
25706 .globl __ada_nothing
25707 __ada_nothing:
25708 #APP
25709    nop
25710 #NO_APP
25711    jmp L1
25712    .align 2,0x90
25713 L1:
25714    ret
25715 @end group
25716 @end smallexample
25717
25718 The assembly code you included is clearly indicated by
25719 the compiler, between the @code{#APP} and @code{#NO_APP}
25720 delimiters. The character before the 'APP' and 'NOAPP'
25721 can differ on different targets. For example, GNU/Linux uses '#APP' while
25722 on NT you will see '/APP'.
25723
25724 If you make a mistake in your assembler code (such as using the
25725 wrong size modifier, or using a wrong operand for the instruction) GNAT
25726 will report this error in a temporary file, which will be deleted when
25727 the compilation is finished.  Generating an assembler file will help
25728 in such cases, since you can assemble this file separately using the
25729 @emph{as} assembler that comes with gcc.
25730
25731 Assembling the file using the command
25732
25733 @smallexample
25734 as @file{nothing.s}
25735 @end smallexample
25736 @noindent
25737 will give you error messages whose lines correspond to the assembler
25738 input file, so you can easily find and correct any mistakes you made.
25739 If there are no errors, @emph{as} will generate an object file
25740 @file{nothing.out}.
25741
25742 @c ---------------------------------------------------------------------------
25743 @node Output Variables in Inline Assembler
25744 @section Output Variables in Inline Assembler
25745
25746 @noindent
25747 The examples in this section, showing how to access the processor flags,
25748 illustrate how to specify the destination operands for assembly language
25749 statements.
25750
25751 @smallexample @c ada
25752 @group
25753 with Interfaces; use Interfaces;
25754 with Ada.Text_IO; use Ada.Text_IO;
25755 with System.Machine_Code; use System.Machine_Code;
25756 procedure Get_Flags is
25757    Flags : Unsigned_32;
25758    use ASCII;
25759 begin
25760    Asm ("pushfl"          & LF & HT & -- push flags on stack
25761         "popl %%eax"      & LF & HT & -- load eax with flags
25762         "movl %%eax, %0",             -- store flags in variable
25763         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25764    Put_Line ("Flags register:" & Flags'Img);
25765 end Get_Flags;
25766 @end group
25767 @end smallexample
25768
25769 In order to have a nicely aligned assembly listing, we have separated
25770 multiple assembler statements in the Asm template string with linefeed
25771 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25772 The resulting section of the assembly output file is:
25773
25774 @smallexample
25775 @group
25776 #APP
25777    pushfl
25778    popl %eax
25779    movl %eax, -40(%ebp)
25780 #NO_APP
25781 @end group
25782 @end smallexample
25783
25784 It would have been legal to write the Asm invocation as:
25785
25786 @smallexample
25787 Asm ("pushfl popl %%eax movl %%eax, %0")
25788 @end smallexample
25789
25790 but in the generated assembler file, this would come out as:
25791
25792 @smallexample
25793 #APP
25794    pushfl popl %eax movl %eax, -40(%ebp)
25795 #NO_APP
25796 @end smallexample
25797
25798 which is not so convenient for the human reader.
25799
25800 We use Ada comments
25801 at the end of each line to explain what the assembler instructions
25802 actually do.  This is a useful convention.
25803
25804 When writing Inline Assembler instructions, you need to precede each register
25805 and variable name with a percent sign.  Since the assembler already requires
25806 a percent sign at the beginning of a register name, you need two consecutive
25807 percent signs for such names in the Asm template string, thus @code{%%eax}.
25808 In the generated assembly code, one of the percent signs will be stripped off.
25809
25810 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25811 variables: operands you later define using @code{Input} or @code{Output}
25812 parameters to @code{Asm}.
25813 An output variable is illustrated in
25814 the third statement in the Asm template string:
25815 @smallexample
25816 movl %%eax, %0
25817 @end smallexample
25818 The intent is to store the contents of the eax register in a variable that can
25819 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25820 necessarily work, since the compiler might optimize by using a register
25821 to hold Flags, and the expansion of the @code{movl} instruction would not be
25822 aware of this optimization.  The solution is not to store the result directly
25823 but rather to advise the compiler to choose the correct operand form;
25824 that is the purpose of the @code{%0} output variable.
25825
25826 Information about the output variable is supplied in the @code{Outputs}
25827 parameter to @code{Asm}:
25828 @smallexample
25829 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25830 @end smallexample
25831
25832 The output is defined by the @code{Asm_Output} attribute of the target type;
25833 the general format is
25834 @smallexample
25835 Type'Asm_Output (constraint_string, variable_name)
25836 @end smallexample
25837
25838 The constraint string directs the compiler how
25839 to store/access the associated variable.  In the example
25840 @smallexample
25841 Unsigned_32'Asm_Output ("=m", Flags);
25842 @end smallexample
25843 the @code{"m"} (memory) constraint tells the compiler that the variable
25844 @code{Flags} should be stored in a memory variable, thus preventing
25845 the optimizer from keeping it in a register.  In contrast,
25846 @smallexample
25847 Unsigned_32'Asm_Output ("=r", Flags);
25848 @end smallexample
25849 uses the @code{"r"} (register) constraint, telling the compiler to
25850 store the variable in a register.
25851
25852 If the constraint is preceded by the equal character (@strong{=}), it tells
25853 the compiler that the variable will be used to store data into it.
25854
25855 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25856 allowing the optimizer to choose whatever it deems best.
25857
25858 There are a fairly large number of constraints, but the ones that are
25859 most useful (for the Intel x86 processor) are the following:
25860
25861 @table @code
25862 @item =
25863 output constraint
25864 @item g
25865 global (i.e.@: can be stored anywhere)
25866 @item m
25867 in memory
25868 @item I
25869 a constant
25870 @item a
25871 use eax
25872 @item b
25873 use ebx
25874 @item c
25875 use ecx
25876 @item d
25877 use edx
25878 @item S
25879 use esi
25880 @item D
25881 use edi
25882 @item r
25883 use one of eax, ebx, ecx or edx
25884 @item q
25885 use one of eax, ebx, ecx, edx, esi or edi
25886 @end table
25887
25888 The full set of constraints is described in the gcc and @emph{as}
25889 documentation; note that it is possible to combine certain constraints
25890 in one constraint string.
25891
25892 You specify the association of an output variable with an assembler operand
25893 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25894 integer.  Thus in
25895 @smallexample @c ada
25896 @group
25897 Asm ("pushfl"          & LF & HT & -- push flags on stack
25898      "popl %%eax"      & LF & HT & -- load eax with flags
25899      "movl %%eax, %0",             -- store flags in variable
25900      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25901 @end group
25902 @end smallexample
25903 @noindent
25904 @code{%0} will be replaced in the expanded code by the appropriate operand,
25905 whatever
25906 the compiler decided for the @code{Flags} variable.
25907
25908 In general, you may have any number of output variables:
25909 @itemize @bullet
25910 @item
25911 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25912 @item
25913 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25914 of @code{Asm_Output} attributes
25915 @end itemize
25916
25917 For example:
25918 @smallexample @c ada
25919 @group
25920 Asm ("movl %%eax, %0" & LF & HT &
25921      "movl %%ebx, %1" & LF & HT &
25922      "movl %%ecx, %2",
25923      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25924                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25925                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25926 @end group
25927 @end smallexample
25928 @noindent
25929 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25930 in the Ada program.
25931
25932 As a variation on the @code{Get_Flags} example, we can use the constraints
25933 string to direct the compiler to store the eax register into the @code{Flags}
25934 variable, instead of including the store instruction explicitly in the
25935 @code{Asm} template string:
25936
25937 @smallexample @c ada
25938 @group
25939 with Interfaces; use Interfaces;
25940 with Ada.Text_IO; use Ada.Text_IO;
25941 with System.Machine_Code; use System.Machine_Code;
25942 procedure Get_Flags_2 is
25943    Flags : Unsigned_32;
25944    use ASCII;
25945 begin
25946    Asm ("pushfl"      & LF & HT & -- push flags on stack
25947         "popl %%eax",             -- save flags in eax
25948         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25949    Put_Line ("Flags register:" & Flags'Img);
25950 end Get_Flags_2;
25951 @end group
25952 @end smallexample
25953
25954 @noindent
25955 The @code{"a"} constraint tells the compiler that the @code{Flags}
25956 variable will come from the eax register. Here is the resulting code:
25957
25958 @smallexample
25959 @group
25960 #APP
25961    pushfl
25962    popl %eax
25963 #NO_APP
25964    movl %eax,-40(%ebp)
25965 @end group
25966 @end smallexample
25967
25968 @noindent
25969 The compiler generated the store of eax into Flags after
25970 expanding the assembler code.
25971
25972 Actually, there was no need to pop the flags into the eax register;
25973 more simply, we could just pop the flags directly into the program variable:
25974
25975 @smallexample @c ada
25976 @group
25977 with Interfaces; use Interfaces;
25978 with Ada.Text_IO; use Ada.Text_IO;
25979 with System.Machine_Code; use System.Machine_Code;
25980 procedure Get_Flags_3 is
25981    Flags : Unsigned_32;
25982    use ASCII;
25983 begin
25984    Asm ("pushfl"  & LF & HT & -- push flags on stack
25985         "pop %0",             -- save flags in Flags
25986         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25987    Put_Line ("Flags register:" & Flags'Img);
25988 end Get_Flags_3;
25989 @end group
25990 @end smallexample
25991
25992 @c ---------------------------------------------------------------------------
25993 @node Input Variables in Inline Assembler
25994 @section Input Variables in Inline Assembler
25995
25996 @noindent
25997 The example in this section illustrates how to specify the source operands
25998 for assembly language statements.
25999 The program simply increments its input value by 1:
26000
26001 @smallexample @c ada
26002 @group
26003 with Interfaces; use Interfaces;
26004 with Ada.Text_IO; use Ada.Text_IO;
26005 with System.Machine_Code; use System.Machine_Code;
26006 procedure Increment is
26007
26008    function Incr (Value : Unsigned_32) return Unsigned_32 is
26009       Result : Unsigned_32;
26010    begin
26011       Asm ("incl %0",
26012            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26013            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26014       return Result;
26015    end Incr;
26016
26017    Value : Unsigned_32;
26018
26019 begin
26020    Value := 5;
26021    Put_Line ("Value before is" & Value'Img);
26022    Value := Incr (Value);
26023    Put_Line ("Value after is" & Value'Img);
26024 end Increment;
26025 @end group
26026 @end smallexample
26027
26028 The @code{Outputs} parameter to @code{Asm} specifies
26029 that the result will be in the eax register and that it is to be stored
26030 in the @code{Result} variable.
26031
26032 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26033 but with an @code{Asm_Input} attribute.
26034 The @code{"="} constraint, indicating an output value, is not present.
26035
26036 You can have multiple input variables, in the same way that you can have more
26037 than one output variable.
26038
26039 The parameter count (%0, %1) etc, now starts at the first input
26040 statement, and continues with the output statements.
26041 When both parameters use the same variable, the
26042 compiler will treat them as the same %n operand, which is the case here.
26043
26044 Just as the @code{Outputs} parameter causes the register to be stored into the
26045 target variable after execution of the assembler statements, so does the
26046 @code{Inputs} parameter cause its variable to be loaded into the register
26047 before execution of the assembler statements.
26048
26049 Thus the effect of the @code{Asm} invocation is:
26050 @enumerate
26051 @item load the 32-bit value of @code{Value} into eax
26052 @item execute the @code{incl %eax} instruction
26053 @item store the contents of eax into the @code{Result} variable
26054 @end enumerate
26055
26056 The resulting assembler file (with @option{-O2} optimization) contains:
26057 @smallexample
26058 @group
26059 _increment__incr.1:
26060    subl $4,%esp
26061    movl 8(%esp),%eax
26062 #APP
26063    incl %eax
26064 #NO_APP
26065    movl %eax,%edx
26066    movl %ecx,(%esp)
26067    addl $4,%esp
26068    ret
26069 @end group
26070 @end smallexample
26071
26072 @c ---------------------------------------------------------------------------
26073 @node Inlining Inline Assembler Code
26074 @section Inlining Inline Assembler Code
26075
26076 @noindent
26077 For a short subprogram such as the @code{Incr} function in the previous
26078 section, the overhead of the call and return (creating / deleting the stack
26079 frame) can be significant, compared to the amount of code in the subprogram
26080 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26081 which directs the compiler to expand invocations of the subprogram at the
26082 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26083 Here is the resulting program:
26084
26085 @smallexample @c ada
26086 @group
26087 with Interfaces; use Interfaces;
26088 with Ada.Text_IO; use Ada.Text_IO;
26089 with System.Machine_Code; use System.Machine_Code;
26090 procedure Increment_2 is
26091
26092    function Incr (Value : Unsigned_32) return Unsigned_32 is
26093       Result : Unsigned_32;
26094    begin
26095       Asm ("incl %0",
26096            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26097            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26098       return Result;
26099    end Incr;
26100    pragma Inline (Increment);
26101
26102    Value : Unsigned_32;
26103
26104 begin
26105    Value := 5;
26106    Put_Line ("Value before is" & Value'Img);
26107    Value := Increment (Value);
26108    Put_Line ("Value after is" & Value'Img);
26109 end Increment_2;
26110 @end group
26111 @end smallexample
26112
26113 Compile the program with both optimization (@option{-O2}) and inlining
26114 (@option{-gnatn}) enabled.
26115
26116 The @code{Incr} function is still compiled as usual, but at the
26117 point in @code{Increment} where our function used to be called:
26118
26119 @smallexample
26120 @group
26121 pushl %edi
26122 call _increment__incr.1
26123 @end group
26124 @end smallexample
26125
26126 @noindent
26127 the code for the function body directly appears:
26128
26129 @smallexample
26130 @group
26131 movl %esi,%eax
26132 #APP
26133    incl %eax
26134 #NO_APP
26135    movl %eax,%edx
26136 @end group
26137 @end smallexample
26138
26139 @noindent
26140 thus saving the overhead of stack frame setup and an out-of-line call.
26141
26142 @c ---------------------------------------------------------------------------
26143 @node Other Asm Functionality
26144 @section Other @code{Asm} Functionality
26145
26146 @noindent
26147 This section describes two important parameters to the @code{Asm}
26148 procedure: @code{Clobber}, which identifies register usage;
26149 and @code{Volatile}, which inhibits unwanted optimizations.
26150
26151 @menu
26152 * The Clobber Parameter::
26153 * The Volatile Parameter::
26154 @end menu
26155
26156 @c ---------------------------------------------------------------------------
26157 @node The Clobber Parameter
26158 @subsection The @code{Clobber} Parameter
26159
26160 @noindent
26161 One of the dangers of intermixing assembly language and a compiled language
26162 such as Ada is that the compiler needs to be aware of which registers are
26163 being used by the assembly code.  In some cases, such as the earlier examples,
26164 the constraint string is sufficient to indicate register usage (e.g.,
26165 @code{"a"} for
26166 the eax register).  But more generally, the compiler needs an explicit
26167 identification of the registers that are used by the Inline Assembly
26168 statements.
26169
26170 Using a register that the compiler doesn't know about
26171 could be a side effect of an instruction (like @code{mull}
26172 storing its result in both eax and edx).
26173 It can also arise from explicit register usage in your
26174 assembly code; for example:
26175 @smallexample
26176 @group
26177 Asm ("movl %0, %%ebx" & LF & HT &
26178      "movl %%ebx, %1",
26179      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26180      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26181 @end group
26182 @end smallexample
26183 @noindent
26184 where the compiler (since it does not analyze the @code{Asm} template string)
26185 does not know you are using the ebx register.
26186
26187 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26188 to identify the registers that will be used by your assembly code:
26189
26190 @smallexample
26191 @group
26192 Asm ("movl %0, %%ebx" & LF & HT &
26193      "movl %%ebx, %1",
26194      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26195      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26196      Clobber => "ebx");
26197 @end group
26198 @end smallexample
26199
26200 The Clobber parameter is a static string expression specifying the
26201 register(s) you are using.  Note that register names are @emph{not} prefixed
26202 by a percent sign. Also, if more than one register is used then their names
26203 are separated by commas; e.g., @code{"eax, ebx"}
26204
26205 The @code{Clobber} parameter has several additional uses:
26206 @enumerate
26207 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26208 @item Use ``register'' name @code{memory} if you changed a memory location
26209 @end enumerate
26210
26211 @c ---------------------------------------------------------------------------
26212 @node The Volatile Parameter
26213 @subsection The @code{Volatile} Parameter
26214 @cindex Volatile parameter
26215
26216 @noindent
26217 Compiler optimizations in the presence of Inline Assembler may sometimes have
26218 unwanted effects.  For example, when an @code{Asm} invocation with an input
26219 variable is inside a loop, the compiler might move the loading of the input
26220 variable outside the loop, regarding it as a one-time initialization.
26221
26222 If this effect is not desired, you can disable such optimizations by setting
26223 the @code{Volatile} parameter to @code{True}; for example:
26224
26225 @smallexample @c ada
26226 @group
26227 Asm ("movl %0, %%ebx" & LF & HT &
26228      "movl %%ebx, %1",
26229      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26230      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26231      Clobber  => "ebx",
26232      Volatile => True);
26233 @end group
26234 @end smallexample
26235
26236 By default, @code{Volatile} is set to @code{False} unless there is no
26237 @code{Outputs} parameter.
26238
26239 Although setting @code{Volatile} to @code{True} prevents unwanted
26240 optimizations, it will also disable other optimizations that might be
26241 important for efficiency. In general, you should set @code{Volatile}
26242 to @code{True} only if the compiler's optimizations have created
26243 problems.
26244 @c END OF INLINE ASSEMBLER CHAPTER
26245 @c ===============================
26246
26247 @c ***********************************
26248 @c * Compatibility and Porting Guide *
26249 @c ***********************************
26250 @node Compatibility and Porting Guide
26251 @appendix Compatibility and Porting Guide
26252
26253 @noindent
26254 This chapter describes the compatibility issues that may arise between
26255 GNAT and other Ada compilation systems (including those for Ada 83),
26256 and shows how GNAT can expedite porting
26257 applications developed in other Ada environments.
26258
26259 @menu
26260 * Compatibility with Ada 83::
26261 * Compatibility between Ada 95 and Ada 2005::
26262 * Implementation-dependent characteristics::
26263 * Compatibility with Other Ada Systems::
26264 * Representation Clauses::
26265 @ifclear vms
26266 @c Brief section is only in non-VMS version
26267 @c Full chapter is in VMS version
26268 * Compatibility with HP Ada 83::
26269 @end ifclear
26270 @ifset vms
26271 * Transitioning to 64-Bit GNAT for OpenVMS::
26272 @end ifset
26273 @end menu
26274
26275 @node Compatibility with Ada 83
26276 @section Compatibility with Ada 83
26277 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26278
26279 @noindent
26280 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26281 particular, the design intention was that the difficulties associated
26282 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26283 that occur when moving from one Ada 83 system to another.
26284
26285 However, there are a number of points at which there are minor
26286 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26287 full details of these issues,
26288 and should be consulted for a complete treatment.
26289 In practice the
26290 following subsections treat the most likely issues to be encountered.
26291
26292 @menu
26293 * Legal Ada 83 programs that are illegal in Ada 95::
26294 * More deterministic semantics::
26295 * Changed semantics::
26296 * Other language compatibility issues::
26297 @end menu
26298
26299 @node Legal Ada 83 programs that are illegal in Ada 95
26300 @subsection Legal Ada 83 programs that are illegal in Ada 95
26301
26302 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26303 Ada 95 and thus also in Ada 2005:
26304
26305 @table @emph
26306 @item Character literals
26307 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26308 @code{Wide_Character} as a new predefined character type, some uses of
26309 character literals that were legal in Ada 83 are illegal in Ada 95.
26310 For example:
26311 @smallexample @c ada
26312    for Char in 'A' .. 'Z' loop @dots{} end loop;
26313 @end smallexample
26314
26315 @noindent
26316 The problem is that @code{'A'} and @code{'Z'} could be from either
26317 @code{Character} or @code{Wide_Character}.  The simplest correction
26318 is to make the type explicit; e.g.:
26319 @smallexample @c ada
26320    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26321 @end smallexample
26322
26323 @item New reserved words
26324 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26325 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26326 Existing Ada 83 code using any of these identifiers must be edited to
26327 use some alternative name.
26328
26329 @item Freezing rules
26330 The rules in Ada 95 are slightly different with regard to the point at
26331 which entities are frozen, and representation pragmas and clauses are
26332 not permitted past the freeze point.  This shows up most typically in
26333 the form of an error message complaining that a representation item
26334 appears too late, and the appropriate corrective action is to move
26335 the item nearer to the declaration of the entity to which it refers.
26336
26337 A particular case is that representation pragmas
26338 @ifset vms
26339 (including the
26340 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26341 @end ifset
26342 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26343 declaration must be introduced to which the pragma can be applied.
26344
26345 @item Optional bodies for library packages
26346 In Ada 83, a package that did not require a package body was nevertheless
26347 allowed to have one.  This lead to certain surprises in compiling large
26348 systems (situations in which the body could be unexpectedly ignored by the
26349 binder).  In Ada 95, if a package does not require a body then it is not
26350 permitted to have a body.  To fix this problem, simply remove a redundant
26351 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26352 into the spec that makes the body required.  One approach is to add a private
26353 part to the package declaration (if necessary), and define a parameterless
26354 procedure called @code{Requires_Body}, which must then be given a dummy
26355 procedure body in the package body, which then becomes required.
26356 Another approach (assuming that this does not introduce elaboration
26357 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26358 since one effect of this pragma is to require the presence of a package body.
26359
26360 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26361 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26362 @code{Constraint_Error}.
26363 This means that it is illegal to have separate exception handlers for
26364 the two exceptions.  The fix is simply to remove the handler for the
26365 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26366 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26367
26368 @item Indefinite subtypes in generics
26369 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26370 as the actual for a generic formal private type, but then the instantiation
26371 would be illegal if there were any instances of declarations of variables
26372 of this type in the generic body.  In Ada 95, to avoid this clear violation
26373 of the methodological principle known as the ``contract model'',
26374 the generic declaration explicitly indicates whether
26375 or not such instantiations are permitted.  If a generic formal parameter
26376 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26377 subtype name, then it can be instantiated with indefinite types, but no
26378 stand-alone variables can be declared of this type.  Any attempt to declare
26379 such a variable will result in an illegality at the time the generic is
26380 declared.  If the @code{(<>)} notation is not used, then it is illegal
26381 to instantiate the generic with an indefinite type.
26382 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26383 It will show up as a compile time error, and
26384 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26385 @end table
26386
26387 @node More deterministic semantics
26388 @subsection More deterministic semantics
26389
26390 @table @emph
26391 @item Conversions
26392 Conversions from real types to integer types round away from 0.  In Ada 83
26393 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26394 implementation freedom was intended to support unbiased rounding in
26395 statistical applications, but in practice it interfered with portability.
26396 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26397 is required.  Numeric code may be affected by this change in semantics.
26398 Note, though, that this issue is no worse than already existed in Ada 83
26399 when porting code from one vendor to another.
26400
26401 @item Tasking
26402 The Real-Time Annex introduces a set of policies that define the behavior of
26403 features that were implementation dependent in Ada 83, such as the order in
26404 which open select branches are executed.
26405 @end table
26406
26407 @node Changed semantics
26408 @subsection Changed semantics
26409
26410 @noindent
26411 The worst kind of incompatibility is one where a program that is legal in
26412 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26413 possible in Ada 83.  Fortunately this is extremely rare, but the one
26414 situation that you should be alert to is the change in the predefined type
26415 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26416
26417 @table @emph
26418 @item Range of type @code{Character}
26419 The range of @code{Standard.Character} is now the full 256 characters
26420 of Latin-1, whereas in most Ada 83 implementations it was restricted
26421 to 128 characters. Although some of the effects of
26422 this change will be manifest in compile-time rejection of legal
26423 Ada 83 programs it is possible for a working Ada 83 program to have
26424 a different effect in Ada 95, one that was not permitted in Ada 83.
26425 As an example, the expression
26426 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26427 delivers @code{255} as its value.
26428 In general, you should look at the logic of any
26429 character-processing Ada 83 program and see whether it needs to be adapted
26430 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26431 character handling package that may be relevant if code needs to be adapted
26432 to account for the additional Latin-1 elements.
26433 The desirable fix is to
26434 modify the program to accommodate the full character set, but in some cases
26435 it may be convenient to define a subtype or derived type of Character that
26436 covers only the restricted range.
26437 @cindex Latin-1
26438 @end table
26439
26440 @node Other language compatibility issues
26441 @subsection Other language compatibility issues
26442
26443 @table @emph
26444 @item @option{-gnat83} switch
26445 All implementations of GNAT provide a switch that causes GNAT to operate
26446 in Ada 83 mode.  In this mode, some but not all compatibility problems
26447 of the type described above are handled automatically.  For example, the
26448 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26449 as identifiers as in Ada 83.
26450 However,
26451 in practice, it is usually advisable to make the necessary modifications
26452 to the program to remove the need for using this switch.
26453 See @ref{Compiling Different Versions of Ada}.
26454
26455 @item Support for removed Ada 83 pragmas and attributes
26456 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26457 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26458 compilers are allowed, but not required, to implement these missing
26459 elements.  In contrast with some other compilers, GNAT implements all
26460 such pragmas and attributes, eliminating this compatibility concern.  These
26461 include @code{pragma Interface} and the floating point type attributes
26462 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26463 @end table
26464
26465
26466 @node Compatibility between Ada 95 and Ada 2005
26467 @section Compatibility between Ada 95 and Ada 2005
26468 @cindex Compatibility between Ada 95 and Ada 2005
26469
26470 @noindent
26471 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26472 a number of incompatibilities. Several are enumerated below;
26473 for a complete description please see the
26474 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26475 @cite{Rationale for Ada 2005}.
26476
26477 @table @emph
26478 @item New reserved words.
26479 The words @code{interface}, @code{overriding} and @code{synchronized} are
26480 reserved in Ada 2005.
26481 A pre-Ada 2005 program that uses any of these as an identifier will be
26482 illegal.
26483
26484 @item New declarations in predefined packages.
26485 A number of packages in the predefined environment contain new declarations:
26486 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26487 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26488 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26489 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26490 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26491 If an Ada 95 program does a @code{with} and @code{use} of any of these
26492 packages, the new declarations may cause name clashes.
26493
26494 @item Access parameters.
26495 A nondispatching subprogram with an access parameter cannot be renamed
26496 as a dispatching operation.  This was permitted in Ada 95.
26497
26498 @item Access types, discriminants, and constraints.
26499 Rule changes in this area have led to some incompatibilities; for example,
26500 constrained subtypes of some access types are not permitted in Ada 2005.
26501
26502 @item Aggregates for limited types.
26503 The allowance of aggregates for limited types in Ada 2005 raises the
26504 possibility of ambiguities in legal Ada 95 programs, since additional types
26505 now need to be considered in expression resolution.
26506
26507 @item Fixed-point multiplication and division.
26508 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26509 were legal in Ada 95 and invoked the predefined versions of these operations,
26510 are now ambiguous.
26511 The ambiguity may be resolved either by applying a type conversion to the
26512 expression, or by explicitly invoking the operation from package
26513 @code{Standard}.
26514
26515 @item Return-by-reference types.
26516 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26517 can declare a function returning a value from an anonymous access type.
26518 @end table
26519
26520
26521 @node Implementation-dependent characteristics
26522 @section Implementation-dependent characteristics
26523 @noindent
26524 Although the Ada language defines the semantics of each construct as
26525 precisely as practical, in some situations (for example for reasons of
26526 efficiency, or where the effect is heavily dependent on the host or target
26527 platform) the implementation is allowed some freedom.  In porting Ada 83
26528 code to GNAT, you need to be aware of whether / how the existing code
26529 exercised such implementation dependencies.  Such characteristics fall into
26530 several categories, and GNAT offers specific support in assisting the
26531 transition from certain Ada 83 compilers.
26532
26533 @menu
26534 * Implementation-defined pragmas::
26535 * Implementation-defined attributes::
26536 * Libraries::
26537 * Elaboration order::
26538 * Target-specific aspects::
26539 @end menu
26540
26541 @node Implementation-defined pragmas
26542 @subsection Implementation-defined pragmas
26543
26544 @noindent
26545 Ada compilers are allowed to supplement the language-defined pragmas, and
26546 these are a potential source of non-portability.  All GNAT-defined pragmas
26547 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26548 Reference Manual}, and these include several that are specifically
26549 intended to correspond to other vendors' Ada 83 pragmas.
26550 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26551 For compatibility with HP Ada 83, GNAT supplies the pragmas
26552 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26553 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26554 and @code{Volatile}.
26555 Other relevant pragmas include @code{External} and @code{Link_With}.
26556 Some vendor-specific
26557 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26558 recognized, thus
26559 avoiding compiler rejection of units that contain such pragmas; they are not
26560 relevant in a GNAT context and hence are not otherwise implemented.
26561
26562 @node Implementation-defined attributes
26563 @subsection Implementation-defined attributes
26564
26565 Analogous to pragmas, the set of attributes may be extended by an
26566 implementation.  All GNAT-defined attributes are described in
26567 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26568 Manual}, and these include several that are specifically intended
26569 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26570 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26571 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26572 @code{Type_Class}.
26573
26574 @node Libraries
26575 @subsection Libraries
26576 @noindent
26577 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26578 code uses vendor-specific libraries then there are several ways to manage
26579 this in Ada 95 or Ada 2005:
26580 @enumerate
26581 @item
26582 If the source code for the libraries (specs and bodies) are
26583 available, then the libraries can be migrated in the same way as the
26584 application.
26585 @item
26586 If the source code for the specs but not the bodies are
26587 available, then you can reimplement the bodies.
26588 @item
26589 Some features introduced by Ada 95 obviate the need for library support.  For
26590 example most Ada 83 vendors supplied a package for unsigned integers.  The
26591 Ada 95 modular type feature is the preferred way to handle this need, so
26592 instead of migrating or reimplementing the unsigned integer package it may
26593 be preferable to retrofit the application using modular types.
26594 @end enumerate
26595
26596 @node Elaboration order
26597 @subsection Elaboration order
26598 @noindent
26599 The implementation can choose any elaboration order consistent with the unit
26600 dependency relationship.  This freedom means that some orders can result in
26601 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26602 to invoke a subprogram its body has been elaborated, or to instantiate a
26603 generic before the generic body has been elaborated.  By default GNAT
26604 attempts to choose a safe order (one that will not encounter access before
26605 elaboration problems) by implicitly inserting @code{Elaborate} or
26606 @code{Elaborate_All} pragmas where
26607 needed.  However, this can lead to the creation of elaboration circularities
26608 and a resulting rejection of the program by gnatbind.  This issue is
26609 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26610 In brief, there are several
26611 ways to deal with this situation:
26612
26613 @itemize @bullet
26614 @item
26615 Modify the program to eliminate the circularities, e.g.@: by moving
26616 elaboration-time code into explicitly-invoked procedures
26617 @item
26618 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26619 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26620 @code{Elaborate_All}
26621 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26622 (by selectively suppressing elaboration checks via pragma
26623 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26624 @end itemize
26625
26626 @node Target-specific aspects
26627 @subsection Target-specific aspects
26628 @noindent
26629 Low-level applications need to deal with machine addresses, data
26630 representations, interfacing with assembler code, and similar issues.  If
26631 such an Ada 83 application is being ported to different target hardware (for
26632 example where the byte endianness has changed) then you will need to
26633 carefully examine the program logic; the porting effort will heavily depend
26634 on the robustness of the original design.  Moreover, Ada 95 (and thus
26635 Ada 2005) are sometimes
26636 incompatible with typical Ada 83 compiler practices regarding implicit
26637 packing, the meaning of the Size attribute, and the size of access values.
26638 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26639
26640 @node Compatibility with Other Ada Systems
26641 @section Compatibility with Other Ada Systems
26642
26643 @noindent
26644 If programs avoid the use of implementation dependent and
26645 implementation defined features, as documented in the @cite{Ada
26646 Reference Manual}, there should be a high degree of portability between
26647 GNAT and other Ada systems.  The following are specific items which
26648 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26649 compilers, but do not affect porting code to GNAT@.
26650 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26651 the following issues may or may not arise for Ada 2005 programs
26652 when other compilers appear.)
26653
26654 @table @emph
26655 @item Ada 83 Pragmas and Attributes
26656 Ada 95 compilers are allowed, but not required, to implement the missing
26657 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26658 GNAT implements all such pragmas and attributes, eliminating this as
26659 a compatibility concern, but some other Ada 95 compilers reject these
26660 pragmas and attributes.
26661
26662 @item Specialized Needs Annexes
26663 GNAT implements the full set of special needs annexes.  At the
26664 current time, it is the only Ada 95 compiler to do so.  This means that
26665 programs making use of these features may not be portable to other Ada
26666 95 compilation systems.
26667
26668 @item Representation Clauses
26669 Some other Ada 95 compilers implement only the minimal set of
26670 representation clauses required by the Ada 95 reference manual.  GNAT goes
26671 far beyond this minimal set, as described in the next section.
26672 @end table
26673
26674 @node Representation Clauses
26675 @section Representation Clauses
26676
26677 @noindent
26678 The Ada 83 reference manual was quite vague in describing both the minimal
26679 required implementation of representation clauses, and also their precise
26680 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26681 minimal set of capabilities required is still quite limited.
26682
26683 GNAT implements the full required set of capabilities in
26684 Ada 95 and Ada 2005, but also goes much further, and in particular
26685 an effort has been made to be compatible with existing Ada 83 usage to the
26686 greatest extent possible.
26687
26688 A few cases exist in which Ada 83 compiler behavior is incompatible with
26689 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26690 intentional or accidental dependence on specific implementation dependent
26691 characteristics of these Ada 83 compilers.  The following is a list of
26692 the cases most likely to arise in existing Ada 83 code.
26693
26694 @table @emph
26695 @item Implicit Packing
26696 Some Ada 83 compilers allowed a Size specification to cause implicit
26697 packing of an array or record.  This could cause expensive implicit
26698 conversions for change of representation in the presence of derived
26699 types, and the Ada design intends to avoid this possibility.
26700 Subsequent AI's were issued to make it clear that such implicit
26701 change of representation in response to a Size clause is inadvisable,
26702 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26703 Reference Manuals as implementation advice that is followed by GNAT@.
26704 The problem will show up as an error
26705 message rejecting the size clause.  The fix is simply to provide
26706 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26707 a Component_Size clause.
26708
26709 @item Meaning of Size Attribute
26710 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26711 the minimal number of bits required to hold values of the type.  For example,
26712 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26713 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26714 some 32 in this situation.  This problem will usually show up as a compile
26715 time error, but not always.  It is a good idea to check all uses of the
26716 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26717 Object_Size can provide a useful way of duplicating the behavior of
26718 some Ada 83 compiler systems.
26719
26720 @item Size of Access Types
26721 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26722 and that therefore it will be the same size as a System.Address value.  This
26723 assumption is true for GNAT in most cases with one exception.  For the case of
26724 a pointer to an unconstrained array type (where the bounds may vary from one
26725 value of the access type to another), the default is to use a ``fat pointer'',
26726 which is represented as two separate pointers, one to the bounds, and one to
26727 the array.  This representation has a number of advantages, including improved
26728 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26729 code which makes the assumption that, for example, pointers fit in 32 bits on
26730 a machine with 32-bit addressing.
26731
26732 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26733 access types in this case (where the designated type is an unconstrained array
26734 type).  These thin pointers are indeed the same size as a System.Address value.
26735 To specify a thin pointer, use a size clause for the type, for example:
26736
26737 @smallexample @c ada
26738 type X is access all String;
26739 for X'Size use Standard'Address_Size;
26740 @end smallexample
26741
26742 @noindent
26743 which will cause the type X to be represented using a single pointer.
26744 When using this representation, the bounds are right behind the array.
26745 This representation is slightly less efficient, and does not allow quite
26746 such flexibility in the use of foreign pointers or in using the
26747 Unrestricted_Access attribute to create pointers to non-aliased objects.
26748 But for any standard portable use of the access type it will work in
26749 a functionally correct manner and allow porting of existing code.
26750 Note that another way of forcing a thin pointer representation
26751 is to use a component size clause for the element size in an array,
26752 or a record representation clause for an access field in a record.
26753 @end table
26754
26755 @ifclear vms
26756 @c This brief section is only in the non-VMS version
26757 @c The complete chapter on HP Ada is in the VMS version
26758 @node Compatibility with HP Ada 83
26759 @section Compatibility with HP Ada 83
26760
26761 @noindent
26762 The VMS version of GNAT fully implements all the pragmas and attributes
26763 provided by HP Ada 83, as well as providing the standard HP Ada 83
26764 libraries, including Starlet.  In addition, data layouts and parameter
26765 passing conventions are highly compatible.  This means that porting
26766 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26767 most other porting efforts.  The following are some of the most
26768 significant differences between GNAT and HP Ada 83.
26769
26770 @table @emph
26771 @item Default floating-point representation
26772 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26773 it is VMS format.  GNAT does implement the necessary pragmas
26774 (Long_Float, Float_Representation) for changing this default.
26775
26776 @item System
26777 The package System in GNAT exactly corresponds to the definition in the
26778 Ada 95 reference manual, which means that it excludes many of the
26779 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26780 that contains the additional definitions, and a special pragma,
26781 Extend_System allows this package to be treated transparently as an
26782 extension of package System.
26783
26784 @item To_Address
26785 The definitions provided by Aux_DEC are exactly compatible with those
26786 in the HP Ada 83 version of System, with one exception.
26787 HP Ada provides the following declarations:
26788
26789 @smallexample @c ada
26790 TO_ADDRESS (INTEGER)
26791 TO_ADDRESS (UNSIGNED_LONGWORD)
26792 TO_ADDRESS (@i{universal_integer})
26793 @end smallexample
26794
26795 @noindent
26796 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26797 an extension to Ada 83 not strictly compatible with the reference manual.
26798 In GNAT, we are constrained to be exactly compatible with the standard,
26799 and this means we cannot provide this capability.  In HP Ada 83, the
26800 point of this definition is to deal with a call like:
26801
26802 @smallexample @c ada
26803 TO_ADDRESS (16#12777#);
26804 @end smallexample
26805
26806 @noindent
26807 Normally, according to the Ada 83 standard, one would expect this to be
26808 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26809 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26810 definition using @i{universal_integer} takes precedence.
26811
26812 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26813 is not possible to be 100% compatible.  Since there are many programs using
26814 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26815 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26816 declarations provided in the GNAT version of AUX_Dec are:
26817
26818 @smallexample @c ada
26819 function To_Address (X : Integer) return Address;
26820 pragma Pure_Function (To_Address);
26821
26822 function To_Address_Long (X : Unsigned_Longword)
26823  return Address;
26824 pragma Pure_Function (To_Address_Long);
26825 @end smallexample
26826
26827 @noindent
26828 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26829 change the name to TO_ADDRESS_LONG@.
26830
26831 @item Task_Id values
26832 The Task_Id values assigned will be different in the two systems, and GNAT
26833 does not provide a specified value for the Task_Id of the environment task,
26834 which in GNAT is treated like any other declared task.
26835 @end table
26836
26837 @noindent
26838 For full details on these and other less significant compatibility issues,
26839 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26840 Overview and Comparison on HP Platforms}.
26841
26842 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26843 attributes are recognized, although only a subset of them can sensibly
26844 be implemented.  The description of pragmas in @ref{Implementation
26845 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26846 indicates whether or not they are applicable to non-VMS systems.
26847 @end ifclear
26848
26849 @ifset vms
26850 @node Transitioning to 64-Bit GNAT for OpenVMS
26851 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26852
26853 @noindent
26854 This section is meant to assist users of pre-2006 @value{EDITION}
26855 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26856 the version of the GNAT technology supplied in 2006 and later for
26857 OpenVMS on both Alpha and I64.
26858
26859 @menu
26860 * Introduction to transitioning::
26861 * Migration of 32 bit code::
26862 * Taking advantage of 64 bit addressing::
26863 * Technical details::
26864 @end menu
26865
26866 @node Introduction to transitioning
26867 @subsection Introduction
26868
26869 @noindent
26870 64-bit @value{EDITION} for Open VMS has been designed to meet
26871 three main goals:
26872
26873 @enumerate
26874 @item
26875 Providing a full conforming implementation of Ada 95 and Ada 2005
26876
26877 @item
26878 Allowing maximum backward compatibility, thus easing migration of existing
26879 Ada source code
26880
26881 @item
26882 Supplying a path for exploiting the full 64-bit address range
26883 @end enumerate
26884
26885 @noindent
26886 Ada's strong typing semantics has made it
26887 impractical to have different 32-bit and 64-bit modes. As soon as
26888 one object could possibly be outside the 32-bit address space, this
26889 would make it necessary for the @code{System.Address} type to be 64 bits.
26890 In particular, this would cause inconsistencies if 32-bit code is
26891 called from 64-bit code that raises an exception.
26892
26893 This issue has been resolved by always using 64-bit addressing
26894 at the system level, but allowing for automatic conversions between
26895 32-bit and 64-bit addresses where required. Thus users who
26896 do not currently require 64-bit addressing capabilities, can
26897 recompile their code with only minimal changes (and indeed
26898 if the code is written in portable Ada, with no assumptions about
26899 the size of the @code{Address} type, then no changes at all are necessary).
26900 At the same time,
26901 this approach provides a simple, gradual upgrade path to future
26902 use of larger memories than available for 32-bit systems.
26903 Also, newly written applications or libraries will by default
26904 be fully compatible with future systems exploiting 64-bit
26905 addressing capabilities.
26906
26907 @ref{Migration of 32 bit code}, will focus on porting applications
26908 that do not require more than 2 GB of
26909 addressable memory. This code will be referred to as
26910 @emph{32-bit code}.
26911 For applications intending to exploit the full 64-bit address space,
26912 @ref{Taking advantage of 64 bit addressing},
26913 will consider further changes that may be required.
26914 Such code will be referred to below as @emph{64-bit code}.
26915
26916 @node Migration of 32 bit code
26917 @subsection Migration of 32-bit code
26918
26919 @menu
26920 * Address types::
26921 * Access types and 32/64-bit allocation::
26922 * Unchecked conversions::
26923 * Predefined constants::
26924 * Interfacing with C::
26925 * 32/64-bit descriptors::
26926 * Experience with source compatibility::
26927 @end menu
26928
26929 @node Address types
26930 @subsubsection Address types
26931
26932 @noindent
26933 To solve the problem of mixing 64-bit and 32-bit addressing,
26934 while maintaining maximum backward compatibility, the following
26935 approach has been taken:
26936
26937 @itemize @bullet
26938 @item
26939 @code{System.Address} always has a size of 64 bits
26940 @cindex @code{System.Address} size
26941 @cindex @code{Address} size
26942
26943 @item
26944 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26945 @cindex @code{System.Short_Address} size
26946 @cindex @code{Short_Address} size
26947 @end itemize
26948
26949 @noindent
26950 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26951 a @code{Short_Address}
26952 may be used where an @code{Address} is required, and vice versa, without
26953 needing explicit type conversions.
26954 By virtue of the Open VMS parameter passing conventions,
26955 even imported
26956 and exported subprograms that have 32-bit address parameters are
26957 compatible with those that have 64-bit address parameters.
26958 (See @ref{Making code 64 bit clean} for details.)
26959
26960 The areas that may need attention are those where record types have
26961 been defined that contain components of the type @code{System.Address}, and
26962 where objects of this type are passed to code expecting a record layout with
26963 32-bit addresses.
26964
26965 Different compilers on different platforms cannot be
26966 expected to represent the same type in the same way,
26967 since alignment constraints
26968 and other system-dependent properties affect the compiler's decision.
26969 For that reason, Ada code
26970 generally uses representation clauses to specify the expected
26971 layout where required.
26972
26973 If such a representation clause uses 32 bits for a component having
26974 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26975 will detect that error and produce a specific diagnostic message.
26976 The developer should then determine whether the representation
26977 should be 64 bits or not and make either of two changes:
26978 change the size to 64 bits and leave the type as @code{System.Address}, or
26979 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26980 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26981 required in any code setting or accessing the field; the compiler will
26982 automatically perform any needed conversions between address
26983 formats.
26984
26985 @node Access types and 32/64-bit allocation
26986 @subsubsection Access types and 32/64-bit allocation
26987 @cindex 32-bit allocation
26988 @cindex 64-bit allocation
26989
26990 @noindent
26991 By default, objects designated by access values are always allocated in
26992 the 64-bit address space, and access values themselves are represented
26993 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26994 is required (for example if the address of an allocated object is assigned
26995 to a @code{Short_Address} variable), then several alternatives are available:
26996
26997 @itemize @bullet
26998 @item
26999 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27000 definition is @code{access T} versus @code{access all T} or
27001 @code{access constant T}), may be declared with a @code{'Size} representation
27002 clause that establishes the size as 32 bits.
27003 In such circumstances allocations for that type will
27004 be from the 32-bit heap.  Such a clause is not permitted
27005 for a general access type (declared with @code{access all} or
27006 @code{access constant}) as values of such types must be able to refer
27007 to any object of the designated type, including objects residing outside
27008 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
27009 type definitions, however, since general access types were introduced
27010 in @w{Ada 95}.
27011
27012 @item
27013 Switches for @command{GNAT BIND} control whether the internal GNAT
27014 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27015 @cindex @code{__gnat_malloc}
27016 The switches are respectively @option{-H64} (the default) and
27017 @option{-H32}.
27018 @cindex @option{-H32} (@command{gnatbind})
27019 @cindex @option{-H64} (@command{gnatbind})
27020
27021 @item
27022 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
27023 @cindex @code{GNAT$NO_MALLOC_64} environment variable
27024 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
27025 If this variable is left
27026 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
27027 then the default (64-bit) allocation is used.
27028 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
27029 then 32-bit allocation is used.  The gnatbind qualifiers described above
27030 override this logical name.
27031
27032 @item
27033 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
27034 @cindex @option{-mno-malloc64} (^gcc^gcc^)
27035 at a low level to convert explicit calls to @code{malloc} and related
27036 functions from the C run-time library so that they perform allocations
27037 in the 32-bit heap.
27038 Since all internal allocations from GNAT use @code{__gnat_malloc},
27039 this switch is not required unless the program makes explicit calls on
27040 @code{malloc} (or related functions) from interfaced C code.
27041 @end itemize
27042
27043
27044 @node Unchecked conversions
27045 @subsubsection Unchecked conversions
27046
27047 @noindent
27048 In the case of an @code{Unchecked_Conversion} where the source type is a
27049 64-bit access type or the type @code{System.Address}, and the target
27050 type is a 32-bit type, the compiler will generate a warning.
27051 Even though the generated code will still perform the required
27052 conversions, it is highly recommended in these cases to use
27053 respectively a 32-bit access type or @code{System.Short_Address}
27054 as the source type.
27055
27056 @node Predefined constants
27057 @subsubsection Predefined constants
27058
27059 @noindent
27060 The following table shows the correspondence between pre-2006 versions of
27061 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27062 (``New''):
27063
27064 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27065 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
27066 @item   @code{System.Word_Size}          @tab 32      @tab 64
27067 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
27068 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
27069 @item   @code{System.Address_Size}       @tab 32      @tab 64
27070 @end multitable
27071
27072 @noindent
27073 If you need to refer to the specific
27074 memory size of a 32-bit implementation, instead of the
27075 actual memory size, use @code{System.Short_Memory_Size}
27076 rather than @code{System.Memory_Size}.
27077 Similarly, references to @code{System.Address_Size} may need
27078 to be replaced by @code{System.Short_Address'Size}.
27079 The program @command{gnatfind} may be useful for locating
27080 references to the above constants, so that you can verify that they
27081 are still correct.
27082
27083 @node Interfacing with C
27084 @subsubsection Interfacing with C
27085
27086 @noindent
27087 In order to minimize the impact of the transition to 64-bit addresses on
27088 legacy programs, some fundamental types in the @code{Interfaces.C}
27089 package hierarchy continue to be represented in 32 bits.
27090 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27091 This eases integration with the default HP C layout choices, for example
27092 as found in the system routines in @code{DECC$SHR.EXE}.
27093 Because of this implementation choice, the type fully compatible with
27094 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27095 Depending on the context the compiler will issue a
27096 warning or an error when type @code{Address} is used, alerting the user to a
27097 potential problem. Otherwise 32-bit programs that use
27098 @code{Interfaces.C} should normally not require code modifications
27099
27100 The other issue arising with C interfacing concerns pragma @code{Convention}.
27101 For VMS 64-bit systems, there is an issue of the appropriate default size
27102 of C convention pointers in the absence of an explicit size clause. The HP
27103 C compiler can choose either 32 or 64 bits depending on compiler options.
27104 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27105 clause is given. This proves a better choice for porting 32-bit legacy
27106 applications. In order to have a 64-bit representation, it is necessary to
27107 specify a size representation clause. For example:
27108
27109 @smallexample @c ada
27110 type int_star is access Interfaces.C.int;
27111 pragma Convention(C, int_star);
27112 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
27113 @end smallexample
27114
27115 @node 32/64-bit descriptors
27116 @subsubsection 32/64-bit descriptors
27117
27118 @noindent
27119 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
27120 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27121 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27122 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27123 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27124
27125 If the configuration pragma @code{Short_Descriptors} is supplied, then
27126 all descriptors will be 32 bits.
27127 @cindex pragma @code{Short_Descriptors}
27128
27129 @node Experience with source compatibility
27130 @subsubsection Experience with source compatibility
27131
27132 @noindent
27133 The Security Server and STARLET on I64 provide an interesting ``test case''
27134 for source compatibility issues, since it is in such system code
27135 where assumptions about @code{Address} size might be expected to occur.
27136 Indeed, there were a small number of occasions in the Security Server
27137 file @file{jibdef.ads}
27138 where a representation clause for a record type specified
27139 32 bits for a component of type @code{Address}.
27140 All of these errors were detected by the compiler.
27141 The repair was obvious and immediate; to simply replace @code{Address} by
27142 @code{Short_Address}.
27143
27144 In the case of STARLET, there were several record types that should
27145 have had representation clauses but did not.  In these record types
27146 there was an implicit assumption that an @code{Address} value occupied
27147 32 bits.
27148 These compiled without error, but their usage resulted in run-time error
27149 returns from STARLET system calls.
27150 Future GNAT technology enhancements may include a tool that detects and flags
27151 these sorts of potential source code porting problems.
27152
27153 @c ****************************************
27154 @node Taking advantage of 64 bit addressing
27155 @subsection Taking advantage of 64-bit addressing
27156
27157 @menu
27158 * Making code 64 bit clean::
27159 * Allocating memory from the 64 bit storage pool::
27160 * Restrictions on use of 64 bit objects::
27161 * STARLET and other predefined libraries::
27162 @end menu
27163
27164 @node Making code 64 bit clean
27165 @subsubsection Making code 64-bit clean
27166
27167 @noindent
27168 In order to prevent problems that may occur when (parts of) a
27169 system start using memory outside the 32-bit address range,
27170 we recommend some additional guidelines:
27171
27172 @itemize @bullet
27173 @item
27174 For imported subprograms that take parameters of the
27175 type @code{System.Address}, ensure that these subprograms can
27176 indeed handle 64-bit addresses. If not, or when in doubt,
27177 change the subprogram declaration to specify
27178 @code{System.Short_Address} instead.
27179
27180 @item
27181 Resolve all warnings related to size mismatches in
27182 unchecked conversions. Failing to do so causes
27183 erroneous execution if the source object is outside
27184 the 32-bit address space.
27185
27186 @item
27187 (optional) Explicitly use the 32-bit storage pool
27188 for access types used in a 32-bit context, or use
27189 generic access types where possible
27190 (@pxref{Restrictions on use of 64 bit objects}).
27191 @end itemize
27192
27193 @noindent
27194 If these rules are followed, the compiler will automatically insert
27195 any necessary checks to ensure that no addresses or access values
27196 passed to 32-bit code ever refer to objects outside the 32-bit
27197 address range.
27198 Any attempt to do this will raise @code{Constraint_Error}.
27199
27200 @node Allocating memory from the 64 bit storage pool
27201 @subsubsection Allocating memory from the 64-bit storage pool
27202
27203 @noindent
27204 By default, all allocations -- for both pool-specific and general
27205 access types -- use the 64-bit storage pool.  To override
27206 this default, for an individual access type or globally, see
27207 @ref{Access types and 32/64-bit allocation}.
27208
27209 @node Restrictions on use of 64 bit objects
27210 @subsubsection Restrictions on use of 64-bit objects
27211
27212 @noindent
27213 Taking the address of an object allocated from a 64-bit storage pool,
27214 and then passing this address to a subprogram expecting
27215 @code{System.Short_Address},
27216 or assigning it to a variable of type @code{Short_Address}, will cause
27217 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27218 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27219 no exception is raised and execution
27220 will become erroneous.
27221
27222 @node STARLET and other predefined libraries
27223 @subsubsection STARLET and other predefined libraries
27224
27225 @noindent
27226 All code that comes as part of GNAT is 64-bit clean, but the
27227 restrictions given in @ref{Restrictions on use of 64 bit objects},
27228 still apply. Look at the package
27229 specs to see in which contexts objects allocated
27230 in 64-bit address space are acceptable.
27231
27232 @node Technical details
27233 @subsection Technical details
27234
27235 @noindent
27236 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27237 Ada standard with respect to the type of @code{System.Address}. Previous
27238 versions of @value{EDITION} have defined this type as private and implemented it as a
27239 modular type.
27240
27241 In order to allow defining @code{System.Short_Address} as a proper subtype,
27242 and to match the implicit sign extension in parameter passing,
27243 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27244 visible (i.e., non-private) integer type.
27245 Standard operations on the type, such as the binary operators ``+'', ``-'',
27246 etc., that take @code{Address} operands and return an @code{Address} result,
27247 have been hidden by declaring these
27248 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27249 ambiguities that would otherwise result from overloading.
27250 (Note that, although @code{Address} is a visible integer type,
27251 good programming practice dictates against exploiting the type's
27252 integer properties such as literals, since this will compromise
27253 code portability.)
27254
27255 Defining @code{Address} as a visible integer type helps achieve
27256 maximum compatibility for existing Ada code,
27257 without sacrificing the capabilities of the 64-bit architecture.
27258 @end ifset
27259
27260 @c ************************************************
27261 @ifset unw
27262 @node Microsoft Windows Topics
27263 @appendix Microsoft Windows Topics
27264 @cindex Windows NT
27265 @cindex Windows 95
27266 @cindex Windows 98
27267
27268 @noindent
27269 This chapter describes topics that are specific to the Microsoft Windows
27270 platforms (NT, 2000, and XP Professional).
27271
27272 @menu
27273 * Using GNAT on Windows::
27274 * Using a network installation of GNAT::
27275 * CONSOLE and WINDOWS subsystems::
27276 * Temporary Files::
27277 * Mixed-Language Programming on Windows::
27278 * Windows Calling Conventions::
27279 * Introduction to Dynamic Link Libraries (DLLs)::
27280 * Using DLLs with GNAT::
27281 * Building DLLs with GNAT Project files::
27282 * Building DLLs with GNAT::
27283 * Building DLLs with gnatdll::
27284 * GNAT and Windows Resources::
27285 * Debugging a DLL::
27286 * Setting Stack Size from gnatlink::
27287 * Setting Heap Size from gnatlink::
27288 @end menu
27289
27290 @node Using GNAT on Windows
27291 @section Using GNAT on Windows
27292
27293 @noindent
27294 One of the strengths of the GNAT technology is that its tool set
27295 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27296 @code{gdb} debugger, etc.) is used in the same way regardless of the
27297 platform.
27298
27299 On Windows this tool set is complemented by a number of Microsoft-specific
27300 tools that have been provided to facilitate interoperability with Windows
27301 when this is required. With these tools:
27302
27303 @itemize @bullet
27304
27305 @item
27306 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27307 subsystems.
27308
27309 @item
27310 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27311 relocatable and non-relocatable DLLs are supported).
27312
27313 @item
27314 You can build Ada DLLs for use in other applications. These applications
27315 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27316 relocatable and non-relocatable Ada DLLs are supported.
27317
27318 @item
27319 You can include Windows resources in your Ada application.
27320
27321 @item
27322 You can use or create COM/DCOM objects.
27323 @end itemize
27324
27325 @noindent
27326 Immediately below are listed all known general GNAT-for-Windows restrictions.
27327 Other restrictions about specific features like Windows Resources and DLLs
27328 are listed in separate sections below.
27329
27330 @itemize @bullet
27331
27332 @item
27333 It is not possible to use @code{GetLastError} and @code{SetLastError}
27334 when tasking, protected records, or exceptions are used. In these
27335 cases, in order to implement Ada semantics, the GNAT run-time system
27336 calls certain Win32 routines that set the last error variable to 0 upon
27337 success. It should be possible to use @code{GetLastError} and
27338 @code{SetLastError} when tasking, protected record, and exception
27339 features are not used, but it is not guaranteed to work.
27340
27341 @item
27342 It is not possible to link against Microsoft libraries except for
27343 import libraries. Interfacing must be done by the mean of DLLs.
27344
27345 @item
27346 When the compilation environment is located on FAT32 drives, users may
27347 experience recompilations of the source files that have not changed if
27348 Daylight Saving Time (DST) state has changed since the last time files
27349 were compiled. NTFS drives do not have this problem.
27350
27351 @item
27352 No components of the GNAT toolset use any entries in the Windows
27353 registry. The only entries that can be created are file associations and
27354 PATH settings, provided the user has chosen to create them at installation
27355 time, as well as some minimal book-keeping information needed to correctly
27356 uninstall or integrate different GNAT products.
27357 @end itemize
27358
27359 @node Using a network installation of GNAT
27360 @section Using a network installation of GNAT
27361
27362 @noindent
27363 Make sure the system on which GNAT is installed is accessible from the
27364 current machine, i.e., the install location is shared over the network.
27365 Shared resources are accessed on Windows by means of UNC paths, which
27366 have the format @code{\\server\sharename\path}
27367
27368 In order to use such a network installation, simply add the UNC path of the
27369 @file{bin} directory of your GNAT installation in front of your PATH. For
27370 example, if GNAT is installed in @file{\GNAT} directory of a share location
27371 called @file{c-drive} on a machine @file{LOKI}, the following command will
27372 make it available:
27373
27374 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27375
27376 Be aware that every compilation using the network installation results in the
27377 transfer of large amounts of data across the network and will likely cause
27378 serious performance penalty.
27379
27380 @node CONSOLE and WINDOWS subsystems
27381 @section CONSOLE and WINDOWS subsystems
27382 @cindex CONSOLE Subsystem
27383 @cindex WINDOWS Subsystem
27384 @cindex -mwindows
27385
27386 @noindent
27387 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27388 (which is the default subsystem) will always create a console when
27389 launching the application. This is not something desirable when the
27390 application has a Windows GUI. To get rid of this console the
27391 application must be using the @code{WINDOWS} subsystem. To do so
27392 the @option{-mwindows} linker option must be specified.
27393
27394 @smallexample
27395 $ gnatmake winprog -largs -mwindows
27396 @end smallexample
27397
27398 @node Temporary Files
27399 @section Temporary Files
27400 @cindex Temporary files
27401
27402 @noindent
27403 It is possible to control where temporary files gets created by setting
27404 the @env{TMP} environment variable. The file will be created:
27405
27406 @itemize
27407 @item Under the directory pointed to by the @env{TMP} environment variable if
27408 this directory exists.
27409
27410 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27411 set (or not pointing to a directory) and if this directory exists.
27412
27413 @item Under the current working directory otherwise.
27414 @end itemize
27415
27416 @noindent
27417 This allows you to determine exactly where the temporary
27418 file will be created. This is particularly useful in networked
27419 environments where you may not have write access to some
27420 directories.
27421
27422 @node Mixed-Language Programming on Windows
27423 @section Mixed-Language Programming on Windows
27424
27425 @noindent
27426 Developing pure Ada applications on Windows is no different than on
27427 other GNAT-supported platforms. However, when developing or porting an
27428 application that contains a mix of Ada and C/C++, the choice of your
27429 Windows C/C++ development environment conditions your overall
27430 interoperability strategy.
27431
27432 If you use @command{gcc} to compile the non-Ada part of your application,
27433 there are no Windows-specific restrictions that affect the overall
27434 interoperability with your Ada code. If you do want to use the
27435 Microsoft tools for your non-Ada code, you have two choices:
27436
27437 @enumerate
27438 @item
27439 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27440 application. In this case, use the Microsoft or whatever environment to
27441 build the DLL and use GNAT to build your executable
27442 (@pxref{Using DLLs with GNAT}).
27443
27444 @item
27445 Or you can encapsulate your Ada code in a DLL to be linked with the
27446 other part of your application. In this case, use GNAT to build the DLL
27447 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27448 or whatever environment to build your executable.
27449 @end enumerate
27450
27451 @node Windows Calling Conventions
27452 @section Windows Calling Conventions
27453 @findex Stdcall
27454 @findex APIENTRY
27455
27456 This section pertain only to Win32. On Win64 there is a single native
27457 calling convention. All convention specifiers are ignored on this
27458 platform.
27459
27460 @menu
27461 * C Calling Convention::
27462 * Stdcall Calling Convention::
27463 * Win32 Calling Convention::
27464 * DLL Calling Convention::
27465 @end menu
27466
27467 @noindent
27468 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27469 (callee), there are several ways to push @code{G}'s parameters on the
27470 stack and there are several possible scenarios to clean up the stack
27471 upon @code{G}'s return. A calling convention is an agreed upon software
27472 protocol whereby the responsibilities between the caller (@code{F}) and
27473 the callee (@code{G}) are clearly defined. Several calling conventions
27474 are available for Windows:
27475
27476 @itemize @bullet
27477 @item
27478 @code{C} (Microsoft defined)
27479
27480 @item
27481 @code{Stdcall} (Microsoft defined)
27482
27483 @item
27484 @code{Win32} (GNAT specific)
27485
27486 @item
27487 @code{DLL} (GNAT specific)
27488 @end itemize
27489
27490 @node C Calling Convention
27491 @subsection @code{C} Calling Convention
27492
27493 @noindent
27494 This is the default calling convention used when interfacing to C/C++
27495 routines compiled with either @command{gcc} or Microsoft Visual C++.
27496
27497 In the @code{C} calling convention subprogram parameters are pushed on the
27498 stack by the caller from right to left. The caller itself is in charge of
27499 cleaning up the stack after the call. In addition, the name of a routine
27500 with @code{C} calling convention is mangled by adding a leading underscore.
27501
27502 The name to use on the Ada side when importing (or exporting) a routine
27503 with @code{C} calling convention is the name of the routine. For
27504 instance the C function:
27505
27506 @smallexample
27507 int get_val (long);
27508 @end smallexample
27509
27510 @noindent
27511 should be imported from Ada as follows:
27512
27513 @smallexample @c ada
27514 @group
27515 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27516 pragma Import (C, Get_Val, External_Name => "get_val");
27517 @end group
27518 @end smallexample
27519
27520 @noindent
27521 Note that in this particular case the @code{External_Name} parameter could
27522 have been omitted since, when missing, this parameter is taken to be the
27523 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27524 is missing, as in the above example, this parameter is set to be the
27525 @code{External_Name} with a leading underscore.
27526
27527 When importing a variable defined in C, you should always use the @code{C}
27528 calling convention unless the object containing the variable is part of a
27529 DLL (in which case you should use the @code{Stdcall} calling
27530 convention, @pxref{Stdcall Calling Convention}).
27531
27532 @node Stdcall Calling Convention
27533 @subsection @code{Stdcall} Calling Convention
27534
27535 @noindent
27536 This convention, which was the calling convention used for Pascal
27537 programs, is used by Microsoft for all the routines in the Win32 API for
27538 efficiency reasons. It must be used to import any routine for which this
27539 convention was specified.
27540
27541 In the @code{Stdcall} calling convention subprogram parameters are pushed
27542 on the stack by the caller from right to left. The callee (and not the
27543 caller) is in charge of cleaning the stack on routine exit. In addition,
27544 the name of a routine with @code{Stdcall} calling convention is mangled by
27545 adding a leading underscore (as for the @code{C} calling convention) and a
27546 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27547 bytes) of the parameters passed to the routine.
27548
27549 The name to use on the Ada side when importing a C routine with a
27550 @code{Stdcall} calling convention is the name of the C routine. The leading
27551 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27552 the compiler. For instance the Win32 function:
27553
27554 @smallexample
27555 @b{APIENTRY} int get_val (long);
27556 @end smallexample
27557
27558 @noindent
27559 should be imported from Ada as follows:
27560
27561 @smallexample @c ada
27562 @group
27563 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27564 pragma Import (Stdcall, Get_Val);
27565 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27566 @end group
27567 @end smallexample
27568
27569 @noindent
27570 As for the @code{C} calling convention, when the @code{External_Name}
27571 parameter is missing, it is taken to be the name of the Ada entity in lower
27572 case. If instead of writing the above import pragma you write:
27573
27574 @smallexample @c ada
27575 @group
27576 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27577 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27578 @end group
27579 @end smallexample
27580
27581 @noindent
27582 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27583 of specifying the @code{External_Name} parameter you specify the
27584 @code{Link_Name} as in the following example:
27585
27586 @smallexample @c ada
27587 @group
27588 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27589 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27590 @end group
27591 @end smallexample
27592
27593 @noindent
27594 then the imported routine is @code{retrieve_val}, that is, there is no
27595 decoration at all. No leading underscore and no Stdcall suffix
27596 @code{@@}@code{@var{nn}}.
27597
27598 @noindent
27599 This is especially important as in some special cases a DLL's entry
27600 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27601 name generated for a call has it.
27602
27603 @noindent
27604 It is also possible to import variables defined in a DLL by using an
27605 import pragma for a variable. As an example, if a DLL contains a
27606 variable defined as:
27607
27608 @smallexample
27609 int my_var;
27610 @end smallexample
27611
27612 @noindent
27613 then, to access this variable from Ada you should write:
27614
27615 @smallexample @c ada
27616 @group
27617 My_Var : Interfaces.C.int;
27618 pragma Import (Stdcall, My_Var);
27619 @end group
27620 @end smallexample
27621
27622 @noindent
27623 Note that to ease building cross-platform bindings this convention
27624 will be handled as a @code{C} calling convention on non-Windows platforms.
27625
27626 @node Win32 Calling Convention
27627 @subsection @code{Win32} Calling Convention
27628
27629 @noindent
27630 This convention, which is GNAT-specific is fully equivalent to the
27631 @code{Stdcall} calling convention described above.
27632
27633 @node DLL Calling Convention
27634 @subsection @code{DLL} Calling Convention
27635
27636 @noindent
27637 This convention, which is GNAT-specific is fully equivalent to the
27638 @code{Stdcall} calling convention described above.
27639
27640 @node Introduction to Dynamic Link Libraries (DLLs)
27641 @section Introduction to Dynamic Link Libraries (DLLs)
27642 @findex DLL
27643
27644 @noindent
27645 A Dynamically Linked Library (DLL) is a library that can be shared by
27646 several applications running under Windows. A DLL can contain any number of
27647 routines and variables.
27648
27649 One advantage of DLLs is that you can change and enhance them without
27650 forcing all the applications that depend on them to be relinked or
27651 recompiled. However, you should be aware than all calls to DLL routines are
27652 slower since, as you will understand below, such calls are indirect.
27653
27654 To illustrate the remainder of this section, suppose that an application
27655 wants to use the services of a DLL @file{API.dll}. To use the services
27656 provided by @file{API.dll} you must statically link against the DLL or
27657 an import library which contains a jump table with an entry for each
27658 routine and variable exported by the DLL. In the Microsoft world this
27659 import library is called @file{API.lib}. When using GNAT this import
27660 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27661 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27662
27663 After you have linked your application with the DLL or the import library
27664 and you run your application, here is what happens:
27665
27666 @enumerate
27667 @item
27668 Your application is loaded into memory.
27669
27670 @item
27671 The DLL @file{API.dll} is mapped into the address space of your
27672 application. This means that:
27673
27674 @itemize @bullet
27675 @item
27676 The DLL will use the stack of the calling thread.
27677
27678 @item
27679 The DLL will use the virtual address space of the calling process.
27680
27681 @item
27682 The DLL will allocate memory from the virtual address space of the calling
27683 process.
27684
27685 @item
27686 Handles (pointers) can be safely exchanged between routines in the DLL
27687 routines and routines in the application using the DLL.
27688 @end itemize
27689
27690 @item
27691 The entries in the jump table (from the import library @file{libAPI.dll.a}
27692 or @file{API.lib} or automatically created when linking against a DLL)
27693 which is part of your application are initialized with the addresses
27694 of the routines and variables in @file{API.dll}.
27695
27696 @item
27697 If present in @file{API.dll}, routines @code{DllMain} or
27698 @code{DllMainCRTStartup} are invoked. These routines typically contain
27699 the initialization code needed for the well-being of the routines and
27700 variables exported by the DLL.
27701 @end enumerate
27702
27703 @noindent
27704 There is an additional point which is worth mentioning. In the Windows
27705 world there are two kind of DLLs: relocatable and non-relocatable
27706 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27707 in the target application address space. If the addresses of two
27708 non-relocatable DLLs overlap and these happen to be used by the same
27709 application, a conflict will occur and the application will run
27710 incorrectly. Hence, when possible, it is always preferable to use and
27711 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27712 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27713 User's Guide) removes the debugging symbols from the DLL but the DLL can
27714 still be relocated.
27715
27716 As a side note, an interesting difference between Microsoft DLLs and
27717 Unix shared libraries, is the fact that on most Unix systems all public
27718 routines are exported by default in a Unix shared library, while under
27719 Windows it is possible (but not required) to list exported routines in
27720 a definition file (@pxref{The Definition File}).
27721
27722 @node Using DLLs with GNAT
27723 @section Using DLLs with GNAT
27724
27725 @menu
27726 * Creating an Ada Spec for the DLL Services::
27727 * Creating an Import Library::
27728 @end menu
27729
27730 @noindent
27731 To use the services of a DLL, say @file{API.dll}, in your Ada application
27732 you must have:
27733
27734 @enumerate
27735 @item
27736 The Ada spec for the routines and/or variables you want to access in
27737 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27738 header files provided with the DLL.
27739
27740 @item
27741 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27742 mentioned an import library is a statically linked library containing the
27743 import table which will be filled at load time to point to the actual
27744 @file{API.dll} routines. Sometimes you don't have an import library for the
27745 DLL you want to use. The following sections will explain how to build
27746 one. Note that this is optional.
27747
27748 @item
27749 The actual DLL, @file{API.dll}.
27750 @end enumerate
27751
27752 @noindent
27753 Once you have all the above, to compile an Ada application that uses the
27754 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27755 you simply issue the command
27756
27757 @smallexample
27758 $ gnatmake my_ada_app -largs -lAPI
27759 @end smallexample
27760
27761 @noindent
27762 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27763 tells the GNAT linker to look for an import library. The linker will
27764 look for a library name in this specific order:
27765
27766 @enumerate
27767 @item @file{libAPI.dll.a}
27768 @item @file{API.dll.a}
27769 @item @file{libAPI.a}
27770 @item @file{API.lib}
27771 @item @file{libAPI.dll}
27772 @item @file{API.dll}
27773 @end enumerate
27774
27775 The first three are the GNU style import libraries. The third is the
27776 Microsoft style import libraries. The last two are the actual DLL names.
27777
27778 Note that if the Ada package spec for @file{API.dll} contains the
27779 following pragma
27780
27781 @smallexample @c ada
27782 pragma Linker_Options ("-lAPI");
27783 @end smallexample
27784
27785 @noindent
27786 you do not have to add @option{-largs -lAPI} at the end of the
27787 @command{gnatmake} command.
27788
27789 If any one of the items above is missing you will have to create it
27790 yourself. The following sections explain how to do so using as an
27791 example a fictitious DLL called @file{API.dll}.
27792
27793 @node Creating an Ada Spec for the DLL Services
27794 @subsection Creating an Ada Spec for the DLL Services
27795
27796 @noindent
27797 A DLL typically comes with a C/C++ header file which provides the
27798 definitions of the routines and variables exported by the DLL. The Ada
27799 equivalent of this header file is a package spec that contains definitions
27800 for the imported entities. If the DLL you intend to use does not come with
27801 an Ada spec you have to generate one such spec yourself. For example if
27802 the header file of @file{API.dll} is a file @file{api.h} containing the
27803 following two definitions:
27804
27805 @smallexample
27806 @group
27807 @cartouche
27808 int some_var;
27809 int get (char *);
27810 @end cartouche
27811 @end group
27812 @end smallexample
27813
27814 @noindent
27815 then the equivalent Ada spec could be:
27816
27817 @smallexample @c ada
27818 @group
27819 @cartouche
27820 with Interfaces.C.Strings;
27821 package API is
27822    use Interfaces;
27823
27824    Some_Var : C.int;
27825    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27826
27827 private
27828    pragma Import (C, Get);
27829    pragma Import (DLL, Some_Var);
27830 end API;
27831 @end cartouche
27832 @end group
27833 @end smallexample
27834
27835 @noindent
27836 Note that a variable is
27837 @strong{always imported with a DLL convention}. A function
27838 can have @code{C} or @code{Stdcall} convention.
27839 (@pxref{Windows Calling Conventions}).
27840
27841 @node Creating an Import Library
27842 @subsection Creating an Import Library
27843 @cindex Import library
27844
27845 @menu
27846 * The Definition File::
27847 * GNAT-Style Import Library::
27848 * Microsoft-Style Import Library::
27849 @end menu
27850
27851 @noindent
27852 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27853 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27854 with @file{API.dll} you can skip this section. You can also skip this
27855 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27856 as in this case it is possible to link directly against the
27857 DLL. Otherwise read on.
27858
27859 @node The Definition File
27860 @subsubsection The Definition File
27861 @cindex Definition file
27862 @findex .def
27863
27864 @noindent
27865 As previously mentioned, and unlike Unix systems, the list of symbols
27866 that are exported from a DLL must be provided explicitly in Windows.
27867 The main goal of a definition file is precisely that: list the symbols
27868 exported by a DLL. A definition file (usually a file with a @code{.def}
27869 suffix) has the following structure:
27870
27871 @smallexample
27872 @group
27873 @cartouche
27874 @r{[}LIBRARY @var{name}@r{]}
27875 @r{[}DESCRIPTION @var{string}@r{]}
27876 EXPORTS
27877    @var{symbol1}
27878    @var{symbol2}
27879    @dots{}
27880 @end cartouche
27881 @end group
27882 @end smallexample
27883
27884 @table @code
27885 @item LIBRARY @var{name}
27886 This section, which is optional, gives the name of the DLL.
27887
27888 @item DESCRIPTION @var{string}
27889 This section, which is optional, gives a description string that will be
27890 embedded in the import library.
27891
27892 @item EXPORTS
27893 This section gives the list of exported symbols (procedures, functions or
27894 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27895 section of @file{API.def} looks like:
27896
27897 @smallexample
27898 @group
27899 @cartouche
27900 EXPORTS
27901    some_var
27902    get
27903 @end cartouche
27904 @end group
27905 @end smallexample
27906 @end table
27907
27908 @noindent
27909 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27910 (@pxref{Windows Calling Conventions}) for a Stdcall
27911 calling convention function in the exported symbols list.
27912
27913 @noindent
27914 There can actually be other sections in a definition file, but these
27915 sections are not relevant to the discussion at hand.
27916
27917 @node GNAT-Style Import Library
27918 @subsubsection GNAT-Style Import Library
27919
27920 @noindent
27921 To create a static import library from @file{API.dll} with the GNAT tools
27922 you should proceed as follows:
27923
27924 @enumerate
27925 @item
27926 Create the definition file @file{API.def} (@pxref{The Definition File}).
27927 For that use the @code{dll2def} tool as follows:
27928
27929 @smallexample
27930 $ dll2def API.dll > API.def
27931 @end smallexample
27932
27933 @noindent
27934 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27935 to standard output the list of entry points in the DLL. Note that if
27936 some routines in the DLL have the @code{Stdcall} convention
27937 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27938 suffix then you'll have to edit @file{api.def} to add it, and specify
27939 @option{-k} to @command{gnatdll} when creating the import library.
27940
27941 @noindent
27942 Here are some hints to find the right @code{@@}@var{nn} suffix.
27943
27944 @enumerate
27945 @item
27946 If you have the Microsoft import library (.lib), it is possible to get
27947 the right symbols by using Microsoft @code{dumpbin} tool (see the
27948 corresponding Microsoft documentation for further details).
27949
27950 @smallexample
27951 $ dumpbin /exports api.lib
27952 @end smallexample
27953
27954 @item
27955 If you have a message about a missing symbol at link time the compiler
27956 tells you what symbol is expected. You just have to go back to the
27957 definition file and add the right suffix.
27958 @end enumerate
27959
27960 @item
27961 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27962 (@pxref{Using gnatdll}) as follows:
27963
27964 @smallexample
27965 $ gnatdll -e API.def -d API.dll
27966 @end smallexample
27967
27968 @noindent
27969 @code{gnatdll} takes as input a definition file @file{API.def} and the
27970 name of the DLL containing the services listed in the definition file
27971 @file{API.dll}. The name of the static import library generated is
27972 computed from the name of the definition file as follows: if the
27973 definition file name is @var{xyz}@code{.def}, the import library name will
27974 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27975 @option{-e} could have been removed because the name of the definition
27976 file (before the ``@code{.def}'' suffix) is the same as the name of the
27977 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27978 @end enumerate
27979
27980 @node Microsoft-Style Import Library
27981 @subsubsection Microsoft-Style Import Library
27982
27983 @noindent
27984 With GNAT you can either use a GNAT-style or Microsoft-style import
27985 library. A Microsoft import library is needed only if you plan to make an
27986 Ada DLL available to applications developed with Microsoft
27987 tools (@pxref{Mixed-Language Programming on Windows}).
27988
27989 To create a Microsoft-style import library for @file{API.dll} you
27990 should proceed as follows:
27991
27992 @enumerate
27993 @item
27994 Create the definition file @file{API.def} from the DLL. For this use either
27995 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27996 tool (see the corresponding Microsoft documentation for further details).
27997
27998 @item
27999 Build the actual import library using Microsoft's @code{lib} utility:
28000
28001 @smallexample
28002 $ lib -machine:IX86 -def:API.def -out:API.lib
28003 @end smallexample
28004
28005 @noindent
28006 If you use the above command the definition file @file{API.def} must
28007 contain a line giving the name of the DLL:
28008
28009 @smallexample
28010 LIBRARY      "API"
28011 @end smallexample
28012
28013 @noindent
28014 See the Microsoft documentation for further details about the usage of
28015 @code{lib}.
28016 @end enumerate
28017
28018 @node Building DLLs with GNAT Project files
28019 @section Building DLLs with GNAT Project files
28020 @cindex DLLs, building
28021
28022 @noindent
28023 There is nothing specific to Windows in the build process.
28024 @pxref{Library Projects}.
28025
28026 @noindent
28027 Due to a system limitation, it is not possible under Windows to create threads
28028 when inside the @code{DllMain} routine which is used for auto-initialization
28029 of shared libraries, so it is not possible to have library level tasks in SALs.
28030
28031 @node Building DLLs with GNAT
28032 @section Building DLLs with GNAT
28033 @cindex DLLs, building
28034
28035 @noindent
28036 This section explain how to build DLLs using the GNAT built-in DLL
28037 support. With the following procedure it is straight forward to build
28038 and use DLLs with GNAT.
28039
28040 @enumerate
28041
28042 @item building object files
28043
28044 The first step is to build all objects files that are to be included
28045 into the DLL. This is done by using the standard @command{gnatmake} tool.
28046
28047 @item building the DLL
28048
28049 To build the DLL you must use @command{gcc}'s @option{-shared} and
28050 @option{-shared-libgcc} options. It is quite simple to use this method:
28051
28052 @smallexample
28053 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28054 @end smallexample
28055
28056 It is important to note that in this case all symbols found in the
28057 object files are automatically exported. It is possible to restrict
28058 the set of symbols to export by passing to @command{gcc} a definition
28059 file, @pxref{The Definition File}. For example:
28060
28061 @smallexample
28062 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28063 @end smallexample
28064
28065 If you use a definition file you must export the elaboration procedures
28066 for every package that required one. Elaboration procedures are named
28067 using the package name followed by "_E".
28068
28069 @item preparing DLL to be used
28070
28071 For the DLL to be used by client programs the bodies must be hidden
28072 from it and the .ali set with read-only attribute. This is very important
28073 otherwise GNAT will recompile all packages and will not actually use
28074 the code in the DLL. For example:
28075
28076 @smallexample
28077 $ mkdir apilib
28078 $ copy *.ads *.ali api.dll apilib
28079 $ attrib +R apilib\*.ali
28080 @end smallexample
28081
28082 @end enumerate
28083
28084 At this point it is possible to use the DLL by directly linking
28085 against it. Note that you must use the GNAT shared runtime when using
28086 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28087 option.
28088
28089 @smallexample
28090 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28091 @end smallexample
28092
28093 @node Building DLLs with gnatdll
28094 @section Building DLLs with gnatdll
28095 @cindex DLLs, building
28096
28097 @menu
28098 * Limitations When Using Ada DLLs from Ada::
28099 * Exporting Ada Entities::
28100 * Ada DLLs and Elaboration::
28101 * Ada DLLs and Finalization::
28102 * Creating a Spec for Ada DLLs::
28103 * Creating the Definition File::
28104 * Using gnatdll::
28105 @end menu
28106
28107 @noindent
28108 Note that it is preferred to use GNAT Project files
28109 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28110 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28111
28112 This section explains how to build DLLs containing Ada code using
28113 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28114 remainder of this section.
28115
28116 The steps required to build an Ada DLL that is to be used by Ada as well as
28117 non-Ada applications are as follows:
28118
28119 @enumerate
28120 @item
28121 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28122 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28123 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28124 skip this step if you plan to use the Ada DLL only from Ada applications.
28125
28126 @item
28127 Your Ada code must export an initialization routine which calls the routine
28128 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28129 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28130 routine exported by the Ada DLL must be invoked by the clients of the DLL
28131 to initialize the DLL.
28132
28133 @item
28134 When useful, the DLL should also export a finalization routine which calls
28135 routine @code{adafinal} generated by @command{gnatbind} to perform the
28136 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28137 The finalization routine exported by the Ada DLL must be invoked by the
28138 clients of the DLL when the DLL services are no further needed.
28139
28140 @item
28141 You must provide a spec for the services exported by the Ada DLL in each
28142 of the programming languages to which you plan to make the DLL available.
28143
28144 @item
28145 You must provide a definition file listing the exported entities
28146 (@pxref{The Definition File}).
28147
28148 @item
28149 Finally you must use @code{gnatdll} to produce the DLL and the import
28150 library (@pxref{Using gnatdll}).
28151 @end enumerate
28152
28153 @noindent
28154 Note that a relocatable DLL stripped using the @code{strip}
28155 binutils tool will not be relocatable anymore. To build a DLL without
28156 debug information pass @code{-largs -s} to @code{gnatdll}. This
28157 restriction does not apply to a DLL built using a Library Project.
28158 @pxref{Library Projects}.
28159
28160 @node Limitations When Using Ada DLLs from Ada
28161 @subsection Limitations When Using Ada DLLs from Ada
28162
28163 @noindent
28164 When using Ada DLLs from Ada applications there is a limitation users
28165 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28166 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28167 each Ada DLL includes the services of the GNAT run time that are necessary
28168 to the Ada code inside the DLL. As a result, when an Ada program uses an
28169 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28170 one in the main program.
28171
28172 It is therefore not possible to exchange GNAT run-time objects between the
28173 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28174 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28175 types, etc.
28176
28177 It is completely safe to exchange plain elementary, array or record types,
28178 Windows object handles, etc.
28179
28180 @node Exporting Ada Entities
28181 @subsection Exporting Ada Entities
28182 @cindex Export table
28183
28184 @noindent
28185 Building a DLL is a way to encapsulate a set of services usable from any
28186 application. As a result, the Ada entities exported by a DLL should be
28187 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28188 any Ada name mangling. As an example here is an Ada package
28189 @code{API}, spec and body, exporting two procedures, a function, and a
28190 variable:
28191
28192 @smallexample @c ada
28193 @group
28194 @cartouche
28195 with Interfaces.C; use Interfaces;
28196 package API is
28197    Count : C.int := 0;
28198    function Factorial (Val : C.int) return C.int;
28199
28200    procedure Initialize_API;
28201    procedure Finalize_API;
28202    --  Initialization & Finalization routines. More in the next section.
28203 private
28204    pragma Export (C, Initialize_API);
28205    pragma Export (C, Finalize_API);
28206    pragma Export (C, Count);
28207    pragma Export (C, Factorial);
28208 end API;
28209 @end cartouche
28210 @end group
28211 @end smallexample
28212
28213 @smallexample @c ada
28214 @group
28215 @cartouche
28216 package body API is
28217    function Factorial (Val : C.int) return C.int is
28218       Fact : C.int := 1;
28219    begin
28220       Count := Count + 1;
28221       for K in 1 .. Val loop
28222          Fact := Fact * K;
28223       end loop;
28224       return Fact;
28225    end Factorial;
28226
28227    procedure Initialize_API is
28228       procedure Adainit;
28229       pragma Import (C, Adainit);
28230    begin
28231       Adainit;
28232    end Initialize_API;
28233
28234    procedure Finalize_API is
28235       procedure Adafinal;
28236       pragma Import (C, Adafinal);
28237    begin
28238       Adafinal;
28239    end Finalize_API;
28240 end API;
28241 @end cartouche
28242 @end group
28243 @end smallexample
28244
28245 @noindent
28246 If the Ada DLL you are building will only be used by Ada applications
28247 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28248 convention. As an example, the previous package could be written as
28249 follows:
28250
28251 @smallexample @c ada
28252 @group
28253 @cartouche
28254 package API is
28255    Count : Integer := 0;
28256    function Factorial (Val : Integer) return Integer;
28257
28258    procedure Initialize_API;
28259    procedure Finalize_API;
28260    --  Initialization and Finalization routines.
28261 end API;
28262 @end cartouche
28263 @end group
28264 @end smallexample
28265
28266 @smallexample @c ada
28267 @group
28268 @cartouche
28269 package body API is
28270    function Factorial (Val : Integer) return Integer is
28271       Fact : Integer := 1;
28272    begin
28273       Count := Count + 1;
28274       for K in 1 .. Val loop
28275          Fact := Fact * K;
28276       end loop;
28277       return Fact;
28278    end Factorial;
28279
28280    @dots{}
28281    --  The remainder of this package body is unchanged.
28282 end API;
28283 @end cartouche
28284 @end group
28285 @end smallexample
28286
28287 @noindent
28288 Note that if you do not export the Ada entities with a @code{C} or
28289 @code{Stdcall} convention you will have to provide the mangled Ada names
28290 in the definition file of the Ada DLL
28291 (@pxref{Creating the Definition File}).
28292
28293 @node Ada DLLs and Elaboration
28294 @subsection Ada DLLs and Elaboration
28295 @cindex DLLs and elaboration
28296
28297 @noindent
28298 The DLL that you are building contains your Ada code as well as all the
28299 routines in the Ada library that are needed by it. The first thing a
28300 user of your DLL must do is elaborate the Ada code
28301 (@pxref{Elaboration Order Handling in GNAT}).
28302
28303 To achieve this you must export an initialization routine
28304 (@code{Initialize_API} in the previous example), which must be invoked
28305 before using any of the DLL services. This elaboration routine must call
28306 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28307 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28308 @code{Initialize_Api} for an example. Note that the GNAT binder is
28309 automatically invoked during the DLL build process by the @code{gnatdll}
28310 tool (@pxref{Using gnatdll}).
28311
28312 When a DLL is loaded, Windows systematically invokes a routine called
28313 @code{DllMain}. It would therefore be possible to call @code{adainit}
28314 directly from @code{DllMain} without having to provide an explicit
28315 initialization routine. Unfortunately, it is not possible to call
28316 @code{adainit} from the @code{DllMain} if your program has library level
28317 tasks because access to the @code{DllMain} entry point is serialized by
28318 the system (that is, only a single thread can execute ``through'' it at a
28319 time), which means that the GNAT run time will deadlock waiting for the
28320 newly created task to complete its initialization.
28321
28322 @node Ada DLLs and Finalization
28323 @subsection Ada DLLs and Finalization
28324 @cindex DLLs and finalization
28325
28326 @noindent
28327 When the services of an Ada DLL are no longer needed, the client code should
28328 invoke the DLL finalization routine, if available. The DLL finalization
28329 routine is in charge of releasing all resources acquired by the DLL. In the
28330 case of the Ada code contained in the DLL, this is achieved by calling
28331 routine @code{adafinal} generated by the GNAT binder
28332 (@pxref{Binding with Non-Ada Main Programs}).
28333 See the body of @code{Finalize_Api} for an
28334 example. As already pointed out the GNAT binder is automatically invoked
28335 during the DLL build process by the @code{gnatdll} tool
28336 (@pxref{Using gnatdll}).
28337
28338 @node Creating a Spec for Ada DLLs
28339 @subsection Creating a Spec for Ada DLLs
28340
28341 @noindent
28342 To use the services exported by the Ada DLL from another programming
28343 language (e.g.@: C), you have to translate the specs of the exported Ada
28344 entities in that language. For instance in the case of @code{API.dll},
28345 the corresponding C header file could look like:
28346
28347 @smallexample
28348 @group
28349 @cartouche
28350 extern int *_imp__count;
28351 #define count (*_imp__count)
28352 int factorial (int);
28353 @end cartouche
28354 @end group
28355 @end smallexample
28356
28357 @noindent
28358 It is important to understand that when building an Ada DLL to be used by
28359 other Ada applications, you need two different specs for the packages
28360 contained in the DLL: one for building the DLL and the other for using
28361 the DLL. This is because the @code{DLL} calling convention is needed to
28362 use a variable defined in a DLL, but when building the DLL, the variable
28363 must have either the @code{Ada} or @code{C} calling convention. As an
28364 example consider a DLL comprising the following package @code{API}:
28365
28366 @smallexample @c ada
28367 @group
28368 @cartouche
28369 package API is
28370    Count : Integer := 0;
28371    @dots{}
28372    --  Remainder of the package omitted.
28373 end API;
28374 @end cartouche
28375 @end group
28376 @end smallexample
28377
28378 @noindent
28379 After producing a DLL containing package @code{API}, the spec that
28380 must be used to import @code{API.Count} from Ada code outside of the
28381 DLL is:
28382
28383 @smallexample @c ada
28384 @group
28385 @cartouche
28386 package API is
28387    Count : Integer;
28388    pragma Import (DLL, Count);
28389 end API;
28390 @end cartouche
28391 @end group
28392 @end smallexample
28393
28394 @node Creating the Definition File
28395 @subsection Creating the Definition File
28396
28397 @noindent
28398 The definition file is the last file needed to build the DLL. It lists
28399 the exported symbols. As an example, the definition file for a DLL
28400 containing only package @code{API} (where all the entities are exported
28401 with a @code{C} calling convention) is:
28402
28403 @smallexample
28404 @group
28405 @cartouche
28406 EXPORTS
28407     count
28408     factorial
28409     finalize_api
28410     initialize_api
28411 @end cartouche
28412 @end group
28413 @end smallexample
28414
28415 @noindent
28416 If the @code{C} calling convention is missing from package @code{API},
28417 then the definition file contains the mangled Ada names of the above
28418 entities, which in this case are:
28419
28420 @smallexample
28421 @group
28422 @cartouche
28423 EXPORTS
28424     api__count
28425     api__factorial
28426     api__finalize_api
28427     api__initialize_api
28428 @end cartouche
28429 @end group
28430 @end smallexample
28431
28432 @node Using gnatdll
28433 @subsection Using @code{gnatdll}
28434 @findex gnatdll
28435
28436 @menu
28437 * gnatdll Example::
28438 * gnatdll behind the Scenes::
28439 * Using dlltool::
28440 @end menu
28441
28442 @noindent
28443 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28444 and non-Ada sources that make up your DLL have been compiled.
28445 @code{gnatdll} is actually in charge of two distinct tasks: build the
28446 static import library for the DLL and the actual DLL. The form of the
28447 @code{gnatdll} command is
28448
28449 @smallexample
28450 @cartouche
28451 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28452 @c Expanding @ovar macro inline (explanation in macro def comments)
28453 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28454 @end cartouche
28455 @end smallexample
28456
28457 @noindent
28458 where @var{list-of-files} is a list of ALI and object files. The object
28459 file list must be the exact list of objects corresponding to the non-Ada
28460 sources whose services are to be included in the DLL. The ALI file list
28461 must be the exact list of ALI files for the corresponding Ada sources
28462 whose services are to be included in the DLL. If @var{list-of-files} is
28463 missing, only the static import library is generated.
28464
28465 @noindent
28466 You may specify any of the following switches to @code{gnatdll}:
28467
28468 @table @code
28469 @c @item -a@ovar{address}
28470 @c Expanding @ovar macro inline (explanation in macro def comments)
28471 @item -a@r{[}@var{address}@r{]}
28472 @cindex @option{-a} (@code{gnatdll})
28473 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28474 specified the default address @var{0x11000000} will be used. By default,
28475 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28476 advise the reader to build relocatable DLL.
28477
28478 @item -b @var{address}
28479 @cindex @option{-b} (@code{gnatdll})
28480 Set the relocatable DLL base address. By default the address is
28481 @code{0x11000000}.
28482
28483 @item -bargs @var{opts}
28484 @cindex @option{-bargs} (@code{gnatdll})
28485 Binder options. Pass @var{opts} to the binder.
28486
28487 @item -d @var{dllfile}
28488 @cindex @option{-d} (@code{gnatdll})
28489 @var{dllfile} is the name of the DLL. This switch must be present for
28490 @code{gnatdll} to do anything. The name of the generated import library is
28491 obtained algorithmically from @var{dllfile} as shown in the following
28492 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28493 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28494 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28495 as shown in the following example:
28496 if @var{dllfile} is @code{xyz.dll}, the definition
28497 file used is @code{xyz.def}.
28498
28499 @item -e @var{deffile}
28500 @cindex @option{-e} (@code{gnatdll})
28501 @var{deffile} is the name of the definition file.
28502
28503 @item -g
28504 @cindex @option{-g} (@code{gnatdll})
28505 Generate debugging information. This information is stored in the object
28506 file and copied from there to the final DLL file by the linker,
28507 where it can be read by the debugger. You must use the
28508 @option{-g} switch if you plan on using the debugger or the symbolic
28509 stack traceback.
28510
28511 @item -h
28512 @cindex @option{-h} (@code{gnatdll})
28513 Help mode. Displays @code{gnatdll} switch usage information.
28514
28515 @item -Idir
28516 @cindex @option{-I} (@code{gnatdll})
28517 Direct @code{gnatdll} to search the @var{dir} directory for source and
28518 object files needed to build the DLL.
28519 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28520
28521 @item -k
28522 @cindex @option{-k} (@code{gnatdll})
28523 Removes the @code{@@}@var{nn} suffix from the import library's exported
28524 names, but keeps them for the link names. You must specify this
28525 option if you want to use a @code{Stdcall} function in a DLL for which
28526 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28527 of the Windows NT DLL for example. This option has no effect when
28528 @option{-n} option is specified.
28529
28530 @item -l @var{file}
28531 @cindex @option{-l} (@code{gnatdll})
28532 The list of ALI and object files used to build the DLL are listed in
28533 @var{file}, instead of being given in the command line. Each line in
28534 @var{file} contains the name of an ALI or object file.
28535
28536 @item -n
28537 @cindex @option{-n} (@code{gnatdll})
28538 No Import. Do not create the import library.
28539
28540 @item -q
28541 @cindex @option{-q} (@code{gnatdll})
28542 Quiet mode. Do not display unnecessary messages.
28543
28544 @item -v
28545 @cindex @option{-v} (@code{gnatdll})
28546 Verbose mode. Display extra information.
28547
28548 @item -largs @var{opts}
28549 @cindex @option{-largs} (@code{gnatdll})
28550 Linker options. Pass @var{opts} to the linker.
28551 @end table
28552
28553 @node gnatdll Example
28554 @subsubsection @code{gnatdll} Example
28555
28556 @noindent
28557 As an example the command to build a relocatable DLL from @file{api.adb}
28558 once @file{api.adb} has been compiled and @file{api.def} created is
28559
28560 @smallexample
28561 $ gnatdll -d api.dll api.ali
28562 @end smallexample
28563
28564 @noindent
28565 The above command creates two files: @file{libapi.dll.a} (the import
28566 library) and @file{api.dll} (the actual DLL). If you want to create
28567 only the DLL, just type:
28568
28569 @smallexample
28570 $ gnatdll -d api.dll -n api.ali
28571 @end smallexample
28572
28573 @noindent
28574 Alternatively if you want to create just the import library, type:
28575
28576 @smallexample
28577 $ gnatdll -d api.dll
28578 @end smallexample
28579
28580 @node gnatdll behind the Scenes
28581 @subsubsection @code{gnatdll} behind the Scenes
28582
28583 @noindent
28584 This section details the steps involved in creating a DLL. @code{gnatdll}
28585 does these steps for you. Unless you are interested in understanding what
28586 goes on behind the scenes, you should skip this section.
28587
28588 We use the previous example of a DLL containing the Ada package @code{API},
28589 to illustrate the steps necessary to build a DLL. The starting point is a
28590 set of objects that will make up the DLL and the corresponding ALI
28591 files. In the case of this example this means that @file{api.o} and
28592 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28593 the following:
28594
28595 @enumerate
28596 @item
28597 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28598 the information necessary to generate relocation information for the
28599 DLL.
28600
28601 @smallexample
28602 @group
28603 $ gnatbind -n api
28604 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28605 @end group
28606 @end smallexample
28607
28608 @noindent
28609 In addition to the base file, the @command{gnatlink} command generates an
28610 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28611 asks @command{gnatlink} to generate the routines @code{DllMain} and
28612 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28613 is loaded into memory.
28614
28615 @item
28616 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28617 export table (@file{api.exp}). The export table contains the relocation
28618 information in a form which can be used during the final link to ensure
28619 that the Windows loader is able to place the DLL anywhere in memory.
28620
28621 @smallexample
28622 @group
28623 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28624           --output-exp api.exp
28625 @end group
28626 @end smallexample
28627
28628 @item
28629 @code{gnatdll} builds the base file using the new export table. Note that
28630 @command{gnatbind} must be called once again since the binder generated file
28631 has been deleted during the previous call to @command{gnatlink}.
28632
28633 @smallexample
28634 @group
28635 $ gnatbind -n api
28636 $ gnatlink api -o api.jnk api.exp -mdll
28637       -Wl,--base-file,api.base
28638 @end group
28639 @end smallexample
28640
28641 @item
28642 @code{gnatdll} builds the new export table using the new base file and
28643 generates the DLL import library @file{libAPI.dll.a}.
28644
28645 @smallexample
28646 @group
28647 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28648           --output-exp api.exp --output-lib libAPI.a
28649 @end group
28650 @end smallexample
28651
28652 @item
28653 Finally @code{gnatdll} builds the relocatable DLL using the final export
28654 table.
28655
28656 @smallexample
28657 @group
28658 $ gnatbind -n api
28659 $ gnatlink api api.exp -o api.dll -mdll
28660 @end group
28661 @end smallexample
28662 @end enumerate
28663
28664 @node Using dlltool
28665 @subsubsection Using @code{dlltool}
28666
28667 @noindent
28668 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28669 DLLs and static import libraries. This section summarizes the most
28670 common @code{dlltool} switches. The form of the @code{dlltool} command
28671 is
28672
28673 @smallexample
28674 @c $ dlltool @ovar{switches}
28675 @c Expanding @ovar macro inline (explanation in macro def comments)
28676 $ dlltool @r{[}@var{switches}@r{]}
28677 @end smallexample
28678
28679 @noindent
28680 @code{dlltool} switches include:
28681
28682 @table @option
28683 @item --base-file @var{basefile}
28684 @cindex @option{--base-file} (@command{dlltool})
28685 Read the base file @var{basefile} generated by the linker. This switch
28686 is used to create a relocatable DLL.
28687
28688 @item --def @var{deffile}
28689 @cindex @option{--def} (@command{dlltool})
28690 Read the definition file.
28691
28692 @item --dllname @var{name}
28693 @cindex @option{--dllname} (@command{dlltool})
28694 Gives the name of the DLL. This switch is used to embed the name of the
28695 DLL in the static import library generated by @code{dlltool} with switch
28696 @option{--output-lib}.
28697
28698 @item -k
28699 @cindex @option{-k} (@command{dlltool})
28700 Kill @code{@@}@var{nn} from exported names
28701 (@pxref{Windows Calling Conventions}
28702 for a discussion about @code{Stdcall}-style symbols.
28703
28704 @item --help
28705 @cindex @option{--help} (@command{dlltool})
28706 Prints the @code{dlltool} switches with a concise description.
28707
28708 @item --output-exp @var{exportfile}
28709 @cindex @option{--output-exp} (@command{dlltool})
28710 Generate an export file @var{exportfile}. The export file contains the
28711 export table (list of symbols in the DLL) and is used to create the DLL.
28712
28713 @item --output-lib @var{libfile}
28714 @cindex @option{--output-lib} (@command{dlltool})
28715 Generate a static import library @var{libfile}.
28716
28717 @item -v
28718 @cindex @option{-v} (@command{dlltool})
28719 Verbose mode.
28720
28721 @item --as @var{assembler-name}
28722 @cindex @option{--as} (@command{dlltool})
28723 Use @var{assembler-name} as the assembler. The default is @code{as}.
28724 @end table
28725
28726 @node GNAT and Windows Resources
28727 @section GNAT and Windows Resources
28728 @cindex Resources, windows
28729
28730 @menu
28731 * Building Resources::
28732 * Compiling Resources::
28733 * Using Resources::
28734 @end menu
28735
28736 @noindent
28737 Resources are an easy way to add Windows specific objects to your
28738 application. The objects that can be added as resources include:
28739
28740 @itemize @bullet
28741 @item menus
28742
28743 @item accelerators
28744
28745 @item dialog boxes
28746
28747 @item string tables
28748
28749 @item bitmaps
28750
28751 @item cursors
28752
28753 @item icons
28754
28755 @item fonts
28756
28757 @item version information
28758 @end itemize
28759
28760 For example, a version information resource can be defined as follow and
28761 embedded into an executable or DLL:
28762
28763 A version information resource can be used to embed information into an
28764 executable or a DLL. These information can be viewed using the file properties
28765 from the Windows Explorer. Here is an example of a version information
28766 resource:
28767
28768 @smallexample
28769 @group
28770 1 VERSIONINFO
28771 FILEVERSION     1,0,0,0
28772 PRODUCTVERSION  1,0,0,0
28773 BEGIN
28774   BLOCK "StringFileInfo"
28775   BEGIN
28776     BLOCK "080904E4"
28777     BEGIN
28778       VALUE "CompanyName", "My Company Name"
28779       VALUE "FileDescription", "My application"
28780       VALUE "FileVersion", "1.0"
28781       VALUE "InternalName", "my_app"
28782       VALUE "LegalCopyright", "My Name"
28783       VALUE "OriginalFilename", "my_app.exe"
28784       VALUE "ProductName", "My App"
28785       VALUE "ProductVersion", "1.0"
28786     END
28787   END
28788
28789   BLOCK "VarFileInfo"
28790   BEGIN
28791     VALUE "Translation", 0x809, 1252
28792   END
28793 END
28794 @end group
28795 @end smallexample
28796
28797 The value @code{0809} (langID) is for the U.K English language and
28798 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28799 multilingual.
28800
28801 @noindent
28802 This section explains how to build, compile and use resources. Note that this
28803 section does not cover all resource objects, for a complete description see
28804 the corresponding Microsoft documentation.
28805
28806 @node Building Resources
28807 @subsection Building Resources
28808 @cindex Resources, building
28809
28810 @noindent
28811 A resource file is an ASCII file. By convention resource files have an
28812 @file{.rc} extension.
28813 The easiest way to build a resource file is to use Microsoft tools
28814 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28815 @code{dlgedit.exe} to build dialogs.
28816 It is always possible to build an @file{.rc} file yourself by writing a
28817 resource script.
28818
28819 It is not our objective to explain how to write a resource file. A
28820 complete description of the resource script language can be found in the
28821 Microsoft documentation.
28822
28823 @node Compiling Resources
28824 @subsection Compiling Resources
28825 @findex rc
28826 @findex windres
28827 @cindex Resources, compiling
28828
28829 @noindent
28830 This section describes how to build a GNAT-compatible (COFF) object file
28831 containing the resources. This is done using the Resource Compiler
28832 @code{windres} as follows:
28833
28834 @smallexample
28835 $ windres -i myres.rc -o myres.o
28836 @end smallexample
28837
28838 @noindent
28839 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28840 file. You can specify an alternate preprocessor (usually named
28841 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28842 parameter. A list of all possible options may be obtained by entering
28843 the command @code{windres} @option{--help}.
28844
28845 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28846 to produce a @file{.res} file (binary resource file). See the
28847 corresponding Microsoft documentation for further details. In this case
28848 you need to use @code{windres} to translate the @file{.res} file to a
28849 GNAT-compatible object file as follows:
28850
28851 @smallexample
28852 $ windres -i myres.res -o myres.o
28853 @end smallexample
28854
28855 @node Using Resources
28856 @subsection Using Resources
28857 @cindex Resources, using
28858
28859 @noindent
28860 To include the resource file in your program just add the
28861 GNAT-compatible object file for the resource(s) to the linker
28862 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28863 option:
28864
28865 @smallexample
28866 $ gnatmake myprog -largs myres.o
28867 @end smallexample
28868
28869 @node Debugging a DLL
28870 @section Debugging a DLL
28871 @cindex DLL debugging
28872
28873 @menu
28874 * Program and DLL Both Built with GCC/GNAT::
28875 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28876 @end menu
28877
28878 @noindent
28879 Debugging a DLL is similar to debugging a standard program. But
28880 we have to deal with two different executable parts: the DLL and the
28881 program that uses it. We have the following four possibilities:
28882
28883 @enumerate 1
28884 @item
28885 The program and the DLL are built with @code{GCC/GNAT}.
28886 @item
28887 The program is built with foreign tools and the DLL is built with
28888 @code{GCC/GNAT}.
28889 @item
28890 The program is built with @code{GCC/GNAT} and the DLL is built with
28891 foreign tools.
28892 @end enumerate
28893
28894 @noindent
28895 In this section we address only cases one and two above.
28896 There is no point in trying to debug
28897 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28898 information in it. To do so you must use a debugger compatible with the
28899 tools suite used to build the DLL.
28900
28901 @node Program and DLL Both Built with GCC/GNAT
28902 @subsection Program and DLL Both Built with GCC/GNAT
28903
28904 @noindent
28905 This is the simplest case. Both the DLL and the program have @code{GDB}
28906 compatible debugging information. It is then possible to break anywhere in
28907 the process. Let's suppose here that the main procedure is named
28908 @code{ada_main} and that in the DLL there is an entry point named
28909 @code{ada_dll}.
28910
28911 @noindent
28912 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28913 program must have been built with the debugging information (see GNAT -g
28914 switch). Here are the step-by-step instructions for debugging it:
28915
28916 @enumerate 1
28917 @item Launch @code{GDB} on the main program.
28918
28919 @smallexample
28920 $ gdb -nw ada_main
28921 @end smallexample
28922
28923 @item Start the program and stop at the beginning of the main procedure
28924
28925 @smallexample
28926 (gdb) start
28927 @end smallexample
28928
28929 @noindent
28930 This step is required to be able to set a breakpoint inside the DLL. As long
28931 as the program is not run, the DLL is not loaded. This has the
28932 consequence that the DLL debugging information is also not loaded, so it is not
28933 possible to set a breakpoint in the DLL.
28934
28935 @item Set a breakpoint inside the DLL
28936
28937 @smallexample
28938 (gdb) break ada_dll
28939 (gdb) cont
28940 @end smallexample
28941
28942 @end enumerate
28943
28944 @noindent
28945 At this stage a breakpoint is set inside the DLL. From there on
28946 you can use the standard approach to debug the whole program
28947 (@pxref{Running and Debugging Ada Programs}).
28948
28949 @ignore
28950 @c This used to work, probably because the DLLs were non-relocatable
28951 @c keep this section around until the problem is sorted out.
28952
28953 To break on the @code{DllMain} routine it is not possible to follow
28954 the procedure above. At the time the program stop on @code{ada_main}
28955 the @code{DllMain} routine as already been called. Either you can use
28956 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28957
28958 @enumerate 1
28959 @item Launch @code{GDB} on the main program.
28960
28961 @smallexample
28962 $ gdb ada_main
28963 @end smallexample
28964
28965 @item Load DLL symbols
28966
28967 @smallexample
28968 (gdb) add-sym api.dll
28969 @end smallexample
28970
28971 @item Set a breakpoint inside the DLL
28972
28973 @smallexample
28974 (gdb) break ada_dll.adb:45
28975 @end smallexample
28976
28977 Note that at this point it is not possible to break using the routine symbol
28978 directly as the program is not yet running. The solution is to break
28979 on the proper line (break in @file{ada_dll.adb} line 45).
28980
28981 @item Start the program
28982
28983 @smallexample
28984 (gdb) run
28985 @end smallexample
28986
28987 @end enumerate
28988 @end ignore
28989
28990 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28991 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28992
28993 @menu
28994 * Debugging the DLL Directly::
28995 * Attaching to a Running Process::
28996 @end menu
28997
28998 @noindent
28999 In this case things are slightly more complex because it is not possible to
29000 start the main program and then break at the beginning to load the DLL and the
29001 associated DLL debugging information. It is not possible to break at the
29002 beginning of the program because there is no @code{GDB} debugging information,
29003 and therefore there is no direct way of getting initial control. This
29004 section addresses this issue by describing some methods that can be used
29005 to break somewhere in the DLL to debug it.
29006
29007 @noindent
29008 First suppose that the main procedure is named @code{main} (this is for
29009 example some C code built with Microsoft Visual C) and that there is a
29010 DLL named @code{test.dll} containing an Ada entry point named
29011 @code{ada_dll}.
29012
29013 @noindent
29014 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29015 been built with debugging information (see GNAT -g option).
29016
29017 @node Debugging the DLL Directly
29018 @subsubsection Debugging the DLL Directly
29019
29020 @enumerate 1
29021 @item
29022 Find out the executable starting address
29023
29024 @smallexample
29025 $ objdump --file-header main.exe
29026 @end smallexample
29027
29028 The starting address is reported on the last line. For example:
29029
29030 @smallexample
29031 main.exe:     file format pei-i386
29032 architecture: i386, flags 0x0000010a:
29033 EXEC_P, HAS_DEBUG, D_PAGED
29034 start address 0x00401010
29035 @end smallexample
29036
29037 @item
29038 Launch the debugger on the executable.
29039
29040 @smallexample
29041 $ gdb main.exe
29042 @end smallexample
29043
29044 @item
29045 Set a breakpoint at the starting address, and launch the program.
29046
29047 @smallexample
29048 $ (gdb) break *0x00401010
29049 $ (gdb) run
29050 @end smallexample
29051
29052 The program will stop at the given address.
29053
29054 @item
29055 Set a breakpoint on a DLL subroutine.
29056
29057 @smallexample
29058 (gdb) break ada_dll.adb:45
29059 @end smallexample
29060
29061 Or if you want to break using a symbol on the DLL, you need first to
29062 select the Ada language (language used by the DLL).
29063
29064 @smallexample
29065 (gdb) set language ada
29066 (gdb) break ada_dll
29067 @end smallexample
29068
29069 @item
29070 Continue the program.
29071
29072 @smallexample
29073 (gdb) cont
29074 @end smallexample
29075
29076 @noindent
29077 This will run the program until it reaches the breakpoint that has been
29078 set. From that point you can use the standard way to debug a program
29079 as described in (@pxref{Running and Debugging Ada Programs}).
29080
29081 @end enumerate
29082
29083 @noindent
29084 It is also possible to debug the DLL by attaching to a running process.
29085
29086 @node Attaching to a Running Process
29087 @subsubsection Attaching to a Running Process
29088 @cindex DLL debugging, attach to process
29089
29090 @noindent
29091 With @code{GDB} it is always possible to debug a running process by
29092 attaching to it. It is possible to debug a DLL this way. The limitation
29093 of this approach is that the DLL must run long enough to perform the
29094 attach operation. It may be useful for instance to insert a time wasting
29095 loop in the code of the DLL to meet this criterion.
29096
29097 @enumerate 1
29098
29099 @item Launch the main program @file{main.exe}.
29100
29101 @smallexample
29102 $ main
29103 @end smallexample
29104
29105 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29106 that the process PID for @file{main.exe} is 208.
29107
29108 @item Launch gdb.
29109
29110 @smallexample
29111 $ gdb
29112 @end smallexample
29113
29114 @item Attach to the running process to be debugged.
29115
29116 @smallexample
29117 (gdb) attach 208
29118 @end smallexample
29119
29120 @item Load the process debugging information.
29121
29122 @smallexample
29123 (gdb) symbol-file main.exe
29124 @end smallexample
29125
29126 @item Break somewhere in the DLL.
29127
29128 @smallexample
29129 (gdb) break ada_dll
29130 @end smallexample
29131
29132 @item Continue process execution.
29133
29134 @smallexample
29135 (gdb) cont
29136 @end smallexample
29137
29138 @end enumerate
29139
29140 @noindent
29141 This last step will resume the process execution, and stop at
29142 the breakpoint we have set. From there you can use the standard
29143 approach to debug a program as described in
29144 (@pxref{Running and Debugging Ada Programs}).
29145
29146 @node Setting Stack Size from gnatlink
29147 @section Setting Stack Size from @command{gnatlink}
29148
29149 @noindent
29150 It is possible to specify the program stack size at link time. On modern
29151 versions of Windows, starting with XP, this is mostly useful to set the size of
29152 the main stack (environment task). The other task stacks are set with pragma
29153 Storage_Size or with the @command{gnatbind -d} command.
29154
29155 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29156 reserve size of individual tasks, the link-time stack size applies to all
29157 tasks, and pragma Storage_Size has no effect.
29158 In particular, Stack Overflow checks are made against this
29159 link-time specified size.
29160
29161 This setting can be done with
29162 @command{gnatlink} using either:
29163
29164 @itemize @bullet
29165
29166 @item using @option{-Xlinker} linker option
29167
29168 @smallexample
29169 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29170 @end smallexample
29171
29172 This sets the stack reserve size to 0x10000 bytes and the stack commit
29173 size to 0x1000 bytes.
29174
29175 @item using @option{-Wl} linker option
29176
29177 @smallexample
29178 $ gnatlink hello -Wl,--stack=0x1000000
29179 @end smallexample
29180
29181 This sets the stack reserve size to 0x1000000 bytes. Note that with
29182 @option{-Wl} option it is not possible to set the stack commit size
29183 because the coma is a separator for this option.
29184
29185 @end itemize
29186
29187 @node Setting Heap Size from gnatlink
29188 @section Setting Heap Size from @command{gnatlink}
29189
29190 @noindent
29191 Under Windows systems, it is possible to specify the program heap size from
29192 @command{gnatlink} using either:
29193
29194 @itemize @bullet
29195
29196 @item using @option{-Xlinker} linker option
29197
29198 @smallexample
29199 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29200 @end smallexample
29201
29202 This sets the heap reserve size to 0x10000 bytes and the heap commit
29203 size to 0x1000 bytes.
29204
29205 @item using @option{-Wl} linker option
29206
29207 @smallexample
29208 $ gnatlink hello -Wl,--heap=0x1000000
29209 @end smallexample
29210
29211 This sets the heap reserve size to 0x1000000 bytes. Note that with
29212 @option{-Wl} option it is not possible to set the heap commit size
29213 because the coma is a separator for this option.
29214
29215 @end itemize
29216
29217 @end ifset
29218
29219 @c **********************************
29220 @c * GNU Free Documentation License *
29221 @c **********************************
29222 @include fdl.texi
29223 @c GNU Free Documentation License
29224
29225 @node Index,,GNU Free Documentation License, Top
29226 @unnumbered Index
29227
29228 @printindex cp
29229
29230 @contents
29231 @c Put table of contents at end, otherwise it precedes the "title page" in
29232 @c the .txt version
29233 @c Edit the pdf file to move the contents to the beginning, after the title
29234 @c page
29235
29236 @bye