OSDN Git Service

2010-09-09 Vincent Celier <celier@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-2010, AdaCore                       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 * Generating Ada Bindings for C and C++ headers::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
198 @ifclear vms
199 * Code Coverage and Profiling::
200 @end ifclear
201 @ifset vms
202 * Compatibility with HP Ada::
203 @end ifset
204 * Platform-Specific Information for the Run-Time Libraries::
205 * Example of Binder Output File::
206 * Elaboration Order Handling in GNAT::
207 * Conditional Compilation::
208 * Inline Assembler::
209 * Compatibility and Porting Guide::
210 @ifset unw
211 * Microsoft Windows Topics::
212 @end ifset
213 * GNU Free Documentation License::
214 * Index::
215
216  --- The Detailed Node Listing ---
217
218 About This Guide
219
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
223 * Conventions::
224
225 Getting Started with GNAT
226
227 * Running GNAT::
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
231 @ifset vms
232 * Editing with Emacs::
233 @end ifset
234 @ifclear vms
235 * Introduction to GPS::
236 @end ifclear
237
238 The GNAT Compilation Model
239
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
250 @ifclear vms
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
253 @end ifclear
254 * Comparison between GNAT and Conventional Ada Library Models::
255 @ifset vms
256 * Placement of temporary files::
257 @end ifset
258
259 Foreign Language Representation
260
261 * Latin-1::
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
264
265 Compiling Ada Programs With gcc
266
267 * Compiling Programs::
268 * Switches for gcc::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
271 * Examples::
272
273 Switches for gcc
274
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
279 * Style Checking::
280 * Run-Time Checks::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
292 @ifset vms
293 * Return Codes::
294 @end ifset
295
296 Binding Ada Programs With gnatbind
297
298 * Running gnatbind::
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
303
304 Switches for gnatbind
305
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
309 * Output Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
312
313 Linking Using gnatlink
314
315 * Running gnatlink::
316 * Switches for gnatlink::
317
318 The GNAT Make Program gnatmake
319
320 * Running gnatmake::
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
326
327 Improving Performance
328 * Performance Considerations::
329 * Text_IO Suggestions::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
332
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
341 @ifset vms
342 * Coverage Analysis::
343 @end ifset
344
345 Reducing Size of Ada Executables with gnatelim
346 * About gnatelim::
347 * Running gnatelim::
348 * Processing Precompiled Libraries::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
352
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
356
357 Renaming Files Using gnatchop
358
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
364
365 Configuration Pragmas
366
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
369
370 Handling Arbitrary File Naming Conventions Using gnatname
371
372 * Arbitrary File Naming Conventions::
373 * Running gnatname::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
376
377 The Cross-Referencing Tools gnatxref and gnatfind
378
379 * Switches for gnatxref::
380 * Switches for gnatfind::
381 * Project Files for gnatxref and gnatfind::
382 * Regular Expressions in gnatfind and gnatxref::
383 * Examples of gnatxref Usage::
384 * Examples of gnatfind Usage::
385
386 The GNAT Pretty-Printer gnatpp
387
388 * Switches for gnatpp::
389 * Formatting Rules::
390
391 The GNAT Metrics Tool gnatmetric
392
393 * Switches for gnatmetric::
394
395 File Name Krunching Using gnatkr
396
397 * About gnatkr::
398 * Using gnatkr::
399 * Krunching Method::
400 * Examples of gnatkr Usage::
401
402 Preprocessing Using gnatprep
403 * Preprocessing Symbols::
404 * Using gnatprep::
405 * Switches for gnatprep::
406 * Form of Definitions File::
407 * Form of Input Text for gnatprep::
408
409 The GNAT Library Browser gnatls
410
411 * Running gnatls::
412 * Switches for gnatls::
413 * Examples of gnatls Usage::
414
415 Cleaning Up Using gnatclean
416
417 * Running gnatclean::
418 * Switches for gnatclean::
419 @c * Examples of gnatclean Usage::
420
421 @ifclear vms
422
423 GNAT and Libraries
424
425 * Introduction to Libraries in GNAT::
426 * General Ada Libraries::
427 * Stand-alone Ada Libraries::
428 * Rebuilding the GNAT Run-Time Library::
429
430 Using the GNU make Utility
431
432 * Using gnatmake in a Makefile::
433 * Automatically Creating a List of Directories::
434 * Generating the Command Line Switches::
435 * Overcoming Command Line Length Limits::
436 @end ifclear
437
438 Memory Management Issues
439
440 * Some Useful Memory Pools::
441 * The GNAT Debug Pool Facility::
442 @ifclear vms
443 * The gnatmem Tool::
444 @end ifclear
445
446 Stack Related Facilities
447
448 * Stack Overflow Checking::
449 * Static Stack Usage Analysis::
450 * Dynamic Stack Usage Analysis::
451
452 Some Useful Memory Pools
453
454 The GNAT Debug Pool Facility
455
456 @ifclear vms
457 The gnatmem Tool
458
459 * Running gnatmem::
460 * Switches for gnatmem::
461 * Example of gnatmem Usage::
462 @end ifclear
463
464 Verifying Properties Using gnatcheck
465
466 * Format of the Report File::
467 * General gnatcheck Switches::
468 * gnatcheck Rule Options::
469 * Adding the Results of Compiler Checks to gnatcheck Output::
470 * Project-Wide Checks::
471 * Rule exemption::
472 * Predefined Rules::
473 * Example of gnatcheck Usage::
474
475 Sample Bodies Using gnatstub
476
477 * Running gnatstub::
478 * Switches for gnatstub::
479
480 Other Utility Programs
481
482 * Using Other Utility Programs with GNAT::
483 * The External Symbol Naming Scheme of GNAT::
484 * Converting Ada Files to html with gnathtml::
485
486 @ifclear vms
487 Code Coverage and Profiling
488
489 * Code Coverage of Ada Programs using gcov::
490 * Profiling an Ada Program using gprof::
491 @end ifclear
492
493 Running and Debugging Ada Programs
494
495 * The GNAT Debugger GDB::
496 * Running GDB::
497 * Introduction to GDB Commands::
498 * Using Ada Expressions::
499 * Calling User-Defined Subprograms::
500 * Using the Next Command in a Function::
501 * Ada Exceptions::
502 * Ada Tasks::
503 * Debugging Generic Units::
504 * Remote Debugging using gdbserver::
505 * GNAT Abnormal Termination or Failure to Terminate::
506 * Naming Conventions for GNAT Source Files::
507 * Getting Internal Debugging Information::
508 * Stack Traceback::
509
510 @ifset vms
511 * LSE::
512 @end ifset
513
514 @ifset vms
515 Compatibility with HP Ada
516
517 * Ada Language Compatibility::
518 * Differences in the Definition of Package System::
519 * Language-Related Features::
520 * The Package STANDARD::
521 * The Package SYSTEM::
522 * Tasking and Task-Related Features::
523 * Pragmas and Pragma-Related Features::
524 * Library of Predefined Units::
525 * Bindings::
526 * Main Program Definition::
527 * Implementation-Defined Attributes::
528 * Compiler and Run-Time Interfacing::
529 * Program Compilation and Library Management::
530 * Input-Output::
531 * Implementation Limits::
532 * Tools and Utilities::
533
534 Language-Related Features
535
536 * Integer Types and Representations::
537 * Floating-Point Types and Representations::
538 * Pragmas Float_Representation and Long_Float::
539 * Fixed-Point Types and Representations::
540 * Record and Array Component Alignment::
541 * Address Clauses::
542 * Other Representation Clauses::
543
544 Tasking and Task-Related Features
545
546 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
547 * Assigning Task IDs::
548 * Task IDs and Delays::
549 * Task-Related Pragmas::
550 * Scheduling and Task Priority::
551 * The Task Stack::
552 * External Interrupts::
553
554 Pragmas and Pragma-Related Features
555
556 * Restrictions on the Pragma INLINE::
557 * Restrictions on the Pragma INTERFACE::
558 * Restrictions on the Pragma SYSTEM_NAME::
559
560 Library of Predefined Units
561
562 * Changes to DECLIB::
563
564 Bindings
565
566 * Shared Libraries and Options Files::
567 * Interfaces to C::
568 @end ifset
569
570 Platform-Specific Information for the Run-Time Libraries
571
572 * Summary of Run-Time Configurations::
573 * Specifying a Run-Time Library::
574 * Choosing the Scheduling Policy::
575 * Solaris-Specific Considerations::
576 * Linux-Specific Considerations::
577 * AIX-Specific Considerations::
578 * Irix-Specific Considerations::
579 * RTX-Specific Considerations::
580 * HP-UX-Specific Considerations::
581
582 Example of Binder Output File
583
584 Elaboration Order Handling in GNAT
585
586 * Elaboration Code::
587 * Checking the Elaboration Order::
588 * Controlling the Elaboration Order::
589 * Controlling Elaboration in GNAT - Internal Calls::
590 * Controlling Elaboration in GNAT - External Calls::
591 * Default Behavior in GNAT - Ensuring Safety::
592 * Treatment of Pragma Elaborate::
593 * Elaboration Issues for Library Tasks::
594 * Mixing Elaboration Models::
595 * What to Do If the Default Elaboration Behavior Fails::
596 * Elaboration for Access-to-Subprogram Values::
597 * Summary of Procedures for Elaboration Control::
598 * Other Elaboration Order Considerations::
599
600 Conditional Compilation
601 * Use of Boolean Constants::
602 * Debugging - A Special Case::
603 * Conditionalizing Declarations::
604 * Use of Alternative Implementations::
605 * Preprocessing::
606
607 Inline Assembler
608
609 * Basic Assembler Syntax::
610 * A Simple Example of Inline Assembler::
611 * Output Variables in Inline Assembler::
612 * Input Variables in Inline Assembler::
613 * Inlining Inline Assembler Code::
614 * Other Asm Functionality::
615
616 Compatibility and Porting Guide
617
618 * Compatibility with Ada 83::
619 * Compatibility between Ada 95 and Ada 2005::
620 * Implementation-dependent characteristics::
621 @ifclear vms
622 @c This brief section is only in the non-VMS version
623 @c The complete chapter on HP Ada issues is in the VMS version
624 * Compatibility with HP Ada 83::
625 @end ifclear
626 * Compatibility with Other Ada Systems::
627 * Representation Clauses::
628 @ifset vms
629 * Transitioning to 64-Bit GNAT for OpenVMS::
630 @end ifset
631
632 @ifset unw
633 Microsoft Windows Topics
634
635 * Using GNAT on Windows::
636 * CONSOLE and WINDOWS subsystems::
637 * Temporary Files::
638 * Mixed-Language Programming on Windows::
639 * Windows Calling Conventions::
640 * Introduction to Dynamic Link Libraries (DLLs)::
641 * Using DLLs with GNAT::
642 * Building DLLs with GNAT::
643 * GNAT and Windows Resources::
644 * Debugging a DLL::
645 * Setting Stack Size from gnatlink::
646 * Setting Heap Size from gnatlink::
647 @end ifset
648
649 * Index::
650 @end menu
651 @end ifnottex
652
653 @node About This Guide
654 @unnumbered About This Guide
655
656 @noindent
657 @ifset vms
658 This guide describes the use of @value{EDITION},
659 a compiler and software development toolset for the full Ada
660 programming language, implemented on OpenVMS for HP's Alpha and
661 Integrity server (I64) platforms.
662 @end ifset
663 @ifclear vms
664 This guide describes the use of @value{EDITION},
665 a compiler and software development
666 toolset for the full Ada programming language.
667 @end ifclear
668 It documents the features of the compiler and tools, and explains
669 how to use them to build Ada applications.
670
671 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
672 Ada 83 compatibility mode.
673 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
674 but you can override with a compiler switch
675 (@pxref{Compiling Different Versions of Ada})
676 to explicitly specify the language version.
677 Throughout this manual, references to ``Ada'' without a year suffix
678 apply to both the Ada 95 and Ada 2005 versions of the language.
679
680
681 @ifclear FSFEDITION
682 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
683 ``GNAT'' in the remainder of this document.
684 @end ifclear
685
686
687
688
689 @menu
690 * What This Guide Contains::
691 * What You Should Know before Reading This Guide::
692 * Related Information::
693 * Conventions::
694 @end menu
695
696 @node What This Guide Contains
697 @unnumberedsec What This Guide Contains
698
699 @noindent
700 This guide contains the following chapters:
701 @itemize @bullet
702
703 @item
704 @ref{Getting Started with GNAT}, describes how to get started compiling
705 and running Ada programs with the GNAT Ada programming environment.
706 @item
707 @ref{The GNAT Compilation Model}, describes the compilation model used
708 by GNAT.
709
710 @item
711 @ref{Compiling Using gcc}, describes how to compile
712 Ada programs with @command{gcc}, the Ada compiler.
713
714 @item
715 @ref{Binding Using gnatbind}, describes how to
716 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
717 utility.
718
719 @item
720 @ref{Linking Using gnatlink},
721 describes @command{gnatlink}, a
722 program that provides for linking using the GNAT run-time library to
723 construct a program. @command{gnatlink} can also incorporate foreign language
724 object units into the executable.
725
726 @item
727 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
728 utility that automatically determines the set of sources
729 needed by an Ada compilation unit, and executes the necessary compilations
730 binding and link.
731
732 @item
733 @ref{Improving Performance}, shows various techniques for making your
734 Ada program run faster or take less space.
735 It discusses the effect of the compiler's optimization switch and
736 also describes the @command{gnatelim} tool and unused subprogram/data
737 elimination.
738
739 @item
740 @ref{Renaming Files Using gnatchop}, describes
741 @code{gnatchop}, a utility that allows you to preprocess a file that
742 contains Ada source code, and split it into one or more new files, one
743 for each compilation unit.
744
745 @item
746 @ref{Configuration Pragmas}, describes the configuration pragmas
747 handled by GNAT.
748
749 @item
750 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
751 shows how to override the default GNAT file naming conventions,
752 either for an individual unit or globally.
753
754 @item
755 @ref{GNAT Project Manager}, describes how to use project files
756 to organize large projects.
757
758 @item
759 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
760 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
761 way to navigate through sources.
762
763 @item
764 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
765 version of an Ada source file with control over casing, indentation,
766 comment placement, and other elements of program presentation style.
767
768 @item
769 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
770 metrics for an Ada source file, such as the number of types and subprograms,
771 and assorted complexity measures.
772
773 @item
774 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
775 file name krunching utility, used to handle shortened
776 file names on operating systems with a limit on the length of names.
777
778 @item
779 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
780 preprocessor utility that allows a single source file to be used to
781 generate multiple or parameterized source files by means of macro
782 substitution.
783
784 @item
785 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
786 utility that displays information about compiled units, including dependences
787 on the corresponding sources files, and consistency of compilations.
788
789 @item
790 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
791 to delete files that are produced by the compiler, binder and linker.
792
793 @ifclear vms
794 @item
795 @ref{GNAT and Libraries}, describes the process of creating and using
796 Libraries with GNAT. It also describes how to recompile the GNAT run-time
797 library.
798
799 @item
800 @ref{Using the GNU make Utility}, describes some techniques for using
801 the GNAT toolset in Makefiles.
802 @end ifclear
803
804 @item
805 @ref{Memory Management Issues}, describes some useful predefined storage pools
806 and in particular the GNAT Debug Pool facility, which helps detect incorrect
807 memory references.
808 @ifclear vms
809 It also describes @command{gnatmem}, a utility that monitors dynamic
810 allocation and deallocation and helps detect ``memory leaks''.
811 @end ifclear
812
813 @item
814 @ref{Stack Related Facilities}, describes some useful tools associated with
815 stack checking and analysis.
816
817 @item
818 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
819 a utility that checks Ada code against a set of rules.
820
821 @item
822 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
823 a utility that generates empty but compilable bodies for library units.
824
825 @item
826 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
827 generate automatically Ada bindings from C and C++ headers.
828
829 @item
830 @ref{Other Utility Programs}, discusses several other GNAT utilities,
831 including @code{gnathtml}.
832
833 @ifclear vms
834 @item
835 @ref{Code Coverage and Profiling}, describes how to perform a structural
836 coverage and profile the execution of Ada programs.
837 @end ifclear
838
839 @item
840 @ref{Running and Debugging Ada Programs}, describes how to run and debug
841 Ada programs.
842
843 @ifset vms
844 @item
845 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
846 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
847 developed by Digital Equipment Corporation and currently supported by HP.}
848 for OpenVMS Alpha. This product was formerly known as DEC Ada,
849 @cindex DEC Ada
850 and for
851 historical compatibility reasons, the relevant libraries still use the
852 DEC prefix.
853 @end ifset
854
855 @item
856 @ref{Platform-Specific Information for the Run-Time Libraries},
857 describes the various run-time
858 libraries supported by GNAT on various platforms and explains how to
859 choose a particular library.
860
861 @item
862 @ref{Example of Binder Output File}, shows the source code for the binder
863 output file for a sample program.
864
865 @item
866 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
867 you deal with elaboration order issues.
868
869 @item
870 @ref{Conditional Compilation}, describes how to model conditional compilation,
871 both with Ada in general and with GNAT facilities in particular.
872
873 @item
874 @ref{Inline Assembler}, shows how to use the inline assembly facility
875 in an Ada program.
876
877 @item
878 @ref{Compatibility and Porting Guide}, contains sections on compatibility
879 of GNAT with other Ada development environments (including Ada 83 systems),
880 to assist in porting code from those environments.
881
882 @ifset unw
883 @item
884 @ref{Microsoft Windows Topics}, presents information relevant to the
885 Microsoft Windows platform.
886 @end ifset
887 @end itemize
888
889 @c *************************************************
890 @node What You Should Know before Reading This Guide
891 @c *************************************************
892 @unnumberedsec What You Should Know before Reading This Guide
893
894 @cindex Ada 95 Language Reference Manual
895 @cindex Ada 2005 Language Reference Manual
896 @noindent
897 This guide assumes a basic familiarity with the Ada 95 language, as
898 described in the International Standard ANSI/ISO/IEC-8652:1995, January
899 1995.
900 It does not require knowledge of the new features introduced by Ada 2005,
901 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
902 and Amendment 1).
903 Both reference manuals are included in the GNAT documentation
904 package.
905
906 @node Related Information
907 @unnumberedsec Related Information
908
909 @noindent
910 For further information about related tools, refer to the following
911 documents:
912
913 @itemize @bullet
914 @item
915 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
916 Reference Manual}, which contains all reference material for the GNAT
917 implementation of Ada.
918
919 @ifset unw
920 @item
921 @cite{Using the GNAT Programming Studio}, which describes the GPS
922 Integrated Development Environment.
923
924 @item
925 @cite{GNAT Programming Studio Tutorial}, which introduces the
926 main GPS features through examples.
927 @end ifset
928
929 @item
930 @cite{Ada 95 Reference Manual}, which contains reference
931 material for the Ada 95 programming language.
932
933 @item
934 @cite{Ada 2005 Reference Manual}, which contains reference
935 material for the Ada 2005 programming language.
936
937 @item
938 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
939 @ifset vms
940 in the GNU:[DOCS] directory,
941 @end ifset
942 for all details on the use of the GNU source-level debugger.
943
944 @item
945 @xref{Top,, The extensible self-documenting text editor, emacs,
946 GNU Emacs Manual},
947 @ifset vms
948 located in the GNU:[DOCS] directory if the EMACS kit is installed,
949 @end ifset
950 for full information on the extensible editor and programming
951 environment Emacs.
952
953 @end itemize
954
955 @c **************
956 @node Conventions
957 @unnumberedsec Conventions
958 @cindex Conventions
959 @cindex Typographical conventions
960
961 @noindent
962 Following are examples of the typographical and graphic conventions used
963 in this guide:
964
965 @itemize @bullet
966 @item
967 @code{Functions}, @command{utility program names}, @code{standard names},
968 and @code{classes}.
969
970 @item
971 @option{Option flags}
972
973 @item
974 @file{File names}, @samp{button names}, and @samp{field names}.
975
976 @item
977 @code{Variables}, @env{environment variables}, and @var{metasyntactic
978 variables}.
979
980 @item
981 @emph{Emphasis}.
982
983 @item
984 @r{[}optional information or parameters@r{]}
985
986 @item
987 Examples are described by text
988 @smallexample
989 and then shown this way.
990 @end smallexample
991 @end itemize
992
993 @noindent
994 Commands that are entered by the user are preceded in this manual by the
995 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
996 uses this sequence as a prompt, then the commands will appear exactly as
997 you see them in the manual. If your system uses some other prompt, then
998 the command will appear with the @code{$} replaced by whatever prompt
999 character you are using.
1000
1001 @ifset unw
1002 Full file names are shown with the ``@code{/}'' character
1003 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1004 If you are using GNAT on a Windows platform, please note that
1005 the ``@code{\}'' character should be used instead.
1006 @end ifset
1007
1008 @c ****************************
1009 @node Getting Started with GNAT
1010 @chapter Getting Started with GNAT
1011
1012 @noindent
1013 This chapter describes some simple ways of using GNAT to build
1014 executable Ada programs.
1015 @ifset unw
1016 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1017 show how to use the command line environment.
1018 @ref{Introduction to GPS}, provides a brief
1019 introduction to the GNAT Programming Studio, a visually-oriented
1020 Integrated Development Environment for GNAT.
1021 GPS offers a graphical ``look and feel'', support for development in
1022 other programming languages, comprehensive browsing features, and
1023 many other capabilities.
1024 For information on GPS please refer to
1025 @cite{Using the GNAT Programming Studio}.
1026 @end ifset
1027
1028 @menu
1029 * Running GNAT::
1030 * Running a Simple Ada Program::
1031 * Running a Program with Multiple Units::
1032 * Using the gnatmake Utility::
1033 @ifset vms
1034 * Editing with Emacs::
1035 @end ifset
1036 @ifclear vms
1037 * Introduction to GPS::
1038 @end ifclear
1039 @end menu
1040
1041 @node Running GNAT
1042 @section Running GNAT
1043
1044 @noindent
1045 Three steps are needed to create an executable file from an Ada source
1046 file:
1047
1048 @enumerate
1049 @item
1050 The source file(s) must be compiled.
1051 @item
1052 The file(s) must be bound using the GNAT binder.
1053 @item
1054 All appropriate object files must be linked to produce an executable.
1055 @end enumerate
1056
1057 @noindent
1058 All three steps are most commonly handled by using the @command{gnatmake}
1059 utility program that, given the name of the main program, automatically
1060 performs the necessary compilation, binding and linking steps.
1061
1062 @node Running a Simple Ada Program
1063 @section Running a Simple Ada Program
1064
1065 @noindent
1066 Any text editor may be used to prepare an Ada program.
1067 (If @code{Emacs} is
1068 used, the optional Ada mode may be helpful in laying out the program.)
1069 The
1070 program text is a normal text file. We will assume in our initial
1071 example that you have used your editor to prepare the following
1072 standard format text file:
1073
1074 @smallexample @c ada
1075 @cartouche
1076 with Ada.Text_IO; use Ada.Text_IO;
1077 procedure Hello is
1078 begin
1079    Put_Line ("Hello WORLD!");
1080 end Hello;
1081 @end cartouche
1082 @end smallexample
1083
1084 @noindent
1085 This file should be named @file{hello.adb}.
1086 With the normal default file naming conventions, GNAT requires
1087 that each file
1088 contain a single compilation unit whose file name is the
1089 unit name,
1090 with periods replaced by hyphens; the
1091 extension is @file{ads} for a
1092 spec and @file{adb} for a body.
1093 You can override this default file naming convention by use of the
1094 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1095 Alternatively, if you want to rename your files according to this default
1096 convention, which is probably more convenient if you will be using GNAT
1097 for all your compilations, then the @code{gnatchop} utility
1098 can be used to generate correctly-named source files
1099 (@pxref{Renaming Files Using gnatchop}).
1100
1101 You can compile the program using the following command (@code{$} is used
1102 as the command prompt in the examples in this document):
1103
1104 @smallexample
1105 $ gcc -c hello.adb
1106 @end smallexample
1107
1108 @noindent
1109 @command{gcc} is the command used to run the compiler. This compiler is
1110 capable of compiling programs in several languages, including Ada and
1111 C. It assumes that you have given it an Ada program if the file extension is
1112 either @file{.ads} or @file{.adb}, and it will then call
1113 the GNAT compiler to compile the specified file.
1114
1115 @ifclear vms
1116 The @option{-c} switch is required. It tells @command{gcc} to only do a
1117 compilation. (For C programs, @command{gcc} can also do linking, but this
1118 capability is not used directly for Ada programs, so the @option{-c}
1119 switch must always be present.)
1120 @end ifclear
1121
1122 This compile command generates a file
1123 @file{hello.o}, which is the object
1124 file corresponding to your Ada program. It also generates
1125 an ``Ada Library Information'' file @file{hello.ali},
1126 which contains additional information used to check
1127 that an Ada program is consistent.
1128 To build an executable file,
1129 use @code{gnatbind} to bind the program
1130 and @command{gnatlink} to link it. The
1131 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1132 @file{ALI} file, but the default extension of @file{.ali} can
1133 be omitted. This means that in the most common case, the argument
1134 is simply the name of the main program:
1135
1136 @smallexample
1137 $ gnatbind hello
1138 $ gnatlink hello
1139 @end smallexample
1140
1141 @noindent
1142 A simpler method of carrying out these steps is to use
1143 @command{gnatmake},
1144 a master program that invokes all the required
1145 compilation, binding and linking tools in the correct order. In particular,
1146 @command{gnatmake} automatically recompiles any sources that have been
1147 modified since they were last compiled, or sources that depend
1148 on such modified sources, so that ``version skew'' is avoided.
1149 @cindex Version skew (avoided by @command{gnatmake})
1150
1151 @smallexample
1152 $ gnatmake hello.adb
1153 @end smallexample
1154
1155 @noindent
1156 The result is an executable program called @file{hello}, which can be
1157 run by entering:
1158
1159 @smallexample
1160 $ ^hello^RUN HELLO^
1161 @end smallexample
1162
1163 @noindent
1164 assuming that the current directory is on the search path
1165 for executable programs.
1166
1167 @noindent
1168 and, if all has gone well, you will see
1169
1170 @smallexample
1171 Hello WORLD!
1172 @end smallexample
1173
1174 @noindent
1175 appear in response to this command.
1176
1177 @c ****************************************
1178 @node Running a Program with Multiple Units
1179 @section Running a Program with Multiple Units
1180
1181 @noindent
1182 Consider a slightly more complicated example that has three files: a
1183 main program, and the spec and body of a package:
1184
1185 @smallexample @c ada
1186 @cartouche
1187 @group
1188 package Greetings is
1189    procedure Hello;
1190    procedure Goodbye;
1191 end Greetings;
1192
1193 with Ada.Text_IO; use Ada.Text_IO;
1194 package body Greetings is
1195    procedure Hello is
1196    begin
1197       Put_Line ("Hello WORLD!");
1198    end Hello;
1199
1200    procedure Goodbye is
1201    begin
1202       Put_Line ("Goodbye WORLD!");
1203    end Goodbye;
1204 end Greetings;
1205 @end group
1206
1207 @group
1208 with Greetings;
1209 procedure Gmain is
1210 begin
1211    Greetings.Hello;
1212    Greetings.Goodbye;
1213 end Gmain;
1214 @end group
1215 @end cartouche
1216 @end smallexample
1217
1218 @noindent
1219 Following the one-unit-per-file rule, place this program in the
1220 following three separate files:
1221
1222 @table @file
1223 @item greetings.ads
1224 spec of package @code{Greetings}
1225
1226 @item greetings.adb
1227 body of package @code{Greetings}
1228
1229 @item gmain.adb
1230 body of main program
1231 @end table
1232
1233 @noindent
1234 To build an executable version of
1235 this program, we could use four separate steps to compile, bind, and link
1236 the program, as follows:
1237
1238 @smallexample
1239 $ gcc -c gmain.adb
1240 $ gcc -c greetings.adb
1241 $ gnatbind gmain
1242 $ gnatlink gmain
1243 @end smallexample
1244
1245 @noindent
1246 Note that there is no required order of compilation when using GNAT.
1247 In particular it is perfectly fine to compile the main program first.
1248 Also, it is not necessary to compile package specs in the case where
1249 there is an accompanying body; you only need to compile the body. If you want
1250 to submit these files to the compiler for semantic checking and not code
1251 generation, then use the
1252 @option{-gnatc} switch:
1253
1254 @smallexample
1255 $ gcc -c greetings.ads -gnatc
1256 @end smallexample
1257
1258 @noindent
1259 Although the compilation can be done in separate steps as in the
1260 above example, in practice it is almost always more convenient
1261 to use the @command{gnatmake} tool. All you need to know in this case
1262 is the name of the main program's source file. The effect of the above four
1263 commands can be achieved with a single one:
1264
1265 @smallexample
1266 $ gnatmake gmain.adb
1267 @end smallexample
1268
1269 @noindent
1270 In the next section we discuss the advantages of using @command{gnatmake} in
1271 more detail.
1272
1273 @c *****************************
1274 @node Using the gnatmake Utility
1275 @section Using the @command{gnatmake} Utility
1276
1277 @noindent
1278 If you work on a program by compiling single components at a time using
1279 @command{gcc}, you typically keep track of the units you modify. In order to
1280 build a consistent system, you compile not only these units, but also any
1281 units that depend on the units you have modified.
1282 For example, in the preceding case,
1283 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1284 you edit @file{greetings.ads}, you must recompile both
1285 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1286 units that depend on @file{greetings.ads}.
1287
1288 @code{gnatbind} will warn you if you forget one of these compilation
1289 steps, so that it is impossible to generate an inconsistent program as a
1290 result of forgetting to do a compilation. Nevertheless it is tedious and
1291 error-prone to keep track of dependencies among units.
1292 One approach to handle the dependency-bookkeeping is to use a
1293 makefile. However, makefiles present maintenance problems of their own:
1294 if the dependencies change as you change the program, you must make
1295 sure that the makefile is kept up-to-date manually, which is also an
1296 error-prone process.
1297
1298 The @command{gnatmake} utility takes care of these details automatically.
1299 Invoke it using either one of the following forms:
1300
1301 @smallexample
1302 $ gnatmake gmain.adb
1303 $ gnatmake ^gmain^GMAIN^
1304 @end smallexample
1305
1306 @noindent
1307 The argument is the name of the file containing the main program;
1308 you may omit the extension. @command{gnatmake}
1309 examines the environment, automatically recompiles any files that need
1310 recompiling, and binds and links the resulting set of object files,
1311 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1312 In a large program, it
1313 can be extremely helpful to use @command{gnatmake}, because working out by hand
1314 what needs to be recompiled can be difficult.
1315
1316 Note that @command{gnatmake}
1317 takes into account all the Ada rules that
1318 establish dependencies among units. These include dependencies that result
1319 from inlining subprogram bodies, and from
1320 generic instantiation. Unlike some other
1321 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1322 found by the compiler on a previous compilation, which may possibly
1323 be wrong when sources change. @command{gnatmake} determines the exact set of
1324 dependencies from scratch each time it is run.
1325
1326 @ifset vms
1327 @node Editing with Emacs
1328 @section Editing with Emacs
1329 @cindex Emacs
1330
1331 @noindent
1332 Emacs is an extensible self-documenting text editor that is available in a
1333 separate VMSINSTAL kit.
1334
1335 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1336 click on the Emacs Help menu and run the Emacs Tutorial.
1337 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1338 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1339
1340 Documentation on Emacs and other tools is available in Emacs under the
1341 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1342 use the middle mouse button to select a topic (e.g.@: Emacs).
1343
1344 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1345 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1346 get to the Emacs manual.
1347 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1348 prompt.
1349
1350 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1351 which is sufficiently extensible to provide for a complete programming
1352 environment and shell for the sophisticated user.
1353 @end ifset
1354
1355 @ifclear vms
1356 @node Introduction to GPS
1357 @section Introduction to GPS
1358 @cindex GPS (GNAT Programming Studio)
1359 @cindex GNAT Programming Studio (GPS)
1360 @noindent
1361 Although the command line interface (@command{gnatmake}, etc.) alone
1362 is sufficient, a graphical Interactive Development
1363 Environment can make it easier for you to compose, navigate, and debug
1364 programs.  This section describes the main features of GPS
1365 (``GNAT Programming Studio''), the GNAT graphical IDE.
1366 You will see how to use GPS to build and debug an executable, and
1367 you will also learn some of the basics of the GNAT ``project'' facility.
1368
1369 GPS enables you to do much more than is presented here;
1370 e.g., you can produce a call graph, interface to a third-party
1371 Version Control System, and inspect the generated assembly language
1372 for a program.
1373 Indeed, GPS also supports languages other than Ada.
1374 Such additional information, and an explanation of all of the GPS menu
1375 items. may be found in the on-line help, which includes
1376 a user's guide and a tutorial (these are also accessible from the GNAT
1377 startup menu).
1378
1379 @menu
1380 * Building a New Program with GPS::
1381 * Simple Debugging with GPS::
1382 @end menu
1383
1384 @node Building a New Program with GPS
1385 @subsection Building a New Program with GPS
1386 @noindent
1387 GPS invokes the GNAT compilation tools using information
1388 contained in a @emph{project} (also known as a @emph{project file}):
1389 a collection of properties such
1390 as source directories, identities of main subprograms, tool switches, etc.,
1391 and their associated values.
1392 See @ref{GNAT Project Manager} for details.
1393 In order to run GPS, you will need to either create a new project
1394 or else open an existing one.
1395
1396 This section will explain how you can use GPS to create a project,
1397 to associate Ada source files with a project, and to build and run
1398 programs.
1399
1400 @enumerate
1401 @item @emph{Creating a project}
1402
1403 Invoke GPS, either from the command line or the platform's IDE.
1404 After it starts, GPS will display a ``Welcome'' screen with three
1405 radio buttons:
1406
1407 @itemize @bullet
1408 @item
1409 @code{Start with default project in directory}
1410
1411 @item
1412 @code{Create new project with wizard}
1413
1414 @item
1415 @code{Open existing project}
1416 @end itemize
1417
1418 @noindent
1419 Select @code{Create new project with wizard} and press @code{OK}.
1420 A new window will appear.  In the text box labeled with
1421 @code{Enter the name of the project to create}, type @file{sample}
1422 as the project name.
1423 In the next box, browse to choose the directory in which you
1424 would like to create the project file.
1425 After selecting an appropriate directory, press @code{Forward}.
1426
1427 A window will appear with the title
1428 @code{Version Control System Configuration}.
1429 Simply press @code{Forward}.
1430
1431 A window will appear with the title
1432 @code{Please select the source directories for this project}.
1433 The directory that you specified for the project file will be selected
1434 by default as the one to use for sources; simply press @code{Forward}.
1435
1436 A window will appear with the title
1437 @code{Please select the build directory for this project}.
1438 The directory that you specified for the project file will be selected
1439 by default for object files and executables;
1440 simply press @code{Forward}.
1441
1442 A window will appear with the title
1443 @code{Please select the main units for this project}.
1444 You will supply this information later, after creating the source file.
1445 Simply press @code{Forward} for now.
1446
1447 A window will appear with the title
1448 @code{Please select the switches to build the project}.
1449 Press @code{Apply}.  This will create a project file named
1450 @file{sample.prj} in the directory that you had specified.
1451
1452 @item @emph{Creating and saving the source file}
1453
1454 After you create the new project, a GPS window will appear, which is
1455 partitioned into two main sections:
1456
1457 @itemize @bullet
1458 @item
1459 A @emph{Workspace area}, initially greyed out, which you will use for
1460 creating and editing source files
1461
1462 @item
1463 Directly below, a @emph{Messages area}, which initially displays a
1464 ``Welcome'' message.
1465 (If the Messages area is not visible, drag its border upward to expand it.)
1466 @end itemize
1467
1468 @noindent
1469 Select @code{File} on the menu bar, and then the @code{New} command.
1470 The Workspace area will become white, and you can now
1471 enter the source program explicitly.
1472 Type the following text
1473
1474 @smallexample @c ada
1475 @group
1476 with Ada.Text_IO; use Ada.Text_IO;
1477 procedure Hello is
1478 begin
1479   Put_Line("Hello from GPS!");
1480 end Hello;
1481 @end group
1482 @end smallexample
1483
1484 @noindent
1485 Select @code{File}, then @code{Save As}, and enter the source file name
1486 @file{hello.adb}.
1487 The file will be saved in the same directory you specified as the
1488 location of the default project file.
1489
1490 @item @emph{Updating the project file}
1491
1492 You need to add the new source file to the project.
1493 To do this, select
1494 the @code{Project} menu and then @code{Edit project properties}.
1495 Click the @code{Main files} tab on the left, and then the
1496 @code{Add} button.
1497 Choose @file{hello.adb} from the list, and press @code{Open}.
1498 The project settings window will reflect this action.
1499 Click @code{OK}.
1500
1501 @item @emph{Building and running the program}
1502
1503 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1504 and select @file{hello.adb}.
1505 The Messages window will display the resulting invocations of @command{gcc},
1506 @command{gnatbind}, and @command{gnatlink}
1507 (reflecting the default switch settings from the
1508 project file that you created) and then a ``successful compilation/build''
1509 message.
1510
1511 To run the program, choose the @code{Build} menu, then @code{Run}, and
1512 select @command{hello}.
1513 An @emph{Arguments Selection} window will appear.
1514 There are no command line arguments, so just click @code{OK}.
1515
1516 The Messages window will now display the program's output (the string
1517 @code{Hello from GPS}), and at the bottom of the GPS window a status
1518 update is displayed (@code{Run: hello}).
1519 Close the GPS window (or select @code{File}, then @code{Exit}) to
1520 terminate this GPS session.
1521 @end enumerate
1522
1523 @node Simple Debugging with GPS
1524 @subsection Simple Debugging with GPS
1525 @noindent
1526 This section illustrates basic debugging techniques (setting breakpoints,
1527 examining/modifying variables, single stepping).
1528
1529 @enumerate
1530 @item @emph{Opening a project}
1531
1532 Start GPS and select @code{Open existing project}; browse to
1533 specify the project file @file{sample.prj} that you had created in the
1534 earlier example.
1535
1536 @item @emph{Creating a source file}
1537
1538 Select @code{File}, then @code{New}, and type in the following program:
1539
1540 @smallexample @c ada
1541 @group
1542 with Ada.Text_IO; use Ada.Text_IO;
1543 procedure Example is
1544    Line : String (1..80);
1545    N    : Natural;
1546 begin
1547    Put_Line("Type a line of text at each prompt; an empty line to exit");
1548    loop
1549       Put(": ");
1550       Get_Line (Line, N);
1551       Put_Line (Line (1..N) );
1552       exit when N=0;
1553    end loop;
1554 end Example;
1555 @end group
1556 @end smallexample
1557
1558 @noindent
1559 Select @code{File}, then @code{Save as}, and enter the file name
1560 @file{example.adb}.
1561
1562 @item @emph{Updating the project file}
1563
1564 Add @code{Example} as a new main unit for the project:
1565 @enumerate a
1566 @item
1567 Select @code{Project}, then @code{Edit Project Properties}.
1568
1569 @item
1570 Select the @code{Main files} tab, click @code{Add}, then
1571 select the file @file{example.adb} from the list, and
1572 click @code{Open}.
1573 You will see the file name appear in the list of main units
1574
1575 @item
1576 Click @code{OK}
1577 @end enumerate
1578
1579 @item @emph{Building/running the executable}
1580
1581 To build the executable
1582 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1583
1584 Run the program to see its effect (in the Messages area).
1585 Each line that you enter is displayed; an empty line will
1586 cause the loop to exit and the program to terminate.
1587
1588 @item @emph{Debugging the program}
1589
1590 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1591 which are required for debugging, are on by default when you create
1592 a new project.
1593 Thus unless you intentionally remove these settings, you will be able
1594 to debug any program that you develop using GPS.
1595
1596 @enumerate a
1597 @item @emph{Initializing}
1598
1599 Select @code{Debug}, then @code{Initialize}, then @file{example}
1600
1601 @item @emph{Setting a breakpoint}
1602
1603 After performing the initialization step, you will observe a small
1604 icon to the right of each line number.
1605 This serves as a toggle for breakpoints; clicking the icon will
1606 set a breakpoint at the corresponding line (the icon will change to
1607 a red circle with an ``x''), and clicking it again
1608 will remove the breakpoint / reset the icon.
1609
1610 For purposes of this example, set a breakpoint at line 10 (the
1611 statement @code{Put_Line@ (Line@ (1..N));}
1612
1613 @item @emph{Starting program execution}
1614
1615 Select @code{Debug}, then @code{Run}.  When the
1616 @code{Program Arguments} window appears, click @code{OK}.
1617 A console window will appear; enter some line of text,
1618 e.g.@: @code{abcde}, at the prompt.
1619 The program will pause execution when it gets to the
1620 breakpoint, and the corresponding line is highlighted.
1621
1622 @item @emph{Examining a variable}
1623
1624 Move the mouse over one of the occurrences of the variable @code{N}.
1625 You will see the value (5) displayed, in ``tool tip'' fashion.
1626 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1627 You will see information about @code{N} appear in the @code{Debugger Data}
1628 pane, showing the value as 5.
1629
1630 @item @emph{Assigning a new value to a variable}
1631
1632 Right click on the @code{N} in the @code{Debugger Data} pane, and
1633 select @code{Set value of N}.
1634 When the input window appears, enter the value @code{4} and click
1635 @code{OK}.
1636 This value does not automatically appear in the @code{Debugger Data}
1637 pane; to see it, right click again on the @code{N} in the
1638 @code{Debugger Data} pane and select @code{Update value}.
1639 The new value, 4, will appear in red.
1640
1641 @item @emph{Single stepping}
1642
1643 Select @code{Debug}, then @code{Next}.
1644 This will cause the next statement to be executed, in this case the
1645 call of @code{Put_Line} with the string slice.
1646 Notice in the console window that the displayed string is simply
1647 @code{abcd} and not @code{abcde} which you had entered.
1648 This is because the upper bound of the slice is now 4 rather than 5.
1649
1650 @item @emph{Removing a breakpoint}
1651
1652 Toggle the breakpoint icon at line 10.
1653
1654 @item @emph{Resuming execution from a breakpoint}
1655
1656 Select @code{Debug}, then @code{Continue}.
1657 The program will reach the next iteration of the loop, and
1658 wait for input after displaying the prompt.
1659 This time, just hit the @kbd{Enter} key.
1660 The value of @code{N} will be 0, and the program will terminate.
1661 The console window will disappear.
1662 @end enumerate
1663 @end enumerate
1664 @end ifclear
1665
1666 @node The GNAT Compilation Model
1667 @chapter The GNAT Compilation Model
1668 @cindex GNAT compilation model
1669 @cindex Compilation model
1670
1671 @menu
1672 * Source Representation::
1673 * Foreign Language Representation::
1674 * File Naming Rules::
1675 * Using Other File Names::
1676 * Alternative File Naming Schemes::
1677 * Generating Object Files::
1678 * Source Dependencies::
1679 * The Ada Library Information Files::
1680 * Binding an Ada Program::
1681 * Mixed Language Programming::
1682 @ifclear vms
1683 * Building Mixed Ada & C++ Programs::
1684 * Comparison between GNAT and C/C++ Compilation Models::
1685 @end ifclear
1686 * Comparison between GNAT and Conventional Ada Library Models::
1687 @ifset vms
1688 * Placement of temporary files::
1689 @end ifset
1690 @end menu
1691
1692 @noindent
1693 This chapter describes the compilation model used by GNAT. Although
1694 similar to that used by other languages, such as C and C++, this model
1695 is substantially different from the traditional Ada compilation models,
1696 which are based on a library. The model is initially described without
1697 reference to the library-based model. If you have not previously used an
1698 Ada compiler, you need only read the first part of this chapter. The
1699 last section describes and discusses the differences between the GNAT
1700 model and the traditional Ada compiler models. If you have used other
1701 Ada compilers, this section will help you to understand those
1702 differences, and the advantages of the GNAT model.
1703
1704 @node Source Representation
1705 @section Source Representation
1706 @cindex Latin-1
1707
1708 @noindent
1709 Ada source programs are represented in standard text files, using
1710 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1711 7-bit ASCII set, plus additional characters used for
1712 representing foreign languages (@pxref{Foreign Language Representation}
1713 for support of non-USA character sets). The format effector characters
1714 are represented using their standard ASCII encodings, as follows:
1715
1716 @table @code
1717 @item VT
1718 @findex VT
1719 Vertical tab, @code{16#0B#}
1720
1721 @item HT
1722 @findex HT
1723 Horizontal tab, @code{16#09#}
1724
1725 @item CR
1726 @findex CR
1727 Carriage return, @code{16#0D#}
1728
1729 @item LF
1730 @findex LF
1731 Line feed, @code{16#0A#}
1732
1733 @item FF
1734 @findex FF
1735 Form feed, @code{16#0C#}
1736 @end table
1737
1738 @noindent
1739 Source files are in standard text file format. In addition, GNAT will
1740 recognize a wide variety of stream formats, in which the end of
1741 physical lines is marked by any of the following sequences:
1742 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1743 in accommodating files that are imported from other operating systems.
1744
1745 @cindex End of source file
1746 @cindex Source file, end
1747 @findex SUB
1748 The end of a source file is normally represented by the physical end of
1749 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1750 recognized as signalling the end of the source file. Again, this is
1751 provided for compatibility with other operating systems where this
1752 code is used to represent the end of file.
1753
1754 Each file contains a single Ada compilation unit, including any pragmas
1755 associated with the unit. For example, this means you must place a
1756 package declaration (a package @dfn{spec}) and the corresponding body in
1757 separate files. An Ada @dfn{compilation} (which is a sequence of
1758 compilation units) is represented using a sequence of files. Similarly,
1759 you will place each subunit or child unit in a separate file.
1760
1761 @node Foreign Language Representation
1762 @section Foreign Language Representation
1763
1764 @noindent
1765 GNAT supports the standard character sets defined in Ada as well as
1766 several other non-standard character sets for use in localized versions
1767 of the compiler (@pxref{Character Set Control}).
1768 @menu
1769 * Latin-1::
1770 * Other 8-Bit Codes::
1771 * Wide Character Encodings::
1772 @end menu
1773
1774 @node Latin-1
1775 @subsection Latin-1
1776 @cindex Latin-1
1777
1778 @noindent
1779 The basic character set is Latin-1. This character set is defined by ISO
1780 standard 8859, part 1. The lower half (character codes @code{16#00#}
1781 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1782 half is used to represent additional characters. These include extended letters
1783 used by European languages, such as French accents, the vowels with umlauts
1784 used in German, and the extra letter A-ring used in Swedish.
1785
1786 @findex Ada.Characters.Latin_1
1787 For a complete list of Latin-1 codes and their encodings, see the source
1788 file of library unit @code{Ada.Characters.Latin_1} in file
1789 @file{a-chlat1.ads}.
1790 You may use any of these extended characters freely in character or
1791 string literals. In addition, the extended characters that represent
1792 letters can be used in identifiers.
1793
1794 @node Other 8-Bit Codes
1795 @subsection Other 8-Bit Codes
1796
1797 @noindent
1798 GNAT also supports several other 8-bit coding schemes:
1799
1800 @table @asis
1801 @item ISO 8859-2 (Latin-2)
1802 @cindex Latin-2
1803 @cindex ISO 8859-2
1804 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1805 equivalence.
1806
1807 @item ISO 8859-3 (Latin-3)
1808 @cindex Latin-3
1809 @cindex ISO 8859-3
1810 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1811 equivalence.
1812
1813 @item ISO 8859-4 (Latin-4)
1814 @cindex Latin-4
1815 @cindex ISO 8859-4
1816 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1817 equivalence.
1818
1819 @item ISO 8859-5 (Cyrillic)
1820 @cindex ISO 8859-5
1821 @cindex Cyrillic
1822 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1823 lowercase equivalence.
1824
1825 @item ISO 8859-15 (Latin-9)
1826 @cindex ISO 8859-15
1827 @cindex Latin-9
1828 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1829 lowercase equivalence
1830
1831 @item IBM PC (code page 437)
1832 @cindex code page 437
1833 This code page is the normal default for PCs in the U.S. It corresponds
1834 to the original IBM PC character set. This set has some, but not all, of
1835 the extended Latin-1 letters, but these letters do not have the same
1836 encoding as Latin-1. In this mode, these letters are allowed in
1837 identifiers with uppercase and lowercase equivalence.
1838
1839 @item IBM PC (code page 850)
1840 @cindex code page 850
1841 This code page is a modification of 437 extended to include all the
1842 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1843 mode, all these letters are allowed in identifiers with uppercase and
1844 lowercase equivalence.
1845
1846 @item Full Upper 8-bit
1847 Any character in the range 80-FF allowed in identifiers, and all are
1848 considered distinct. In other words, there are no uppercase and lowercase
1849 equivalences in this range. This is useful in conjunction with
1850 certain encoding schemes used for some foreign character sets (e.g.,
1851 the typical method of representing Chinese characters on the PC).
1852
1853 @item No Upper-Half
1854 No upper-half characters in the range 80-FF are allowed in identifiers.
1855 This gives Ada 83 compatibility for identifier names.
1856 @end table
1857
1858 @noindent
1859 For precise data on the encodings permitted, and the uppercase and lowercase
1860 equivalences that are recognized, see the file @file{csets.adb} in
1861 the GNAT compiler sources. You will need to obtain a full source release
1862 of GNAT to obtain this file.
1863
1864 @node Wide Character Encodings
1865 @subsection Wide Character Encodings
1866
1867 @noindent
1868 GNAT allows wide character codes to appear in character and string
1869 literals, and also optionally in identifiers, by means of the following
1870 possible encoding schemes:
1871
1872 @table @asis
1873
1874 @item Hex Coding
1875 In this encoding, a wide character is represented by the following five
1876 character sequence:
1877
1878 @smallexample
1879 ESC a b c d
1880 @end smallexample
1881
1882 @noindent
1883 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1884 characters (using uppercase letters) of the wide character code. For
1885 example, ESC A345 is used to represent the wide character with code
1886 @code{16#A345#}.
1887 This scheme is compatible with use of the full Wide_Character set.
1888
1889 @item Upper-Half Coding
1890 @cindex Upper-Half Coding
1891 The wide character with encoding @code{16#abcd#} where the upper bit is on
1892 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1893 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1894 character, but is not required to be in the upper half. This method can
1895 be also used for shift-JIS or EUC, where the internal coding matches the
1896 external coding.
1897
1898 @item Shift JIS Coding
1899 @cindex Shift JIS Coding
1900 A wide character is represented by a two-character sequence,
1901 @code{16#ab#} and
1902 @code{16#cd#}, with the restrictions described for upper-half encoding as
1903 described above. The internal character code is the corresponding JIS
1904 character according to the standard algorithm for Shift-JIS
1905 conversion. Only characters defined in the JIS code set table can be
1906 used with this encoding method.
1907
1908 @item EUC Coding
1909 @cindex EUC Coding
1910 A wide character is represented by a two-character sequence
1911 @code{16#ab#} and
1912 @code{16#cd#}, with both characters being in the upper half. The internal
1913 character code is the corresponding JIS character according to the EUC
1914 encoding algorithm. Only characters defined in the JIS code set table
1915 can be used with this encoding method.
1916
1917 @item UTF-8 Coding
1918 A wide character is represented using
1919 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1920 10646-1/Am.2. Depending on the character value, the representation
1921 is a one, two, or three byte sequence:
1922 @smallexample
1923 @iftex
1924 @leftskip=.7cm
1925 @end iftex
1926 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1927 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1928 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1929
1930 @end smallexample
1931
1932 @noindent
1933 where the @var{xxx} bits correspond to the left-padded bits of the
1934 16-bit character value. Note that all lower half ASCII characters
1935 are represented as ASCII bytes and all upper half characters and
1936 other wide characters are represented as sequences of upper-half
1937 (The full UTF-8 scheme allows for encoding 31-bit characters as
1938 6-byte sequences, but in this implementation, all UTF-8 sequences
1939 of four or more bytes length will be treated as illegal).
1940 @item Brackets Coding
1941 In this encoding, a wide character is represented by the following eight
1942 character sequence:
1943
1944 @smallexample
1945 [ " a b c d " ]
1946 @end smallexample
1947
1948 @noindent
1949 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1950 characters (using uppercase letters) of the wide character code. For
1951 example, [``A345''] is used to represent the wide character with code
1952 @code{16#A345#}. It is also possible (though not required) to use the
1953 Brackets coding for upper half characters. For example, the code
1954 @code{16#A3#} can be represented as @code{[``A3'']}.
1955
1956 This scheme is compatible with use of the full Wide_Character set,
1957 and is also the method used for wide character encoding in the standard
1958 ACVC (Ada Compiler Validation Capability) test suite distributions.
1959
1960 @end table
1961
1962 @noindent
1963 Note: Some of these coding schemes do not permit the full use of the
1964 Ada character set. For example, neither Shift JIS, nor EUC allow the
1965 use of the upper half of the Latin-1 set.
1966
1967 @node File Naming Rules
1968 @section File Naming Rules
1969
1970 @noindent
1971 The default file name is determined by the name of the unit that the
1972 file contains. The name is formed by taking the full expanded name of
1973 the unit and replacing the separating dots with hyphens and using
1974 ^lowercase^uppercase^ for all letters.
1975
1976 An exception arises if the file name generated by the above rules starts
1977 with one of the characters
1978 @ifset vms
1979 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1980 @end ifset
1981 @ifclear vms
1982 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1983 @end ifclear
1984 and the second character is a
1985 minus. In this case, the character ^tilde^dollar sign^ is used in place
1986 of the minus. The reason for this special rule is to avoid clashes with
1987 the standard names for child units of the packages System, Ada,
1988 Interfaces, and GNAT, which use the prefixes
1989 @ifset vms
1990 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1991 @end ifset
1992 @ifclear vms
1993 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1994 @end ifclear
1995 respectively.
1996
1997 The file extension is @file{.ads} for a spec and
1998 @file{.adb} for a body. The following list shows some
1999 examples of these rules.
2000
2001 @table @file
2002 @item main.ads
2003 Main (spec)
2004 @item main.adb
2005 Main (body)
2006 @item arith_functions.ads
2007 Arith_Functions (package spec)
2008 @item arith_functions.adb
2009 Arith_Functions (package body)
2010 @item func-spec.ads
2011 Func.Spec (child package spec)
2012 @item func-spec.adb
2013 Func.Spec (child package body)
2014 @item main-sub.adb
2015 Sub (subunit of Main)
2016 @item ^a~bad.adb^A$BAD.ADB^
2017 A.Bad (child package body)
2018 @end table
2019
2020 @noindent
2021 Following these rules can result in excessively long
2022 file names if corresponding
2023 unit names are long (for example, if child units or subunits are
2024 heavily nested). An option is available to shorten such long file names
2025 (called file name ``krunching''). This may be particularly useful when
2026 programs being developed with GNAT are to be used on operating systems
2027 with limited file name lengths. @xref{Using gnatkr}.
2028
2029 Of course, no file shortening algorithm can guarantee uniqueness over
2030 all possible unit names; if file name krunching is used, it is your
2031 responsibility to ensure no name clashes occur. Alternatively you
2032 can specify the exact file names that you want used, as described
2033 in the next section. Finally, if your Ada programs are migrating from a
2034 compiler with a different naming convention, you can use the gnatchop
2035 utility to produce source files that follow the GNAT naming conventions.
2036 (For details @pxref{Renaming Files Using gnatchop}.)
2037
2038 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2039 systems, case is not significant. So for example on @code{Windows XP}
2040 if the canonical name is @code{main-sub.adb}, you can use the file name
2041 @code{Main-Sub.adb} instead. However, case is significant for other
2042 operating systems, so for example, if you want to use other than
2043 canonically cased file names on a Unix system, you need to follow
2044 the procedures described in the next section.
2045
2046 @node Using Other File Names
2047 @section Using Other File Names
2048 @cindex File names
2049
2050 @noindent
2051 In the previous section, we have described the default rules used by
2052 GNAT to determine the file name in which a given unit resides. It is
2053 often convenient to follow these default rules, and if you follow them,
2054 the compiler knows without being explicitly told where to find all
2055 the files it needs.
2056
2057 However, in some cases, particularly when a program is imported from
2058 another Ada compiler environment, it may be more convenient for the
2059 programmer to specify which file names contain which units. GNAT allows
2060 arbitrary file names to be used by means of the Source_File_Name pragma.
2061 The form of this pragma is as shown in the following examples:
2062 @cindex Source_File_Name pragma
2063
2064 @smallexample @c ada
2065 @cartouche
2066 pragma Source_File_Name (My_Utilities.Stacks,
2067   Spec_File_Name => "myutilst_a.ada");
2068 pragma Source_File_name (My_Utilities.Stacks,
2069   Body_File_Name => "myutilst.ada");
2070 @end cartouche
2071 @end smallexample
2072
2073 @noindent
2074 As shown in this example, the first argument for the pragma is the unit
2075 name (in this example a child unit). The second argument has the form
2076 of a named association. The identifier
2077 indicates whether the file name is for a spec or a body;
2078 the file name itself is given by a string literal.
2079
2080 The source file name pragma is a configuration pragma, which means that
2081 normally it will be placed in the @file{gnat.adc}
2082 file used to hold configuration
2083 pragmas that apply to a complete compilation environment.
2084 For more details on how the @file{gnat.adc} file is created and used
2085 see @ref{Handling of Configuration Pragmas}.
2086 @cindex @file{gnat.adc}
2087
2088 @ifclear vms
2089 GNAT allows completely arbitrary file names to be specified using the
2090 source file name pragma. However, if the file name specified has an
2091 extension other than @file{.ads} or @file{.adb} it is necessary to use
2092 a special syntax when compiling the file. The name in this case must be
2093 preceded by the special sequence @option{-x} followed by a space and the name
2094 of the language, here @code{ada}, as in:
2095
2096 @smallexample
2097 $ gcc -c -x ada peculiar_file_name.sim
2098 @end smallexample
2099 @end ifclear
2100
2101 @noindent
2102 @command{gnatmake} handles non-standard file names in the usual manner (the
2103 non-standard file name for the main program is simply used as the
2104 argument to gnatmake). Note that if the extension is also non-standard,
2105 then it must be included in the @command{gnatmake} command, it may not
2106 be omitted.
2107
2108 @node Alternative File Naming Schemes
2109 @section Alternative File Naming Schemes
2110 @cindex File naming schemes, alternative
2111 @cindex File names
2112
2113 In the previous section, we described the use of the @code{Source_File_Name}
2114 pragma to allow arbitrary names to be assigned to individual source files.
2115 However, this approach requires one pragma for each file, and especially in
2116 large systems can result in very long @file{gnat.adc} files, and also create
2117 a maintenance problem.
2118
2119 GNAT also provides a facility for specifying systematic file naming schemes
2120 other than the standard default naming scheme previously described. An
2121 alternative scheme for naming is specified by the use of
2122 @code{Source_File_Name} pragmas having the following format:
2123 @cindex Source_File_Name pragma
2124
2125 @smallexample @c ada
2126 pragma Source_File_Name (
2127    Spec_File_Name  => FILE_NAME_PATTERN
2128  @r{[},Casing          => CASING_SPEC@r{]}
2129  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2130
2131 pragma Source_File_Name (
2132    Body_File_Name  => FILE_NAME_PATTERN
2133  @r{[},Casing          => CASING_SPEC@r{]}
2134  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2135
2136 pragma Source_File_Name (
2137    Subunit_File_Name  => FILE_NAME_PATTERN
2138  @r{[},Casing             => CASING_SPEC@r{]}
2139  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2140
2141 FILE_NAME_PATTERN ::= STRING_LITERAL
2142 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2143 @end smallexample
2144
2145 @noindent
2146 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2147 It contains a single asterisk character, and the unit name is substituted
2148 systematically for this asterisk. The optional parameter
2149 @code{Casing} indicates
2150 whether the unit name is to be all upper-case letters, all lower-case letters,
2151 or mixed-case. If no
2152 @code{Casing} parameter is used, then the default is all
2153 ^lower-case^upper-case^.
2154
2155 The optional @code{Dot_Replacement} string is used to replace any periods
2156 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2157 argument is used then separating dots appear unchanged in the resulting
2158 file name.
2159 Although the above syntax indicates that the
2160 @code{Casing} argument must appear
2161 before the @code{Dot_Replacement} argument, but it
2162 is also permissible to write these arguments in the opposite order.
2163
2164 As indicated, it is possible to specify different naming schemes for
2165 bodies, specs, and subunits. Quite often the rule for subunits is the
2166 same as the rule for bodies, in which case, there is no need to give
2167 a separate @code{Subunit_File_Name} rule, and in this case the
2168 @code{Body_File_name} rule is used for subunits as well.
2169
2170 The separate rule for subunits can also be used to implement the rather
2171 unusual case of a compilation environment (e.g.@: a single directory) which
2172 contains a subunit and a child unit with the same unit name. Although
2173 both units cannot appear in the same partition, the Ada Reference Manual
2174 allows (but does not require) the possibility of the two units coexisting
2175 in the same environment.
2176
2177 The file name translation works in the following steps:
2178
2179 @itemize @bullet
2180
2181 @item
2182 If there is a specific @code{Source_File_Name} pragma for the given unit,
2183 then this is always used, and any general pattern rules are ignored.
2184
2185 @item
2186 If there is a pattern type @code{Source_File_Name} pragma that applies to
2187 the unit, then the resulting file name will be used if the file exists. If
2188 more than one pattern matches, the latest one will be tried first, and the
2189 first attempt resulting in a reference to a file that exists will be used.
2190
2191 @item
2192 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2193 for which the corresponding file exists, then the standard GNAT default
2194 naming rules are used.
2195
2196 @end itemize
2197
2198 @noindent
2199 As an example of the use of this mechanism, consider a commonly used scheme
2200 in which file names are all lower case, with separating periods copied
2201 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2202 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2203 two pragmas appear:
2204
2205 @smallexample @c ada
2206 pragma Source_File_Name
2207   (Spec_File_Name => "*.1.ada");
2208 pragma Source_File_Name
2209   (Body_File_Name => "*.2.ada");
2210 @end smallexample
2211
2212 @noindent
2213 The default GNAT scheme is actually implemented by providing the following
2214 default pragmas internally:
2215
2216 @smallexample @c ada
2217 pragma Source_File_Name
2218   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2219 pragma Source_File_Name
2220   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2221 @end smallexample
2222
2223 @noindent
2224 Our final example implements a scheme typically used with one of the
2225 Ada 83 compilers, where the separator character for subunits was ``__''
2226 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2227 by adding @file{.ADA}, and subunits by
2228 adding @file{.SEP}. All file names were
2229 upper case. Child units were not present of course since this was an
2230 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2231 the same double underscore separator for child units.
2232
2233 @smallexample @c ada
2234 pragma Source_File_Name
2235   (Spec_File_Name => "*_.ADA",
2236    Dot_Replacement => "__",
2237    Casing = Uppercase);
2238 pragma Source_File_Name
2239   (Body_File_Name => "*.ADA",
2240    Dot_Replacement => "__",
2241    Casing = Uppercase);
2242 pragma Source_File_Name
2243   (Subunit_File_Name => "*.SEP",
2244    Dot_Replacement => "__",
2245    Casing = Uppercase);
2246 @end smallexample
2247
2248 @node Generating Object Files
2249 @section Generating Object Files
2250
2251 @noindent
2252 An Ada program consists of a set of source files, and the first step in
2253 compiling the program is to generate the corresponding object files.
2254 These are generated by compiling a subset of these source files.
2255 The files you need to compile are the following:
2256
2257 @itemize @bullet
2258 @item
2259 If a package spec has no body, compile the package spec to produce the
2260 object file for the package.
2261
2262 @item
2263 If a package has both a spec and a body, compile the body to produce the
2264 object file for the package. The source file for the package spec need
2265 not be compiled in this case because there is only one object file, which
2266 contains the code for both the spec and body of the package.
2267
2268 @item
2269 For a subprogram, compile the subprogram body to produce the object file
2270 for the subprogram. The spec, if one is present, is as usual in a
2271 separate file, and need not be compiled.
2272
2273 @item
2274 @cindex Subunits
2275 In the case of subunits, only compile the parent unit. A single object
2276 file is generated for the entire subunit tree, which includes all the
2277 subunits.
2278
2279 @item
2280 Compile child units independently of their parent units
2281 (though, of course, the spec of all the ancestor unit must be present in order
2282 to compile a child unit).
2283
2284 @item
2285 @cindex Generics
2286 Compile generic units in the same manner as any other units. The object
2287 files in this case are small dummy files that contain at most the
2288 flag used for elaboration checking. This is because GNAT always handles generic
2289 instantiation by means of macro expansion. However, it is still necessary to
2290 compile generic units, for dependency checking and elaboration purposes.
2291 @end itemize
2292
2293 @noindent
2294 The preceding rules describe the set of files that must be compiled to
2295 generate the object files for a program. Each object file has the same
2296 name as the corresponding source file, except that the extension is
2297 @file{.o} as usual.
2298
2299 You may wish to compile other files for the purpose of checking their
2300 syntactic and semantic correctness. For example, in the case where a
2301 package has a separate spec and body, you would not normally compile the
2302 spec. However, it is convenient in practice to compile the spec to make
2303 sure it is error-free before compiling clients of this spec, because such
2304 compilations will fail if there is an error in the spec.
2305
2306 GNAT provides an option for compiling such files purely for the
2307 purposes of checking correctness; such compilations are not required as
2308 part of the process of building a program. To compile a file in this
2309 checking mode, use the @option{-gnatc} switch.
2310
2311 @node Source Dependencies
2312 @section Source Dependencies
2313
2314 @noindent
2315 A given object file clearly depends on the source file which is compiled
2316 to produce it. Here we are using @dfn{depends} in the sense of a typical
2317 @code{make} utility; in other words, an object file depends on a source
2318 file if changes to the source file require the object file to be
2319 recompiled.
2320 In addition to this basic dependency, a given object may depend on
2321 additional source files as follows:
2322
2323 @itemize @bullet
2324 @item
2325 If a file being compiled @code{with}'s a unit @var{X}, the object file
2326 depends on the file containing the spec of unit @var{X}. This includes
2327 files that are @code{with}'ed implicitly either because they are parents
2328 of @code{with}'ed child units or they are run-time units required by the
2329 language constructs used in a particular unit.
2330
2331 @item
2332 If a file being compiled instantiates a library level generic unit, the
2333 object file depends on both the spec and body files for this generic
2334 unit.
2335
2336 @item
2337 If a file being compiled instantiates a generic unit defined within a
2338 package, the object file depends on the body file for the package as
2339 well as the spec file.
2340
2341 @item
2342 @findex Inline
2343 @cindex @option{-gnatn} switch
2344 If a file being compiled contains a call to a subprogram for which
2345 pragma @code{Inline} applies and inlining is activated with the
2346 @option{-gnatn} switch, the object file depends on the file containing the
2347 body of this subprogram as well as on the file containing the spec. Note
2348 that for inlining to actually occur as a result of the use of this switch,
2349 it is necessary to compile in optimizing mode.
2350
2351 @cindex @option{-gnatN} switch
2352 The use of @option{-gnatN} activates  inlining optimization
2353 that is performed by the front end of the compiler. This inlining does
2354 not require that the code generation be optimized. Like @option{-gnatn},
2355 the use of this switch generates additional dependencies.
2356
2357 When using a gcc-based back end (in practice this means using any version
2358 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2359 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2360 Historically front end inlining was more extensive than the gcc back end
2361 inlining, but that is no longer the case.
2362
2363 @item
2364 If an object file @file{O} depends on the proper body of a subunit through
2365 inlining or instantiation, it depends on the parent unit of the subunit.
2366 This means that any modification of the parent unit or one of its subunits
2367 affects the compilation of @file{O}.
2368
2369 @item
2370 The object file for a parent unit depends on all its subunit body files.
2371
2372 @item
2373 The previous two rules meant that for purposes of computing dependencies and
2374 recompilation, a body and all its subunits are treated as an indivisible whole.
2375
2376 @noindent
2377 These rules are applied transitively: if unit @code{A} @code{with}'s
2378 unit @code{B}, whose elaboration calls an inlined procedure in package
2379 @code{C}, the object file for unit @code{A} will depend on the body of
2380 @code{C}, in file @file{c.adb}.
2381
2382 The set of dependent files described by these rules includes all the
2383 files on which the unit is semantically dependent, as dictated by the
2384 Ada language standard. However, it is a superset of what the
2385 standard describes, because it includes generic, inline, and subunit
2386 dependencies.
2387
2388 An object file must be recreated by recompiling the corresponding source
2389 file if any of the source files on which it depends are modified. For
2390 example, if the @code{make} utility is used to control compilation,
2391 the rule for an Ada object file must mention all the source files on
2392 which the object file depends, according to the above definition.
2393 The determination of the necessary
2394 recompilations is done automatically when one uses @command{gnatmake}.
2395 @end itemize
2396
2397 @node The Ada Library Information Files
2398 @section The Ada Library Information Files
2399 @cindex Ada Library Information files
2400 @cindex @file{ALI} files
2401
2402 @noindent
2403 Each compilation actually generates two output files. The first of these
2404 is the normal object file that has a @file{.o} extension. The second is a
2405 text file containing full dependency information. It has the same
2406 name as the source file, but an @file{.ali} extension.
2407 This file is known as the Ada Library Information (@file{ALI}) file.
2408 The following information is contained in the @file{ALI} file.
2409
2410 @itemize @bullet
2411 @item
2412 Version information (indicates which version of GNAT was used to compile
2413 the unit(s) in question)
2414
2415 @item
2416 Main program information (including priority and time slice settings,
2417 as well as the wide character encoding used during compilation).
2418
2419 @item
2420 List of arguments used in the @command{gcc} command for the compilation
2421
2422 @item
2423 Attributes of the unit, including configuration pragmas used, an indication
2424 of whether the compilation was successful, exception model used etc.
2425
2426 @item
2427 A list of relevant restrictions applying to the unit (used for consistency)
2428 checking.
2429
2430 @item
2431 Categorization information (e.g.@: use of pragma @code{Pure}).
2432
2433 @item
2434 Information on all @code{with}'ed units, including presence of
2435 @code{Elaborate} or @code{Elaborate_All} pragmas.
2436
2437 @item
2438 Information from any @code{Linker_Options} pragmas used in the unit
2439
2440 @item
2441 Information on the use of @code{Body_Version} or @code{Version}
2442 attributes in the unit.
2443
2444 @item
2445 Dependency information. This is a list of files, together with
2446 time stamp and checksum information. These are files on which
2447 the unit depends in the sense that recompilation is required
2448 if any of these units are modified.
2449
2450 @item
2451 Cross-reference data. Contains information on all entities referenced
2452 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2453 provide cross-reference information.
2454
2455 @end itemize
2456
2457 @noindent
2458 For a full detailed description of the format of the @file{ALI} file,
2459 see the source of the body of unit @code{Lib.Writ}, contained in file
2460 @file{lib-writ.adb} in the GNAT compiler sources.
2461
2462 @node Binding an Ada Program
2463 @section Binding an Ada Program
2464
2465 @noindent
2466 When using languages such as C and C++, once the source files have been
2467 compiled the only remaining step in building an executable program
2468 is linking the object modules together. This means that it is possible to
2469 link an inconsistent version of a program, in which two units have
2470 included different versions of the same header.
2471
2472 The rules of Ada do not permit such an inconsistent program to be built.
2473 For example, if two clients have different versions of the same package,
2474 it is illegal to build a program containing these two clients.
2475 These rules are enforced by the GNAT binder, which also determines an
2476 elaboration order consistent with the Ada rules.
2477
2478 The GNAT binder is run after all the object files for a program have
2479 been created. It is given the name of the main program unit, and from
2480 this it determines the set of units required by the program, by reading the
2481 corresponding ALI files. It generates error messages if the program is
2482 inconsistent or if no valid order of elaboration exists.
2483
2484 If no errors are detected, the binder produces a main program, in Ada by
2485 default, that contains calls to the elaboration procedures of those
2486 compilation unit that require them, followed by
2487 a call to the main program. This Ada program is compiled to generate the
2488 object file for the main program. The name of
2489 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2490 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2491 main program unit.
2492
2493 Finally, the linker is used to build the resulting executable program,
2494 using the object from the main program from the bind step as well as the
2495 object files for the Ada units of the program.
2496
2497 @node Mixed Language Programming
2498 @section Mixed Language Programming
2499 @cindex Mixed Language Programming
2500
2501 @noindent
2502 This section describes how to develop a mixed-language program,
2503 specifically one that comprises units in both Ada and C.
2504
2505 @menu
2506 * Interfacing to C::
2507 * Calling Conventions::
2508 @end menu
2509
2510 @node Interfacing to C
2511 @subsection Interfacing to C
2512 @noindent
2513 Interfacing Ada with a foreign language such as C involves using
2514 compiler directives to import and/or export entity definitions in each
2515 language---using @code{extern} statements in C, for instance, and the
2516 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2517 A full treatment of these topics is provided in Appendix B, section 1
2518 of the Ada Reference Manual.
2519
2520 There are two ways to build a program using GNAT that contains some Ada
2521 sources and some foreign language sources, depending on whether or not
2522 the main subprogram is written in Ada.  Here is a source example with
2523 the main subprogram in Ada:
2524
2525 @smallexample
2526 /* file1.c */
2527 #include <stdio.h>
2528
2529 void print_num (int num)
2530 @{
2531   printf ("num is %d.\n", num);
2532   return;
2533 @}
2534
2535 /* file2.c */
2536
2537 /* num_from_Ada is declared in my_main.adb */
2538 extern int num_from_Ada;
2539
2540 int get_num (void)
2541 @{
2542   return num_from_Ada;
2543 @}
2544 @end smallexample
2545
2546 @smallexample @c ada
2547 --  my_main.adb
2548 procedure My_Main is
2549
2550    --  Declare then export an Integer entity called num_from_Ada
2551    My_Num : Integer := 10;
2552    pragma Export (C, My_Num, "num_from_Ada");
2553
2554    --  Declare an Ada function spec for Get_Num, then use
2555    --  C function get_num for the implementation.
2556    function Get_Num return Integer;
2557    pragma Import (C, Get_Num, "get_num");
2558
2559    --  Declare an Ada procedure spec for Print_Num, then use
2560    --  C function print_num for the implementation.
2561    procedure Print_Num (Num : Integer);
2562    pragma Import (C, Print_Num, "print_num");
2563
2564 begin
2565    Print_Num (Get_Num);
2566 end My_Main;
2567 @end smallexample
2568
2569 @enumerate
2570 @item
2571 To build this example, first compile the foreign language files to
2572 generate object files:
2573 @smallexample
2574 ^gcc -c file1.c^gcc -c FILE1.C^
2575 ^gcc -c file2.c^gcc -c FILE2.C^
2576 @end smallexample
2577
2578 @item
2579 Then, compile the Ada units to produce a set of object files and ALI
2580 files:
2581 @smallexample
2582 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2583 @end smallexample
2584
2585 @item
2586 Run the Ada binder on the Ada main program:
2587 @smallexample
2588 gnatbind my_main.ali
2589 @end smallexample
2590
2591 @item
2592 Link the Ada main program, the Ada objects and the other language
2593 objects:
2594 @smallexample
2595 gnatlink my_main.ali file1.o file2.o
2596 @end smallexample
2597 @end enumerate
2598
2599 The last three steps can be grouped in a single command:
2600 @smallexample
2601 gnatmake my_main.adb -largs file1.o file2.o
2602 @end smallexample
2603
2604 @cindex Binder output file
2605 @noindent
2606 If the main program is in a language other than Ada, then you may have
2607 more than one entry point into the Ada subsystem. You must use a special
2608 binder option to generate callable routines that initialize and
2609 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2610 Calls to the initialization and finalization routines must be inserted
2611 in the main program, or some other appropriate point in the code. The
2612 call to initialize the Ada units must occur before the first Ada
2613 subprogram is called, and the call to finalize the Ada units must occur
2614 after the last Ada subprogram returns. The binder will place the
2615 initialization and finalization subprograms into the
2616 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2617 sources.  To illustrate, we have the following example:
2618
2619 @smallexample
2620 /* main.c */
2621 extern void adainit (void);
2622 extern void adafinal (void);
2623 extern int add (int, int);
2624 extern int sub (int, int);
2625
2626 int main (int argc, char *argv[])
2627 @{
2628   int a = 21, b = 7;
2629
2630   adainit();
2631
2632   /* Should print "21 + 7 = 28" */
2633   printf ("%d + %d = %d\n", a, b, add (a, b));
2634   /* Should print "21 - 7 = 14" */
2635   printf ("%d - %d = %d\n", a, b, sub (a, b));
2636
2637   adafinal();
2638 @}
2639 @end smallexample
2640
2641 @smallexample @c ada
2642 --  unit1.ads
2643 package Unit1 is
2644    function Add (A, B : Integer) return Integer;
2645    pragma Export (C, Add, "add");
2646 end Unit1;
2647
2648 --  unit1.adb
2649 package body Unit1 is
2650    function Add (A, B : Integer) return Integer is
2651    begin
2652       return A + B;
2653    end Add;
2654 end Unit1;
2655
2656 --  unit2.ads
2657 package Unit2 is
2658    function Sub (A, B : Integer) return Integer;
2659    pragma Export (C, Sub, "sub");
2660 end Unit2;
2661
2662 --  unit2.adb
2663 package body Unit2 is
2664    function Sub (A, B : Integer) return Integer is
2665    begin
2666       return A - B;
2667    end Sub;
2668 end Unit2;
2669 @end smallexample
2670
2671 @enumerate
2672 @item
2673 The build procedure for this application is similar to the last
2674 example's.  First, compile the foreign language files to generate object
2675 files:
2676 @smallexample
2677 ^gcc -c main.c^gcc -c main.c^
2678 @end smallexample
2679
2680 @item
2681 Next, compile the Ada units to produce a set of object files and ALI
2682 files:
2683 @smallexample
2684 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2685 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2686 @end smallexample
2687
2688 @item
2689 Run the Ada binder on every generated ALI file.  Make sure to use the
2690 @option{-n} option to specify a foreign main program:
2691 @smallexample
2692 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2693 @end smallexample
2694
2695 @item
2696 Link the Ada main program, the Ada objects and the foreign language
2697 objects. You need only list the last ALI file here:
2698 @smallexample
2699 gnatlink unit2.ali main.o -o exec_file
2700 @end smallexample
2701
2702 This procedure yields a binary executable called @file{exec_file}.
2703 @end enumerate
2704
2705 @noindent
2706 Depending on the circumstances (for example when your non-Ada main object
2707 does not provide symbol @code{main}), you may also need to instruct the
2708 GNAT linker not to include the standard startup objects by passing the
2709 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2710
2711 @node Calling Conventions
2712 @subsection Calling Conventions
2713 @cindex Foreign Languages
2714 @cindex Calling Conventions
2715 GNAT follows standard calling sequence conventions and will thus interface
2716 to any other language that also follows these conventions. The following
2717 Convention identifiers are recognized by GNAT:
2718
2719 @table @code
2720 @cindex Interfacing to Ada
2721 @cindex Other Ada compilers
2722 @cindex Convention Ada
2723 @item Ada
2724 This indicates that the standard Ada calling sequence will be
2725 used and all Ada data items may be passed without any limitations in the
2726 case where GNAT is used to generate both the caller and callee. It is also
2727 possible to mix GNAT generated code and code generated by another Ada
2728 compiler. In this case, the data types should be restricted to simple
2729 cases, including primitive types. Whether complex data types can be passed
2730 depends on the situation. Probably it is safe to pass simple arrays, such
2731 as arrays of integers or floats. Records may or may not work, depending
2732 on whether both compilers lay them out identically. Complex structures
2733 involving variant records, access parameters, tasks, or protected types,
2734 are unlikely to be able to be passed.
2735
2736 Note that in the case of GNAT running
2737 on a platform that supports HP Ada 83, a higher degree of compatibility
2738 can be guaranteed, and in particular records are layed out in an identical
2739 manner in the two compilers. Note also that if output from two different
2740 compilers is mixed, the program is responsible for dealing with elaboration
2741 issues. Probably the safest approach is to write the main program in the
2742 version of Ada other than GNAT, so that it takes care of its own elaboration
2743 requirements, and then call the GNAT-generated adainit procedure to ensure
2744 elaboration of the GNAT components. Consult the documentation of the other
2745 Ada compiler for further details on elaboration.
2746
2747 However, it is not possible to mix the tasking run time of GNAT and
2748 HP Ada 83, All the tasking operations must either be entirely within
2749 GNAT compiled sections of the program, or entirely within HP Ada 83
2750 compiled sections of the program.
2751
2752 @cindex Interfacing to Assembly
2753 @cindex Convention Assembler
2754 @item Assembler
2755 Specifies assembler as the convention. In practice this has the
2756 same effect as convention Ada (but is not equivalent in the sense of being
2757 considered the same convention).
2758
2759 @cindex Convention Asm
2760 @findex Asm
2761 @item Asm
2762 Equivalent to Assembler.
2763
2764 @cindex Interfacing to COBOL
2765 @cindex Convention COBOL
2766 @findex COBOL
2767 @item COBOL
2768 Data will be passed according to the conventions described
2769 in section B.4 of the Ada Reference Manual.
2770
2771 @findex C
2772 @cindex Interfacing to C
2773 @cindex Convention C
2774 @item C
2775 Data will be passed according to the conventions described
2776 in section B.3 of the Ada Reference Manual.
2777
2778 A note on interfacing to a C ``varargs'' function:
2779 @findex C varargs function
2780 @cindex Interfacing to C varargs function
2781 @cindex varargs function interfaces
2782
2783 @itemize @bullet
2784 @item
2785 In C, @code{varargs} allows a function to take a variable number of
2786 arguments. There is no direct equivalent in this to Ada. One
2787 approach that can be used is to create a C wrapper for each
2788 different profile and then interface to this C wrapper. For
2789 example, to print an @code{int} value using @code{printf},
2790 create a C function @code{printfi} that takes two arguments, a
2791 pointer to a string and an int, and calls @code{printf}.
2792 Then in the Ada program, use pragma @code{Import} to
2793 interface to @code{printfi}.
2794
2795 @item
2796 It may work on some platforms to directly interface to
2797 a @code{varargs} function by providing a specific Ada profile
2798 for a particular call. However, this does not work on
2799 all platforms, since there is no guarantee that the
2800 calling sequence for a two argument normal C function
2801 is the same as for calling a @code{varargs} C function with
2802 the same two arguments.
2803 @end itemize
2804
2805 @cindex Convention Default
2806 @findex Default
2807 @item Default
2808 Equivalent to C.
2809
2810 @cindex Convention External
2811 @findex External
2812 @item External
2813 Equivalent to C.
2814
2815 @ifclear vms
2816 @findex C++
2817 @cindex Interfacing to C++
2818 @cindex Convention C++
2819 @item C_Plus_Plus (or CPP)
2820 This stands for C++. For most purposes this is identical to C.
2821 See the separate description of the specialized GNAT pragmas relating to
2822 C++ interfacing for further details.
2823 @end ifclear
2824
2825 @findex Fortran
2826 @cindex Interfacing to Fortran
2827 @cindex Convention Fortran
2828 @item Fortran
2829 Data will be passed according to the conventions described
2830 in section B.5 of the Ada Reference Manual.
2831
2832 @item Intrinsic
2833 This applies to an intrinsic operation, as defined in the Ada
2834 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2835 this means that the body of the subprogram is provided by the compiler itself,
2836 usually by means of an efficient code sequence, and that the user does not
2837 supply an explicit body for it. In an application program, the pragma may
2838 be applied to the following sets of names:
2839
2840 @itemize @bullet
2841 @item
2842 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2843 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2844 two formal parameters. The
2845 first one must be a signed integer type or a modular type with a binary
2846 modulus, and the second parameter must be of type Natural.
2847 The return type must be the same as the type of the first argument. The size
2848 of this type can only be 8, 16, 32, or 64.
2849
2850 @item
2851 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2852 The corresponding operator declaration must have parameters and result type
2853 that have the same root numeric type (for example, all three are long_float
2854 types). This simplifies the definition of operations that use type checking
2855 to perform dimensional checks:
2856
2857 @smallexample @c ada
2858 type Distance is new Long_Float;
2859 type Time     is new Long_Float;
2860 type Velocity is new Long_Float;
2861 function "/" (D : Distance; T : Time)
2862   return Velocity;
2863 pragma Import (Intrinsic, "/");
2864 @end smallexample
2865
2866 @noindent
2867 This common idiom is often programmed with a generic definition and an
2868 explicit body. The pragma makes it simpler to introduce such declarations.
2869 It incurs no overhead in compilation time or code size, because it is
2870 implemented as a single machine instruction.
2871
2872 @item
2873 General subprogram entities, to bind an Ada subprogram declaration to
2874 a compiler builtin by name with back-ends where such interfaces are
2875 available. A typical example is the set of ``__builtin'' functions
2876 exposed by the GCC back-end, as in the following example:
2877
2878 @smallexample @c ada
2879    function builtin_sqrt (F : Float) return Float;
2880    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2881 @end smallexample
2882
2883 Most of the GCC builtins are accessible this way, and as for other
2884 import conventions (e.g. C), it is the user's responsibility to ensure
2885 that the Ada subprogram profile matches the underlying builtin
2886 expectations.
2887 @end itemize
2888
2889 @noindent
2890
2891 @ifset unw
2892 @findex Stdcall
2893 @cindex Convention Stdcall
2894 @item Stdcall
2895 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2896 and specifies that the @code{Stdcall} calling sequence will be used,
2897 as defined by the NT API. Nevertheless, to ease building
2898 cross-platform bindings this convention will be handled as a @code{C} calling
2899 convention on non-Windows platforms.
2900
2901 @findex DLL
2902 @cindex Convention DLL
2903 @item DLL
2904 This is equivalent to @code{Stdcall}.
2905
2906 @findex Win32
2907 @cindex Convention Win32
2908 @item Win32
2909 This is equivalent to @code{Stdcall}.
2910 @end ifset
2911
2912 @findex Stubbed
2913 @cindex Convention Stubbed
2914 @item Stubbed
2915 This is a special convention that indicates that the compiler
2916 should provide a stub body that raises @code{Program_Error}.
2917 @end table
2918
2919 @noindent
2920 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2921 that can be used to parametrize conventions and allow additional synonyms
2922 to be specified. For example if you have legacy code in which the convention
2923 identifier Fortran77 was used for Fortran, you can use the configuration
2924 pragma:
2925
2926 @smallexample @c ada
2927 pragma Convention_Identifier (Fortran77, Fortran);
2928 @end smallexample
2929
2930 @noindent
2931 And from now on the identifier Fortran77 may be used as a convention
2932 identifier (for example in an @code{Import} pragma) with the same
2933 meaning as Fortran.
2934
2935 @ifclear vms
2936 @node Building Mixed Ada & C++ Programs
2937 @section Building Mixed Ada and C++ Programs
2938
2939 @noindent
2940 A programmer inexperienced with mixed-language development may find that
2941 building an application containing both Ada and C++ code can be a
2942 challenge.  This section gives a few
2943 hints that should make this task easier. The first section addresses
2944 the differences between interfacing with C and interfacing with C++.
2945 The second section
2946 looks into the delicate problem of linking the complete application from
2947 its Ada and C++ parts. The last section gives some hints on how the GNAT
2948 run-time library can be adapted in order to allow inter-language dispatching
2949 with a new C++ compiler.
2950
2951 @menu
2952 * Interfacing to C++::
2953 * Linking a Mixed C++ & Ada Program::
2954 * A Simple Example::
2955 * Interfacing with C++ constructors::
2956 * Interfacing with C++ at the Class Level::
2957 @end menu
2958
2959 @node Interfacing to C++
2960 @subsection Interfacing to C++
2961
2962 @noindent
2963 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2964 generating code that is compatible with the G++ Application Binary
2965 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2966
2967 @noindent
2968 Interfacing can be done at 3 levels: simple data, subprograms, and
2969 classes. In the first two cases, GNAT offers a specific @code{Convention
2970 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2971 Usually, C++ mangles the names of subprograms. To generate proper mangled
2972 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2973 This problem can also be addressed manually in two ways:
2974
2975 @itemize @bullet
2976 @item
2977 by modifying the C++ code in order to force a C convention using
2978 the @code{extern "C"} syntax.
2979
2980 @item
2981 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2982 Link_Name argument of the pragma import.
2983 @end itemize
2984
2985 @noindent
2986 Interfacing at the class level can be achieved by using the GNAT specific
2987 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2988 gnat_rm, GNAT Reference Manual}, for additional information.
2989
2990 @node Linking a Mixed C++ & Ada Program
2991 @subsection Linking a Mixed C++ & Ada Program
2992
2993 @noindent
2994 Usually the linker of the C++ development system must be used to link
2995 mixed applications because most C++ systems will resolve elaboration
2996 issues (such as calling constructors on global class instances)
2997 transparently during the link phase. GNAT has been adapted to ease the
2998 use of a foreign linker for the last phase. Three cases can be
2999 considered:
3000 @enumerate
3001
3002 @item
3003 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3004 The C++ linker can simply be called by using the C++ specific driver
3005 called @code{g++}.
3006
3007 Note that if the C++ code uses inline functions, you will need to
3008 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3009 order to provide an existing function implementation that the Ada code can
3010 link with.
3011
3012 @smallexample
3013 $ g++ -c -fkeep-inline-functions file1.C
3014 $ g++ -c -fkeep-inline-functions file2.C
3015 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3016 @end smallexample
3017
3018 @item
3019 Using GNAT and G++ from two different GCC installations: If both
3020 compilers are on the @env{PATH}, the previous method may be used. It is
3021 important to note that environment variables such as
3022 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3023 @env{GCC_ROOT} will affect both compilers
3024 at the same time and may make one of the two compilers operate
3025 improperly if set during invocation of the wrong compiler.  It is also
3026 very important that the linker uses the proper @file{libgcc.a} GCC
3027 library -- that is, the one from the C++ compiler installation. The
3028 implicit link command as suggested in the @command{gnatmake} command
3029 from the former example can be replaced by an explicit link command with
3030 the full-verbosity option in order to verify which library is used:
3031 @smallexample
3032 $ gnatbind ada_unit
3033 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3034 @end smallexample
3035 If there is a problem due to interfering environment variables, it can
3036 be worked around by using an intermediate script. The following example
3037 shows the proper script to use when GNAT has not been installed at its
3038 default location and g++ has been installed at its default location:
3039
3040 @smallexample
3041 $ cat ./my_script
3042 #!/bin/sh
3043 unset BINUTILS_ROOT
3044 unset GCC_ROOT
3045 c++ $*
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3047 @end smallexample
3048
3049 @item
3050 Using a non-GNU C++ compiler: The commands previously described can be
3051 used to insure that the C++ linker is used. Nonetheless, you need to add
3052 a few more parameters to the link command line, depending on the exception
3053 mechanism used.
3054
3055 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3056 to the libgcc libraries are required:
3057
3058 @smallexample
3059 $ cat ./my_script
3060 #!/bin/sh
3061 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3062 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3063 @end smallexample
3064
3065 Where CC is the name of the non-GNU C++ compiler.
3066
3067 If the @code{zero cost} exception mechanism is used, and the platform
3068 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3069 paths to more objects are required:
3070
3071 @smallexample
3072 $ cat ./my_script
3073 #!/bin/sh
3074 CC `gcc -print-file-name=crtbegin.o` $* \
3075 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3076 `gcc -print-file-name=crtend.o`
3077 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3078 @end smallexample
3079
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3082 Tru64 or AIX), the simple approach described above will not work and
3083 a pre-linking phase using GNAT will be necessary.
3084
3085 @end enumerate
3086
3087 Another alternative is to use the @command{gprbuild} multi-language builder
3088 which has a large knowledge base and knows how to link Ada and C++ code
3089 together automatically in most cases.
3090
3091 @node A Simple Example
3092 @subsection  A Simple Example
3093 @noindent
3094 The following example, provided as part of the GNAT examples, shows how
3095 to achieve procedural interfacing between Ada and C++ in both
3096 directions. The C++ class A has two methods. The first method is exported
3097 to Ada by the means of an extern C wrapper function. The second method
3098 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3099 a limited record with a layout comparable to the C++ class. The Ada
3100 subprogram, in turn, calls the C++ method. So, starting from the C++
3101 main program, the process passes back and forth between the two
3102 languages.
3103
3104 @noindent
3105 Here are the compilation commands:
3106 @smallexample
3107 $ gnatmake -c simple_cpp_interface
3108 $ g++ -c cpp_main.C
3109 $ g++ -c ex7.C
3110 $ gnatbind -n simple_cpp_interface
3111 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3112       -lstdc++ ex7.o cpp_main.o
3113 @end smallexample
3114
3115 @noindent
3116 Here are the corresponding sources:
3117 @smallexample
3118
3119 //cpp_main.C
3120
3121 #include "ex7.h"
3122
3123 extern "C" @{
3124   void adainit (void);
3125   void adafinal (void);
3126   void method1 (A *t);
3127 @}
3128
3129 void method1 (A *t)
3130 @{
3131   t->method1 ();
3132 @}
3133
3134 int main ()
3135 @{
3136   A obj;
3137   adainit ();
3138   obj.method2 (3030);
3139   adafinal ();
3140 @}
3141
3142 //ex7.h
3143
3144 class Origin @{
3145  public:
3146   int o_value;
3147 @};
3148 class A : public Origin @{
3149  public:
3150   void method1 (void);
3151   void method2 (int v);
3152   A();
3153   int   a_value;
3154 @};
3155
3156 //ex7.C
3157
3158 #include "ex7.h"
3159 #include <stdio.h>
3160
3161 extern "C" @{ void ada_method2 (A *t, int v);@}
3162
3163 void A::method1 (void)
3164 @{
3165   a_value = 2020;
3166   printf ("in A::method1, a_value = %d \n",a_value);
3167
3168 @}
3169
3170 void A::method2 (int v)
3171 @{
3172    ada_method2 (this, v);
3173    printf ("in A::method2, a_value = %d \n",a_value);
3174
3175 @}
3176
3177 A::A(void)
3178 @{
3179    a_value = 1010;
3180   printf ("in A::A, a_value = %d \n",a_value);
3181 @}
3182 @end smallexample
3183
3184 @smallexample @c ada
3185 -- Ada sources
3186 package body Simple_Cpp_Interface is
3187
3188    procedure Ada_Method2 (This : in out A; V : Integer) is
3189    begin
3190       Method1 (This);
3191       This.A_Value := V;
3192    end Ada_Method2;
3193
3194 end Simple_Cpp_Interface;
3195
3196 with System;
3197 package Simple_Cpp_Interface is
3198    type A is limited
3199       record
3200          Vptr    : System.Address;
3201          O_Value : Integer;
3202          A_Value : Integer;
3203       end record;
3204    pragma Convention (C, A);
3205
3206    procedure Method1 (This : in out A);
3207    pragma Import (C, Method1);
3208
3209    procedure Ada_Method2 (This : in out A; V : Integer);
3210    pragma Export (C, Ada_Method2);
3211
3212 end Simple_Cpp_Interface;
3213 @end smallexample
3214
3215 @node Interfacing with C++ constructors
3216 @subsection Interfacing with C++ constructors
3217 @noindent
3218
3219 In order to interface with C++ constructors GNAT provides the
3220 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3221 gnat_rm, GNAT Reference Manual}, for additional information).
3222 In this section we present some common uses of C++ constructors
3223 in mixed-languages programs in GNAT.
3224
3225 Let us assume that we need to interface with the following
3226 C++ class:
3227
3228 @smallexample
3229 @b{class} Root @{
3230 @b{public}:
3231   int  a_value;
3232   int  b_value;
3233   @b{virtual} int Get_Value ();
3234   Root();              // Default constructor
3235   Root(int v);         // 1st non-default constructor
3236   Root(int v, int w);  // 2nd non-default constructor
3237 @};
3238 @end smallexample
3239
3240 For this purpose we can write the following package spec (further
3241 information on how to build this spec is available in
3242 @ref{Interfacing with C++ at the Class Level} and
3243 @ref{Generating Ada Bindings for C and C++ headers}).
3244
3245 @smallexample @c ada
3246 with Interfaces.C; use Interfaces.C;
3247 package Pkg_Root is
3248   type Root is tagged limited record
3249      A_Value : int;
3250      B_Value : int;
3251   end record;
3252   pragma Import (CPP, Root);
3253
3254   function Get_Value (Obj : Root) return int;
3255   pragma Import (CPP, Get_Value);
3256
3257   function Constructor return Root;
3258   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3259
3260   function Constructor (v : Integer) return Root;
3261   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3262
3263   function Constructor (v, w : Integer) return Root;
3264   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3265 end Pkg_Root;
3266 @end smallexample
3267
3268 On the Ada side the constructor is represented by a function (whose
3269 name is arbitrary) that returns the classwide type corresponding to
3270 the imported C++ class. Although the constructor is described as a
3271 function, it is typically a procedure with an extra implicit argument
3272 (the object being initialized) at the implementation level. GNAT
3273 issues the appropriate call, whatever it is, to get the object
3274 properly initialized.
3275
3276 Constructors can only appear in the following contexts:
3277
3278 @itemize @bullet
3279 @item
3280 On the right side of an initialization of an object of type @var{T}.
3281 @item
3282 On the right side of an initialization of a record component of type @var{T}.
3283 @item
3284 In an Ada 2005 limited aggregate.
3285 @item
3286 In an Ada 2005 nested limited aggregate.
3287 @item
3288 In an Ada 2005 limited aggregate that initializes an object built in
3289 place by an extended return statement.
3290 @end itemize
3291
3292 @noindent
3293 In a declaration of an object whose type is a class imported from C++,
3294 either the default C++ constructor is implicitly called by GNAT, or
3295 else the required C++ constructor must be explicitly called in the
3296 expression that initializes the object. For example:
3297
3298 @smallexample @c ada
3299   Obj1 : Root;
3300   Obj2 : Root := Constructor;
3301   Obj3 : Root := Constructor (v => 10);
3302   Obj4 : Root := Constructor (30, 40);
3303 @end smallexample
3304
3305 The first two declarations are equivalent: in both cases the default C++
3306 constructor is invoked (in the former case the call to the constructor is
3307 implicit, and in the latter case the call is explicit in the object
3308 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3309 that takes an integer argument, and @code{Obj4} is initialized by the
3310 non-default C++ constructor that takes two integers.
3311
3312 Let us derive the imported C++ class in the Ada side. For example:
3313
3314 @smallexample @c ada
3315   type DT is new Root with record
3316      C_Value : Natural := 2009;
3317   end record;
3318 @end smallexample
3319
3320 In this case the components DT inherited from the C++ side must be
3321 initialized by a C++ constructor, and the additional Ada components
3322 of type DT are initialized by GNAT. The initialization of such an
3323 object is done either by default, or by means of a function returning
3324 an aggregate of type DT, or by means of an extension aggregate.
3325
3326 @smallexample @c ada
3327   Obj5 : DT;
3328   Obj6 : DT := Function_Returning_DT (50);
3329   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3330 @end smallexample
3331
3332 The declaration of @code{Obj5} invokes the default constructors: the
3333 C++ default constructor of the parent type takes care of the initialization
3334 of the components inherited from Root, and GNAT takes care of the default
3335 initialization of the additional Ada components of type DT (that is,
3336 @code{C_Value} is initialized to value 2009). The order of invocation of
3337 the constructors is consistent with the order of elaboration required by
3338 Ada and C++. That is, the constructor of the parent type is always called
3339 before the constructor of the derived type.
3340
3341 Let us now consider a record that has components whose type is imported
3342 from C++. For example:
3343
3344 @smallexample @c ada
3345   type Rec1 is limited record
3346      Data1 : Root := Constructor (10);
3347      Value : Natural := 1000;
3348   end record;
3349
3350   type Rec2 (D : Integer := 20) is limited record
3351      Rec   : Rec1;
3352      Data2 : Root := Constructor (D, 30);
3353   end record;
3354 @end smallexample
3355
3356 The initialization of an object of type @code{Rec2} will call the
3357 non-default C++ constructors specified for the imported components.
3358 For example:
3359
3360 @smallexample @c ada
3361   Obj8 : Rec2 (40);
3362 @end smallexample
3363
3364 Using Ada 2005 we can use limited aggregates to initialize an object
3365 invoking C++ constructors that differ from those specified in the type
3366 declarations. For example:
3367
3368 @smallexample @c ada
3369   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3370                           others => <>),
3371                   others => <>);
3372 @end smallexample
3373
3374 The above declaration uses an Ada 2005 limited aggregate to
3375 initialize @code{Obj9}, and the C++ constructor that has two integer
3376 arguments is invoked to initialize the @code{Data1} component instead
3377 of the constructor specified in the declaration of type @code{Rec1}. In
3378 Ada 2005 the box in the aggregate indicates that unspecified components
3379 are initialized using the expression (if any) available in the component
3380 declaration. That is, in this case discriminant @code{D} is initialized
3381 to value @code{20}, @code{Value} is initialized to value 1000, and the
3382 non-default C++ constructor that handles two integers takes care of
3383 initializing component @code{Data2} with values @code{20,30}.
3384
3385 In Ada 2005 we can use the extended return statement to build the Ada
3386 equivalent to C++ non-default constructors. For example:
3387
3388 @smallexample @c ada
3389   function Constructor (V : Integer) return Rec2 is
3390   begin
3391      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3392                                    others => <>),
3393                            others => <>) do
3394         --  Further actions required for construction of
3395         --  objects of type Rec2
3396         ...
3397      end record;
3398   end Constructor;
3399 @end smallexample
3400
3401 In this example the extended return statement construct is used to
3402 build in place the returned object whose components are initialized
3403 by means of a limited aggregate. Any further action associated with
3404 the constructor can be placed inside the construct.
3405
3406 @node Interfacing with C++ at the Class Level
3407 @subsection Interfacing with C++ at the Class Level
3408 @noindent
3409 In this section we demonstrate the GNAT features for interfacing with
3410 C++ by means of an example making use of Ada 2005 abstract interface
3411 types. This example consists of a classification of animals; classes
3412 have been used to model our main classification of animals, and
3413 interfaces provide support for the management of secondary
3414 classifications. We first demonstrate a case in which the types and
3415 constructors are defined on the C++ side and imported from the Ada
3416 side, and latter the reverse case.
3417
3418 The root of our derivation will be the @code{Animal} class, with a
3419 single private attribute (the @code{Age} of the animal) and two public
3420 primitives to set and get the value of this attribute.
3421
3422 @smallexample
3423 @b{class} Animal @{
3424  @b{public}:
3425    @b{virtual} void Set_Age (int New_Age);
3426    @b{virtual} int Age ();
3427  @b{private}:
3428    int Age_Count;
3429 @};
3430 @end smallexample
3431
3432 Abstract interface types are defined in C++ by means of classes with pure
3433 virtual functions and no data members. In our example we will use two
3434 interfaces that provide support for the common management of @code{Carnivore}
3435 and @code{Domestic} animals:
3436
3437 @smallexample
3438 @b{class} Carnivore @{
3439 @b{public}:
3440    @b{virtual} int Number_Of_Teeth () = 0;
3441 @};
3442
3443 @b{class} Domestic @{
3444 @b{public}:
3445    @b{virtual void} Set_Owner (char* Name) = 0;
3446 @};
3447 @end smallexample
3448
3449 Using these declarations, we can now say that a @code{Dog} is an animal that is
3450 both Carnivore and Domestic, that is:
3451
3452 @smallexample
3453 @b{class} Dog : Animal, Carnivore, Domestic @{
3454  @b{public}:
3455    @b{virtual} int  Number_Of_Teeth ();
3456    @b{virtual} void Set_Owner (char* Name);
3457
3458    Dog(); // Constructor
3459  @b{private}:
3460    int  Tooth_Count;
3461    char *Owner;
3462 @};
3463 @end smallexample
3464
3465 In the following examples we will assume that the previous declarations are
3466 located in a file named @code{animals.h}. The following package demonstrates
3467 how to import these C++ declarations from the Ada side:
3468
3469 @smallexample @c ada
3470 with Interfaces.C.Strings; use Interfaces.C.Strings;
3471 package Animals is
3472   type Carnivore is interface;
3473   pragma Convention (C_Plus_Plus, Carnivore);
3474   function Number_Of_Teeth (X : Carnivore)
3475      return Natural is abstract;
3476
3477   type Domestic is interface;
3478   pragma Convention (C_Plus_Plus, Set_Owner);
3479   procedure Set_Owner
3480     (X    : in out Domestic;
3481      Name : Chars_Ptr) is abstract;
3482
3483   type Animal is tagged record
3484     Age : Natural := 0;
3485   end record;
3486   pragma Import (C_Plus_Plus, Animal);
3487
3488   procedure Set_Age (X : in out Animal; Age : Integer);
3489   pragma Import (C_Plus_Plus, Set_Age);
3490
3491   function Age (X : Animal) return Integer;
3492   pragma Import (C_Plus_Plus, Age);
3493
3494   type Dog is new Animal and Carnivore and Domestic with record
3495     Tooth_Count : Natural;
3496     Owner       : String (1 .. 30);
3497   end record;
3498   pragma Import (C_Plus_Plus, Dog);
3499
3500   function Number_Of_Teeth (A : Dog) return Integer;
3501   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3502
3503   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3504   pragma Import (C_Plus_Plus, Set_Owner);
3505
3506   function New_Dog return Dog;
3507   pragma CPP_Constructor (New_Dog);
3508   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3509 end Animals;
3510 @end smallexample
3511
3512 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3513 interfacing with these C++ classes is easy. The only requirement is that all
3514 the primitives and components must be declared exactly in the same order in
3515 the two languages.
3516
3517 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3518 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3519 the arguments to the called primitives will be the same as for C++. For the
3520 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3521 to indicate that they have been defined on the C++ side; this is required
3522 because the dispatch table associated with these tagged types will be built
3523 in the C++ side and therefore will not contain the predefined Ada primitives
3524 which Ada would otherwise expect.
3525
3526 As the reader can see there is no need to indicate the C++ mangled names
3527 associated with each subprogram because it is assumed that all the calls to
3528 these primitives will be dispatching calls. The only exception is the
3529 constructor, which must be registered with the compiler by means of
3530 @code{pragma CPP_Constructor} and needs to provide its associated C++
3531 mangled name because the Ada compiler generates direct calls to it.
3532
3533 With the above packages we can now declare objects of type Dog on the Ada side
3534 and dispatch calls to the corresponding subprograms on the C++ side. We can
3535 also extend the tagged type Dog with further fields and primitives, and
3536 override some of its C++ primitives on the Ada side. For example, here we have
3537 a type derivation defined on the Ada side that inherits all the dispatching
3538 primitives of the ancestor from the C++ side.
3539
3540 @smallexample
3541 @b{with} Animals; @b{use} Animals;
3542 @b{package} Vaccinated_Animals @b{is}
3543   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3544   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3545 @b{end} Vaccinated_Animals;
3546 @end smallexample
3547
3548 It is important to note that, because of the ABI compatibility, the programmer
3549 does not need to add any further information to indicate either the object
3550 layout or the dispatch table entry associated with each dispatching operation.
3551
3552 Now let us define all the types and constructors on the Ada side and export
3553 them to C++, using the same hierarchy of our previous example:
3554
3555 @smallexample @c ada
3556 with Interfaces.C.Strings;
3557 use Interfaces.C.Strings;
3558 package Animals is
3559   type Carnivore is interface;
3560   pragma Convention (C_Plus_Plus, Carnivore);
3561   function Number_Of_Teeth (X : Carnivore)
3562      return Natural is abstract;
3563
3564   type Domestic is interface;
3565   pragma Convention (C_Plus_Plus, Set_Owner);
3566   procedure Set_Owner
3567     (X    : in out Domestic;
3568      Name : Chars_Ptr) is abstract;
3569
3570   type Animal is tagged record
3571     Age : Natural := 0;
3572   end record;
3573   pragma Convention (C_Plus_Plus, Animal);
3574
3575   procedure Set_Age (X : in out Animal; Age : Integer);
3576   pragma Export (C_Plus_Plus, Set_Age);
3577
3578   function Age (X : Animal) return Integer;
3579   pragma Export (C_Plus_Plus, Age);
3580
3581   type Dog is new Animal and Carnivore and Domestic with record
3582     Tooth_Count : Natural;
3583     Owner       : String (1 .. 30);
3584   end record;
3585   pragma Convention (C_Plus_Plus, Dog);
3586
3587   function Number_Of_Teeth (A : Dog) return Integer;
3588   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3589
3590   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3591   pragma Export (C_Plus_Plus, Set_Owner);
3592
3593   function New_Dog return Dog'Class;
3594   pragma Export (C_Plus_Plus, New_Dog);
3595 end Animals;
3596 @end smallexample
3597
3598 Compared with our previous example the only difference is the use of
3599 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3600 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3601 nothing else to be done; as explained above, the only requirement is that all
3602 the primitives and components are declared in exactly the same order.
3603
3604 For completeness, let us see a brief C++ main program that uses the
3605 declarations available in @code{animals.h} (presented in our first example) to
3606 import and use the declarations from the Ada side, properly initializing and
3607 finalizing the Ada run-time system along the way:
3608
3609 @smallexample
3610 @b{#include} "animals.h"
3611 @b{#include} <iostream>
3612 @b{using namespace} std;
3613
3614 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3615 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3616 void Check_Animal (Animal *obj)       @{@dots{}@}
3617 void Check_Dog (Dog *obj)             @{@dots{}@}
3618
3619 @b{extern} "C" @{
3620   void adainit (void);
3621   void adafinal (void);
3622   Dog* new_dog ();
3623 @}
3624
3625 void test ()
3626 @{
3627   Dog *obj = new_dog();  // Ada constructor
3628   Check_Carnivore (obj); // Check secondary DT
3629   Check_Domestic (obj);  // Check secondary DT
3630   Check_Animal (obj);    // Check primary DT
3631   Check_Dog (obj);       // Check primary DT
3632 @}
3633
3634 int main ()
3635 @{
3636   adainit ();  test();  adafinal ();
3637   return 0;
3638 @}
3639 @end smallexample
3640
3641 @node Comparison between GNAT and C/C++ Compilation Models
3642 @section Comparison between GNAT and C/C++ Compilation Models
3643
3644 @noindent
3645 The GNAT model of compilation is close to the C and C++ models. You can
3646 think of Ada specs as corresponding to header files in C. As in C, you
3647 don't need to compile specs; they are compiled when they are used. The
3648 Ada @code{with} is similar in effect to the @code{#include} of a C
3649 header.
3650
3651 One notable difference is that, in Ada, you may compile specs separately
3652 to check them for semantic and syntactic accuracy. This is not always
3653 possible with C headers because they are fragments of programs that have
3654 less specific syntactic or semantic rules.
3655
3656 The other major difference is the requirement for running the binder,
3657 which performs two important functions. First, it checks for
3658 consistency. In C or C++, the only defense against assembling
3659 inconsistent programs lies outside the compiler, in a makefile, for
3660 example. The binder satisfies the Ada requirement that it be impossible
3661 to construct an inconsistent program when the compiler is used in normal
3662 mode.
3663
3664 @cindex Elaboration order control
3665 The other important function of the binder is to deal with elaboration
3666 issues. There are also elaboration issues in C++ that are handled
3667 automatically. This automatic handling has the advantage of being
3668 simpler to use, but the C++ programmer has no control over elaboration.
3669 Where @code{gnatbind} might complain there was no valid order of
3670 elaboration, a C++ compiler would simply construct a program that
3671 malfunctioned at run time.
3672 @end ifclear
3673
3674 @node Comparison between GNAT and Conventional Ada Library Models
3675 @section Comparison between GNAT and Conventional Ada Library Models
3676
3677 @noindent
3678 This section is intended for Ada programmers who have
3679 used an Ada compiler implementing the traditional Ada library
3680 model, as described in the Ada Reference Manual.
3681
3682 @cindex GNAT library
3683 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3684 source files themselves acts as the library. Compiling Ada programs does
3685 not generate any centralized information, but rather an object file and
3686 a ALI file, which are of interest only to the binder and linker.
3687 In a traditional system, the compiler reads information not only from
3688 the source file being compiled, but also from the centralized library.
3689 This means that the effect of a compilation depends on what has been
3690 previously compiled. In particular:
3691
3692 @itemize @bullet
3693 @item
3694 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3695 to the version of the unit most recently compiled into the library.
3696
3697 @item
3698 Inlining is effective only if the necessary body has already been
3699 compiled into the library.
3700
3701 @item
3702 Compiling a unit may obsolete other units in the library.
3703 @end itemize
3704
3705 @noindent
3706 In GNAT, compiling one unit never affects the compilation of any other
3707 units because the compiler reads only source files. Only changes to source
3708 files can affect the results of a compilation. In particular:
3709
3710 @itemize @bullet
3711 @item
3712 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3713 to the source version of the unit that is currently accessible to the
3714 compiler.
3715
3716 @item
3717 @cindex Inlining
3718 Inlining requires the appropriate source files for the package or
3719 subprogram bodies to be available to the compiler. Inlining is always
3720 effective, independent of the order in which units are complied.
3721
3722 @item
3723 Compiling a unit never affects any other compilations. The editing of
3724 sources may cause previous compilations to be out of date if they
3725 depended on the source file being modified.
3726 @end itemize
3727
3728 @noindent
3729 The most important result of these differences is that order of compilation
3730 is never significant in GNAT. There is no situation in which one is
3731 required to do one compilation before another. What shows up as order of
3732 compilation requirements in the traditional Ada library becomes, in
3733 GNAT, simple source dependencies; in other words, there is only a set
3734 of rules saying what source files must be present when a file is
3735 compiled.
3736
3737 @ifset vms
3738 @node Placement of temporary files
3739 @section Placement of temporary files
3740 @cindex Temporary files (user control over placement)
3741
3742 @noindent
3743 GNAT creates temporary files in the directory designated by the environment
3744 variable @env{TMPDIR}.
3745 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3746 for detailed information on how environment variables are resolved.
3747 For most users the easiest way to make use of this feature is to simply
3748 define @env{TMPDIR} as a job level logical name).
3749 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3750 for compiler temporary files, then you can include something like the
3751 following command in your @file{LOGIN.COM} file:
3752
3753 @smallexample
3754 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3755 @end smallexample
3756
3757 @noindent
3758 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3759 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3760 designated by @env{TEMP}.
3761 If none of these environment variables are defined then GNAT uses the
3762 directory designated by the logical name @code{SYS$SCRATCH:}
3763 (by default the user's home directory). If all else fails
3764 GNAT uses the current directory for temporary files.
3765 @end ifset
3766
3767 @c *************************
3768 @node Compiling Using gcc
3769 @chapter Compiling Using @command{gcc}
3770
3771 @noindent
3772 This chapter discusses how to compile Ada programs using the @command{gcc}
3773 command. It also describes the set of switches
3774 that can be used to control the behavior of the compiler.
3775 @menu
3776 * Compiling Programs::
3777 * Switches for gcc::
3778 * Search Paths and the Run-Time Library (RTL)::
3779 * Order of Compilation Issues::
3780 * Examples::
3781 @end menu
3782
3783 @node Compiling Programs
3784 @section Compiling Programs
3785
3786 @noindent
3787 The first step in creating an executable program is to compile the units
3788 of the program using the @command{gcc} command. You must compile the
3789 following files:
3790
3791 @itemize @bullet
3792 @item
3793 the body file (@file{.adb}) for a library level subprogram or generic
3794 subprogram
3795
3796 @item
3797 the spec file (@file{.ads}) for a library level package or generic
3798 package that has no body
3799
3800 @item
3801 the body file (@file{.adb}) for a library level package
3802 or generic package that has a body
3803
3804 @end itemize
3805
3806 @noindent
3807 You need @emph{not} compile the following files
3808
3809 @itemize @bullet
3810
3811 @item
3812 the spec of a library unit which has a body
3813
3814 @item
3815 subunits
3816 @end itemize
3817
3818 @noindent
3819 because they are compiled as part of compiling related units. GNAT
3820 package specs
3821 when the corresponding body is compiled, and subunits when the parent is
3822 compiled.
3823
3824 @cindex cannot generate code
3825 If you attempt to compile any of these files, you will get one of the
3826 following error messages (where @var{fff} is the name of the file you
3827 compiled):
3828
3829 @smallexample
3830 cannot generate code for file @var{fff} (package spec)
3831 to check package spec, use -gnatc
3832
3833 cannot generate code for file @var{fff} (missing subunits)
3834 to check parent unit, use -gnatc
3835
3836 cannot generate code for file @var{fff} (subprogram spec)
3837 to check subprogram spec, use -gnatc
3838
3839 cannot generate code for file @var{fff} (subunit)
3840 to check subunit, use -gnatc
3841 @end smallexample
3842
3843 @noindent
3844 As indicated by the above error messages, if you want to submit
3845 one of these files to the compiler to check for correct semantics
3846 without generating code, then use the @option{-gnatc} switch.
3847
3848 The basic command for compiling a file containing an Ada unit is
3849
3850 @smallexample
3851 @c $ gcc -c @ovar{switches} @file{file name}
3852 @c Expanding @ovar macro inline (explanation in macro def comments)
3853 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3854 @end smallexample
3855
3856 @noindent
3857 where @var{file name} is the name of the Ada file (usually
3858 having an extension
3859 @file{.ads} for a spec or @file{.adb} for a body).
3860 @ifclear vms
3861 You specify the
3862 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3863 @end ifclear
3864 The result of a successful compilation is an object file, which has the
3865 same name as the source file but an extension of @file{.o} and an Ada
3866 Library Information (ALI) file, which also has the same name as the
3867 source file, but with @file{.ali} as the extension. GNAT creates these
3868 two output files in the current directory, but you may specify a source
3869 file in any directory using an absolute or relative path specification
3870 containing the directory information.
3871
3872 @findex gnat1
3873 @command{gcc} is actually a driver program that looks at the extensions of
3874 the file arguments and loads the appropriate compiler. For example, the
3875 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3876 These programs are in directories known to the driver program (in some
3877 configurations via environment variables you set), but need not be in
3878 your path. The @command{gcc} driver also calls the assembler and any other
3879 utilities needed to complete the generation of the required object
3880 files.
3881
3882 It is possible to supply several file names on the same @command{gcc}
3883 command. This causes @command{gcc} to call the appropriate compiler for
3884 each file. For example, the following command lists three separate
3885 files to be compiled:
3886
3887 @smallexample
3888 $ gcc -c x.adb y.adb z.c
3889 @end smallexample
3890
3891 @noindent
3892 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3893 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3894 The compiler generates three object files @file{x.o}, @file{y.o} and
3895 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3896 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3897 @ifclear vms
3898 except for
3899 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3900 @end ifclear
3901
3902 @node Switches for gcc
3903 @section Switches for @command{gcc}
3904
3905 @noindent
3906 The @command{gcc} command accepts switches that control the
3907 compilation process. These switches are fully described in this section.
3908 First we briefly list all the switches, in alphabetical order, then we
3909 describe the switches in more detail in functionally grouped sections.
3910
3911 More switches exist for GCC than those documented here, especially
3912 for specific targets. However, their use is not recommended as
3913 they may change code generation in ways that are incompatible with
3914 the Ada run-time library, or can cause inconsistencies between
3915 compilation units.
3916
3917 @menu
3918 * Output and Error Message Control::
3919 * Warning Message Control::
3920 * Debugging and Assertion Control::
3921 * Validity Checking::
3922 * Style Checking::
3923 * Run-Time Checks::
3924 * Using gcc for Syntax Checking::
3925 * Using gcc for Semantic Checking::
3926 * Compiling Different Versions of Ada::
3927 * Character Set Control::
3928 * File Naming Control::
3929 * Subprogram Inlining Control::
3930 * Auxiliary Output Control::
3931 * Debugging Control::
3932 * Exception Handling Control::
3933 * Units to Sources Mapping Files::
3934 * Integrated Preprocessing::
3935 * Code Generation Control::
3936 @ifset vms
3937 * Return Codes::
3938 @end ifset
3939 @end menu
3940
3941 @table @option
3942 @c !sort!
3943 @ifclear vms
3944 @cindex @option{-b} (@command{gcc})
3945 @item -b @var{target}
3946 Compile your program to run on @var{target}, which is the name of a
3947 system configuration. You must have a GNAT cross-compiler built if
3948 @var{target} is not the same as your host system.
3949
3950 @item -B@var{dir}
3951 @cindex @option{-B} (@command{gcc})
3952 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3953 from @var{dir} instead of the default location. Only use this switch
3954 when multiple versions of the GNAT compiler are available.
3955 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3956 GNU Compiler Collection (GCC)}, for further details. You would normally
3957 use the @option{-b} or @option{-V} switch instead.
3958
3959 @item -c
3960 @cindex @option{-c} (@command{gcc})
3961 Compile. Always use this switch when compiling Ada programs.
3962
3963 Note: for some other languages when using @command{gcc}, notably in
3964 the case of C and C++, it is possible to use
3965 use @command{gcc} without a @option{-c} switch to
3966 compile and link in one step. In the case of GNAT, you
3967 cannot use this approach, because the binder must be run
3968 and @command{gcc} cannot be used to run the GNAT binder.
3969 @end ifclear
3970
3971 @item -fno-inline
3972 @cindex @option{-fno-inline} (@command{gcc})
3973 Suppresses all back-end inlining, even if other optimization or inlining
3974 switches are set.
3975 This includes suppression of inlining that results
3976 from the use of the pragma @code{Inline_Always}.
3977 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3978 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3979 effect if this switch is present.
3980
3981 @item -fno-inline-functions
3982 @cindex @option{-fno-inline-functions} (@command{gcc})
3983 Suppresses automatic inlining of subprograms, which is enabled
3984 if @option{-O3} is used.
3985
3986 @item -fno-inline-small-functions
3987 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3988 Suppresses automatic inlining of small subprograms, which is enabled
3989 if @option{-O2} is used.
3990
3991 @item -fno-inline-functions-called-once
3992 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3993 Suppresses inlining of subprograms local to the unit and called once
3994 from within it, which is enabled if @option{-O1} is used.
3995
3996 @item -fno-ivopts
3997 @cindex @option{-fno-ivopts} (@command{gcc})
3998 Suppresses high-level loop induction variable optimizations, which are
3999 enabled if @option{-O1} is used. These optimizations are generally
4000 profitable but, for some specific cases of loops with numerous uses
4001 of the iteration variable that follow a common pattern, they may end
4002 up destroying the regularity that could be exploited at a lower level
4003 and thus producing inferior code.
4004
4005 @item -fno-strict-aliasing
4006 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4007 Causes the compiler to avoid assumptions regarding non-aliasing
4008 of objects of different types. See
4009 @ref{Optimization and Strict Aliasing} for details.
4010
4011 @item -fstack-check
4012 @cindex @option{-fstack-check} (@command{gcc})
4013 Activates stack checking.
4014 See @ref{Stack Overflow Checking} for details.
4015
4016 @item -fstack-usage
4017 @cindex @option{-fstack-usage} (@command{gcc})
4018 Makes the compiler output stack usage information for the program, on a
4019 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4020
4021 @item -fcallgraph-info@r{[}=su@r{]}
4022 @cindex @option{-fcallgraph-info} (@command{gcc})
4023 Makes the compiler output callgraph information for the program, on a
4024 per-file basis.  The information is generated in the VCG format.  It can
4025 be decorated with stack-usage per-node information.
4026
4027 @item ^-g^/DEBUG^
4028 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4029 Generate debugging information. This information is stored in the object
4030 file and copied from there to the final executable file by the linker,
4031 where it can be read by the debugger. You must use the
4032 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4033
4034 @item -gnat83
4035 @cindex @option{-gnat83} (@command{gcc})
4036 Enforce Ada 83 restrictions.
4037
4038 @item -gnat95
4039 @cindex @option{-gnat95} (@command{gcc})
4040 Enforce Ada 95 restrictions.
4041
4042 @item -gnat05
4043 @cindex @option{-gnat05} (@command{gcc})
4044 Allow full Ada 2005 features.
4045
4046 @item -gnat2005
4047 @cindex @option{-gnat2005} (@command{gcc})
4048 Allow full Ada 2005 features (same as @option{-gnat05}
4049
4050 @item -gnat12
4051 @cindex @option{-gnat12} (@command{gcc})
4052
4053 @item -gnat2012
4054 @cindex @option{-gnat2012} (@command{gcc})
4055 Allow full Ada 2012 features (same as @option{-gnat12}
4056
4057 @item -gnata
4058 @cindex @option{-gnata} (@command{gcc})
4059 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4060 activated. Note that these pragmas can also be controlled using the
4061 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4062 It also activates pragmas @code{Check}, @code{Precondition}, and
4063 @code{Postcondition}. Note that these pragmas can also be controlled
4064 using the configuration pragma @code{Check_Policy}.
4065
4066 @item -gnatA
4067 @cindex @option{-gnatA} (@command{gcc})
4068 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4069 it will be ignored.
4070
4071 @item -gnatb
4072 @cindex @option{-gnatb} (@command{gcc})
4073 Generate brief messages to @file{stderr} even if verbose mode set.
4074
4075 @item -gnatB
4076 @cindex @option{-gnatB} (@command{gcc})
4077 Assume no invalid (bad) values except for 'Valid attribute use
4078 (@pxref{Validity Checking}).
4079
4080 @item -gnatc
4081 @cindex @option{-gnatc} (@command{gcc})
4082 Check syntax and semantics only (no code generation attempted).
4083
4084 @item -gnatC
4085 @cindex @option{-gnatC} (@command{gcc})
4086 Generate CodePeer information (no code generation attempted).
4087 This switch will generate an intermediate representation suitable for
4088 use by CodePeer (@file{.scil} files). This switch is not compatible with
4089 code generation (it will, among other things, disable some switches such
4090 as -gnatn, and enable others such as -gnata).
4091
4092 @item -gnatd
4093 @cindex @option{-gnatd} (@command{gcc})
4094 Specify debug options for the compiler. The string of characters after
4095 the @option{-gnatd} specify the specific debug options. The possible
4096 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4097 compiler source file @file{debug.adb} for details of the implemented
4098 debug options. Certain debug options are relevant to applications
4099 programmers, and these are documented at appropriate points in this
4100 users guide.
4101
4102 @ifclear vms
4103 @item -gnatD
4104 @cindex @option{-gnatD[nn]} (@command{gcc})
4105 @end ifclear
4106 @ifset vms
4107 @item /XDEBUG /LXDEBUG=nnn
4108 @end ifset
4109 Create expanded source files for source level debugging. This switch
4110 also suppress generation of cross-reference information
4111 (see @option{-gnatx}).
4112
4113 @item -gnatec=@var{path}
4114 @cindex @option{-gnatec} (@command{gcc})
4115 Specify a configuration pragma file
4116 @ifclear vms
4117 (the equal sign is optional)
4118 @end ifclear
4119 (@pxref{The Configuration Pragmas Files}).
4120
4121 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4122 @cindex @option{-gnateD} (@command{gcc})
4123 Defines a symbol, associated with @var{value}, for preprocessing.
4124 (@pxref{Integrated Preprocessing}).
4125
4126 @item -gnatef
4127 @cindex @option{-gnatef} (@command{gcc})
4128 Display full source path name in brief error messages.
4129
4130 @item -gnateG
4131 @cindex @option{-gnateG} (@command{gcc})
4132 Save result of preprocessing in a text file.
4133
4134 @item -gnatem=@var{path}
4135 @cindex @option{-gnatem} (@command{gcc})
4136 Specify a mapping file
4137 @ifclear vms
4138 (the equal sign is optional)
4139 @end ifclear
4140 (@pxref{Units to Sources Mapping Files}).
4141
4142 @item -gnatep=@var{file}
4143 @cindex @option{-gnatep} (@command{gcc})
4144 Specify a preprocessing data file
4145 @ifclear vms
4146 (the equal sign is optional)
4147 @end ifclear
4148 (@pxref{Integrated Preprocessing}).
4149
4150 @item -gnateS
4151 @cindex @option{-gnateS} (@command{gcc})
4152 Generate SCO (Source Coverage Obligation) information in the ALI
4153 file. This information is used by advanced coverage tools. See
4154 unit @file{SCOs} in the compiler sources for details in files
4155 @file{scos.ads} and @file{scos.adb}.
4156
4157 @item -gnatE
4158 @cindex @option{-gnatE} (@command{gcc})
4159 Full dynamic elaboration checks.
4160
4161 @item -gnatf
4162 @cindex @option{-gnatf} (@command{gcc})
4163 Full errors. Multiple errors per line, all undefined references, do not
4164 attempt to suppress cascaded errors.
4165
4166 @item -gnatF
4167 @cindex @option{-gnatF} (@command{gcc})
4168 Externals names are folded to all uppercase.
4169
4170 @item ^-gnatg^/GNAT_INTERNAL^
4171 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4172 Internal GNAT implementation mode. This should not be used for
4173 applications programs, it is intended only for use by the compiler
4174 and its run-time library. For documentation, see the GNAT sources.
4175 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4176 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4177 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4178 so that all standard warnings and all standard style options are turned on.
4179 All warnings and style messages are treated as errors.
4180
4181 @ifclear vms
4182 @item -gnatG=nn
4183 @cindex @option{-gnatG[nn]} (@command{gcc})
4184 @end ifclear
4185 @ifset vms
4186 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4187 @end ifset
4188 List generated expanded code in source form.
4189
4190 @item ^-gnath^/HELP^
4191 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4192 Output usage information. The output is written to @file{stdout}.
4193
4194 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4195 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4196 Identifier character set
4197 @ifclear vms
4198 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4199 @end ifclear
4200 For details of the possible selections for @var{c},
4201 see @ref{Character Set Control}.
4202
4203 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4204 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4205 Ignore representation clauses. When this switch is used,
4206 representation clauses are treated as comments. This is useful
4207 when initially porting code where you want to ignore rep clause
4208 problems, and also for compiling foreign code (particularly
4209 for use with ASIS). The representation clauses that are ignored
4210 are: enumeration_representation_clause, record_representation_clause,
4211 and attribute_definition_clause for the following attributes:
4212 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4213 Object_Size, Size, Small, Stream_Size, and Value_Size.
4214 Note that this option should be used only for compiling -- the
4215 code is likely to malfunction at run time.
4216
4217 @item -gnatjnn
4218 @cindex @option{-gnatjnn} (@command{gcc})
4219 Reformat error messages to fit on nn character lines
4220
4221 @item -gnatk=@var{n}
4222 @cindex @option{-gnatk} (@command{gcc})
4223 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4224
4225 @item -gnatl
4226 @cindex @option{-gnatl} (@command{gcc})
4227 Output full source listing with embedded error messages.
4228
4229 @item -gnatL
4230 @cindex @option{-gnatL} (@command{gcc})
4231 Used in conjunction with -gnatG or -gnatD to intersperse original
4232 source lines (as comment lines with line numbers) in the expanded
4233 source output.
4234
4235 @item -gnatm=@var{n}
4236 @cindex @option{-gnatm} (@command{gcc})
4237 Limit number of detected error or warning messages to @var{n}
4238 where @var{n} is in the range 1..999999. The default setting if
4239 no switch is given is 9999. If the number of warnings reaches this
4240 limit, then a message is output and further warnings are suppressed,
4241 but the compilation is continued. If the number of error messages
4242 reaches this limit, then a message is output and the compilation
4243 is abandoned. The equal sign here is optional. A value of zero
4244 means that no limit applies.
4245
4246 @item -gnatn
4247 @cindex @option{-gnatn} (@command{gcc})
4248 Activate inlining for subprograms for which
4249 pragma @code{inline} is specified. This inlining is performed
4250 by the GCC back-end.
4251
4252 @item -gnatN
4253 @cindex @option{-gnatN} (@command{gcc})
4254 Activate front end inlining for subprograms for which
4255 pragma @code{Inline} is specified. This inlining is performed
4256 by the front end and will be visible in the
4257 @option{-gnatG} output.
4258
4259 When using a gcc-based back end (in practice this means using any version
4260 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4261 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4262 Historically front end inlining was more extensive than the gcc back end
4263 inlining, but that is no longer the case.
4264
4265 @item -gnato
4266 @cindex @option{-gnato} (@command{gcc})
4267 Enable numeric overflow checking (which is not normally enabled by
4268 default). Note that division by zero is a separate check that is not
4269 controlled by this switch (division by zero checking is on by default).
4270
4271 @item -gnatp
4272 @cindex @option{-gnatp} (@command{gcc})
4273 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4274 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4275
4276 @item -gnat-p
4277 @cindex @option{-gnat-p} (@command{gcc})
4278 Cancel effect of previous @option{-gnatp} switch.
4279
4280 @item -gnatP
4281 @cindex @option{-gnatP} (@command{gcc})
4282 Enable polling. This is required on some systems (notably Windows NT) to
4283 obtain asynchronous abort and asynchronous transfer of control capability.
4284 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4285 details.
4286
4287 @item -gnatq
4288 @cindex @option{-gnatq} (@command{gcc})
4289 Don't quit. Try semantics, even if parse errors.
4290
4291 @item -gnatQ
4292 @cindex @option{-gnatQ} (@command{gcc})
4293 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4294
4295 @item -gnatr
4296 @cindex @option{-gnatr} (@command{gcc})
4297 Treat pragma Restrictions as Restriction_Warnings.
4298
4299 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4300 @cindex @option{-gnatR} (@command{gcc})
4301 Output representation information for declared types and objects.
4302
4303 @item -gnats
4304 @cindex @option{-gnats} (@command{gcc})
4305 Syntax check only.
4306
4307 @item -gnatS
4308 @cindex @option{-gnatS} (@command{gcc})
4309 Print package Standard.
4310
4311 @item -gnatt
4312 @cindex @option{-gnatt} (@command{gcc})
4313 Generate tree output file.
4314
4315 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4316 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4317 All compiler tables start at @var{nnn} times usual starting size.
4318
4319 @item -gnatu
4320 @cindex @option{-gnatu} (@command{gcc})
4321 List units for this compilation.
4322
4323 @item -gnatU
4324 @cindex @option{-gnatU} (@command{gcc})
4325 Tag all error messages with the unique string ``error:''
4326
4327 @item -gnatv
4328 @cindex @option{-gnatv} (@command{gcc})
4329 Verbose mode. Full error output with source lines to @file{stdout}.
4330
4331 @item -gnatV
4332 @cindex @option{-gnatV} (@command{gcc})
4333 Control level of validity checking (@pxref{Validity Checking}).
4334
4335 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4336 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4337 Warning mode where
4338 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4339 the exact warnings that
4340 are enabled or disabled (@pxref{Warning Message Control}).
4341
4342 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4343 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4344 Wide character encoding method
4345 @ifclear vms
4346 (@var{e}=n/h/u/s/e/8).
4347 @end ifclear
4348 @ifset vms
4349 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4350 @end ifset
4351
4352 @item -gnatx
4353 @cindex @option{-gnatx} (@command{gcc})
4354 Suppress generation of cross-reference information.
4355
4356 @item -gnatX
4357 @cindex @option{-gnatX} (@command{gcc})
4358 Enable GNAT implementation extensions and latest Ada version.
4359
4360 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4361 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4362 Enable built-in style checks (@pxref{Style Checking}).
4363
4364 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4365 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4366 Distribution stub generation and compilation
4367 @ifclear vms
4368 (@var{m}=r/c for receiver/caller stubs).
4369 @end ifclear
4370 @ifset vms
4371 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4372 to be generated and compiled).
4373 @end ifset
4374
4375 @item ^-I^/SEARCH=^@var{dir}
4376 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4377 @cindex RTL
4378 Direct GNAT to search the @var{dir} directory for source files needed by
4379 the current compilation
4380 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4381
4382 @item ^-I-^/NOCURRENT_DIRECTORY^
4383 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4384 @cindex RTL
4385 Except for the source file named in the command line, do not look for source
4386 files in the directory containing the source file named in the command line
4387 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4388
4389 @ifclear vms
4390 @item -mbig-switch
4391 @cindex @option{-mbig-switch} (@command{gcc})
4392 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4393 This standard gcc switch causes the compiler to use larger offsets in its
4394 jump table representation for @code{case} statements.
4395 This may result in less efficient code, but is sometimes necessary
4396 (for example on HP-UX targets)
4397 @cindex HP-UX and @option{-mbig-switch} option
4398 in order to compile large and/or nested @code{case} statements.
4399
4400 @item -o @var{file}
4401 @cindex @option{-o} (@command{gcc})
4402 This switch is used in @command{gcc} to redirect the generated object file
4403 and its associated ALI file. Beware of this switch with GNAT, because it may
4404 cause the object file and ALI file to have different names which in turn
4405 may confuse the binder and the linker.
4406 @end ifclear
4407
4408 @item -nostdinc
4409 @cindex @option{-nostdinc} (@command{gcc})
4410 Inhibit the search of the default location for the GNAT Run Time
4411 Library (RTL) source files.
4412
4413 @item -nostdlib
4414 @cindex @option{-nostdlib} (@command{gcc})
4415 Inhibit the search of the default location for the GNAT Run Time
4416 Library (RTL) ALI files.
4417
4418 @ifclear vms
4419 @c @item -O@ovar{n}
4420 @c Expanding @ovar macro inline (explanation in macro def comments)
4421 @item -O@r{[}@var{n}@r{]}
4422 @cindex @option{-O} (@command{gcc})
4423 @var{n} controls the optimization level.
4424
4425 @table @asis
4426 @item n = 0
4427 No optimization, the default setting if no @option{-O} appears
4428
4429 @item n = 1
4430 Normal optimization, the default if you specify @option{-O} without
4431 an operand. A good compromise between code quality and compilation
4432 time.
4433
4434 @item n = 2
4435 Extensive optimization, may improve execution time, possibly at the cost of
4436 substantially increased compilation time.
4437
4438 @item n = 3
4439 Same as @option{-O2}, and also includes inline expansion for small subprograms
4440 in the same unit.
4441
4442 @item n = s
4443 Optimize space usage
4444 @end table
4445
4446 @noindent
4447 See also @ref{Optimization Levels}.
4448 @end ifclear
4449
4450 @ifset vms
4451 @item  /NOOPTIMIZE
4452 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4453 Equivalent to @option{/OPTIMIZE=NONE}.
4454 This is the default behavior in the absence of an @option{/OPTIMIZE}
4455 qualifier.
4456
4457 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4458 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4459 Selects the level of optimization for your program. The supported
4460 keywords are as follows:
4461 @table @code
4462 @item   ALL
4463 Perform most optimizations, including those that
4464 are expensive.
4465 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4466 without keyword options.
4467
4468 @item   NONE
4469 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4470
4471 @item SOME
4472 Perform some optimizations, but omit ones that are costly.
4473
4474 @item   DEVELOPMENT
4475 Same as @code{SOME}.
4476
4477 @item INLINING
4478 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4479 automatic inlining of small subprograms within a unit
4480
4481 @item   UNROLL_LOOPS
4482 Try to unroll loops. This keyword may be specified together with
4483 any keyword above other than @code{NONE}. Loop unrolling
4484 usually, but not always, improves the performance of programs.
4485
4486 @item SPACE
4487 Optimize space usage
4488 @end table
4489
4490 @noindent
4491 See also @ref{Optimization Levels}.
4492 @end ifset
4493
4494 @ifclear vms
4495 @item -pass-exit-codes
4496 @cindex @option{-pass-exit-codes} (@command{gcc})
4497 Catch exit codes from the compiler and use the most meaningful as
4498 exit status.
4499 @end ifclear
4500
4501 @item --RTS=@var{rts-path}
4502 @cindex @option{--RTS} (@command{gcc})
4503 Specifies the default location of the runtime library. Same meaning as the
4504 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4505
4506 @item ^-S^/ASM^
4507 @cindex @option{^-S^/ASM^} (@command{gcc})
4508 ^Used in place of @option{-c} to^Used to^
4509 cause the assembler source file to be
4510 generated, using @file{^.s^.S^} as the extension,
4511 instead of the object file.
4512 This may be useful if you need to examine the generated assembly code.
4513
4514 @item ^-fverbose-asm^/VERBOSE_ASM^
4515 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4516 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4517 to cause the generated assembly code file to be annotated with variable
4518 names, making it significantly easier to follow.
4519
4520 @item ^-v^/VERBOSE^
4521 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4522 Show commands generated by the @command{gcc} driver. Normally used only for
4523 debugging purposes or if you need to be sure what version of the
4524 compiler you are executing.
4525
4526 @ifclear vms
4527 @item -V @var{ver}
4528 @cindex @option{-V} (@command{gcc})
4529 Execute @var{ver} version of the compiler. This is the @command{gcc}
4530 version, not the GNAT version.
4531 @end ifclear
4532
4533 @item ^-w^/NO_BACK_END_WARNINGS^
4534 @cindex @option{-w} (@command{gcc})
4535 Turn off warnings generated by the back end of the compiler. Use of
4536 this switch also causes the default for front end warnings to be set
4537 to suppress (as though @option{-gnatws} had appeared at the start of
4538 the options).
4539
4540 @end table
4541
4542 @ifclear vms
4543 @c Combining qualifiers does not work on VMS
4544 You may combine a sequence of GNAT switches into a single switch. For
4545 example, the combined switch
4546
4547 @cindex Combining GNAT switches
4548 @smallexample
4549 -gnatofi3
4550 @end smallexample
4551
4552 @noindent
4553 is equivalent to specifying the following sequence of switches:
4554
4555 @smallexample
4556 -gnato -gnatf -gnati3
4557 @end smallexample
4558 @end ifclear
4559
4560 @noindent
4561 The following restrictions apply to the combination of switches
4562 in this manner:
4563
4564 @itemize @bullet
4565 @item
4566 The switch @option{-gnatc} if combined with other switches must come
4567 first in the string.
4568
4569 @item
4570 The switch @option{-gnats} if combined with other switches must come
4571 first in the string.
4572
4573 @item
4574 The switches
4575 ^^@option{/DISTRIBUTION_STUBS=},^
4576 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4577 switches, and only one of them may appear in the command line.
4578
4579 @item
4580 The switch @option{-gnat-p} may not be combined with any other switch.
4581
4582 @ifclear vms
4583 @item
4584 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4585 switch), then all further characters in the switch are interpreted
4586 as style modifiers (see description of @option{-gnaty}).
4587
4588 @item
4589 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4590 switch), then all further characters in the switch are interpreted
4591 as debug flags (see description of @option{-gnatd}).
4592
4593 @item
4594 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4595 switch), then all further characters in the switch are interpreted
4596 as warning mode modifiers (see description of @option{-gnatw}).
4597
4598 @item
4599 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4600 switch), then all further characters in the switch are interpreted
4601 as validity checking options (@pxref{Validity Checking}).
4602
4603 @item
4604 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4605 a combined list of options.
4606 @end ifclear
4607 @end itemize
4608
4609 @node Output and Error Message Control
4610 @subsection Output and Error Message Control
4611 @findex stderr
4612
4613 @noindent
4614 The standard default format for error messages is called ``brief format''.
4615 Brief format messages are written to @file{stderr} (the standard error
4616 file) and have the following form:
4617
4618 @smallexample
4619 e.adb:3:04: Incorrect spelling of keyword "function"
4620 e.adb:4:20: ";" should be "is"
4621 @end smallexample
4622
4623 @noindent
4624 The first integer after the file name is the line number in the file,
4625 and the second integer is the column number within the line.
4626 @ifclear vms
4627 @code{GPS} can parse the error messages
4628 and point to the referenced character.
4629 @end ifclear
4630 The following switches provide control over the error message
4631 format:
4632
4633 @table @option
4634 @c !sort!
4635 @item -gnatv
4636 @cindex @option{-gnatv} (@command{gcc})
4637 @findex stdout
4638 @ifclear vms
4639 The v stands for verbose.
4640 @end ifclear
4641 The effect of this setting is to write long-format error
4642 messages to @file{stdout} (the standard output file.
4643 The same program compiled with the
4644 @option{-gnatv} switch would generate:
4645
4646 @smallexample
4647 @cartouche
4648 3. funcion X (Q : Integer)
4649    |
4650 >>> Incorrect spelling of keyword "function"
4651 4. return Integer;
4652                  |
4653 >>> ";" should be "is"
4654 @end cartouche
4655 @end smallexample
4656
4657 @noindent
4658 The vertical bar indicates the location of the error, and the @samp{>>>}
4659 prefix can be used to search for error messages. When this switch is
4660 used the only source lines output are those with errors.
4661
4662 @item -gnatl
4663 @cindex @option{-gnatl} (@command{gcc})
4664 @ifclear vms
4665 The @code{l} stands for list.
4666 @end ifclear
4667 This switch causes a full listing of
4668 the file to be generated. In the case where a body is
4669 compiled, the corresponding spec is also listed, along
4670 with any subunits. Typical output from compiling a package
4671 body @file{p.adb} might look like:
4672
4673 @smallexample @c ada
4674 @cartouche
4675  Compiling: p.adb
4676
4677      1. package body p is
4678      2.    procedure a;
4679      3.    procedure a is separate;
4680      4. begin
4681      5.    null
4682                |
4683         >>> missing ";"
4684
4685      6. end;
4686
4687 Compiling: p.ads
4688
4689      1. package p is
4690      2.    pragma Elaborate_Body
4691                                 |
4692         >>> missing ";"
4693
4694      3. end p;
4695
4696 Compiling: p-a.adb
4697
4698      1. separate p
4699                 |
4700         >>> missing "("
4701
4702      2. procedure a is
4703      3. begin
4704      4.    null
4705                |
4706         >>> missing ";"
4707
4708      5. end;
4709 @end cartouche
4710 @end smallexample
4711
4712 @noindent
4713 @findex stderr
4714 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4715 standard output is redirected, a brief summary is written to
4716 @file{stderr} (standard error) giving the number of error messages and
4717 warning messages generated.
4718
4719 @item -^gnatl^OUTPUT_FILE^=file
4720 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4721 This has the same effect as @option{-gnatl} except that the output is
4722 written to a file instead of to standard output. If the given name
4723 @file{fname} does not start with a period, then it is the full name
4724 of the file to be written. If @file{fname} is an extension, it is
4725 appended to the name of the file being compiled. For example, if
4726 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4727 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4728
4729 @item -gnatU
4730 @cindex @option{-gnatU} (@command{gcc})
4731 This switch forces all error messages to be preceded by the unique
4732 string ``error:''. This means that error messages take a few more
4733 characters in space, but allows easy searching for and identification
4734 of error messages.
4735
4736 @item -gnatb
4737 @cindex @option{-gnatb} (@command{gcc})
4738 @ifclear vms
4739 The @code{b} stands for brief.
4740 @end ifclear
4741 This switch causes GNAT to generate the
4742 brief format error messages to @file{stderr} (the standard error
4743 file) as well as the verbose
4744 format message or full listing (which as usual is written to
4745 @file{stdout} (the standard output file).
4746
4747 @item -gnatm=@var{n}
4748 @cindex @option{-gnatm} (@command{gcc})
4749 @ifclear vms
4750 The @code{m} stands for maximum.
4751 @end ifclear
4752 @var{n} is a decimal integer in the
4753 range of 1 to 999999 and limits the number of error or warning
4754 messages to be generated. For example, using
4755 @option{-gnatm2} might yield
4756
4757 @smallexample
4758 e.adb:3:04: Incorrect spelling of keyword "function"
4759 e.adb:5:35: missing ".."
4760 fatal error: maximum number of errors detected
4761 compilation abandoned
4762 @end smallexample
4763
4764 @noindent
4765 The default setting if
4766 no switch is given is 9999. If the number of warnings reaches this
4767 limit, then a message is output and further warnings are suppressed,
4768 but the compilation is continued. If the number of error messages
4769 reaches this limit, then a message is output and the compilation
4770 is abandoned. A value of zero means that no limit applies.
4771
4772 @noindent
4773 Note that the equal sign is optional, so the switches
4774 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4775
4776 @item -gnatf
4777 @cindex @option{-gnatf} (@command{gcc})
4778 @cindex Error messages, suppressing
4779 @ifclear vms
4780 The @code{f} stands for full.
4781 @end ifclear
4782 Normally, the compiler suppresses error messages that are likely to be
4783 redundant. This switch causes all error
4784 messages to be generated. In particular, in the case of
4785 references to undefined variables. If a given variable is referenced
4786 several times, the normal format of messages is
4787 @smallexample
4788 e.adb:7:07: "V" is undefined (more references follow)
4789 @end smallexample
4790
4791 @noindent
4792 where the parenthetical comment warns that there are additional
4793 references to the variable @code{V}. Compiling the same program with the
4794 @option{-gnatf} switch yields
4795
4796 @smallexample
4797 e.adb:7:07: "V" is undefined
4798 e.adb:8:07: "V" is undefined
4799 e.adb:8:12: "V" is undefined
4800 e.adb:8:16: "V" is undefined
4801 e.adb:9:07: "V" is undefined
4802 e.adb:9:12: "V" is undefined
4803 @end smallexample
4804
4805 @noindent
4806 The @option{-gnatf} switch also generates additional information for
4807 some error messages.  Some examples are:
4808
4809 @itemize @bullet
4810 @item
4811 Details on possibly non-portable unchecked conversion
4812 @item
4813 List possible interpretations for ambiguous calls
4814 @item
4815 Additional details on incorrect parameters
4816 @end itemize
4817
4818 @item -gnatjnn
4819 @cindex @option{-gnatjnn} (@command{gcc})
4820 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4821 with continuation lines are treated as though the continuation lines were
4822 separate messages (and so a warning with two continuation lines counts as
4823 three warnings, and is listed as three separate messages).
4824
4825 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4826 messages are output in a different manner. A message and all its continuation
4827 lines are treated as a unit, and count as only one warning or message in the
4828 statistics totals. Furthermore, the message is reformatted so that no line
4829 is longer than nn characters.
4830
4831 @item -gnatq
4832 @cindex @option{-gnatq} (@command{gcc})
4833 @ifclear vms
4834 The @code{q} stands for quit (really ``don't quit'').
4835 @end ifclear
4836 In normal operation mode, the compiler first parses the program and
4837 determines if there are any syntax errors. If there are, appropriate
4838 error messages are generated and compilation is immediately terminated.
4839 This switch tells
4840 GNAT to continue with semantic analysis even if syntax errors have been
4841 found. This may enable the detection of more errors in a single run. On
4842 the other hand, the semantic analyzer is more likely to encounter some
4843 internal fatal error when given a syntactically invalid tree.
4844
4845 @item -gnatQ
4846 @cindex @option{-gnatQ} (@command{gcc})
4847 In normal operation mode, the @file{ALI} file is not generated if any
4848 illegalities are detected in the program. The use of @option{-gnatQ} forces
4849 generation of the @file{ALI} file. This file is marked as being in
4850 error, so it cannot be used for binding purposes, but it does contain
4851 reasonably complete cross-reference information, and thus may be useful
4852 for use by tools (e.g., semantic browsing tools or integrated development
4853 environments) that are driven from the @file{ALI} file. This switch
4854 implies @option{-gnatq}, since the semantic phase must be run to get a
4855 meaningful ALI file.
4856
4857 In addition, if @option{-gnatt} is also specified, then the tree file is
4858 generated even if there are illegalities. It may be useful in this case
4859 to also specify @option{-gnatq} to ensure that full semantic processing
4860 occurs. The resulting tree file can be processed by ASIS, for the purpose
4861 of providing partial information about illegal units, but if the error
4862 causes the tree to be badly malformed, then ASIS may crash during the
4863 analysis.
4864
4865 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4866 being in error, @command{gnatmake} will attempt to recompile the source when it
4867 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4868
4869 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4870 since ALI files are never generated if @option{-gnats} is set.
4871
4872 @end table
4873
4874 @node Warning Message Control
4875 @subsection Warning Message Control
4876 @cindex Warning messages
4877 @noindent
4878 In addition to error messages, which correspond to illegalities as defined
4879 in the Ada Reference Manual, the compiler detects two kinds of warning
4880 situations.
4881
4882 First, the compiler considers some constructs suspicious and generates a
4883 warning message to alert you to a possible error. Second, if the
4884 compiler detects a situation that is sure to raise an exception at
4885 run time, it generates a warning message. The following shows an example
4886 of warning messages:
4887 @smallexample
4888 e.adb:4:24: warning: creation of object may raise Storage_Error
4889 e.adb:10:17: warning: static value out of range
4890 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4891 @end smallexample
4892
4893 @noindent
4894 GNAT considers a large number of situations as appropriate
4895 for the generation of warning messages. As always, warnings are not
4896 definite indications of errors. For example, if you do an out-of-range
4897 assignment with the deliberate intention of raising a
4898 @code{Constraint_Error} exception, then the warning that may be
4899 issued does not indicate an error. Some of the situations for which GNAT
4900 issues warnings (at least some of the time) are given in the following
4901 list. This list is not complete, and new warnings are often added to
4902 subsequent versions of GNAT. The list is intended to give a general idea
4903 of the kinds of warnings that are generated.
4904
4905 @itemize @bullet
4906 @item
4907 Possible infinitely recursive calls
4908
4909 @item
4910 Out-of-range values being assigned
4911
4912 @item
4913 Possible order of elaboration problems
4914
4915 @item
4916 Assertions (pragma Assert) that are sure to fail
4917
4918 @item
4919 Unreachable code
4920
4921 @item
4922 Address clauses with possibly unaligned values, or where an attempt is
4923 made to overlay a smaller variable with a larger one.
4924
4925 @item
4926 Fixed-point type declarations with a null range
4927
4928 @item
4929 Direct_IO or Sequential_IO instantiated with a type that has access values
4930
4931 @item
4932 Variables that are never assigned a value
4933
4934 @item
4935 Variables that are referenced before being initialized
4936
4937 @item
4938 Task entries with no corresponding @code{accept} statement
4939
4940 @item
4941 Duplicate accepts for the same task entry in a @code{select}
4942
4943 @item
4944 Objects that take too much storage
4945
4946 @item
4947 Unchecked conversion between types of differing sizes
4948
4949 @item
4950 Missing @code{return} statement along some execution path in a function
4951
4952 @item
4953 Incorrect (unrecognized) pragmas
4954
4955 @item
4956 Incorrect external names
4957
4958 @item
4959 Allocation from empty storage pool
4960
4961 @item
4962 Potentially blocking operation in protected type
4963
4964 @item
4965 Suspicious parenthesization of expressions
4966
4967 @item
4968 Mismatching bounds in an aggregate
4969
4970 @item
4971 Attempt to return local value by reference
4972
4973 @item
4974 Premature instantiation of a generic body
4975
4976 @item
4977 Attempt to pack aliased components
4978
4979 @item
4980 Out of bounds array subscripts
4981
4982 @item
4983 Wrong length on string assignment
4984
4985 @item
4986 Violations of style rules if style checking is enabled
4987
4988 @item
4989 Unused @code{with} clauses
4990
4991 @item
4992 @code{Bit_Order} usage that does not have any effect
4993
4994 @item
4995 @code{Standard.Duration} used to resolve universal fixed expression
4996
4997 @item
4998 Dereference of possibly null value
4999
5000 @item
5001 Declaration that is likely to cause storage error
5002
5003 @item
5004 Internal GNAT unit @code{with}'ed by application unit
5005
5006 @item
5007 Values known to be out of range at compile time
5008
5009 @item
5010 Unreferenced labels and variables
5011
5012 @item
5013 Address overlays that could clobber memory
5014
5015 @item
5016 Unexpected initialization when address clause present
5017
5018 @item
5019 Bad alignment for address clause
5020
5021 @item
5022 Useless type conversions
5023
5024 @item
5025 Redundant assignment statements and other redundant constructs
5026
5027 @item
5028 Useless exception handlers
5029
5030 @item
5031 Accidental hiding of name by child unit
5032
5033 @item
5034 Access before elaboration detected at compile time
5035
5036 @item
5037 A range in a @code{for} loop that is known to be null or might be null
5038
5039 @end itemize
5040
5041 @noindent
5042 The following section lists compiler switches that are available
5043 to control the handling of warning messages. It is also possible
5044 to exercise much finer control over what warnings are issued and
5045 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5046 gnat_rm, GNAT Reference manual}.
5047
5048 @table @option
5049 @c !sort!
5050 @item -gnatwa
5051 @emph{Activate all optional errors.}
5052 @cindex @option{-gnatwa} (@command{gcc})
5053 This switch activates most optional warning messages, see remaining list
5054 in this section for details on optional warning messages that can be
5055 individually controlled.  The warnings that are not turned on by this
5056 switch are
5057 @option{-gnatwd} (implicit dereferencing),
5058 @option{-gnatwh} (hiding),
5059 @option{-gnatwl} (elaboration warnings),
5060 @option{-gnatw.o} (warn on values set by out parameters ignored)
5061 and @option{-gnatwt} (tracking of deleted conditional code).
5062 All other optional warnings are turned on.
5063
5064 @item -gnatwA
5065 @emph{Suppress all optional errors.}
5066 @cindex @option{-gnatwA} (@command{gcc})
5067 This switch suppresses all optional warning messages, see remaining list
5068 in this section for details on optional warning messages that can be
5069 individually controlled.
5070
5071 @item -gnatw.a
5072 @emph{Activate warnings on failing assertions.}
5073 @cindex @option{-gnatw.a} (@command{gcc})
5074 @cindex Assert failures
5075 This switch activates warnings for assertions where the compiler can tell at
5076 compile time that the assertion will fail. Note that this warning is given
5077 even if assertions are disabled. The default is that such warnings are
5078 generated.
5079
5080 @item -gnatw.A
5081 @emph{Suppress warnings on failing assertions.}
5082 @cindex @option{-gnatw.A} (@command{gcc})
5083 @cindex Assert failures
5084 This switch suppresses warnings for assertions where the compiler can tell at
5085 compile time that the assertion will fail.
5086
5087 @item -gnatwb
5088 @emph{Activate warnings on bad fixed values.}
5089 @cindex @option{-gnatwb} (@command{gcc})
5090 @cindex Bad fixed values
5091 @cindex Fixed-point Small value
5092 @cindex Small value
5093 This switch activates warnings for static fixed-point expressions whose
5094 value is not an exact multiple of Small. Such values are implementation
5095 dependent, since an implementation is free to choose either of the multiples
5096 that surround the value. GNAT always chooses the closer one, but this is not
5097 required behavior, and it is better to specify a value that is an exact
5098 multiple, ensuring predictable execution. The default is that such warnings
5099 are not generated.
5100
5101 @item -gnatwB
5102 @emph{Suppress warnings on bad fixed values.}
5103 @cindex @option{-gnatwB} (@command{gcc})
5104 This switch suppresses warnings for static fixed-point expressions whose
5105 value is not an exact multiple of Small.
5106
5107 @item -gnatw.b
5108 @emph{Activate warnings on biased representation.}
5109 @cindex @option{-gnatw.b} (@command{gcc})
5110 @cindex Biased representation
5111 This switch activates warnings when a size clause, value size clause, component
5112 clause, or component size clause forces the use of biased representation for an
5113 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5114 to represent 10/11). The default is that such warnings are generated.
5115
5116 @item -gnatw.B
5117 @emph{Suppress warnings on biased representation.}
5118 @cindex @option{-gnatwB} (@command{gcc})
5119 This switch suppresses warnings for representation clauses that force the use
5120 of biased representation.
5121
5122 @item -gnatwc
5123 @emph{Activate warnings on conditionals.}
5124 @cindex @option{-gnatwc} (@command{gcc})
5125 @cindex Conditionals, constant
5126 This switch activates warnings for conditional expressions used in
5127 tests that are known to be True or False at compile time. The default
5128 is that such warnings are not generated.
5129 Note that this warning does
5130 not get issued for the use of boolean variables or constants whose
5131 values are known at compile time, since this is a standard technique
5132 for conditional compilation in Ada, and this would generate too many
5133 false positive warnings.
5134
5135 This warning option also activates a special test for comparisons using
5136 the operators ``>='' and`` <=''.
5137 If the compiler can tell that only the equality condition is possible,
5138 then it will warn that the ``>'' or ``<'' part of the test
5139 is useless and that the operator could be replaced by ``=''.
5140 An example would be comparing a @code{Natural} variable <= 0.
5141
5142 This warning option also generates warnings if
5143 one or both tests is optimized away in a membership test for integer
5144 values if the result can be determined at compile time. Range tests on
5145 enumeration types are not included, since it is common for such tests
5146 to include an end point.
5147
5148 This warning can also be turned on using @option{-gnatwa}.
5149
5150 @item -gnatwC
5151 @emph{Suppress warnings on conditionals.}
5152 @cindex @option{-gnatwC} (@command{gcc})
5153 This switch suppresses warnings for conditional expressions used in
5154 tests that are known to be True or False at compile time.
5155
5156 @item -gnatw.c
5157 @emph{Activate warnings on missing component clauses.}
5158 @cindex @option{-gnatw.c} (@command{gcc})
5159 @cindex Component clause, missing
5160 This switch activates warnings for record components where a record
5161 representation clause is present and has component clauses for the
5162 majority, but not all, of the components. A warning is given for each
5163 component for which no component clause is present.
5164
5165 This warning can also be turned on using @option{-gnatwa}.
5166
5167 @item -gnatw.C
5168 @emph{Suppress warnings on missing component clauses.}
5169 @cindex @option{-gnatwC} (@command{gcc})
5170 This switch suppresses warnings for record components that are
5171 missing a component clause in the situation described above.
5172
5173 @item -gnatwd
5174 @emph{Activate warnings on implicit dereferencing.}
5175 @cindex @option{-gnatwd} (@command{gcc})
5176 If this switch is set, then the use of a prefix of an access type
5177 in an indexed component, slice, or selected component without an
5178 explicit @code{.all} will generate a warning. With this warning
5179 enabled, access checks occur only at points where an explicit
5180 @code{.all} appears in the source code (assuming no warnings are
5181 generated as a result of this switch). The default is that such
5182 warnings are not generated.
5183 Note that @option{-gnatwa} does not affect the setting of
5184 this warning option.
5185
5186 @item -gnatwD
5187 @emph{Suppress warnings on implicit dereferencing.}
5188 @cindex @option{-gnatwD} (@command{gcc})
5189 @cindex Implicit dereferencing
5190 @cindex Dereferencing, implicit
5191 This switch suppresses warnings for implicit dereferences in
5192 indexed components, slices, and selected components.
5193
5194 @item -gnatwe
5195 @emph{Treat warnings and style checks as errors.}
5196 @cindex @option{-gnatwe} (@command{gcc})
5197 @cindex Warnings, treat as error
5198 This switch causes warning messages and style check messages to be
5199 treated as errors.
5200 The warning string still appears, but the warning messages are counted
5201 as errors, and prevent the generation of an object file. Note that this
5202 is the only -gnatw switch that affects the handling of style check messages.
5203
5204 @item -gnatw.e
5205 @emph{Activate every optional warning}
5206 @cindex @option{-gnatw.e} (@command{gcc})
5207 @cindex Warnings, activate every optional warning
5208 This switch activates all optional warnings, including those which
5209 are not activated by @code{-gnatwa}.
5210
5211 @item -gnatwf
5212 @emph{Activate warnings on unreferenced formals.}
5213 @cindex @option{-gnatwf} (@command{gcc})
5214 @cindex Formals, unreferenced
5215 This switch causes a warning to be generated if a formal parameter
5216 is not referenced in the body of the subprogram. This warning can
5217 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5218 default is that these warnings are not generated.
5219
5220 @item -gnatwF
5221 @emph{Suppress warnings on unreferenced formals.}
5222 @cindex @option{-gnatwF} (@command{gcc})
5223 This switch suppresses warnings for unreferenced formal
5224 parameters. Note that the
5225 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5226 effect of warning on unreferenced entities other than subprogram
5227 formals.
5228
5229 @item -gnatwg
5230 @emph{Activate warnings on unrecognized pragmas.}
5231 @cindex @option{-gnatwg} (@command{gcc})
5232 @cindex Pragmas, unrecognized
5233 This switch causes a warning to be generated if an unrecognized
5234 pragma is encountered. Apart from issuing this warning, the
5235 pragma is ignored and has no effect. This warning can
5236 also be turned on using @option{-gnatwa}. The default
5237 is that such warnings are issued (satisfying the Ada Reference
5238 Manual requirement that such warnings appear).
5239
5240 @item -gnatwG
5241 @emph{Suppress warnings on unrecognized pragmas.}
5242 @cindex @option{-gnatwG} (@command{gcc})
5243 This switch suppresses warnings for unrecognized pragmas.
5244
5245 @item -gnatwh
5246 @emph{Activate warnings on hiding.}
5247 @cindex @option{-gnatwh} (@command{gcc})
5248 @cindex Hiding of Declarations
5249 This switch activates warnings on hiding declarations.
5250 A declaration is considered hiding
5251 if it is for a non-overloadable entity, and it declares an entity with the
5252 same name as some other entity that is directly or use-visible. The default
5253 is that such warnings are not generated.
5254 Note that @option{-gnatwa} does not affect the setting of this warning option.
5255
5256 @item -gnatwH
5257 @emph{Suppress warnings on hiding.}
5258 @cindex @option{-gnatwH} (@command{gcc})
5259 This switch suppresses warnings on hiding declarations.
5260
5261 @item -gnatwi
5262 @emph{Activate warnings on implementation units.}
5263 @cindex @option{-gnatwi} (@command{gcc})
5264 This switch activates warnings for a @code{with} of an internal GNAT
5265 implementation unit, defined as any unit from the @code{Ada},
5266 @code{Interfaces}, @code{GNAT},
5267 ^^@code{DEC},^ or @code{System}
5268 hierarchies that is not
5269 documented in either the Ada Reference Manual or the GNAT
5270 Programmer's Reference Manual. Such units are intended only
5271 for internal implementation purposes and should not be @code{with}'ed
5272 by user programs. The default is that such warnings are generated
5273 This warning can also be turned on using @option{-gnatwa}.
5274
5275 @item -gnatwI
5276 @emph{Disable warnings on implementation units.}
5277 @cindex @option{-gnatwI} (@command{gcc})
5278 This switch disables warnings for a @code{with} of an internal GNAT
5279 implementation unit.
5280
5281 @item -gnatw.i
5282 @emph{Activate warnings on overlapping actuals.}
5283 @cindex @option{-gnatw.i} (@command{gcc})
5284 This switch enables a warning on statically detectable overlapping actuals in
5285 a subprogram call, when one of the actuals is an in-out parameter, and the
5286 types of the actuals are not by-copy types. The warning is off by default,
5287 and is not included under -gnatwa.
5288
5289 @item -gnatw.I
5290 @emph{Disable warnings on overlapping actuals.}
5291 @cindex @option{-gnatw.I} (@command{gcc})
5292 This switch disables warnings on overlapping actuals in a call..
5293
5294 @item -gnatwj
5295 @emph{Activate warnings on obsolescent features (Annex J).}
5296 @cindex @option{-gnatwj} (@command{gcc})
5297 @cindex Features, obsolescent
5298 @cindex Obsolescent features
5299 If this warning option is activated, then warnings are generated for
5300 calls to subprograms marked with @code{pragma Obsolescent} and
5301 for use of features in Annex J of the Ada Reference Manual. In the
5302 case of Annex J, not all features are flagged. In particular use
5303 of the renamed packages (like @code{Text_IO}) and use of package
5304 @code{ASCII} are not flagged, since these are very common and
5305 would generate many annoying positive warnings. The default is that
5306 such warnings are not generated. This warning is also turned on by
5307 the use of @option{-gnatwa}.
5308
5309 In addition to the above cases, warnings are also generated for
5310 GNAT features that have been provided in past versions but which
5311 have been superseded (typically by features in the new Ada standard).
5312 For example, @code{pragma Ravenscar} will be flagged since its
5313 function is replaced by @code{pragma Profile(Ravenscar)}.
5314
5315 Note that this warning option functions differently from the
5316 restriction @code{No_Obsolescent_Features} in two respects.
5317 First, the restriction applies only to annex J features.
5318 Second, the restriction does flag uses of package @code{ASCII}.
5319
5320 @item -gnatwJ
5321 @emph{Suppress warnings on obsolescent features (Annex J).}
5322 @cindex @option{-gnatwJ} (@command{gcc})
5323 This switch disables warnings on use of obsolescent features.
5324
5325 @item -gnatwk
5326 @emph{Activate warnings on variables that could be constants.}
5327 @cindex @option{-gnatwk} (@command{gcc})
5328 This switch activates warnings for variables that are initialized but
5329 never modified, and then could be declared constants. The default is that
5330 such warnings are not given.
5331 This warning can also be turned on using @option{-gnatwa}.
5332
5333 @item -gnatwK
5334 @emph{Suppress warnings on variables that could be constants.}
5335 @cindex @option{-gnatwK} (@command{gcc})
5336 This switch disables warnings on variables that could be declared constants.
5337
5338 @item -gnatwl
5339 @emph{Activate warnings for elaboration pragmas.}
5340 @cindex @option{-gnatwl} (@command{gcc})
5341 @cindex Elaboration, warnings
5342 This switch activates warnings on missing
5343 @code{Elaborate_All} and @code{Elaborate} pragmas.
5344 See the section in this guide on elaboration checking for details on
5345 when such pragmas should be used. In dynamic elaboration mode, this switch
5346 generations warnings about the need to add elaboration pragmas. Note however,
5347 that if you blindly follow these warnings, and add @code{Elaborate_All}
5348 warnings wherever they are recommended, you basically end up with the
5349 equivalent of the static elaboration model, which may not be what you want for
5350 legacy code for which the static model does not work.
5351
5352 For the static model, the messages generated are labeled "info:" (for
5353 information messages). They are not warnings to add elaboration pragmas,
5354 merely informational messages showing what implicit elaboration pragmas
5355 have been added, for use in analyzing elaboration circularity problems.
5356
5357 Warnings are also generated if you
5358 are using the static mode of elaboration, and a @code{pragma Elaborate}
5359 is encountered. The default is that such warnings
5360 are not generated.
5361 This warning is not automatically turned on by the use of @option{-gnatwa}.
5362
5363 @item -gnatwL
5364 @emph{Suppress warnings for elaboration pragmas.}
5365 @cindex @option{-gnatwL} (@command{gcc})
5366 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5367 See the section in this guide on elaboration checking for details on
5368 when such pragmas should be used.
5369
5370 @item -gnatwm
5371 @emph{Activate warnings on modified but unreferenced variables.}
5372 @cindex @option{-gnatwm} (@command{gcc})
5373 This switch activates warnings for variables that are assigned (using
5374 an initialization value or with one or more assignment statements) but
5375 whose value is never read. The warning is suppressed for volatile
5376 variables and also for variables that are renamings of other variables
5377 or for which an address clause is given.
5378 This warning can also be turned on using @option{-gnatwa}.
5379 The default is that these warnings are not given.
5380
5381 @item -gnatwM
5382 @emph{Disable warnings on modified but unreferenced variables.}
5383 @cindex @option{-gnatwM} (@command{gcc})
5384 This switch disables warnings for variables that are assigned or
5385 initialized, but never read.
5386
5387 @item -gnatw.m
5388 @emph{Activate warnings on suspicious modulus values.}
5389 @cindex @option{-gnatw.m} (@command{gcc})
5390 This switch activates warnings for modulus values that seem suspicious.
5391 The cases caught are where the size is the same as the modulus (e.g.
5392 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5393 with no size clause. The guess in both cases is that 2**x was intended
5394 rather than x. The default is that these warnings are given.
5395
5396 @item -gnatw.M
5397 @emph{Disable warnings on suspicious modulus values.}
5398 @cindex @option{-gnatw.M} (@command{gcc})
5399 This switch disables warnings for suspicious modulus values.
5400
5401 @item -gnatwn
5402 @emph{Set normal warnings mode.}
5403 @cindex @option{-gnatwn} (@command{gcc})
5404 This switch sets normal warning mode, in which enabled warnings are
5405 issued and treated as warnings rather than errors. This is the default
5406 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5407 an explicit @option{-gnatws} or
5408 @option{-gnatwe}. It also cancels the effect of the
5409 implicit @option{-gnatwe} that is activated by the
5410 use of @option{-gnatg}.
5411
5412 @item -gnatwo
5413 @emph{Activate warnings on address clause overlays.}
5414 @cindex @option{-gnatwo} (@command{gcc})
5415 @cindex Address Clauses, warnings
5416 This switch activates warnings for possibly unintended initialization
5417 effects of defining address clauses that cause one variable to overlap
5418 another. The default is that such warnings are generated.
5419 This warning can also be turned on using @option{-gnatwa}.
5420
5421 @item -gnatwO
5422 @emph{Suppress warnings on address clause overlays.}
5423 @cindex @option{-gnatwO} (@command{gcc})
5424 This switch suppresses warnings on possibly unintended initialization
5425 effects of defining address clauses that cause one variable to overlap
5426 another.
5427
5428 @item -gnatw.o
5429 @emph{Activate warnings on modified but unreferenced out parameters.}
5430 @cindex @option{-gnatw.o} (@command{gcc})
5431 This switch activates warnings for variables that are modified by using
5432 them as actuals for a call to a procedure with an out mode formal, where
5433 the resulting assigned value is never read. It is applicable in the case
5434 where there is more than one out mode formal. If there is only one out
5435 mode formal, the warning is issued by default (controlled by -gnatwu).
5436 The warning is suppressed for volatile
5437 variables and also for variables that are renamings of other variables
5438 or for which an address clause is given.
5439 The default is that these warnings are not given. Note that this warning
5440 is not included in -gnatwa, it must be activated explicitly.
5441
5442 @item -gnatw.O
5443 @emph{Disable warnings on modified but unreferenced out parameters.}
5444 @cindex @option{-gnatw.O} (@command{gcc})
5445 This switch suppresses warnings for variables that are modified by using
5446 them as actuals for a call to a procedure with an out mode formal, where
5447 the resulting assigned value is never read.
5448
5449 @item -gnatwp
5450 @emph{Activate warnings on ineffective pragma Inlines.}
5451 @cindex @option{-gnatwp} (@command{gcc})
5452 @cindex Inlining, warnings
5453 This switch activates warnings for failure of front end inlining
5454 (activated by @option{-gnatN}) to inline a particular call. There are
5455 many reasons for not being able to inline a call, including most
5456 commonly that the call is too complex to inline. The default is
5457 that such warnings are not given.
5458 This warning can also be turned on using @option{-gnatwa}.
5459 Warnings on ineffective inlining by the gcc back-end can be activated
5460 separately, using the gcc switch -Winline.
5461
5462 @item -gnatwP
5463 @emph{Suppress warnings on ineffective pragma Inlines.}
5464 @cindex @option{-gnatwP} (@command{gcc})
5465 This switch suppresses warnings on ineffective pragma Inlines. If the
5466 inlining mechanism cannot inline a call, it will simply ignore the
5467 request silently.
5468
5469 @item -gnatw.p
5470 @emph{Activate warnings on parameter ordering.}
5471 @cindex @option{-gnatw.p} (@command{gcc})
5472 @cindex Parameter order, warnings
5473 This switch activates warnings for cases of suspicious parameter
5474 ordering when the list of arguments are all simple identifiers that
5475 match the names of the formals, but are in a different order. The
5476 warning is suppressed if any use of named parameter notation is used,
5477 so this is the appropriate way to suppress a false positive (and
5478 serves to emphasize that the "misordering" is deliberate). The
5479 default is
5480 that such warnings are not given.
5481 This warning can also be turned on using @option{-gnatwa}.
5482
5483 @item -gnatw.P
5484 @emph{Suppress warnings on parameter ordering.}
5485 @cindex @option{-gnatw.P} (@command{gcc})
5486 This switch suppresses warnings on cases of suspicious parameter
5487 ordering.
5488
5489 @item -gnatwq
5490 @emph{Activate warnings on questionable missing parentheses.}
5491 @cindex @option{-gnatwq} (@command{gcc})
5492 @cindex Parentheses, warnings
5493 This switch activates warnings for cases where parentheses are not used and
5494 the result is potential ambiguity from a readers point of view. For example
5495 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5496 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5497 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5498 follow the rule of always parenthesizing to make the association clear, and
5499 this warning switch warns if such parentheses are not present. The default
5500 is that these warnings are given.
5501 This warning can also be turned on using @option{-gnatwa}.
5502
5503 @item -gnatwQ
5504 @emph{Suppress warnings on questionable missing parentheses.}
5505 @cindex @option{-gnatwQ} (@command{gcc})
5506 This switch suppresses warnings for cases where the association is not
5507 clear and the use of parentheses is preferred.
5508
5509 @item -gnatwr
5510 @emph{Activate warnings on redundant constructs.}
5511 @cindex @option{-gnatwr} (@command{gcc})
5512 This switch activates warnings for redundant constructs. The following
5513 is the current list of constructs regarded as redundant:
5514
5515 @itemize @bullet
5516 @item
5517 Assignment of an item to itself.
5518 @item
5519 Type conversion that converts an expression to its own type.
5520 @item
5521 Use of the attribute @code{Base} where @code{typ'Base} is the same
5522 as @code{typ}.
5523 @item
5524 Use of pragma @code{Pack} when all components are placed by a record
5525 representation clause.
5526 @item
5527 Exception handler containing only a reraise statement (raise with no
5528 operand) which has no effect.
5529 @item
5530 Use of the operator abs on an operand that is known at compile time
5531 to be non-negative
5532 @item
5533 Comparison of boolean expressions to an explicit True value.
5534 @end itemize
5535
5536 This warning can also be turned on using @option{-gnatwa}.
5537 The default is that warnings for redundant constructs are not given.
5538
5539 @item -gnatwR
5540 @emph{Suppress warnings on redundant constructs.}
5541 @cindex @option{-gnatwR} (@command{gcc})
5542 This switch suppresses warnings for redundant constructs.
5543
5544 @item -gnatw.r
5545 @emph{Activate warnings for object renaming function.}
5546 @cindex @option{-gnatw.r} (@command{gcc})
5547 This switch activates warnings for an object renaming that renames a
5548 function call, which is equivalent to a constant declaration (as
5549 opposed to renaming the function itself).  The default is that these
5550 warnings are given.  This warning can also be turned on using
5551 @option{-gnatwa}.
5552
5553 @item -gnatw.R
5554 @emph{Suppress warnings for object renaming function.}
5555 @cindex @option{-gnatwT} (@command{gcc})
5556 This switch suppresses warnings for object renaming function.
5557
5558 @item -gnatws
5559 @emph{Suppress all warnings.}
5560 @cindex @option{-gnatws} (@command{gcc})
5561 This switch completely suppresses the
5562 output of all warning messages from the GNAT front end.
5563 Note that it does not suppress warnings from the @command{gcc} back end.
5564 To suppress these back end warnings as well, use the switch @option{-w}
5565 in addition to @option{-gnatws}. Also this switch has no effect on the
5566 handling of style check messages.
5567
5568 @item -gnatwt
5569 @emph{Activate warnings for tracking of deleted conditional code.}
5570 @cindex @option{-gnatwt} (@command{gcc})
5571 @cindex Deactivated code, warnings
5572 @cindex Deleted code, warnings
5573 This switch activates warnings for tracking of code in conditionals (IF and
5574 CASE statements) that is detected to be dead code which cannot be executed, and
5575 which is removed by the front end. This warning is off by default, and is not
5576 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5577 useful for detecting deactivated code in certified applications.
5578
5579 @item -gnatwT
5580 @emph{Suppress warnings for tracking of deleted conditional code.}
5581 @cindex @option{-gnatwT} (@command{gcc})
5582 This switch suppresses warnings for tracking of deleted conditional code.
5583
5584 @item -gnatwu
5585 @emph{Activate warnings on unused entities.}
5586 @cindex @option{-gnatwu} (@command{gcc})
5587 This switch activates warnings to be generated for entities that
5588 are declared but not referenced, and for units that are @code{with}'ed
5589 and not
5590 referenced. In the case of packages, a warning is also generated if
5591 no entities in the package are referenced. This means that if the package
5592 is referenced but the only references are in @code{use}
5593 clauses or @code{renames}
5594 declarations, a warning is still generated. A warning is also generated
5595 for a generic package that is @code{with}'ed but never instantiated.
5596 In the case where a package or subprogram body is compiled, and there
5597 is a @code{with} on the corresponding spec
5598 that is only referenced in the body,
5599 a warning is also generated, noting that the
5600 @code{with} can be moved to the body. The default is that
5601 such warnings are not generated.
5602 This switch also activates warnings on unreferenced formals
5603 (it includes the effect of @option{-gnatwf}).
5604 This warning can also be turned on using @option{-gnatwa}.
5605
5606 @item -gnatwU
5607 @emph{Suppress warnings on unused entities.}
5608 @cindex @option{-gnatwU} (@command{gcc})
5609 This switch suppresses warnings for unused entities and packages.
5610 It also turns off warnings on unreferenced formals (and thus includes
5611 the effect of @option{-gnatwF}).
5612
5613 @item -gnatw.u
5614 @emph{Activate warnings on unordered enumeration types.}
5615 @cindex @option{-gnatw.u} (@command{gcc})
5616 This switch causes enumeration types to be considered as conceptually
5617 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5618 The effect is to generate warnings in clients that use explicit comparisons
5619 or subranges, since these constructs both treat objects of the type as
5620 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5621 which the type is declared, or its body or subunits.) Please refer to
5622 the description of pragma @code{Ordered} in the
5623 @cite{@value{EDITION} Reference Manual} for further details.
5624
5625 @item -gnatw.U
5626 @emph{Deactivate warnings on unordered enumeration types.}
5627 @cindex @option{-gnatw.U} (@command{gcc})
5628 This switch causes all enumeration types to be considered as ordered, so
5629 that no warnings are given for comparisons or subranges for any type.
5630
5631 @item -gnatwv
5632 @emph{Activate warnings on unassigned variables.}
5633 @cindex @option{-gnatwv} (@command{gcc})
5634 @cindex Unassigned variable warnings
5635 This switch activates warnings for access to variables which
5636 may not be properly initialized. The default is that
5637 such warnings are generated.
5638 This warning can also be turned on using @option{-gnatwa}.
5639
5640 @item -gnatwV
5641 @emph{Suppress warnings on unassigned variables.}
5642 @cindex @option{-gnatwV} (@command{gcc})
5643 This switch suppresses warnings for access to variables which
5644 may not be properly initialized.
5645 For variables of a composite type, the warning can also be suppressed in
5646 Ada 2005 by using a default initialization with a box. For example, if
5647 Table is an array of records whose components are only partially uninitialized,
5648 then the following code:
5649
5650 @smallexample @c ada
5651    Tab : Table := (others => <>);
5652 @end smallexample
5653
5654 will suppress warnings on subsequent statements that access components
5655 of variable Tab.
5656
5657 @item -gnatww
5658 @emph{Activate warnings on wrong low bound assumption.}
5659 @cindex @option{-gnatww} (@command{gcc})
5660 @cindex String indexing warnings
5661 This switch activates warnings for indexing an unconstrained string parameter
5662 with a literal or S'Length. This is a case where the code is assuming that the
5663 low bound is one, which is in general not true (for example when a slice is
5664 passed). The default is that such warnings are generated.
5665 This warning can also be turned on using @option{-gnatwa}.
5666
5667 @item -gnatwW
5668 @emph{Suppress warnings on wrong low bound assumption.}
5669 @cindex @option{-gnatwW} (@command{gcc})
5670 This switch suppresses warnings for indexing an unconstrained string parameter
5671 with a literal or S'Length. Note that this warning can also be suppressed
5672 in a particular case by adding an
5673 assertion that the lower bound is 1,
5674 as shown in the following example.
5675
5676 @smallexample @c ada
5677    procedure K (S : String) is
5678       pragma Assert (S'First = 1);
5679       @dots{}
5680 @end smallexample
5681
5682 @item -gnatw.w
5683 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5684 @cindex @option{-gnatw.w} (@command{gcc})
5685 @cindex Warnings Off control
5686 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5687 where either the pragma is entirely useless (because it suppresses no
5688 warnings), or it could be replaced by @code{pragma Unreferenced} or
5689 @code{pragma Unmodified}.The default is that these warnings are not given.
5690 Note that this warning is not included in -gnatwa, it must be
5691 activated explicitly.
5692
5693 @item -gnatw.W
5694 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5695 @cindex @option{-gnatw.W} (@command{gcc})
5696 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5697
5698 @item -gnatwx
5699 @emph{Activate warnings on Export/Import pragmas.}
5700 @cindex @option{-gnatwx} (@command{gcc})
5701 @cindex Export/Import pragma warnings
5702 This switch activates warnings on Export/Import pragmas when
5703 the compiler detects a possible conflict between the Ada and
5704 foreign language calling sequences. For example, the use of
5705 default parameters in a convention C procedure is dubious
5706 because the C compiler cannot supply the proper default, so
5707 a warning is issued. The default is that such warnings are
5708 generated.
5709 This warning can also be turned on using @option{-gnatwa}.
5710
5711 @item -gnatwX
5712 @emph{Suppress warnings on Export/Import pragmas.}
5713 @cindex @option{-gnatwX} (@command{gcc})
5714 This switch suppresses warnings on Export/Import pragmas.
5715 The sense of this is that you are telling the compiler that
5716 you know what you are doing in writing the pragma, and it
5717 should not complain at you.
5718
5719 @item -gnatw.x
5720 @emph{Activate warnings for No_Exception_Propagation mode.}
5721 @cindex @option{-gnatwm} (@command{gcc})
5722 This switch activates warnings for exception usage when pragma Restrictions
5723 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5724 explicit exception raises which are not covered by a local handler, and for
5725 exception handlers which do not cover a local raise. The default is that these
5726 warnings are not given.
5727
5728 @item -gnatw.X
5729 @emph{Disable warnings for No_Exception_Propagation mode.}
5730 This switch disables warnings for exception usage when pragma Restrictions
5731 (No_Exception_Propagation) is in effect.
5732
5733 @item -gnatwy
5734 @emph{Activate warnings for Ada 2005 compatibility issues.}
5735 @cindex @option{-gnatwy} (@command{gcc})
5736 @cindex Ada 2005 compatibility issues warnings
5737 For the most part Ada 2005 is upwards compatible with Ada 95,
5738 but there are some exceptions (for example the fact that
5739 @code{interface} is now a reserved word in Ada 2005). This
5740 switch activates several warnings to help in identifying
5741 and correcting such incompatibilities. The default is that
5742 these warnings are generated. Note that at one point Ada 2005
5743 was called Ada 0Y, hence the choice of character.
5744 This warning can also be turned on using @option{-gnatwa}.
5745
5746 @item -gnatwY
5747 @emph{Disable warnings for Ada 2005 compatibility issues.}
5748 @cindex @option{-gnatwY} (@command{gcc})
5749 @cindex Ada 2005 compatibility issues warnings
5750 This switch suppresses several warnings intended to help in identifying
5751 incompatibilities between Ada 95 and Ada 2005.
5752
5753 @item -gnatwz
5754 @emph{Activate warnings on unchecked conversions.}
5755 @cindex @option{-gnatwz} (@command{gcc})
5756 @cindex Unchecked_Conversion warnings
5757 This switch activates warnings for unchecked conversions
5758 where the types are known at compile time to have different
5759 sizes. The default
5760 is that such warnings are generated. Warnings are also
5761 generated for subprogram pointers with different conventions,
5762 and, on VMS only, for data pointers with different conventions.
5763 This warning can also be turned on using @option{-gnatwa}.
5764
5765 @item -gnatwZ
5766 @emph{Suppress warnings on unchecked conversions.}
5767 @cindex @option{-gnatwZ} (@command{gcc})
5768 This switch suppresses warnings for unchecked conversions
5769 where the types are known at compile time to have different
5770 sizes or conventions.
5771
5772 @item ^-Wunused^WARNINGS=UNUSED^
5773 @cindex @option{-Wunused}
5774 The warnings controlled by the @option{-gnatw} switch are generated by
5775 the front end of the compiler. The @option{GCC} back end can provide
5776 additional warnings and they are controlled by the @option{-W} switch.
5777 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5778 warnings for entities that are declared but not referenced.
5779
5780 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5781 @cindex @option{-Wuninitialized}
5782 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5783 the back end warning for uninitialized variables. This switch must be
5784 used in conjunction with an optimization level greater than zero.
5785
5786 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5787 @cindex @option{-Wall}
5788 This switch enables all the above warnings from the @option{GCC} back end.
5789 The code generator detects a number of warning situations that are missed
5790 by the @option{GNAT} front end, and this switch can be used to activate them.
5791 The use of this switch also sets the default front end warning mode to
5792 @option{-gnatwa}, that is, most front end warnings activated as well.
5793
5794 @item ^-w^/NO_BACK_END_WARNINGS^
5795 @cindex @option{-w}
5796 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5797 The use of this switch also sets the default front end warning mode to
5798 @option{-gnatws}, that is, front end warnings suppressed as well.
5799
5800 @end table
5801
5802 @noindent
5803 @ifclear vms
5804 A string of warning parameters can be used in the same parameter. For example:
5805
5806 @smallexample
5807 -gnatwaLe
5808 @end smallexample
5809
5810 @noindent
5811 will turn on all optional warnings except for elaboration pragma warnings,
5812 and also specify that warnings should be treated as errors.
5813 @end ifclear
5814 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5815
5816 @table @option
5817 @c !sort!
5818 @item -gnatwC
5819 @item -gnatwD
5820 @item -gnatwF
5821 @item -gnatwg
5822 @item -gnatwH
5823 @item -gnatwi
5824 @item -gnatwJ
5825 @item -gnatwK
5826 @item -gnatwL
5827 @item -gnatwM
5828 @item -gnatwn
5829 @item -gnatwo
5830 @item -gnatwP
5831 @item -gnatwR
5832 @item -gnatwU
5833 @item -gnatwv
5834 @item -gnatwz
5835 @item -gnatwx
5836
5837 @end table
5838
5839 @node Debugging and Assertion Control
5840 @subsection Debugging and Assertion Control
5841
5842 @table @option
5843 @item -gnata
5844 @cindex @option{-gnata} (@command{gcc})
5845 @findex Assert
5846 @findex Debug
5847 @cindex Assertions
5848
5849 @noindent
5850 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5851 are ignored. This switch, where @samp{a} stands for assert, causes
5852 @code{Assert} and @code{Debug} pragmas to be activated.
5853
5854 The pragmas have the form:
5855
5856 @smallexample
5857 @cartouche
5858    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5859                       @var{static-string-expression}@r{]})
5860    @b{pragma} Debug (@var{procedure call})
5861 @end cartouche
5862 @end smallexample
5863
5864 @noindent
5865 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5866 If the result is @code{True}, the pragma has no effect (other than
5867 possible side effects from evaluating the expression). If the result is
5868 @code{False}, the exception @code{Assert_Failure} declared in the package
5869 @code{System.Assertions} is
5870 raised (passing @var{static-string-expression}, if present, as the
5871 message associated with the exception). If no string expression is
5872 given the default is a string giving the file name and line number
5873 of the pragma.
5874
5875 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5876 @code{pragma Debug} may appear within a declaration sequence, allowing
5877 debugging procedures to be called between declarations.
5878
5879 @ifset vms
5880 @item /DEBUG@r{[}=debug-level@r{]}
5881 @itemx  /NODEBUG
5882 Specifies how much debugging information is to be included in
5883 the resulting object file where 'debug-level' is one of the following:
5884 @table @code
5885 @item   TRACEBACK
5886 Include both debugger symbol records and traceback
5887 the object file.
5888 This is the default setting.
5889 @item   ALL
5890 Include both debugger symbol records and traceback in
5891 object file.
5892 @item   NONE
5893 Excludes both debugger symbol records and traceback
5894 the object file. Same as /NODEBUG.
5895 @item   SYMBOLS
5896 Includes only debugger symbol records in the object
5897 file. Note that this doesn't include traceback information.
5898 @end table
5899 @end ifset
5900 @end table
5901
5902 @node Validity Checking
5903 @subsection Validity Checking
5904 @findex Validity Checking
5905
5906 @noindent
5907 The Ada Reference Manual defines the concept of invalid values (see
5908 RM 13.9.1). The primary source of invalid values is uninitialized
5909 variables. A scalar variable that is left uninitialized may contain
5910 an invalid value; the concept of invalid does not apply to access or
5911 composite types.
5912
5913 It is an error to read an invalid value, but the RM does not require
5914 run-time checks to detect such errors, except for some minimal
5915 checking to prevent erroneous execution (i.e. unpredictable
5916 behavior). This corresponds to the @option{-gnatVd} switch below,
5917 which is the default. For example, by default, if the expression of a
5918 case statement is invalid, it will raise Constraint_Error rather than
5919 causing a wild jump, and if an array index on the left-hand side of an
5920 assignment is invalid, it will raise Constraint_Error rather than
5921 overwriting an arbitrary memory location.
5922
5923 The @option{-gnatVa} may be used to enable additional validity checks,
5924 which are not required by the RM. These checks are often very
5925 expensive (which is why the RM does not require them). These checks
5926 are useful in tracking down uninitialized variables, but they are
5927 not usually recommended for production builds.
5928
5929 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5930 control; you can enable whichever validity checks you desire. However,
5931 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5932 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5933 sufficient for non-debugging use.
5934
5935 The @option{-gnatB} switch tells the compiler to assume that all
5936 values are valid (that is, within their declared subtype range)
5937 except in the context of a use of the Valid attribute. This means
5938 the compiler can generate more efficient code, since the range
5939 of values is better known at compile time. However, an uninitialized
5940 variable can cause wild jumps and memory corruption in this mode.
5941
5942 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5943 checking mode as described below.
5944 @ifclear vms
5945 The @code{x} argument is a string of letters that
5946 indicate validity checks that are performed or not performed in addition
5947 to the default checks required by Ada as described above.
5948 @end ifclear
5949 @ifset vms
5950 The options allowed for this qualifier
5951 indicate validity checks that are performed or not performed in addition
5952 to the default checks required by Ada as described above.
5953 @end ifset
5954
5955 @table @option
5956 @c !sort!
5957 @item -gnatVa
5958 @emph{All validity checks.}
5959 @cindex @option{-gnatVa} (@command{gcc})
5960 All validity checks are turned on.
5961 @ifclear vms
5962 That is, @option{-gnatVa} is
5963 equivalent to @option{gnatVcdfimorst}.
5964 @end ifclear
5965
5966 @item -gnatVc
5967 @emph{Validity checks for copies.}
5968 @cindex @option{-gnatVc} (@command{gcc})
5969 The right hand side of assignments, and the initializing values of
5970 object declarations are validity checked.
5971
5972 @item -gnatVd
5973 @emph{Default (RM) validity checks.}
5974 @cindex @option{-gnatVd} (@command{gcc})
5975 Some validity checks are done by default following normal Ada semantics
5976 (RM 13.9.1 (9-11)).
5977 A check is done in case statements that the expression is within the range
5978 of the subtype. If it is not, Constraint_Error is raised.
5979 For assignments to array components, a check is done that the expression used
5980 as index is within the range. If it is not, Constraint_Error is raised.
5981 Both these validity checks may be turned off using switch @option{-gnatVD}.
5982 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5983 switch @option{-gnatVd} will leave the checks turned on.
5984 Switch @option{-gnatVD} should be used only if you are sure that all such
5985 expressions have valid values. If you use this switch and invalid values
5986 are present, then the program is erroneous, and wild jumps or memory
5987 overwriting may occur.
5988
5989 @item -gnatVe
5990 @emph{Validity checks for elementary components.}
5991 @cindex @option{-gnatVe} (@command{gcc})
5992 In the absence of this switch, assignments to record or array components are
5993 not validity checked, even if validity checks for assignments generally
5994 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5995 require valid data, but assignment of individual components does. So for
5996 example, there is a difference between copying the elements of an array with a
5997 slice assignment, compared to assigning element by element in a loop. This
5998 switch allows you to turn off validity checking for components, even when they
5999 are assigned component by component.
6000
6001 @item -gnatVf
6002 @emph{Validity checks for floating-point values.}
6003 @cindex @option{-gnatVf} (@command{gcc})
6004 In the absence of this switch, validity checking occurs only for discrete
6005 values. If @option{-gnatVf} is specified, then validity checking also applies
6006 for floating-point values, and NaNs and infinities are considered invalid,
6007 as well as out of range values for constrained types. Note that this means
6008 that standard IEEE infinity mode is not allowed. The exact contexts
6009 in which floating-point values are checked depends on the setting of other
6010 options. For example,
6011 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6012 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6013 (the order does not matter) specifies that floating-point parameters of mode
6014 @code{in} should be validity checked.
6015
6016 @item -gnatVi
6017 @emph{Validity checks for @code{in} mode parameters}
6018 @cindex @option{-gnatVi} (@command{gcc})
6019 Arguments for parameters of mode @code{in} are validity checked in function
6020 and procedure calls at the point of call.
6021
6022 @item -gnatVm
6023 @emph{Validity checks for @code{in out} mode parameters.}
6024 @cindex @option{-gnatVm} (@command{gcc})
6025 Arguments for parameters of mode @code{in out} are validity checked in
6026 procedure calls at the point of call. The @code{'m'} here stands for
6027 modify, since this concerns parameters that can be modified by the call.
6028 Note that there is no specific option to test @code{out} parameters,
6029 but any reference within the subprogram will be tested in the usual
6030 manner, and if an invalid value is copied back, any reference to it
6031 will be subject to validity checking.
6032
6033 @item -gnatVn
6034 @emph{No validity checks.}
6035 @cindex @option{-gnatVn} (@command{gcc})
6036 This switch turns off all validity checking, including the default checking
6037 for case statements and left hand side subscripts. Note that the use of
6038 the switch @option{-gnatp} suppresses all run-time checks, including
6039 validity checks, and thus implies @option{-gnatVn}. When this switch
6040 is used, it cancels any other @option{-gnatV} previously issued.
6041
6042 @item -gnatVo
6043 @emph{Validity checks for operator and attribute operands.}
6044 @cindex @option{-gnatVo} (@command{gcc})
6045 Arguments for predefined operators and attributes are validity checked.
6046 This includes all operators in package @code{Standard},
6047 the shift operators defined as intrinsic in package @code{Interfaces}
6048 and operands for attributes such as @code{Pos}. Checks are also made
6049 on individual component values for composite comparisons, and on the
6050 expressions in type conversions and qualified expressions. Checks are
6051 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6052
6053 @item -gnatVp
6054 @emph{Validity checks for parameters.}
6055 @cindex @option{-gnatVp} (@command{gcc})
6056 This controls the treatment of parameters within a subprogram (as opposed
6057 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6058 of parameters on a call. If either of these call options is used, then
6059 normally an assumption is made within a subprogram that the input arguments
6060 have been validity checking at the point of call, and do not need checking
6061 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6062 is not made, and parameters are not assumed to be valid, so their validity
6063 will be checked (or rechecked) within the subprogram.
6064
6065 @item -gnatVr
6066 @emph{Validity checks for function returns.}
6067 @cindex @option{-gnatVr} (@command{gcc})
6068 The expression in @code{return} statements in functions is validity
6069 checked.
6070
6071 @item -gnatVs
6072 @emph{Validity checks for subscripts.}
6073 @cindex @option{-gnatVs} (@command{gcc})
6074 All subscripts expressions are checked for validity, whether they appear
6075 on the right side or left side (in default mode only left side subscripts
6076 are validity checked).
6077
6078 @item -gnatVt
6079 @emph{Validity checks for tests.}
6080 @cindex @option{-gnatVt} (@command{gcc})
6081 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6082 statements are checked, as well as guard expressions in entry calls.
6083
6084 @end table
6085
6086 @noindent
6087 The @option{-gnatV} switch may be followed by
6088 ^a string of letters^a list of options^
6089 to turn on a series of validity checking options.
6090 For example,
6091 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6092 specifies that in addition to the default validity checking, copies and
6093 function return expressions are to be validity checked.
6094 In order to make it easier
6095 to specify the desired combination of effects,
6096 @ifclear vms
6097 the upper case letters @code{CDFIMORST} may
6098 be used to turn off the corresponding lower case option.
6099 @end ifclear
6100 @ifset vms
6101 the prefix @code{NO} on an option turns off the corresponding validity
6102 checking:
6103 @itemize @bullet
6104 @item @code{NOCOPIES}
6105 @item @code{NODEFAULT}
6106 @item @code{NOFLOATS}
6107 @item @code{NOIN_PARAMS}
6108 @item @code{NOMOD_PARAMS}
6109 @item @code{NOOPERANDS}
6110 @item @code{NORETURNS}
6111 @item @code{NOSUBSCRIPTS}
6112 @item @code{NOTESTS}
6113 @end itemize
6114 @end ifset
6115 Thus
6116 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6117 turns on all validity checking options except for
6118 checking of @code{@b{in out}} procedure arguments.
6119
6120 The specification of additional validity checking generates extra code (and
6121 in the case of @option{-gnatVa} the code expansion can be substantial).
6122 However, these additional checks can be very useful in detecting
6123 uninitialized variables, incorrect use of unchecked conversion, and other
6124 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6125 is useful in conjunction with the extra validity checking, since this
6126 ensures that wherever possible uninitialized variables have invalid values.
6127
6128 See also the pragma @code{Validity_Checks} which allows modification of
6129 the validity checking mode at the program source level, and also allows for
6130 temporary disabling of validity checks.
6131
6132 @node Style Checking
6133 @subsection Style Checking
6134 @findex Style checking
6135
6136 @noindent
6137 The @option{-gnaty^x^(option,option,@dots{})^} switch
6138 @cindex @option{-gnaty} (@command{gcc})
6139 causes the compiler to
6140 enforce specified style rules. A limited set of style rules has been used
6141 in writing the GNAT sources themselves. This switch allows user programs
6142 to activate all or some of these checks. If the source program fails a
6143 specified style check, an appropriate message is given, preceded by
6144 the character sequence ``(style)''. This message does not prevent
6145 successful compilation (unless the @option{-gnatwe} switch is used).
6146
6147 @ifset vms
6148 @code{(option,option,@dots{})} is a sequence of keywords
6149 @end ifset
6150 @ifclear vms
6151 The string @var{x} is a sequence of letters or digits
6152 @end ifclear
6153 indicating the particular style
6154 checks to be performed. The following checks are defined:
6155
6156 @table @option
6157 @c !sort!
6158 @item 0-9
6159 @emph{Specify indentation level.}
6160 If a digit from 1-9 appears
6161 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6162 then proper indentation is checked, with the digit indicating the
6163 indentation level required. A value of zero turns off this style check.
6164 The general style of required indentation is as specified by
6165 the examples in the Ada Reference Manual. Full line comments must be
6166 aligned with the @code{--} starting on a column that is a multiple of
6167 the alignment level, or they may be aligned the same way as the following
6168 non-blank line (this is useful when full line comments appear in the middle
6169 of a statement.
6170
6171 @item ^a^ATTRIBUTE^
6172 @emph{Check attribute casing.}
6173 Attribute names, including the case of keywords such as @code{digits}
6174 used as attributes names, must be written in mixed case, that is, the
6175 initial letter and any letter following an underscore must be uppercase.
6176 All other letters must be lowercase.
6177
6178 @item ^A^ARRAY_INDEXES^
6179 @emph{Use of array index numbers in array attributes.}
6180 When using the array attributes First, Last, Range,
6181 or Length, the index number must be omitted for one-dimensional arrays
6182 and is required for multi-dimensional arrays.
6183
6184 @item ^b^BLANKS^
6185 @emph{Blanks not allowed at statement end.}
6186 Trailing blanks are not allowed at the end of statements. The purpose of this
6187 rule, together with h (no horizontal tabs), is to enforce a canonical format
6188 for the use of blanks to separate source tokens.
6189
6190 @item ^B^BOOLEAN_OPERATORS^
6191 @emph{Check Boolean operators.}
6192 The use of AND/OR operators is not permitted except in the cases of modular
6193 operands, array operands, and simple stand-alone boolean variables or
6194 boolean constants. In all other cases AND THEN/OR ELSE are required.
6195
6196 @item ^c^COMMENTS^
6197 @emph{Check comments.}
6198 Comments must meet the following set of rules:
6199
6200 @itemize @bullet
6201
6202 @item
6203 The ``@code{--}'' that starts the column must either start in column one,
6204 or else at least one blank must precede this sequence.
6205
6206 @item
6207 Comments that follow other tokens on a line must have at least one blank
6208 following the ``@code{--}'' at the start of the comment.
6209
6210 @item
6211 Full line comments must have two blanks following the ``@code{--}'' that
6212 starts the comment, with the following exceptions.
6213
6214 @item
6215 A line consisting only of the ``@code{--}'' characters, possibly preceded
6216 by blanks is permitted.
6217
6218 @item
6219 A comment starting with ``@code{--x}'' where @code{x} is a special character
6220 is permitted.
6221 This allows proper processing of the output generated by specialized tools
6222 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6223 annotation
6224 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6225 special character is defined as being in one of the ASCII ranges
6226 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6227 Note that this usage is not permitted
6228 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6229
6230 @item
6231 A line consisting entirely of minus signs, possibly preceded by blanks, is
6232 permitted. This allows the construction of box comments where lines of minus
6233 signs are used to form the top and bottom of the box.
6234
6235 @item
6236 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6237 least one blank follows the initial ``@code{--}''. Together with the preceding
6238 rule, this allows the construction of box comments, as shown in the following
6239 example:
6240 @smallexample
6241 ---------------------------
6242 -- This is a box comment --
6243 -- with two text lines.  --
6244 ---------------------------
6245 @end smallexample
6246 @end itemize
6247
6248 @item ^d^DOS_LINE_ENDINGS^
6249 @emph{Check no DOS line terminators present.}
6250 All lines must be terminated by a single ASCII.LF
6251 character (in particular the DOS line terminator sequence CR/LF is not
6252 allowed).
6253
6254 @item ^e^END^
6255 @emph{Check end/exit labels.}
6256 Optional labels on @code{end} statements ending subprograms and on
6257 @code{exit} statements exiting named loops, are required to be present.
6258
6259 @item ^f^VTABS^
6260 @emph{No form feeds or vertical tabs.}
6261 Neither form feeds nor vertical tab characters are permitted
6262 in the source text.
6263
6264 @item ^g^GNAT^
6265 @emph{GNAT style mode}
6266 The set of style check switches is set to match that used by the GNAT sources.
6267 This may be useful when developing code that is eventually intended to be
6268 incorporated into GNAT. For further details, see GNAT sources.
6269
6270 @item ^h^HTABS^
6271 @emph{No horizontal tabs.}
6272 Horizontal tab characters are not permitted in the source text.
6273 Together with the b (no blanks at end of line) check, this
6274 enforces a canonical form for the use of blanks to separate
6275 source tokens.
6276
6277 @item ^i^IF_THEN^
6278 @emph{Check if-then layout.}
6279 The keyword @code{then} must appear either on the same
6280 line as corresponding @code{if}, or on a line on its own, lined
6281 up under the @code{if} with at least one non-blank line in between
6282 containing all or part of the condition to be tested.
6283
6284 @item ^I^IN_MODE^
6285 @emph{check mode IN keywords}
6286 Mode @code{in} (the default mode) is not
6287 allowed to be given explicitly. @code{in out} is fine,
6288 but not @code{in} on its own.
6289
6290 @item ^k^KEYWORD^
6291 @emph{Check keyword casing.}
6292 All keywords must be in lower case (with the exception of keywords
6293 such as @code{digits} used as attribute names to which this check
6294 does not apply).
6295
6296 @item ^l^LAYOUT^
6297 @emph{Check layout.}
6298 Layout of statement and declaration constructs must follow the
6299 recommendations in the Ada Reference Manual, as indicated by the
6300 form of the syntax rules. For example an @code{else} keyword must
6301 be lined up with the corresponding @code{if} keyword.
6302
6303 There are two respects in which the style rule enforced by this check
6304 option are more liberal than those in the Ada Reference Manual. First
6305 in the case of record declarations, it is permissible to put the
6306 @code{record} keyword on the same line as the @code{type} keyword, and
6307 then the @code{end} in @code{end record} must line up under @code{type}.
6308 This is also permitted when the type declaration is split on two lines.
6309 For example, any of the following three layouts is acceptable:
6310
6311 @smallexample @c ada
6312 @cartouche
6313 type q is record
6314    a : integer;
6315    b : integer;
6316 end record;
6317
6318 type q is
6319    record
6320       a : integer;
6321       b : integer;
6322    end record;
6323
6324 type q is
6325    record
6326       a : integer;
6327       b : integer;
6328 end record;
6329
6330 @end cartouche
6331 @end smallexample
6332
6333 @noindent
6334 Second, in the case of a block statement, a permitted alternative
6335 is to put the block label on the same line as the @code{declare} or
6336 @code{begin} keyword, and then line the @code{end} keyword up under
6337 the block label. For example both the following are permitted:
6338
6339 @smallexample @c ada
6340 @cartouche
6341 Block : declare
6342    A : Integer := 3;
6343 begin
6344    Proc (A, A);
6345 end Block;
6346
6347 Block :
6348    declare
6349       A : Integer := 3;
6350    begin
6351       Proc (A, A);
6352    end Block;
6353 @end cartouche
6354 @end smallexample
6355
6356 @noindent
6357 The same alternative format is allowed for loops. For example, both of
6358 the following are permitted:
6359
6360 @smallexample @c ada
6361 @cartouche
6362 Clear : while J < 10 loop
6363    A (J) := 0;
6364 end loop Clear;
6365
6366 Clear :
6367    while J < 10 loop
6368       A (J) := 0;
6369    end loop Clear;
6370 @end cartouche
6371 @end smallexample
6372
6373 @item ^Lnnn^MAX_NESTING=nnn^
6374 @emph{Set maximum nesting level}
6375 The maximum level of nesting of constructs (including subprograms, loops,
6376 blocks, packages, and conditionals) may not exceed the given value
6377 @option{nnn}. A value of zero disconnects this style check.
6378
6379 @item ^m^LINE_LENGTH^
6380 @emph{Check maximum line length.}
6381 The length of source lines must not exceed 79 characters, including
6382 any trailing blanks. The value of 79 allows convenient display on an
6383 80 character wide device or window, allowing for possible special
6384 treatment of 80 character lines. Note that this count is of
6385 characters in the source text. This means that a tab character counts
6386 as one character in this count but a wide character sequence counts as
6387 a single character (however many bytes are needed in the encoding).
6388
6389 @item ^Mnnn^MAX_LENGTH=nnn^
6390 @emph{Set maximum line length.}
6391 The length of lines must not exceed the
6392 given value @option{nnn}. The maximum value that can be specified is 32767.
6393
6394 @item ^n^STANDARD_CASING^
6395 @emph{Check casing of entities in Standard.}
6396 Any identifier from Standard must be cased
6397 to match the presentation in the Ada Reference Manual (for example,
6398 @code{Integer} and @code{ASCII.NUL}).
6399
6400 @item ^N^NONE^
6401 @emph{Turn off all style checks}
6402 All style check options are turned off.
6403
6404 @item ^o^ORDERED_SUBPROGRAMS^
6405 @emph{Check order of subprogram bodies.}
6406 All subprogram bodies in a given scope
6407 (e.g.@: a package body) must be in alphabetical order. The ordering
6408 rule uses normal Ada rules for comparing strings, ignoring casing
6409 of letters, except that if there is a trailing numeric suffix, then
6410 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6411 before Junk10).
6412
6413 @item ^O^OVERRIDING_INDICATORS^
6414 @emph{Check that overriding subprograms are explicitly marked as such.}
6415 The declaration of a primitive operation of a type extension that overrides
6416 an inherited operation must carry an overriding indicator.
6417
6418 @item ^p^PRAGMA^
6419 @emph{Check pragma casing.}
6420 Pragma names must be written in mixed case, that is, the
6421 initial letter and any letter following an underscore must be uppercase.
6422 All other letters must be lowercase.
6423
6424 @item ^r^REFERENCES^
6425 @emph{Check references.}
6426 All identifier references must be cased in the same way as the
6427 corresponding declaration. No specific casing style is imposed on
6428 identifiers. The only requirement is for consistency of references
6429 with declarations.
6430
6431 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6432 @emph{Check no statements after THEN/ELSE.}
6433 No statements are allowed
6434 on the same line as a THEN or ELSE keyword following the
6435 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6436 and a special exception allows a pragma to appear after ELSE.
6437
6438 @item ^s^SPECS^
6439 @emph{Check separate specs.}
6440 Separate declarations (``specs'') are required for subprograms (a
6441 body is not allowed to serve as its own declaration). The only
6442 exception is that parameterless library level procedures are
6443 not required to have a separate declaration. This exception covers
6444 the most frequent form of main program procedures.
6445
6446 @item ^t^TOKEN^
6447 @emph{Check token spacing.}
6448 The following token spacing rules are enforced:
6449
6450 @itemize @bullet
6451
6452 @item
6453 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6454
6455 @item
6456 The token @code{=>} must be surrounded by spaces.
6457
6458 @item
6459 The token @code{<>} must be preceded by a space or a left parenthesis.
6460
6461 @item
6462 Binary operators other than @code{**} must be surrounded by spaces.
6463 There is no restriction on the layout of the @code{**} binary operator.
6464
6465 @item
6466 Colon must be surrounded by spaces.
6467
6468 @item
6469 Colon-equal (assignment, initialization) must be surrounded by spaces.
6470
6471 @item
6472 Comma must be the first non-blank character on the line, or be
6473 immediately preceded by a non-blank character, and must be followed
6474 by a space.
6475
6476 @item
6477 If the token preceding a left parenthesis ends with a letter or digit, then
6478 a space must separate the two tokens.
6479
6480 @item
6481 if the token following a right parenthesis starts with a letter or digit, then
6482 a space must separate the two tokens.
6483
6484 @item
6485 A right parenthesis must either be the first non-blank character on
6486 a line, or it must be preceded by a non-blank character.
6487
6488 @item
6489 A semicolon must not be preceded by a space, and must not be followed by
6490 a non-blank character.
6491
6492 @item
6493 A unary plus or minus may not be followed by a space.
6494
6495 @item
6496 A vertical bar must be surrounded by spaces.
6497 @end itemize
6498
6499 @item ^u^UNNECESSARY_BLANK_LINES^
6500 @emph{Check unnecessary blank lines.}
6501 Unnecessary blank lines are not allowed. A blank line is considered
6502 unnecessary if it appears at the end of the file, or if more than
6503 one blank line occurs in sequence.
6504
6505 @item ^x^XTRA_PARENS^
6506 @emph{Check extra parentheses.}
6507 Unnecessary extra level of parentheses (C-style) are not allowed
6508 around conditions in @code{if} statements, @code{while} statements and
6509 @code{exit} statements.
6510
6511 @item ^y^ALL_BUILTIN^
6512 @emph{Set all standard style check options}
6513 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6514 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6515 @option{-gnatyS}, @option{-gnatyLnnn},
6516 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6517
6518 @ifclear vms
6519 @item -
6520 @emph{Remove style check options}
6521 This causes any subsequent options in the string to act as canceling the
6522 corresponding style check option. To cancel maximum nesting level control,
6523 use @option{L} parameter witout any integer value after that, because any
6524 digit following @option{-} in the parameter string of the @option{-gnaty}
6525 option will be threated as canceling indentation check. The same is true
6526 for @option{M} parameter. @option{y} and @option{N} parameters are not
6527 allowed after @option{-}.
6528
6529 @item +
6530 This causes any subsequent options in the string to enable the corresponding
6531 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6532 if any.
6533 @end ifclear
6534
6535 @ifset vms
6536 @item NOxxx
6537 @emph{Removing style check options}
6538 If the name of a style check is preceded by @option{NO} then the corresponding
6539 style check is turned off. For example @option{NOCOMMENTS} turns off style
6540 checking for comments.
6541 @end ifset
6542 @end table
6543
6544 @noindent
6545 In the above rules, appearing in column one is always permitted, that is,
6546 counts as meeting either a requirement for a required preceding space,
6547 or as meeting a requirement for no preceding space.
6548
6549 Appearing at the end of a line is also always permitted, that is, counts
6550 as meeting either a requirement for a following space, or as meeting
6551 a requirement for no following space.
6552
6553 @noindent
6554 If any of these style rules is violated, a message is generated giving
6555 details on the violation. The initial characters of such messages are
6556 always ``@code{(style)}''. Note that these messages are treated as warning
6557 messages, so they normally do not prevent the generation of an object
6558 file. The @option{-gnatwe} switch can be used to treat warning messages,
6559 including style messages, as fatal errors.
6560
6561 The switch
6562 @ifclear vms
6563 @option{-gnaty} on its own (that is not
6564 followed by any letters or digits), then the effect is equivalent
6565 to the use of @option{-gnatyy}, as described above, that is all
6566 built-in standard style check options are enabled.
6567
6568 @end ifclear
6569 @ifset vms
6570 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6571 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6572 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6573 @end ifset
6574
6575 The switch
6576 @ifclear vms
6577 @option{-gnatyN}
6578 @end ifclear
6579 @ifset vms
6580 /STYLE_CHECKS=NONE
6581 @end ifset
6582 clears any previously set style checks.
6583
6584 @node Run-Time Checks
6585 @subsection Run-Time Checks
6586 @cindex Division by zero
6587 @cindex Access before elaboration
6588 @cindex Checks, division by zero
6589 @cindex Checks, access before elaboration
6590 @cindex Checks, stack overflow checking
6591
6592 @noindent
6593 By default, the following checks are suppressed: integer overflow
6594 checks, stack overflow checks, and checks for access before
6595 elaboration on subprogram calls. All other checks, including range
6596 checks and array bounds checks, are turned on by default. The
6597 following @command{gcc} switches refine this default behavior.
6598
6599 @table @option
6600 @c !sort!
6601 @item -gnatp
6602 @cindex @option{-gnatp} (@command{gcc})
6603 @cindex Suppressing checks
6604 @cindex Checks, suppressing
6605 @findex Suppress
6606 This switch causes the unit to be compiled
6607 as though @code{pragma Suppress (All_checks)}
6608 had been present in the source. Validity checks are also eliminated (in
6609 other words @option{-gnatp} also implies @option{-gnatVn}.
6610 Use this switch to improve the performance
6611 of the code at the expense of safety in the presence of invalid data or
6612 program bugs.
6613
6614 Note that when checks are suppressed, the compiler is allowed, but not
6615 required, to omit the checking code. If the run-time cost of the
6616 checking code is zero or near-zero, the compiler will generate it even
6617 if checks are suppressed. In particular, if the compiler can prove
6618 that a certain check will necessarily fail, it will generate code to
6619 do an unconditional ``raise'', even if checks are suppressed. The
6620 compiler warns in this case. Another case in which checks may not be
6621 eliminated is when they are embedded in certain run time routines such
6622 as math library routines.
6623
6624 Of course, run-time checks are omitted whenever the compiler can prove
6625 that they will not fail, whether or not checks are suppressed.
6626
6627 Note that if you suppress a check that would have failed, program
6628 execution is erroneous, which means the behavior is totally
6629 unpredictable. The program might crash, or print wrong answers, or
6630 do anything else. It might even do exactly what you wanted it to do
6631 (and then it might start failing mysteriously next week or next
6632 year). The compiler will generate code based on the assumption that
6633 the condition being checked is true, which can result in disaster if
6634 that assumption is wrong.
6635
6636 The @option{-gnatp} switch has no effect if a subsequent
6637 @option{-gnat-p} switch appears.
6638
6639 @item -gnat-p
6640 @cindex @option{-gnat-p} (@command{gcc})
6641 @cindex Suppressing checks
6642 @cindex Checks, suppressing
6643 @findex Suppress
6644 This switch cancels the effect of a previous @option{gnatp} switch.
6645
6646 @item -gnato
6647 @cindex @option{-gnato} (@command{gcc})
6648 @cindex Overflow checks
6649 @cindex Check, overflow
6650 Enables overflow checking for integer operations.
6651 This causes GNAT to generate slower and larger executable
6652 programs by adding code to check for overflow (resulting in raising
6653 @code{Constraint_Error} as required by standard Ada
6654 semantics). These overflow checks correspond to situations in which
6655 the true value of the result of an operation may be outside the base
6656 range of the result type. The following example shows the distinction:
6657
6658 @smallexample @c ada
6659 X1 : Integer := "Integer'Last";
6660 X2 : Integer range 1 .. 5 := "5";
6661 X3 : Integer := "Integer'Last";
6662 X4 : Integer range 1 .. 5 := "5";
6663 F  : Float := "2.0E+20";
6664 @dots{}
6665 X1 := X1 + 1;
6666 X2 := X2 + 1;
6667 X3 := Integer (F);
6668 X4 := Integer (F);
6669 @end smallexample
6670
6671 @noindent
6672 Note that if explicit values are assigned at compile time, the
6673 compiler may be able to detect overflow at compile time, in which case
6674 no actual run-time checking code is required, and Constraint_Error
6675 will be raised unconditionally, with or without
6676 @option{-gnato}. That's why the assigned values in the above fragment
6677 are in quotes, the meaning is "assign a value not known to the
6678 compiler that happens to be equal to ...". The remaining discussion
6679 assumes that the compiler cannot detect the values at compile time.
6680
6681 Here the first addition results in a value that is outside the base range
6682 of Integer, and hence requires an overflow check for detection of the
6683 constraint error. Thus the first assignment to @code{X1} raises a
6684 @code{Constraint_Error} exception only if @option{-gnato} is set.
6685
6686 The second increment operation results in a violation of the explicit
6687 range constraint; such range checks are performed by default, and are
6688 unaffected by @option{-gnato}.
6689
6690 The two conversions of @code{F} both result in values that are outside
6691 the base range of type @code{Integer} and thus will raise
6692 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6693 The fact that the result of the second conversion is assigned to
6694 variable @code{X4} with a restricted range is irrelevant, since the problem
6695 is in the conversion, not the assignment.
6696
6697 Basically the rule is that in the default mode (@option{-gnato} not
6698 used), the generated code assures that all integer variables stay
6699 within their declared ranges, or within the base range if there is
6700 no declared range. This prevents any serious problems like indexes
6701 out of range for array operations.
6702
6703 What is not checked in default mode is an overflow that results in
6704 an in-range, but incorrect value. In the above example, the assignments
6705 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6706 range of the target variable, but the result is wrong in the sense that
6707 it is too large to be represented correctly. Typically the assignment
6708 to @code{X1} will result in wrap around to the largest negative number.
6709 The conversions of @code{F} will result in some @code{Integer} value
6710 and if that integer value is out of the @code{X4} range then the
6711 subsequent assignment would generate an exception.
6712
6713 @findex Machine_Overflows
6714 Note that the @option{-gnato} switch does not affect the code generated
6715 for any floating-point operations; it applies only to integer
6716 semantics).
6717 For floating-point, GNAT has the @code{Machine_Overflows}
6718 attribute set to @code{False} and the normal mode of operation is to
6719 generate IEEE NaN and infinite values on overflow or invalid operations
6720 (such as dividing 0.0 by 0.0).
6721
6722 The reason that we distinguish overflow checking from other kinds of
6723 range constraint checking is that a failure of an overflow check, unlike
6724 for example the failure of a range check, can result in an incorrect
6725 value, but cannot cause random memory destruction (like an out of range
6726 subscript), or a wild jump (from an out of range case value). Overflow
6727 checking is also quite expensive in time and space, since in general it
6728 requires the use of double length arithmetic.
6729
6730 Note again that @option{-gnato} is off by default, so overflow checking is
6731 not performed in default mode. This means that out of the box, with the
6732 default settings, GNAT does not do all the checks expected from the
6733 language description in the Ada Reference Manual. If you want all constraint
6734 checks to be performed, as described in this Manual, then you must
6735 explicitly use the -gnato switch either on the @command{gnatmake} or
6736 @command{gcc} command.
6737
6738 @item -gnatE
6739 @cindex @option{-gnatE} (@command{gcc})
6740 @cindex Elaboration checks
6741 @cindex Check, elaboration
6742 Enables dynamic checks for access-before-elaboration
6743 on subprogram calls and generic instantiations.
6744 Note that @option{-gnatE} is not necessary for safety, because in the
6745 default mode, GNAT ensures statically that the checks would not fail.
6746 For full details of the effect and use of this switch,
6747 @xref{Compiling Using gcc}.
6748
6749 @item -fstack-check
6750 @cindex @option{-fstack-check} (@command{gcc})
6751 @cindex Stack Overflow Checking
6752 @cindex Checks, stack overflow checking
6753 Activates stack overflow checking. For full details of the effect and use of
6754 this switch see @ref{Stack Overflow Checking}.
6755 @end table
6756
6757 @findex Unsuppress
6758 @noindent
6759 The setting of these switches only controls the default setting of the
6760 checks. You may modify them using either @code{Suppress} (to remove
6761 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6762 the program source.
6763
6764 @node Using gcc for Syntax Checking
6765 @subsection Using @command{gcc} for Syntax Checking
6766 @table @option
6767 @item -gnats
6768 @cindex @option{-gnats} (@command{gcc})
6769 @ifclear vms
6770
6771 @noindent
6772 The @code{s} stands for ``syntax''.
6773 @end ifclear
6774
6775 Run GNAT in syntax checking only mode. For
6776 example, the command
6777
6778 @smallexample
6779 $ gcc -c -gnats x.adb
6780 @end smallexample
6781
6782 @noindent
6783 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6784 series of files in a single command
6785 @ifclear vms
6786 , and can use wild cards to specify such a group of files.
6787 Note that you must specify the @option{-c} (compile
6788 only) flag in addition to the @option{-gnats} flag.
6789 @end ifclear
6790 .
6791 You may use other switches in conjunction with @option{-gnats}. In
6792 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6793 format of any generated error messages.
6794
6795 When the source file is empty or contains only empty lines and/or comments,
6796 the output is a warning:
6797
6798 @smallexample
6799 $ gcc -c -gnats -x ada toto.txt
6800 toto.txt:1:01: warning: empty file, contains no compilation units
6801 $
6802 @end smallexample
6803
6804 Otherwise, the output is simply the error messages, if any. No object file or
6805 ALI file is generated by a syntax-only compilation. Also, no units other
6806 than the one specified are accessed. For example, if a unit @code{X}
6807 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6808 check only mode does not access the source file containing unit
6809 @code{Y}.
6810
6811 @cindex Multiple units, syntax checking
6812 Normally, GNAT allows only a single unit in a source file. However, this
6813 restriction does not apply in syntax-check-only mode, and it is possible
6814 to check a file containing multiple compilation units concatenated
6815 together. This is primarily used by the @code{gnatchop} utility
6816 (@pxref{Renaming Files Using gnatchop}).
6817 @end table
6818
6819 @node Using gcc for Semantic Checking
6820 @subsection Using @command{gcc} for Semantic Checking
6821 @table @option
6822 @item -gnatc
6823 @cindex @option{-gnatc} (@command{gcc})
6824
6825 @ifclear vms
6826 @noindent
6827 The @code{c} stands for ``check''.
6828 @end ifclear
6829 Causes the compiler to operate in semantic check mode,
6830 with full checking for all illegalities specified in the
6831 Ada Reference Manual, but without generation of any object code
6832 (no object file is generated).
6833
6834 Because dependent files must be accessed, you must follow the GNAT
6835 semantic restrictions on file structuring to operate in this mode:
6836
6837 @itemize @bullet
6838 @item
6839 The needed source files must be accessible
6840 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6841
6842 @item
6843 Each file must contain only one compilation unit.
6844
6845 @item
6846 The file name and unit name must match (@pxref{File Naming Rules}).
6847 @end itemize
6848
6849 The output consists of error messages as appropriate. No object file is
6850 generated. An @file{ALI} file is generated for use in the context of
6851 cross-reference tools, but this file is marked as not being suitable
6852 for binding (since no object file is generated).
6853 The checking corresponds exactly to the notion of
6854 legality in the Ada Reference Manual.
6855
6856 Any unit can be compiled in semantics-checking-only mode, including
6857 units that would not normally be compiled (subunits,
6858 and specifications where a separate body is present).
6859 @end table
6860
6861 @node Compiling Different Versions of Ada
6862 @subsection Compiling Different Versions of Ada
6863
6864 @noindent
6865 The switches described in this section allow you to explicitly specify
6866 the version of the Ada language that your programs are written in.
6867 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6868 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6869 indicate Ada 83 compatibility mode.
6870
6871 @table @option
6872 @cindex Compatibility with Ada 83
6873
6874 @item -gnat83 (Ada 83 Compatibility Mode)
6875 @cindex @option{-gnat83} (@command{gcc})
6876 @cindex ACVC, Ada 83 tests
6877 @cindex Ada 83 mode
6878
6879 @noindent
6880 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6881 specifies that the program is to be compiled in Ada 83 mode. With
6882 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6883 semantics where this can be done easily.
6884 It is not possible to guarantee this switch does a perfect
6885 job; some subtle tests, such as are
6886 found in earlier ACVC tests (and that have been removed from the ACATS suite
6887 for Ada 95), might not compile correctly.
6888 Nevertheless, this switch may be useful in some circumstances, for example
6889 where, due to contractual reasons, existing code needs to be maintained
6890 using only Ada 83 features.
6891
6892 With few exceptions (most notably the need to use @code{<>} on
6893 @cindex Generic formal parameters
6894 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6895 reserved words, and the use of packages
6896 with optional bodies), it is not necessary to specify the
6897 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6898 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6899 a correct Ada 83 program is usually also a correct program
6900 in these later versions of the language standard.
6901 For further information, please refer to @ref{Compatibility and Porting Guide}.
6902
6903 @item -gnat95 (Ada 95 mode)
6904 @cindex @option{-gnat95} (@command{gcc})
6905 @cindex Ada 95 mode
6906
6907 @noindent
6908 This switch directs the compiler to implement the Ada 95 version of the
6909 language.
6910 Since Ada 95 is almost completely upwards
6911 compatible with Ada 83, Ada 83 programs may generally be compiled using
6912 this switch (see the description of the @option{-gnat83} switch for further
6913 information about Ada 83 mode).
6914 If an Ada 2005 program is compiled in Ada 95 mode,
6915 uses of the new Ada 2005 features will cause error
6916 messages or warnings.
6917
6918 This switch also can be used to cancel the effect of a previous
6919 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6920 switch earlier in the command line.
6921
6922 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6923 @cindex @option{-gnat05} (@command{gcc})
6924 @cindex @option{-gnat2005} (@command{gcc})
6925 @cindex Ada 2005 mode
6926
6927 @noindent
6928 This switch directs the compiler to implement the Ada 2005 version of the
6929 language, as documented in the official Ada standards document.
6930 Since Ada 2005 is almost completely upwards
6931 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6932 may generally be compiled using this switch (see the description of the
6933 @option{-gnat83} and @option{-gnat95} switches for further
6934 information).
6935
6936 Note that even though Ada 2005 is the current official version of the
6937 language, GNAT still compiles in Ada 95 mode by default, so if you are
6938 using Ada 2005 features in your program, you must use this switch (or
6939 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6940
6941 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6942 @cindex @option{-gnat12} (@command{gcc})
6943 @cindex @option{-gnat2012} (@command{gcc})
6944 @cindex Ada 2012 mode
6945
6946 @noindent
6947 This switch directs the compiler to implement the Ada 2012 version of the
6948 language.
6949 Since Ada 2012 is almost completely upwards
6950 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6951 Ada 83 and Ada 95 programs
6952 may generally be compiled using this switch (see the description of the
6953 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6954 for further information).
6955
6956 For information about the approved ``Ada Issues'' that have been incorporated
6957 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6958 Included with GNAT releases is a file @file{features-ada12} that describes
6959 the set of implemented Ada 2012 features.
6960
6961 @item -gnatX (Enable GNAT Extensions)
6962 @cindex @option{-gnatX} (@command{gcc})
6963 @cindex Ada language extensions
6964 @cindex GNAT extensions
6965
6966 @noindent
6967 This switch directs the compiler to implement the latest version of the
6968 language (currently Ada 2012) and also to enable certain GNAT implementation
6969 extensions that are not part of any Ada standard. For a full list of these
6970 extensions, see the GNAT reference manual.
6971
6972 @end table
6973
6974 @node Character Set Control
6975 @subsection Character Set Control
6976 @table @option
6977 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6978 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6979
6980 @noindent
6981 Normally GNAT recognizes the Latin-1 character set in source program
6982 identifiers, as described in the Ada Reference Manual.
6983 This switch causes
6984 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6985 single character ^^or word^ indicating the character set, as follows:
6986
6987 @table @code
6988 @item 1
6989 ISO 8859-1 (Latin-1) identifiers
6990
6991 @item 2
6992 ISO 8859-2 (Latin-2) letters allowed in identifiers
6993
6994 @item 3
6995 ISO 8859-3 (Latin-3) letters allowed in identifiers
6996
6997 @item 4
6998 ISO 8859-4 (Latin-4) letters allowed in identifiers
6999
7000 @item 5
7001 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7002
7003 @item 9
7004 ISO 8859-15 (Latin-9) letters allowed in identifiers
7005
7006 @item ^p^PC^
7007 IBM PC letters (code page 437) allowed in identifiers
7008
7009 @item ^8^PC850^
7010 IBM PC letters (code page 850) allowed in identifiers
7011
7012 @item ^f^FULL_UPPER^
7013 Full upper-half codes allowed in identifiers
7014
7015 @item ^n^NO_UPPER^
7016 No upper-half codes allowed in identifiers
7017
7018 @item ^w^WIDE^
7019 Wide-character codes (that is, codes greater than 255)
7020 allowed in identifiers
7021 @end table
7022
7023 @xref{Foreign Language Representation}, for full details on the
7024 implementation of these character sets.
7025
7026 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7027 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7028 Specify the method of encoding for wide characters.
7029 @var{e} is one of the following:
7030
7031 @table @code
7032
7033 @item ^h^HEX^
7034 Hex encoding (brackets coding also recognized)
7035
7036 @item ^u^UPPER^
7037 Upper half encoding (brackets encoding also recognized)
7038
7039 @item ^s^SHIFT_JIS^
7040 Shift/JIS encoding (brackets encoding also recognized)
7041
7042 @item ^e^EUC^
7043 EUC encoding (brackets encoding also recognized)
7044
7045 @item ^8^UTF8^
7046 UTF-8 encoding (brackets encoding also recognized)
7047
7048 @item ^b^BRACKETS^
7049 Brackets encoding only (default value)
7050 @end table
7051 For full details on these encoding
7052 methods see @ref{Wide Character Encodings}.
7053 Note that brackets coding is always accepted, even if one of the other
7054 options is specified, so for example @option{-gnatW8} specifies that both
7055 brackets and UTF-8 encodings will be recognized. The units that are
7056 with'ed directly or indirectly will be scanned using the specified
7057 representation scheme, and so if one of the non-brackets scheme is
7058 used, it must be used consistently throughout the program. However,
7059 since brackets encoding is always recognized, it may be conveniently
7060 used in standard libraries, allowing these libraries to be used with
7061 any of the available coding schemes.
7062 scheme.
7063
7064 If no @option{-gnatW?} parameter is present, then the default
7065 representation is normally Brackets encoding only. However, if the
7066 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7067 byte order mark or BOM for UTF-8), then these three characters are
7068 skipped and the default representation for the file is set to UTF-8.
7069
7070 Note that the wide character representation that is specified (explicitly
7071 or by default) for the main program also acts as the default encoding used
7072 for Wide_Text_IO files if not specifically overridden by a WCEM form
7073 parameter.
7074
7075 @end table
7076 @node File Naming Control
7077 @subsection File Naming Control
7078
7079 @table @option
7080 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7081 @cindex @option{-gnatk} (@command{gcc})
7082 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7083 1-999, indicates the maximum allowable length of a file name (not
7084 including the @file{.ads} or @file{.adb} extension). The default is not
7085 to enable file name krunching.
7086
7087 For the source file naming rules, @xref{File Naming Rules}.
7088 @end table
7089
7090 @node Subprogram Inlining Control
7091 @subsection Subprogram Inlining Control
7092
7093 @table @option
7094 @c !sort!
7095 @item -gnatn
7096 @cindex @option{-gnatn} (@command{gcc})
7097 @ifclear vms
7098 The @code{n} here is intended to suggest the first syllable of the
7099 word ``inline''.
7100 @end ifclear
7101 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7102 inlining to actually occur, optimization must be enabled. To enable
7103 inlining of subprograms specified by pragma @code{Inline},
7104 you must also specify this switch.
7105 In the absence of this switch, GNAT does not attempt
7106 inlining and does not need to access the bodies of
7107 subprograms for which @code{pragma Inline} is specified if they are not
7108 in the current unit.
7109
7110 If you specify this switch the compiler will access these bodies,
7111 creating an extra source dependency for the resulting object file, and
7112 where possible, the call will be inlined.
7113 For further details on when inlining is possible
7114 see @ref{Inlining of Subprograms}.
7115
7116 @item -gnatN
7117 @cindex @option{-gnatN} (@command{gcc})
7118 This switch activates front-end inlining which also
7119 generates additional dependencies.
7120
7121 When using a gcc-based back end (in practice this means using any version
7122 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7123 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7124 Historically front end inlining was more extensive than the gcc back end
7125 inlining, but that is no longer the case.
7126 @end table
7127
7128 @node Auxiliary Output Control
7129 @subsection Auxiliary Output Control
7130
7131 @table @option
7132 @item -gnatt
7133 @cindex @option{-gnatt} (@command{gcc})
7134 @cindex Writing internal trees
7135 @cindex Internal trees, writing to file
7136 Causes GNAT to write the internal tree for a unit to a file (with the
7137 extension @file{.adt}.
7138 This not normally required, but is used by separate analysis tools.
7139 Typically
7140 these tools do the necessary compilations automatically, so you should
7141 not have to specify this switch in normal operation.
7142 Note that the combination of switches @option{-gnatct}
7143 generates a tree in the form required by ASIS applications.
7144
7145 @item -gnatu
7146 @cindex @option{-gnatu} (@command{gcc})
7147 Print a list of units required by this compilation on @file{stdout}.
7148 The listing includes all units on which the unit being compiled depends
7149 either directly or indirectly.
7150
7151 @ifclear vms
7152 @item -pass-exit-codes
7153 @cindex @option{-pass-exit-codes} (@command{gcc})
7154 If this switch is not used, the exit code returned by @command{gcc} when
7155 compiling multiple files indicates whether all source files have
7156 been successfully used to generate object files or not.
7157
7158 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7159 exit status and allows an integrated development environment to better
7160 react to a compilation failure. Those exit status are:
7161
7162 @table @asis
7163 @item 5
7164 There was an error in at least one source file.
7165 @item 3
7166 At least one source file did not generate an object file.
7167 @item 2
7168 The compiler died unexpectedly (internal error for example).
7169 @item 0
7170 An object file has been generated for every source file.
7171 @end table
7172 @end ifclear
7173 @end table
7174
7175 @node Debugging Control
7176 @subsection Debugging Control
7177
7178 @table @option
7179 @c !sort!
7180 @cindex Debugging options
7181 @ifclear vms
7182 @item -gnatd@var{x}
7183 @cindex @option{-gnatd} (@command{gcc})
7184 Activate internal debugging switches. @var{x} is a letter or digit, or
7185 string of letters or digits, which specifies the type of debugging
7186 outputs desired. Normally these are used only for internal development
7187 or system debugging purposes. You can find full documentation for these
7188 switches in the body of the @code{Debug} unit in the compiler source
7189 file @file{debug.adb}.
7190 @end ifclear
7191
7192 @item -gnatG[=nn]
7193 @cindex @option{-gnatG} (@command{gcc})
7194 This switch causes the compiler to generate auxiliary output containing
7195 a pseudo-source listing of the generated expanded code. Like most Ada
7196 compilers, GNAT works by first transforming the high level Ada code into
7197 lower level constructs. For example, tasking operations are transformed
7198 into calls to the tasking run-time routines. A unique capability of GNAT
7199 is to list this expanded code in a form very close to normal Ada source.
7200 This is very useful in understanding the implications of various Ada
7201 usage on the efficiency of the generated code. There are many cases in
7202 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7203 generate a lot of run-time code. By using @option{-gnatG} you can identify
7204 these cases, and consider whether it may be desirable to modify the coding
7205 approach to improve efficiency.
7206
7207 The optional parameter @code{nn} if present after -gnatG specifies an
7208 alternative maximum line length that overrides the normal default of 72.
7209 This value is in the range 40-999999, values less than 40 being silently
7210 reset to 40. The equal sign is optional.
7211
7212 The format of the output is very similar to standard Ada source, and is
7213 easily understood by an Ada programmer. The following special syntactic
7214 additions correspond to low level features used in the generated code that
7215 do not have any exact analogies in pure Ada source form. The following
7216 is a partial list of these special constructions. See the spec
7217 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7218
7219 If the switch @option{-gnatL} is used in conjunction with
7220 @cindex @option{-gnatL} (@command{gcc})
7221 @option{-gnatG}, then the original source lines are interspersed
7222 in the expanded source (as comment lines with the original line number).
7223
7224 @table @code
7225 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7226 Shows the storage pool being used for an allocator.
7227
7228 @item at end @var{procedure-name};
7229 Shows the finalization (cleanup) procedure for a scope.
7230
7231 @item (if @var{expr} then @var{expr} else @var{expr})
7232 Conditional expression equivalent to the @code{x?y:z} construction in C.
7233
7234 @item @var{target}^^^(@var{source})
7235 A conversion with floating-point truncation instead of rounding.
7236
7237 @item @var{target}?(@var{source})
7238 A conversion that bypasses normal Ada semantic checking. In particular
7239 enumeration types and fixed-point types are treated simply as integers.
7240
7241 @item @var{target}?^^^(@var{source})
7242 Combines the above two cases.
7243
7244 @item @var{x} #/ @var{y}
7245 @itemx @var{x} #mod @var{y}
7246 @itemx @var{x} #* @var{y}
7247 @itemx @var{x} #rem @var{y}
7248 A division or multiplication of fixed-point values which are treated as
7249 integers without any kind of scaling.
7250
7251 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7252 Shows the storage pool associated with a @code{free} statement.
7253
7254 @item [subtype or type declaration]
7255 Used to list an equivalent declaration for an internally generated
7256 type that is referenced elsewhere in the listing.
7257
7258 @c @item freeze @var{type-name} @ovar{actions}
7259 @c Expanding @ovar macro inline (explanation in macro def comments)
7260 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7261 Shows the point at which @var{type-name} is frozen, with possible
7262 associated actions to be performed at the freeze point.
7263
7264 @item reference @var{itype}
7265 Reference (and hence definition) to internal type @var{itype}.
7266
7267 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7268 Intrinsic function call.
7269
7270 @item @var{label-name} : label
7271 Declaration of label @var{labelname}.
7272
7273 @item #$ @var{subprogram-name}
7274 An implicit call to a run-time support routine
7275 (to meet the requirement of H.3.1(9) in a
7276 convenient manner).
7277
7278 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7279 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7280 @var{expr}, but handled more efficiently).
7281
7282 @item [constraint_error]
7283 Raise the @code{Constraint_Error} exception.
7284
7285 @item @var{expression}'reference
7286 A pointer to the result of evaluating @var{expression}.
7287
7288 @item @var{target-type}!(@var{source-expression})
7289 An unchecked conversion of @var{source-expression} to @var{target-type}.
7290
7291 @item [@var{numerator}/@var{denominator}]
7292 Used to represent internal real literals (that) have no exact
7293 representation in base 2-16 (for example, the result of compile time
7294 evaluation of the expression 1.0/27.0).
7295 @end table
7296
7297 @item -gnatD[=nn]
7298 @cindex @option{-gnatD} (@command{gcc})
7299 When used in conjunction with @option{-gnatG}, this switch causes
7300 the expanded source, as described above for
7301 @option{-gnatG} to be written to files with names
7302 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7303 instead of to the standard output file. For
7304 example, if the source file name is @file{hello.adb}, then a file
7305 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7306 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7307 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7308 you to do source level debugging using the generated code which is
7309 sometimes useful for complex code, for example to find out exactly
7310 which part of a complex construction raised an exception. This switch
7311 also suppress generation of cross-reference information (see
7312 @option{-gnatx}) since otherwise the cross-reference information
7313 would refer to the @file{^.dg^.DG^} file, which would cause
7314 confusion since this is not the original source file.
7315
7316 Note that @option{-gnatD} actually implies @option{-gnatG}
7317 automatically, so it is not necessary to give both options.
7318 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7319
7320 If the switch @option{-gnatL} is used in conjunction with
7321 @cindex @option{-gnatL} (@command{gcc})
7322 @option{-gnatDG}, then the original source lines are interspersed
7323 in the expanded source (as comment lines with the original line number).
7324
7325 The optional parameter @code{nn} if present after -gnatD specifies an
7326 alternative maximum line length that overrides the normal default of 72.
7327 This value is in the range 40-999999, values less than 40 being silently
7328 reset to 40. The equal sign is optional.
7329
7330 @item -gnatr
7331 @cindex @option{-gnatr} (@command{gcc})
7332 @cindex pragma Restrictions
7333 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7334 so that violation of restrictions causes warnings rather than illegalities.
7335 This is useful during the development process when new restrictions are added
7336 or investigated. The switch also causes pragma Profile to be treated as
7337 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7338 restriction warnings rather than restrictions.
7339
7340 @ifclear vms
7341 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7342 @cindex @option{-gnatR} (@command{gcc})
7343 This switch controls output from the compiler of a listing showing
7344 representation information for declared types and objects. For
7345 @option{-gnatR0}, no information is output (equivalent to omitting
7346 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7347 so @option{-gnatR} with no parameter has the same effect), size and alignment
7348 information is listed for declared array and record types. For
7349 @option{-gnatR2}, size and alignment information is listed for all
7350 declared types and objects. Finally @option{-gnatR3} includes symbolic
7351 expressions for values that are computed at run time for
7352 variant records. These symbolic expressions have a mostly obvious
7353 format with #n being used to represent the value of the n'th
7354 discriminant. See source files @file{repinfo.ads/adb} in the
7355 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7356 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7357 the output is to a file with the name @file{^file.rep^file_REP^} where
7358 file is the name of the corresponding source file.
7359 @end ifclear
7360 @ifset vms
7361 @item /REPRESENTATION_INFO
7362 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7363 This qualifier controls output from the compiler of a listing showing
7364 representation information for declared types and objects. For
7365 @option{/REPRESENTATION_INFO=NONE}, no information is output
7366 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7367 @option{/REPRESENTATION_INFO} without option is equivalent to
7368 @option{/REPRESENTATION_INFO=ARRAYS}.
7369 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7370 information is listed for declared array and record types. For
7371 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7372 is listed for all expression information for values that are computed
7373 at run time for variant records. These symbolic expressions have a mostly
7374 obvious format with #n being used to represent the value of the n'th
7375 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7376 @code{GNAT} sources for full details on the format of
7377 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7378 If _FILE is added at the end of an option
7379 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7380 then the output is to a file with the name @file{file_REP} where
7381 file is the name of the corresponding source file.
7382 @end ifset
7383 Note that it is possible for record components to have zero size. In
7384 this case, the component clause uses an obvious extension of permitted
7385 Ada syntax, for example @code{at 0 range 0 .. -1}.
7386
7387 Representation information requires that code be generated (since it is the
7388 code generator that lays out complex data structures). If an attempt is made
7389 to output representation information when no code is generated, for example
7390 when a subunit is compiled on its own, then no information can be generated
7391 and the compiler outputs a message to this effect.
7392
7393 @item -gnatS
7394 @cindex @option{-gnatS} (@command{gcc})
7395 The use of the switch @option{-gnatS} for an
7396 Ada compilation will cause the compiler to output a
7397 representation of package Standard in a form very
7398 close to standard Ada. It is not quite possible to
7399 do this entirely in standard Ada (since new
7400 numeric base types cannot be created in standard
7401 Ada), but the output is easily
7402 readable to any Ada programmer, and is useful to
7403 determine the characteristics of target dependent
7404 types in package Standard.
7405
7406 @item -gnatx
7407 @cindex @option{-gnatx} (@command{gcc})
7408 Normally the compiler generates full cross-referencing information in
7409 the @file{ALI} file. This information is used by a number of tools,
7410 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7411 suppresses this information. This saves some space and may slightly
7412 speed up compilation, but means that these tools cannot be used.
7413 @end table
7414
7415 @node Exception Handling Control
7416 @subsection Exception Handling Control
7417
7418 @noindent
7419 GNAT uses two methods for handling exceptions at run-time. The
7420 @code{setjmp/longjmp} method saves the context when entering
7421 a frame with an exception handler. Then when an exception is
7422 raised, the context can be restored immediately, without the
7423 need for tracing stack frames. This method provides very fast
7424 exception propagation, but introduces significant overhead for
7425 the use of exception handlers, even if no exception is raised.
7426
7427 The other approach is called ``zero cost'' exception handling.
7428 With this method, the compiler builds static tables to describe
7429 the exception ranges. No dynamic code is required when entering
7430 a frame containing an exception handler. When an exception is
7431 raised, the tables are used to control a back trace of the
7432 subprogram invocation stack to locate the required exception
7433 handler. This method has considerably poorer performance for
7434 the propagation of exceptions, but there is no overhead for
7435 exception handlers if no exception is raised. Note that in this
7436 mode and in the context of mixed Ada and C/C++ programming,
7437 to propagate an exception through a C/C++ code, the C/C++ code
7438 must be compiled with the @option{-funwind-tables} GCC's
7439 option.
7440
7441 The following switches may be used to control which of the
7442 two exception handling methods is used.
7443
7444 @table @option
7445 @c !sort!
7446
7447 @item --RTS=sjlj
7448 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7449 This switch causes the setjmp/longjmp run-time (when available) to be used
7450 for exception handling. If the default
7451 mechanism for the target is zero cost exceptions, then
7452 this switch can be used to modify this default, and must be
7453 used for all units in the partition.
7454 This option is rarely used. One case in which it may be
7455 advantageous is if you have an application where exception
7456 raising is common and the overall performance of the
7457 application is improved by favoring exception propagation.
7458
7459 @item --RTS=zcx
7460 @cindex @option{--RTS=zcx} (@command{gnatmake})
7461 @cindex Zero Cost Exceptions
7462 This switch causes the zero cost approach to be used
7463 for exception handling. If this is the default mechanism for the
7464 target (see below), then this switch is unneeded. If the default
7465 mechanism for the target is setjmp/longjmp exceptions, then
7466 this switch can be used to modify this default, and must be
7467 used for all units in the partition.
7468 This option can only be used if the zero cost approach
7469 is available for the target in use, otherwise it will generate an error.
7470 @end table
7471
7472 @noindent
7473 The same option @option{--RTS} must be used both for @command{gcc}
7474 and @command{gnatbind}. Passing this option to @command{gnatmake}
7475 (@pxref{Switches for gnatmake}) will ensure the required consistency
7476 through the compilation and binding steps.
7477
7478 @node Units to Sources Mapping Files
7479 @subsection Units to Sources Mapping Files
7480
7481 @table @option
7482
7483 @item -gnatem=@var{path}
7484 @cindex @option{-gnatem} (@command{gcc})
7485 A mapping file is a way to communicate to the compiler two mappings:
7486 from unit names to file names (without any directory information) and from
7487 file names to path names (with full directory information). These mappings
7488 are used by the compiler to short-circuit the path search.
7489
7490 The use of mapping files is not required for correct operation of the
7491 compiler, but mapping files can improve efficiency, particularly when
7492 sources are read over a slow network connection. In normal operation,
7493 you need not be concerned with the format or use of mapping files,
7494 and the @option{-gnatem} switch is not a switch that you would use
7495 explicitly. It is intended primarily for use by automatic tools such as
7496 @command{gnatmake} running under the project file facility. The
7497 description here of the format of mapping files is provided
7498 for completeness and for possible use by other tools.
7499
7500 A mapping file is a sequence of sets of three lines. In each set, the
7501 first line is the unit name, in lower case, with @code{%s} appended
7502 for specs and @code{%b} appended for bodies; the second line is the
7503 file name; and the third line is the path name.
7504
7505 Example:
7506 @smallexample
7507    main%b
7508    main.2.ada
7509    /gnat/project1/sources/main.2.ada
7510 @end smallexample
7511
7512 When the switch @option{-gnatem} is specified, the compiler will
7513 create in memory the two mappings from the specified file. If there is
7514 any problem (nonexistent file, truncated file or duplicate entries),
7515 no mapping will be created.
7516
7517 Several @option{-gnatem} switches may be specified; however, only the
7518 last one on the command line will be taken into account.
7519
7520 When using a project file, @command{gnatmake} creates a temporary
7521 mapping file and communicates it to the compiler using this switch.
7522
7523 @end table
7524
7525 @node Integrated Preprocessing
7526 @subsection Integrated Preprocessing
7527
7528 @noindent
7529 GNAT sources may be preprocessed immediately before compilation.
7530 In this case, the actual
7531 text of the source is not the text of the source file, but is derived from it
7532 through a process called preprocessing. Integrated preprocessing is specified
7533 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7534 indicates, through a text file, the preprocessing data to be used.
7535 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7536
7537 @noindent
7538 Note that when integrated preprocessing is used, the output from the
7539 preprocessor is not written to any external file. Instead it is passed
7540 internally to the compiler. If you need to preserve the result of
7541 preprocessing in a file, then you should use @command{gnatprep}
7542 to perform the desired preprocessing in stand-alone mode.
7543
7544 @noindent
7545 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7546 used when Integrated Preprocessing is used. The reason is that preprocessing
7547 with another Preprocessing Data file without changing the sources will
7548 not trigger recompilation without this switch.
7549
7550 @noindent
7551 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7552 always trigger recompilation for sources that are preprocessed,
7553 because @command{gnatmake} cannot compute the checksum of the source after
7554 preprocessing.
7555
7556 @noindent
7557 The actual preprocessing function is described in details in section
7558 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7559 preprocessing is triggered and parameterized.
7560
7561 @table @code
7562
7563 @item -gnatep=@var{file}
7564 @cindex @option{-gnatep} (@command{gcc})
7565 This switch indicates to the compiler the file name (without directory
7566 information) of the preprocessor data file to use. The preprocessor data file
7567 should be found in the source directories.
7568
7569 @noindent
7570 A preprocessing data file is a text file with significant lines indicating
7571 how should be preprocessed either a specific source or all sources not
7572 mentioned in other lines. A significant line is a nonempty, non-comment line.
7573 Comments are similar to Ada comments.
7574
7575 @noindent
7576 Each significant line starts with either a literal string or the character '*'.
7577 A literal string is the file name (without directory information) of the source
7578 to preprocess. A character '*' indicates the preprocessing for all the sources
7579 that are not specified explicitly on other lines (order of the lines is not
7580 significant). It is an error to have two lines with the same file name or two
7581 lines starting with the character '*'.
7582
7583 @noindent
7584 After the file name or the character '*', another optional literal string
7585 indicating the file name of the definition file to be used for preprocessing
7586 (@pxref{Form of Definitions File}). The definition files are found by the
7587 compiler in one of the source directories. In some cases, when compiling
7588 a source in a directory other than the current directory, if the definition
7589 file is in the current directory, it may be necessary to add the current
7590 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7591 the compiler would not find the definition file.
7592
7593 @noindent
7594 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7595 be found. Those ^switches^switches^ are:
7596
7597 @table @code
7598
7599 @item -b
7600 Causes both preprocessor lines and the lines deleted by
7601 preprocessing to be replaced by blank lines, preserving the line number.
7602 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7603 it cancels the effect of @option{-c}.
7604
7605 @item -c
7606 Causes both preprocessor lines and the lines deleted
7607 by preprocessing to be retained as comments marked
7608 with the special string ``@code{--! }''.
7609
7610 @item -Dsymbol=value
7611 Define or redefine a symbol, associated with value. A symbol is an Ada
7612 identifier, or an Ada reserved word, with the exception of @code{if},
7613 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7614 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7615 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7616 same name defined in a definition file.
7617
7618 @item -s
7619 Causes a sorted list of symbol names and values to be
7620 listed on the standard output file.
7621
7622 @item -u
7623 Causes undefined symbols to be treated as having the value @code{FALSE}
7624 in the context
7625 of a preprocessor test. In the absence of this option, an undefined symbol in
7626 a @code{#if} or @code{#elsif} test will be treated as an error.
7627
7628 @end table
7629
7630 @noindent
7631 Examples of valid lines in a preprocessor data file:
7632
7633 @smallexample
7634   "toto.adb"  "prep.def" -u
7635   --  preprocess "toto.adb", using definition file "prep.def",
7636   --  undefined symbol are False.
7637
7638   * -c -DVERSION=V101
7639   --  preprocess all other sources without a definition file;
7640   --  suppressed lined are commented; symbol VERSION has the value V101.
7641
7642   "titi.adb" "prep2.def" -s
7643   --  preprocess "titi.adb", using definition file "prep2.def";
7644   --  list all symbols with their values.
7645 @end smallexample
7646
7647 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7648 @cindex @option{-gnateD} (@command{gcc})
7649 Define or redefine a preprocessing symbol, associated with value. If no value
7650 is given on the command line, then the value of the symbol is @code{True}.
7651 A symbol is an identifier, following normal Ada (case-insensitive)
7652 rules for its syntax, and value is any sequence (including an empty sequence)
7653 of characters from the set (letters, digits, period, underline).
7654 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7655 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7656
7657 @noindent
7658 A symbol declared with this ^switch^switch^ on the command line replaces a
7659 symbol with the same name either in a definition file or specified with a
7660 ^switch^switch^ -D in the preprocessor data file.
7661
7662 @noindent
7663 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7664
7665 @item -gnateG
7666 When integrated preprocessing is performed and the preprocessor modifies
7667 the source text, write the result of this preprocessing into a file
7668 <source>^.prep^_prep^.
7669
7670 @end table
7671
7672 @node Code Generation Control
7673 @subsection Code Generation Control
7674
7675 @noindent
7676
7677 The GCC technology provides a wide range of target dependent
7678 @option{-m} switches for controlling
7679 details of code generation with respect to different versions of
7680 architectures. This includes variations in instruction sets (e.g.@:
7681 different members of the power pc family), and different requirements
7682 for optimal arrangement of instructions (e.g.@: different members of
7683 the x86 family). The list of available @option{-m} switches may be
7684 found in the GCC documentation.
7685
7686 Use of these @option{-m} switches may in some cases result in improved
7687 code performance.
7688
7689 The GNAT Pro technology is tested and qualified without any
7690 @option{-m} switches,
7691 so generally the most reliable approach is to avoid the use of these
7692 switches. However, we generally expect most of these switches to work
7693 successfully with GNAT Pro, and many customers have reported successful
7694 use of these options.
7695
7696 Our general advice is to avoid the use of @option{-m} switches unless
7697 special needs lead to requirements in this area. In particular,
7698 there is no point in using @option{-m} switches to improve performance
7699 unless you actually see a performance improvement.
7700
7701 @ifset vms
7702 @node Return Codes
7703 @subsection Return Codes
7704 @cindex Return Codes
7705 @cindex @option{/RETURN_CODES=VMS}
7706
7707 @noindent
7708 On VMS, GNAT compiled programs return POSIX-style codes by default,
7709 e.g.@: @option{/RETURN_CODES=POSIX}.
7710
7711 To enable VMS style return codes, use GNAT BIND and LINK with the option
7712 @option{/RETURN_CODES=VMS}. For example:
7713
7714 @smallexample
7715 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7716 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7717 @end smallexample
7718
7719 @noindent
7720 Programs built with /RETURN_CODES=VMS are suitable to be called in
7721 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7722 are suitable for spawning with appropriate GNAT RTL routines.
7723
7724 @end ifset
7725
7726 @node Search Paths and the Run-Time Library (RTL)
7727 @section Search Paths and the Run-Time Library (RTL)
7728
7729 @noindent
7730 With the GNAT source-based library system, the compiler must be able to
7731 find source files for units that are needed by the unit being compiled.
7732 Search paths are used to guide this process.
7733
7734 The compiler compiles one source file whose name must be given
7735 explicitly on the command line. In other words, no searching is done
7736 for this file. To find all other source files that are needed (the most
7737 common being the specs of units), the compiler examines the following
7738 directories, in the following order:
7739
7740 @enumerate
7741 @item
7742 The directory containing the source file of the main unit being compiled
7743 (the file name on the command line).
7744
7745 @item
7746 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7747 @command{gcc} command line, in the order given.
7748
7749 @item
7750 @findex ADA_PRJ_INCLUDE_FILE
7751 Each of the directories listed in the text file whose name is given
7752 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7753
7754 @noindent
7755 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7756 driver when project files are used. It should not normally be set
7757 by other means.
7758
7759 @item
7760 @findex ADA_INCLUDE_PATH
7761 Each of the directories listed in the value of the
7762 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7763 @ifclear vms
7764 Construct this value
7765 exactly as the @env{PATH} environment variable: a list of directory
7766 names separated by colons (semicolons when working with the NT version).
7767 @end ifclear
7768 @ifset vms
7769 Normally, define this value as a logical name containing a comma separated
7770 list of directory names.
7771
7772 This variable can also be defined by means of an environment string
7773 (an argument to the HP C exec* set of functions).
7774
7775 Logical Name:
7776 @smallexample
7777 DEFINE ANOTHER_PATH FOO:[BAG]
7778 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7779 @end smallexample
7780
7781 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7782 first, followed by the standard Ada
7783 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7784 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7785 (Text_IO, Sequential_IO, etc)
7786 instead of the standard Ada packages. Thus, in order to get the standard Ada
7787 packages by default, ADA_INCLUDE_PATH must be redefined.
7788 @end ifset
7789
7790 @item
7791 The content of the @file{ada_source_path} file which is part of the GNAT
7792 installation tree and is used to store standard libraries such as the
7793 GNAT Run Time Library (RTL) source files.
7794 @ifclear vms
7795 @ref{Installing a library}
7796 @end ifclear
7797 @end enumerate
7798
7799 @noindent
7800 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7801 inhibits the use of the directory
7802 containing the source file named in the command line. You can still
7803 have this directory on your search path, but in this case it must be
7804 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7805
7806 Specifying the switch @option{-nostdinc}
7807 inhibits the search of the default location for the GNAT Run Time
7808 Library (RTL) source files.
7809
7810 The compiler outputs its object files and ALI files in the current
7811 working directory.
7812 @ifclear vms
7813 Caution: The object file can be redirected with the @option{-o} switch;
7814 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7815 so the @file{ALI} file will not go to the right place. Therefore, you should
7816 avoid using the @option{-o} switch.
7817 @end ifclear
7818
7819 @findex System.IO
7820 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7821 children make up the GNAT RTL, together with the simple @code{System.IO}
7822 package used in the @code{"Hello World"} example. The sources for these units
7823 are needed by the compiler and are kept together in one directory. Not
7824 all of the bodies are needed, but all of the sources are kept together
7825 anyway. In a normal installation, you need not specify these directory
7826 names when compiling or binding. Either the environment variables or
7827 the built-in defaults cause these files to be found.
7828
7829 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7830 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7831 consisting of child units of @code{GNAT}. This is a collection of generally
7832 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7833 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7834
7835 Besides simplifying access to the RTL, a major use of search paths is
7836 in compiling sources from multiple directories. This can make
7837 development environments much more flexible.
7838
7839 @node Order of Compilation Issues
7840 @section Order of Compilation Issues
7841
7842 @noindent
7843 If, in our earlier example, there was a spec for the @code{hello}
7844 procedure, it would be contained in the file @file{hello.ads}; yet this
7845 file would not have to be explicitly compiled. This is the result of the
7846 model we chose to implement library management. Some of the consequences
7847 of this model are as follows:
7848
7849 @itemize @bullet
7850 @item
7851 There is no point in compiling specs (except for package
7852 specs with no bodies) because these are compiled as needed by clients. If
7853 you attempt a useless compilation, you will receive an error message.
7854 It is also useless to compile subunits because they are compiled as needed
7855 by the parent.
7856
7857 @item
7858 There are no order of compilation requirements: performing a
7859 compilation never obsoletes anything. The only way you can obsolete
7860 something and require recompilations is to modify one of the
7861 source files on which it depends.
7862
7863 @item
7864 There is no library as such, apart from the ALI files
7865 (@pxref{The Ada Library Information Files}, for information on the format
7866 of these files). For now we find it convenient to create separate ALI files,
7867 but eventually the information therein may be incorporated into the object
7868 file directly.
7869
7870 @item
7871 When you compile a unit, the source files for the specs of all units
7872 that it @code{with}'s, all its subunits, and the bodies of any generics it
7873 instantiates must be available (reachable by the search-paths mechanism
7874 described above), or you will receive a fatal error message.
7875 @end itemize
7876
7877 @node Examples
7878 @section Examples
7879
7880 @noindent
7881 The following are some typical Ada compilation command line examples:
7882
7883 @table @code
7884 @item $ gcc -c xyz.adb
7885 Compile body in file @file{xyz.adb} with all default options.
7886
7887 @ifclear vms
7888 @item $ gcc -c -O2 -gnata xyz-def.adb
7889 @end ifclear
7890 @ifset vms
7891 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7892 @end ifset
7893
7894 Compile the child unit package in file @file{xyz-def.adb} with extensive
7895 optimizations, and pragma @code{Assert}/@code{Debug} statements
7896 enabled.
7897
7898 @item $ gcc -c -gnatc abc-def.adb
7899 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7900 mode.
7901 @end table
7902
7903 @node Binding Using gnatbind
7904 @chapter Binding Using @code{gnatbind}
7905 @findex gnatbind
7906
7907 @menu
7908 * Running gnatbind::
7909 * Switches for gnatbind::
7910 * Command-Line Access::
7911 * Search Paths for gnatbind::
7912 * Examples of gnatbind Usage::
7913 @end menu
7914
7915 @noindent
7916 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7917 to bind compiled GNAT objects.
7918
7919 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7920 driver (see @ref{The GNAT Driver and Project Files}).
7921
7922 The @code{gnatbind} program performs four separate functions:
7923
7924 @enumerate
7925 @item
7926 Checks that a program is consistent, in accordance with the rules in
7927 Chapter 10 of the Ada Reference Manual. In particular, error
7928 messages are generated if a program uses inconsistent versions of a
7929 given unit.
7930
7931 @item
7932 Checks that an acceptable order of elaboration exists for the program
7933 and issues an error message if it cannot find an order of elaboration
7934 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7935
7936 @item
7937 Generates a main program incorporating the given elaboration order.
7938 This program is a small Ada package (body and spec) that
7939 must be subsequently compiled
7940 using the GNAT compiler. The necessary compilation step is usually
7941 performed automatically by @command{gnatlink}. The two most important
7942 functions of this program
7943 are to call the elaboration routines of units in an appropriate order
7944 and to call the main program.
7945
7946 @item
7947 Determines the set of object files required by the given main program.
7948 This information is output in the forms of comments in the generated program,
7949 to be read by the @command{gnatlink} utility used to link the Ada application.
7950 @end enumerate
7951
7952 @node Running gnatbind
7953 @section Running @code{gnatbind}
7954
7955 @noindent
7956 The form of the @code{gnatbind} command is
7957
7958 @smallexample
7959 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7960 @c Expanding @ovar macro inline (explanation in macro def comments)
7961 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7962 @end smallexample
7963
7964 @noindent
7965 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7966 unit body. @code{gnatbind} constructs an Ada
7967 package in two files whose names are
7968 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7969 For example, if given the
7970 parameter @file{hello.ali}, for a main program contained in file
7971 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7972 and @file{b~hello.adb}.
7973
7974 When doing consistency checking, the binder takes into consideration
7975 any source files it can locate. For example, if the binder determines
7976 that the given main program requires the package @code{Pack}, whose
7977 @file{.ALI}
7978 file is @file{pack.ali} and whose corresponding source spec file is
7979 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7980 (using the same search path conventions as previously described for the
7981 @command{gcc} command). If it can locate this source file, it checks that
7982 the time stamps
7983 or source checksums of the source and its references to in @file{ALI} files
7984 match. In other words, any @file{ALI} files that mentions this spec must have
7985 resulted from compiling this version of the source file (or in the case
7986 where the source checksums match, a version close enough that the
7987 difference does not matter).
7988
7989 @cindex Source files, use by binder
7990 The effect of this consistency checking, which includes source files, is
7991 that the binder ensures that the program is consistent with the latest
7992 version of the source files that can be located at bind time. Editing a
7993 source file without compiling files that depend on the source file cause
7994 error messages to be generated by the binder.
7995
7996 For example, suppose you have a main program @file{hello.adb} and a
7997 package @code{P}, from file @file{p.ads} and you perform the following
7998 steps:
7999
8000 @enumerate
8001 @item
8002 Enter @code{gcc -c hello.adb} to compile the main program.
8003
8004 @item
8005 Enter @code{gcc -c p.ads} to compile package @code{P}.
8006
8007 @item
8008 Edit file @file{p.ads}.
8009
8010 @item
8011 Enter @code{gnatbind hello}.
8012 @end enumerate
8013
8014 @noindent
8015 At this point, the file @file{p.ali} contains an out-of-date time stamp
8016 because the file @file{p.ads} has been edited. The attempt at binding
8017 fails, and the binder generates the following error messages:
8018
8019 @smallexample
8020 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8021 error: "p.ads" has been modified and must be recompiled
8022 @end smallexample
8023
8024 @noindent
8025 Now both files must be recompiled as indicated, and then the bind can
8026 succeed, generating a main program. You need not normally be concerned
8027 with the contents of this file, but for reference purposes a sample
8028 binder output file is given in @ref{Example of Binder Output File}.
8029
8030 In most normal usage, the default mode of @command{gnatbind} which is to
8031 generate the main package in Ada, as described in the previous section.
8032 In particular, this means that any Ada programmer can read and understand
8033 the generated main program. It can also be debugged just like any other
8034 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8035 @command{gnatbind} and @command{gnatlink}.
8036
8037 @node Switches for gnatbind
8038 @section Switches for @command{gnatbind}
8039
8040 @noindent
8041 The following switches are available with @code{gnatbind}; details will
8042 be presented in subsequent sections.
8043
8044 @menu
8045 * Consistency-Checking Modes::
8046 * Binder Error Message Control::
8047 * Elaboration Control::
8048 * Output Control::
8049 * Binding with Non-Ada Main Programs::
8050 * Binding Programs with No Main Subprogram::
8051 @end menu
8052
8053 @table @option
8054 @c !sort!
8055
8056 @item --version
8057 @cindex @option{--version} @command{gnatbind}
8058 Display Copyright and version, then exit disregarding all other options.
8059
8060 @item --help
8061 @cindex @option{--help} @command{gnatbind}
8062 If @option{--version} was not used, display usage, then exit disregarding
8063 all other options.
8064
8065 @item -a
8066 @cindex @option{-a} @command{gnatbind}
8067 Indicates that, if supported by the platform, the adainit procedure should
8068 be treated as an initialisation routine by the linker (a constructor). This
8069 is intended to be used by the Project Manager to automatically initialize
8070 shared Stand-Alone Libraries.
8071
8072 @item ^-aO^/OBJECT_SEARCH^
8073 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8074 Specify directory to be searched for ALI files.
8075
8076 @item ^-aI^/SOURCE_SEARCH^
8077 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8078 Specify directory to be searched for source file.
8079
8080 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8081 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8082 Output ALI list (to standard output or to the named file).
8083
8084 @item ^-b^/REPORT_ERRORS=BRIEF^
8085 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8086 Generate brief messages to @file{stderr} even if verbose mode set.
8087
8088 @item ^-c^/NOOUTPUT^
8089 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8090 Check only, no generation of binder output file.
8091
8092 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8093 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8094 This switch can be used to change the default task stack size value
8095 to a specified size @var{nn}, which is expressed in bytes by default, or
8096 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8097 with @var{m}.
8098 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8099 in effect, to completing all task specs with
8100 @smallexample @c ada
8101    pragma Storage_Size (nn);
8102 @end smallexample
8103 When they do not already have such a pragma.
8104
8105 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8106 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8107 This switch can be used to change the default secondary stack size value
8108 to a specified size @var{nn}, which is expressed in bytes by default, or
8109 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8110 with @var{m}.
8111
8112 The secondary stack is used to deal with functions that return a variable
8113 sized result, for example a function returning an unconstrained
8114 String. There are two ways in which this secondary stack is allocated.
8115
8116 For most targets, the secondary stack is growing on demand and is allocated
8117 as a chain of blocks in the heap. The -D option is not very
8118 relevant. It only give some control over the size of the allocated
8119 blocks (whose size is the minimum of the default secondary stack size value,
8120 and the actual size needed for the current allocation request).
8121
8122 For certain targets, notably VxWorks 653,
8123 the secondary stack is allocated by carving off a fixed ratio chunk of the
8124 primary task stack. The -D option is used to define the
8125 size of the environment task's secondary stack.
8126
8127 @item ^-e^/ELABORATION_DEPENDENCIES^
8128 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8129 Output complete list of elaboration-order dependencies.
8130
8131 @item ^-E^/STORE_TRACEBACKS^
8132 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8133 Store tracebacks in exception occurrences when the target supports it.
8134 @ignore
8135 @c The following may get moved to an appendix
8136 This option is currently supported on the following targets:
8137 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8138 @end ignore
8139 See also the packages @code{GNAT.Traceback} and
8140 @code{GNAT.Traceback.Symbolic} for more information.
8141 @ifclear vms
8142 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8143 @command{gcc} option.
8144 @end ifclear
8145
8146 @item ^-F^/FORCE_ELABS_FLAGS^
8147 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8148 Force the checks of elaboration flags. @command{gnatbind} does not normally
8149 generate checks of elaboration flags for the main executable, except when
8150 a Stand-Alone Library is used. However, there are cases when this cannot be
8151 detected by gnatbind. An example is importing an interface of a Stand-Alone
8152 Library through a pragma Import and only specifying through a linker switch
8153 this Stand-Alone Library. This switch is used to guarantee that elaboration
8154 flag checks are generated.
8155
8156 @item ^-h^/HELP^
8157 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8158 Output usage (help) information
8159
8160 @item ^-I^/SEARCH^
8161 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8162 Specify directory to be searched for source and ALI files.
8163
8164 @item ^-I-^/NOCURRENT_DIRECTORY^
8165 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8166 Do not look for sources in the current directory where @code{gnatbind} was
8167 invoked, and do not look for ALI files in the directory containing the
8168 ALI file named in the @code{gnatbind} command line.
8169
8170 @item ^-l^/ORDER_OF_ELABORATION^
8171 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8172 Output chosen elaboration order.
8173
8174 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8175 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8176 Bind the units for library building. In this case the adainit and
8177 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8178 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8179 ^@var{xxx}final^@var{XXX}FINAL^.
8180 Implies ^-n^/NOCOMPILE^.
8181 @ifclear vms
8182 (@xref{GNAT and Libraries}, for more details.)
8183 @end ifclear
8184 @ifset vms
8185 On OpenVMS, these init and final procedures are exported in uppercase
8186 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8187 the init procedure will be "TOTOINIT" and the exported name of the final
8188 procedure will be "TOTOFINAL".
8189 @end ifset
8190
8191 @item ^-Mxyz^/RENAME_MAIN=xyz^
8192 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8193 Rename generated main program from main to xyz. This option is
8194 supported on cross environments only.
8195
8196 @item ^-m^/ERROR_LIMIT=^@var{n}
8197 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8198 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8199 in the range 1..999999. The default value if no switch is
8200 given is 9999. If the number of warnings reaches this limit, then a
8201 message is output and further warnings are suppressed, the bind
8202 continues in this case. If the number of errors reaches this
8203 limit, then a message is output and the bind is abandoned.
8204 A value of zero means that no limit is enforced. The equal
8205 sign is optional.
8206
8207 @ifset unw
8208 Furthermore, under Windows, the sources pointed to by the libraries path
8209 set in the registry are not searched for.
8210 @end ifset
8211
8212 @item ^-n^/NOMAIN^
8213 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8214 No main program.
8215
8216 @item -nostdinc
8217 @cindex @option{-nostdinc} (@command{gnatbind})
8218 Do not look for sources in the system default directory.
8219
8220 @item -nostdlib
8221 @cindex @option{-nostdlib} (@command{gnatbind})
8222 Do not look for library files in the system default directory.
8223
8224 @item --RTS=@var{rts-path}
8225 @cindex @option{--RTS} (@code{gnatbind})
8226 Specifies the default location of the runtime library. Same meaning as the
8227 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8228
8229 @item ^-o ^/OUTPUT=^@var{file}
8230 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8231 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8232 Note that if this option is used, then linking must be done manually,
8233 gnatlink cannot be used.
8234
8235 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8236 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8237 Output object list (to standard output or to the named file).
8238
8239 @item ^-p^/PESSIMISTIC_ELABORATION^
8240 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8241 Pessimistic (worst-case) elaboration order
8242
8243 @item ^-R^-R^
8244 @cindex @option{^-R^-R^} (@command{gnatbind})
8245 Output closure source list.
8246
8247 @item ^-s^/READ_SOURCES=ALL^
8248 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8249 Require all source files to be present.
8250
8251 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8252 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8253 Specifies the value to be used when detecting uninitialized scalar
8254 objects with pragma Initialize_Scalars.
8255 The @var{xxx} ^string specified with the switch^option^ may be either
8256 @itemize @bullet
8257 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8258 @item ``@option{^lo^LOW^}'' for the lowest possible value
8259 @item ``@option{^hi^HIGH^}'' for the highest possible value
8260 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8261 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8262 @end itemize
8263
8264 In addition, you can specify @option{-Sev} to indicate that the value is
8265 to be set at run time. In this case, the program will look for an environment
8266 @cindex GNAT_INIT_SCALARS
8267 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8268 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8269 If no environment variable is found, or if it does not have a valid value,
8270 then the default is @option{in} (invalid values).
8271
8272 @ifclear vms
8273 @item -static
8274 @cindex @option{-static} (@code{gnatbind})
8275 Link against a static GNAT run time.
8276
8277 @item -shared
8278 @cindex @option{-shared} (@code{gnatbind})
8279 Link against a shared GNAT run time when available.
8280 @end ifclear
8281
8282 @item ^-t^/NOTIME_STAMP_CHECK^
8283 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8284 Tolerate time stamp and other consistency errors
8285
8286 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8287 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8288 Set the time slice value to @var{n} milliseconds. If the system supports
8289 the specification of a specific time slice value, then the indicated value
8290 is used. If the system does not support specific time slice values, but
8291 does support some general notion of round-robin scheduling, then any
8292 nonzero value will activate round-robin scheduling.
8293
8294 A value of zero is treated specially. It turns off time
8295 slicing, and in addition, indicates to the tasking run time that the
8296 semantics should match as closely as possible the Annex D
8297 requirements of the Ada RM, and in particular sets the default
8298 scheduling policy to @code{FIFO_Within_Priorities}.
8299
8300 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8301 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8302 Enable dynamic stack usage, with @var{n} results stored and displayed
8303 at program termination. A result is generated when a task
8304 terminates. Results that can't be stored are displayed on the fly, at
8305 task termination. This option is currently not supported on Itanium
8306 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8307
8308 @item ^-v^/REPORT_ERRORS=VERBOSE^
8309 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8310 Verbose mode. Write error messages, header, summary output to
8311 @file{stdout}.
8312
8313 @ifclear vms
8314 @item -w@var{x}
8315 @cindex @option{-w} (@code{gnatbind})
8316 Warning mode (@var{x}=s/e for suppress/treat as error)
8317 @end ifclear
8318
8319 @ifset vms
8320 @item /WARNINGS=NORMAL
8321 @cindex @option{/WARNINGS} (@code{gnatbind})
8322 Normal warnings mode. Warnings are issued but ignored
8323
8324 @item /WARNINGS=SUPPRESS
8325 @cindex @option{/WARNINGS} (@code{gnatbind})
8326 All warning messages are suppressed
8327
8328 @item /WARNINGS=ERROR
8329 @cindex @option{/WARNINGS} (@code{gnatbind})
8330 Warning messages are treated as fatal errors
8331 @end ifset
8332
8333 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8334 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8335 Override default wide character encoding for standard Text_IO files.
8336
8337 @item ^-x^/READ_SOURCES=NONE^
8338 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8339 Exclude source files (check object consistency only).
8340
8341 @ifset vms
8342 @item /READ_SOURCES=AVAILABLE
8343 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8344 Default mode, in which sources are checked for consistency only if
8345 they are available.
8346 @end ifset
8347
8348 @item ^-y^/ENABLE_LEAP_SECONDS^
8349 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8350 Enable leap seconds support in @code{Ada.Calendar} and its children.
8351
8352 @item ^-z^/ZERO_MAIN^
8353 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8354 No main subprogram.
8355 @end table
8356
8357 @ifclear vms
8358 @noindent
8359 You may obtain this listing of switches by running @code{gnatbind} with
8360 no arguments.
8361 @end ifclear
8362
8363 @node Consistency-Checking Modes
8364 @subsection Consistency-Checking Modes
8365
8366 @noindent
8367 As described earlier, by default @code{gnatbind} checks
8368 that object files are consistent with one another and are consistent
8369 with any source files it can locate. The following switches control binder
8370 access to sources.
8371
8372 @table @option
8373 @c !sort!
8374 @item ^-s^/READ_SOURCES=ALL^
8375 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8376 Require source files to be present. In this mode, the binder must be
8377 able to locate all source files that are referenced, in order to check
8378 their consistency. In normal mode, if a source file cannot be located it
8379 is simply ignored. If you specify this switch, a missing source
8380 file is an error.
8381
8382 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8383 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8384 Override default wide character encoding for standard Text_IO files.
8385 Normally the default wide character encoding method used for standard
8386 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8387 the main source input (see description of switch
8388 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8389 use of this switch for the binder (which has the same set of
8390 possible arguments) overrides this default as specified.
8391
8392 @item ^-x^/READ_SOURCES=NONE^
8393 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8394 Exclude source files. In this mode, the binder only checks that ALI
8395 files are consistent with one another. Source files are not accessed.
8396 The binder runs faster in this mode, and there is still a guarantee that
8397 the resulting program is self-consistent.
8398 If a source file has been edited since it was last compiled, and you
8399 specify this switch, the binder will not detect that the object
8400 file is out of date with respect to the source file. Note that this is the
8401 mode that is automatically used by @command{gnatmake} because in this
8402 case the checking against sources has already been performed by
8403 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8404
8405 @ifset vms
8406 @item /READ_SOURCES=AVAILABLE
8407 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8408 This is the default mode in which source files are checked if they are
8409 available, and ignored if they are not available.
8410 @end ifset
8411 @end table
8412
8413 @node Binder Error Message Control
8414 @subsection Binder Error Message Control
8415
8416 @noindent
8417 The following switches provide control over the generation of error
8418 messages from the binder:
8419
8420 @table @option
8421 @c !sort!
8422 @item ^-v^/REPORT_ERRORS=VERBOSE^
8423 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8424 Verbose mode. In the normal mode, brief error messages are generated to
8425 @file{stderr}. If this switch is present, a header is written
8426 to @file{stdout} and any error messages are directed to @file{stdout}.
8427 All that is written to @file{stderr} is a brief summary message.
8428
8429 @item ^-b^/REPORT_ERRORS=BRIEF^
8430 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8431 Generate brief error messages to @file{stderr} even if verbose mode is
8432 specified. This is relevant only when used with the
8433 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8434
8435 @ifclear vms
8436 @item -m@var{n}
8437 @cindex @option{-m} (@code{gnatbind})
8438 Limits the number of error messages to @var{n}, a decimal integer in the
8439 range 1-999. The binder terminates immediately if this limit is reached.
8440
8441 @item -M@var{xxx}
8442 @cindex @option{-M} (@code{gnatbind})
8443 Renames the generated main program from @code{main} to @code{xxx}.
8444 This is useful in the case of some cross-building environments, where
8445 the actual main program is separate from the one generated
8446 by @code{gnatbind}.
8447 @end ifclear
8448
8449 @item ^-ws^/WARNINGS=SUPPRESS^
8450 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8451 @cindex Warnings
8452 Suppress all warning messages.
8453
8454 @item ^-we^/WARNINGS=ERROR^
8455 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8456 Treat any warning messages as fatal errors.
8457
8458 @ifset vms
8459 @item /WARNINGS=NORMAL
8460 Standard mode with warnings generated, but warnings do not get treated
8461 as errors.
8462 @end ifset
8463
8464 @item ^-t^/NOTIME_STAMP_CHECK^
8465 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8466 @cindex Time stamp checks, in binder
8467 @cindex Binder consistency checks
8468 @cindex Consistency checks, in binder
8469 The binder performs a number of consistency checks including:
8470
8471 @itemize @bullet
8472 @item
8473 Check that time stamps of a given source unit are consistent
8474 @item
8475 Check that checksums of a given source unit are consistent
8476 @item
8477 Check that consistent versions of @code{GNAT} were used for compilation
8478 @item
8479 Check consistency of configuration pragmas as required
8480 @end itemize
8481
8482 @noindent
8483 Normally failure of such checks, in accordance with the consistency
8484 requirements of the Ada Reference Manual, causes error messages to be
8485 generated which abort the binder and prevent the output of a binder
8486 file and subsequent link to obtain an executable.
8487
8488 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8489 into warnings, so that
8490 binding and linking can continue to completion even in the presence of such
8491 errors. The result may be a failed link (due to missing symbols), or a
8492 non-functional executable which has undefined semantics.
8493 @emph{This means that
8494 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8495 with extreme care.}
8496 @end table
8497
8498 @node Elaboration Control
8499 @subsection Elaboration Control
8500
8501 @noindent
8502 The following switches provide additional control over the elaboration
8503 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8504
8505 @table @option
8506 @item ^-p^/PESSIMISTIC_ELABORATION^
8507 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8508 Normally the binder attempts to choose an elaboration order that is
8509 likely to minimize the likelihood of an elaboration order error resulting
8510 in raising a @code{Program_Error} exception. This switch reverses the
8511 action of the binder, and requests that it deliberately choose an order
8512 that is likely to maximize the likelihood of an elaboration error.
8513 This is useful in ensuring portability and avoiding dependence on
8514 accidental fortuitous elaboration ordering.
8515
8516 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8517 switch if dynamic
8518 elaboration checking is used (@option{-gnatE} switch used for compilation).
8519 This is because in the default static elaboration mode, all necessary
8520 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8521 These implicit pragmas are still respected by the binder in
8522 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8523 safe elaboration order is assured.
8524 @end table
8525
8526 @node Output Control
8527 @subsection Output Control
8528
8529 @noindent
8530 The following switches allow additional control over the output
8531 generated by the binder.
8532
8533 @table @option
8534 @c !sort!
8535
8536 @item ^-c^/NOOUTPUT^
8537 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8538 Check only. Do not generate the binder output file. In this mode the
8539 binder performs all error checks but does not generate an output file.
8540
8541 @item ^-e^/ELABORATION_DEPENDENCIES^
8542 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8543 Output complete list of elaboration-order dependencies, showing the
8544 reason for each dependency. This output can be rather extensive but may
8545 be useful in diagnosing problems with elaboration order. The output is
8546 written to @file{stdout}.
8547
8548 @item ^-h^/HELP^
8549 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8550 Output usage information. The output is written to @file{stdout}.
8551
8552 @item ^-K^/LINKER_OPTION_LIST^
8553 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8554 Output linker options to @file{stdout}. Includes library search paths,
8555 contents of pragmas Ident and Linker_Options, and libraries added
8556 by @code{gnatbind}.
8557
8558 @item ^-l^/ORDER_OF_ELABORATION^
8559 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8560 Output chosen elaboration order. The output is written to @file{stdout}.
8561
8562 @item ^-O^/OBJECT_LIST^
8563 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8564 Output full names of all the object files that must be linked to provide
8565 the Ada component of the program. The output is written to @file{stdout}.
8566 This list includes the files explicitly supplied and referenced by the user
8567 as well as implicitly referenced run-time unit files. The latter are
8568 omitted if the corresponding units reside in shared libraries. The
8569 directory names for the run-time units depend on the system configuration.
8570
8571 @item ^-o ^/OUTPUT=^@var{file}
8572 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8573 Set name of output file to @var{file} instead of the normal
8574 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8575 binder generated body filename.
8576 Note that if this option is used, then linking must be done manually.
8577 It is not possible to use gnatlink in this case, since it cannot locate
8578 the binder file.
8579
8580 @item ^-r^/RESTRICTION_LIST^
8581 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8582 Generate list of @code{pragma Restrictions} that could be applied to
8583 the current unit. This is useful for code audit purposes, and also may
8584 be used to improve code generation in some cases.
8585
8586 @end table
8587
8588 @node Binding with Non-Ada Main Programs
8589 @subsection Binding with Non-Ada Main Programs
8590
8591 @noindent
8592 In our description so far we have assumed that the main
8593 program is in Ada, and that the task of the binder is to generate a
8594 corresponding function @code{main} that invokes this Ada main
8595 program. GNAT also supports the building of executable programs where
8596 the main program is not in Ada, but some of the called routines are
8597 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8598 The following switch is used in this situation:
8599
8600 @table @option
8601 @item ^-n^/NOMAIN^
8602 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8603 No main program. The main program is not in Ada.
8604 @end table
8605
8606 @noindent
8607 In this case, most of the functions of the binder are still required,
8608 but instead of generating a main program, the binder generates a file
8609 containing the following callable routines:
8610
8611 @table @code
8612 @item adainit
8613 @findex adainit
8614 You must call this routine to initialize the Ada part of the program by
8615 calling the necessary elaboration routines. A call to @code{adainit} is
8616 required before the first call to an Ada subprogram.
8617
8618 Note that it is assumed that the basic execution environment must be setup
8619 to be appropriate for Ada execution at the point where the first Ada
8620 subprogram is called. In particular, if the Ada code will do any
8621 floating-point operations, then the FPU must be setup in an appropriate
8622 manner. For the case of the x86, for example, full precision mode is
8623 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8624 that the FPU is in the right state.
8625
8626 @item adafinal
8627 @findex adafinal
8628 You must call this routine to perform any library-level finalization
8629 required by the Ada subprograms. A call to @code{adafinal} is required
8630 after the last call to an Ada subprogram, and before the program
8631 terminates.
8632 @end table
8633
8634 @noindent
8635 If the @option{^-n^/NOMAIN^} switch
8636 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8637 @cindex Binder, multiple input files
8638 is given, more than one ALI file may appear on
8639 the command line for @code{gnatbind}. The normal @dfn{closure}
8640 calculation is performed for each of the specified units. Calculating
8641 the closure means finding out the set of units involved by tracing
8642 @code{with} references. The reason it is necessary to be able to
8643 specify more than one ALI file is that a given program may invoke two or
8644 more quite separate groups of Ada units.
8645
8646 The binder takes the name of its output file from the last specified ALI
8647 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8648 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8649 The output is an Ada unit in source form that can be compiled with GNAT.
8650 This compilation occurs automatically as part of the @command{gnatlink}
8651 processing.
8652
8653 Currently the GNAT run time requires a FPU using 80 bits mode
8654 precision. Under targets where this is not the default it is required to
8655 call GNAT.Float_Control.Reset before using floating point numbers (this
8656 include float computation, float input and output) in the Ada code. A
8657 side effect is that this could be the wrong mode for the foreign code
8658 where floating point computation could be broken after this call.
8659
8660 @node Binding Programs with No Main Subprogram
8661 @subsection Binding Programs with No Main Subprogram
8662
8663 @noindent
8664 It is possible to have an Ada program which does not have a main
8665 subprogram. This program will call the elaboration routines of all the
8666 packages, then the finalization routines.
8667
8668 The following switch is used to bind programs organized in this manner:
8669
8670 @table @option
8671 @item ^-z^/ZERO_MAIN^
8672 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8673 Normally the binder checks that the unit name given on the command line
8674 corresponds to a suitable main subprogram. When this switch is used,
8675 a list of ALI files can be given, and the execution of the program
8676 consists of elaboration of these units in an appropriate order. Note
8677 that the default wide character encoding method for standard Text_IO
8678 files is always set to Brackets if this switch is set (you can use
8679 the binder switch
8680 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8681 @end table
8682
8683 @node Command-Line Access
8684 @section Command-Line Access
8685
8686 @noindent
8687 The package @code{Ada.Command_Line} provides access to the command-line
8688 arguments and program name. In order for this interface to operate
8689 correctly, the two variables
8690
8691 @smallexample
8692 @group
8693 int gnat_argc;
8694 char **gnat_argv;
8695 @end group
8696 @end smallexample
8697
8698 @noindent
8699 @findex gnat_argv
8700 @findex gnat_argc
8701 are declared in one of the GNAT library routines. These variables must
8702 be set from the actual @code{argc} and @code{argv} values passed to the
8703 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8704 generates the C main program to automatically set these variables.
8705 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8706 set these variables. If they are not set, the procedures in
8707 @code{Ada.Command_Line} will not be available, and any attempt to use
8708 them will raise @code{Constraint_Error}. If command line access is
8709 required, your main program must set @code{gnat_argc} and
8710 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8711 it.
8712
8713 @node Search Paths for gnatbind
8714 @section Search Paths for @code{gnatbind}
8715
8716 @noindent
8717 The binder takes the name of an ALI file as its argument and needs to
8718 locate source files as well as other ALI files to verify object consistency.
8719
8720 For source files, it follows exactly the same search rules as @command{gcc}
8721 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8722 directories searched are:
8723
8724 @enumerate
8725 @item
8726 The directory containing the ALI file named in the command line, unless
8727 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8728
8729 @item
8730 All directories specified by @option{^-I^/SEARCH^}
8731 switches on the @code{gnatbind}
8732 command line, in the order given.
8733
8734 @item
8735 @findex ADA_PRJ_OBJECTS_FILE
8736 Each of the directories listed in the text file whose name is given
8737 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8738
8739 @noindent
8740 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8741 driver when project files are used. It should not normally be set
8742 by other means.
8743
8744 @item
8745 @findex ADA_OBJECTS_PATH
8746 Each of the directories listed in the value of the
8747 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8748 @ifset unw
8749 Construct this value
8750 exactly as the @env{PATH} environment variable: a list of directory
8751 names separated by colons (semicolons when working with the NT version
8752 of GNAT).
8753 @end ifset
8754 @ifset vms
8755 Normally, define this value as a logical name containing a comma separated
8756 list of directory names.
8757
8758 This variable can also be defined by means of an environment string
8759 (an argument to the HP C exec* set of functions).
8760
8761 Logical Name:
8762 @smallexample
8763 DEFINE ANOTHER_PATH FOO:[BAG]
8764 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8765 @end smallexample
8766
8767 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8768 first, followed by the standard Ada
8769 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8770 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8771 (Text_IO, Sequential_IO, etc)
8772 instead of the standard Ada packages. Thus, in order to get the standard Ada
8773 packages by default, ADA_OBJECTS_PATH must be redefined.
8774 @end ifset
8775
8776 @item
8777 The content of the @file{ada_object_path} file which is part of the GNAT
8778 installation tree and is used to store standard libraries such as the
8779 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8780 specified.
8781 @ifclear vms
8782 @ref{Installing a library}
8783 @end ifclear
8784 @end enumerate
8785
8786 @noindent
8787 In the binder the switch @option{^-I^/SEARCH^}
8788 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8789 is used to specify both source and
8790 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8791 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8792 instead if you want to specify
8793 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8794 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8795 if you want to specify library paths
8796 only. This means that for the binder
8797 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8798 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8799 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8800 The binder generates the bind file (a C language source file) in the
8801 current working directory.
8802
8803 @findex Ada
8804 @findex System
8805 @findex Interfaces
8806 @findex GNAT
8807 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8808 children make up the GNAT Run-Time Library, together with the package
8809 GNAT and its children, which contain a set of useful additional
8810 library functions provided by GNAT. The sources for these units are
8811 needed by the compiler and are kept together in one directory. The ALI
8812 files and object files generated by compiling the RTL are needed by the
8813 binder and the linker and are kept together in one directory, typically
8814 different from the directory containing the sources. In a normal
8815 installation, you need not specify these directory names when compiling
8816 or binding. Either the environment variables or the built-in defaults
8817 cause these files to be found.
8818
8819 Besides simplifying access to the RTL, a major use of search paths is
8820 in compiling sources from multiple directories. This can make
8821 development environments much more flexible.
8822
8823 @node Examples of gnatbind Usage
8824 @section Examples of @code{gnatbind} Usage
8825
8826 @noindent
8827 This section contains a number of examples of using the GNAT binding
8828 utility @code{gnatbind}.
8829
8830 @table @code
8831 @item gnatbind hello
8832 The main program @code{Hello} (source program in @file{hello.adb}) is
8833 bound using the standard switch settings. The generated main program is
8834 @file{b~hello.adb}. This is the normal, default use of the binder.
8835
8836 @ifclear vms
8837 @item gnatbind hello -o mainprog.adb
8838 @end ifclear
8839 @ifset vms
8840 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8841 @end ifset
8842 The main program @code{Hello} (source program in @file{hello.adb}) is
8843 bound using the standard switch settings. The generated main program is
8844 @file{mainprog.adb} with the associated spec in
8845 @file{mainprog.ads}. Note that you must specify the body here not the
8846 spec. Note that if this option is used, then linking must be done manually,
8847 since gnatlink will not be able to find the generated file.
8848 @end table
8849
8850 @c ------------------------------------
8851 @node Linking Using gnatlink
8852 @chapter Linking Using @command{gnatlink}
8853 @c ------------------------------------
8854 @findex gnatlink
8855
8856 @noindent
8857 This chapter discusses @command{gnatlink}, a tool that links
8858 an Ada program and builds an executable file. This utility
8859 invokes the system linker ^(via the @command{gcc} command)^^
8860 with a correct list of object files and library references.
8861 @command{gnatlink} automatically determines the list of files and
8862 references for the Ada part of a program. It uses the binder file
8863 generated by the @command{gnatbind} to determine this list.
8864
8865 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8866 driver (see @ref{The GNAT Driver and Project Files}).
8867
8868 @menu
8869 * Running gnatlink::
8870 * Switches for gnatlink::
8871 @end menu
8872
8873 @node Running gnatlink
8874 @section Running @command{gnatlink}
8875
8876 @noindent
8877 The form of the @command{gnatlink} command is
8878
8879 @smallexample
8880 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8881 @c            @ovar{non-Ada objects} @ovar{linker options}
8882 @c Expanding @ovar macro inline (explanation in macro def comments)
8883 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8884            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8885
8886 @end smallexample
8887
8888 @noindent
8889 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8890 non-Ada objects
8891 or linker options) may be in any order, provided that no non-Ada object may
8892 be mistaken for a main @file{ALI} file.
8893 Any file name @file{F} without the @file{.ali}
8894 extension will be taken as the main @file{ALI} file if a file exists
8895 whose name is the concatenation of @file{F} and @file{.ali}.
8896
8897 @noindent
8898 @file{@var{mainprog}.ali} references the ALI file of the main program.
8899 The @file{.ali} extension of this file can be omitted. From this
8900 reference, @command{gnatlink} locates the corresponding binder file
8901 @file{b~@var{mainprog}.adb} and, using the information in this file along
8902 with the list of non-Ada objects and linker options, constructs a
8903 linker command file to create the executable.
8904
8905 The arguments other than the @command{gnatlink} switches and the main
8906 @file{ALI} file are passed to the linker uninterpreted.
8907 They typically include the names of
8908 object files for units written in other languages than Ada and any library
8909 references required to resolve references in any of these foreign language
8910 units, or in @code{Import} pragmas in any Ada units.
8911
8912 @var{linker options} is an optional list of linker specific
8913 switches.
8914 The default linker called by gnatlink is @command{gcc} which in
8915 turn calls the appropriate system linker.
8916 Standard options for the linker such as @option{-lmy_lib} or
8917 @option{-Ldir} can be added as is.
8918 For options that are not recognized by
8919 @command{gcc} as linker options, use the @command{gcc} switches
8920 @option{-Xlinker} or @option{-Wl,}.
8921 Refer to the GCC documentation for
8922 details. Here is an example showing how to generate a linker map:
8923
8924 @smallexample
8925 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8926 @end smallexample
8927
8928 Using @var{linker options} it is possible to set the program stack and
8929 heap size.
8930 @ifset unw
8931 See @ref{Setting Stack Size from gnatlink} and
8932 @ref{Setting Heap Size from gnatlink}.
8933 @end ifset
8934
8935 @command{gnatlink} determines the list of objects required by the Ada
8936 program and prepends them to the list of objects passed to the linker.
8937 @command{gnatlink} also gathers any arguments set by the use of
8938 @code{pragma Linker_Options} and adds them to the list of arguments
8939 presented to the linker.
8940
8941 @ifset vms
8942 @command{gnatlink} accepts the following types of extra files on the command
8943 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8944 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8945 handled according to their extension.
8946 @end ifset
8947
8948 @node Switches for gnatlink
8949 @section Switches for @command{gnatlink}
8950
8951 @noindent
8952 The following switches are available with the @command{gnatlink} utility:
8953
8954 @table @option
8955 @c !sort!
8956
8957 @item --version
8958 @cindex @option{--version} @command{gnatlink}
8959 Display Copyright and version, then exit disregarding all other options.
8960
8961 @item --help
8962 @cindex @option{--help} @command{gnatlink}
8963 If @option{--version} was not used, display usage, then exit disregarding
8964 all other options.
8965
8966 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8967 @cindex Command line length
8968 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8969 On some targets, the command line length is limited, and @command{gnatlink}
8970 will generate a separate file for the linker if the list of object files
8971 is too long.
8972 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8973 to be generated even if
8974 the limit is not exceeded. This is useful in some cases to deal with
8975 special situations where the command line length is exceeded.
8976
8977 @item ^-g^/DEBUG^
8978 @cindex Debugging information, including
8979 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8980 The option to include debugging information causes the Ada bind file (in
8981 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8982 @option{^-g^/DEBUG^}.
8983 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8984 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8985 Without @option{^-g^/DEBUG^}, the binder removes these files by
8986 default. The same procedure apply if a C bind file was generated using
8987 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8988 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8989
8990 @item ^-n^/NOCOMPILE^
8991 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8992 Do not compile the file generated by the binder. This may be used when
8993 a link is rerun with different options, but there is no need to recompile
8994 the binder file.
8995
8996 @item ^-v^/VERBOSE^
8997 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8998 Causes additional information to be output, including a full list of the
8999 included object files. This switch option is most useful when you want
9000 to see what set of object files are being used in the link step.
9001
9002 @item ^-v -v^/VERBOSE/VERBOSE^
9003 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9004 Very verbose mode. Requests that the compiler operate in verbose mode when
9005 it compiles the binder file, and that the system linker run in verbose mode.
9006
9007 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9008 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9009 @var{exec-name} specifies an alternate name for the generated
9010 executable program. If this switch is omitted, the executable has the same
9011 name as the main unit. For example, @code{gnatlink try.ali} creates
9012 an executable called @file{^try^TRY.EXE^}.
9013
9014 @ifclear vms
9015 @item -b @var{target}
9016 @cindex @option{-b} (@command{gnatlink})
9017 Compile your program to run on @var{target}, which is the name of a
9018 system configuration. You must have a GNAT cross-compiler built if
9019 @var{target} is not the same as your host system.
9020
9021 @item -B@var{dir}
9022 @cindex @option{-B} (@command{gnatlink})
9023 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9024 from @var{dir} instead of the default location. Only use this switch
9025 when multiple versions of the GNAT compiler are available.
9026 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9027 for further details. You would normally use the @option{-b} or
9028 @option{-V} switch instead.
9029
9030 @item --GCC=@var{compiler_name}
9031 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9032 Program used for compiling the binder file. The default is
9033 @command{gcc}. You need to use quotes around @var{compiler_name} if
9034 @code{compiler_name} contains spaces or other separator characters.
9035 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9036 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9037 inserted after your command name. Thus in the above example the compiler
9038 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9039 A limitation of this syntax is that the name and path name of the executable
9040 itself must not include any embedded spaces. If the compiler executable is
9041 different from the default one (gcc or <prefix>-gcc), then the back-end
9042 switches in the ALI file are not used to compile the binder generated source.
9043 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9044 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9045 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9046 is taken into account. However, all the additional switches are also taken
9047 into account. Thus,
9048 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9049 @option{--GCC="bar -x -y -z -t"}.
9050
9051 @item --LINK=@var{name}
9052 @cindex @option{--LINK=} (@command{gnatlink})
9053 @var{name} is the name of the linker to be invoked. This is especially
9054 useful in mixed language programs since languages such as C++ require
9055 their own linker to be used. When this switch is omitted, the default
9056 name for the linker is @command{gcc}. When this switch is used, the
9057 specified linker is called instead of @command{gcc} with exactly the same
9058 parameters that would have been passed to @command{gcc} so if the desired
9059 linker requires different parameters it is necessary to use a wrapper
9060 script that massages the parameters before invoking the real linker. It
9061 may be useful to control the exact invocation by using the verbose
9062 switch.
9063
9064 @end ifclear
9065
9066 @ifset vms
9067 @item /DEBUG=TRACEBACK
9068 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9069 This qualifier causes sufficient information to be included in the
9070 executable file to allow a traceback, but does not include the full
9071 symbol information needed by the debugger.
9072
9073 @item /IDENTIFICATION="<string>"
9074 @code{"<string>"} specifies the string to be stored in the image file
9075 identification field in the image header.
9076 It overrides any pragma @code{Ident} specified string.
9077
9078 @item /NOINHIBIT-EXEC
9079 Generate the executable file even if there are linker warnings.
9080
9081 @item /NOSTART_FILES
9082 Don't link in the object file containing the ``main'' transfer address.
9083 Used when linking with a foreign language main program compiled with an
9084 HP compiler.
9085
9086 @item /STATIC
9087 Prefer linking with object libraries over sharable images, even without
9088 /DEBUG.
9089 @end ifset
9090
9091 @end table
9092
9093 @node The GNAT Make Program gnatmake
9094 @chapter The GNAT Make Program @command{gnatmake}
9095 @findex gnatmake
9096
9097 @menu
9098 * Running gnatmake::
9099 * Switches for gnatmake::
9100 * Mode Switches for gnatmake::
9101 * Notes on the Command Line::
9102 * How gnatmake Works::
9103 * Examples of gnatmake Usage::
9104 @end menu
9105 @noindent
9106 A typical development cycle when working on an Ada program consists of
9107 the following steps:
9108
9109 @enumerate
9110 @item
9111 Edit some sources to fix bugs.
9112
9113 @item
9114 Add enhancements.
9115
9116 @item
9117 Compile all sources affected.
9118
9119 @item
9120 Rebind and relink.
9121
9122 @item
9123 Test.
9124 @end enumerate
9125
9126 @noindent
9127 The third step can be tricky, because not only do the modified files
9128 @cindex Dependency rules
9129 have to be compiled, but any files depending on these files must also be
9130 recompiled. The dependency rules in Ada can be quite complex, especially
9131 in the presence of overloading, @code{use} clauses, generics and inlined
9132 subprograms.
9133
9134 @command{gnatmake} automatically takes care of the third and fourth steps
9135 of this process. It determines which sources need to be compiled,
9136 compiles them, and binds and links the resulting object files.
9137
9138 Unlike some other Ada make programs, the dependencies are always
9139 accurately recomputed from the new sources. The source based approach of
9140 the GNAT compilation model makes this possible. This means that if
9141 changes to the source program cause corresponding changes in
9142 dependencies, they will always be tracked exactly correctly by
9143 @command{gnatmake}.
9144
9145 @node Running gnatmake
9146 @section Running @command{gnatmake}
9147
9148 @noindent
9149 The usual form of the @command{gnatmake} command is
9150
9151 @smallexample
9152 @c $ gnatmake @ovar{switches} @var{file_name}
9153 @c       @ovar{file_names} @ovar{mode_switches}
9154 @c Expanding @ovar macro inline (explanation in macro def comments)
9155 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9156       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9157 @end smallexample
9158
9159 @noindent
9160 The only required argument is one @var{file_name}, which specifies
9161 a compilation unit that is a main program. Several @var{file_names} can be
9162 specified: this will result in several executables being built.
9163 If @code{switches} are present, they can be placed before the first
9164 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9165 If @var{mode_switches} are present, they must always be placed after
9166 the last @var{file_name} and all @code{switches}.
9167
9168 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9169 extension may be omitted from the @var{file_name} arguments. However, if
9170 you are using non-standard extensions, then it is required that the
9171 extension be given. A relative or absolute directory path can be
9172 specified in a @var{file_name}, in which case, the input source file will
9173 be searched for in the specified directory only. Otherwise, the input
9174 source file will first be searched in the directory where
9175 @command{gnatmake} was invoked and if it is not found, it will be search on
9176 the source path of the compiler as described in
9177 @ref{Search Paths and the Run-Time Library (RTL)}.
9178
9179 All @command{gnatmake} output (except when you specify
9180 @option{^-M^/DEPENDENCIES_LIST^}) is to
9181 @file{stderr}. The output produced by the
9182 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9183 @file{stdout}.
9184
9185 @node Switches for gnatmake
9186 @section Switches for @command{gnatmake}
9187
9188 @noindent
9189 You may specify any of the following switches to @command{gnatmake}:
9190
9191 @table @option
9192 @c !sort!
9193
9194 @item --version
9195 @cindex @option{--version} @command{gnatmake}
9196 Display Copyright and version, then exit disregarding all other options.
9197
9198 @item --help
9199 @cindex @option{--help} @command{gnatmake}
9200 If @option{--version} was not used, display usage, then exit disregarding
9201 all other options.
9202
9203 @ifclear vms
9204 @item --GCC=@var{compiler_name}
9205 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9206 Program used for compiling. The default is `@command{gcc}'. You need to use
9207 quotes around @var{compiler_name} if @code{compiler_name} contains
9208 spaces or other separator characters. As an example @option{--GCC="foo -x
9209 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9210 compiler. A limitation of this syntax is that the name and path name of
9211 the executable itself must not include any embedded spaces. Note that
9212 switch @option{-c} is always inserted after your command name. Thus in the
9213 above example the compiler command that will be used by @command{gnatmake}
9214 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9215 used, only the last @var{compiler_name} is taken into account. However,
9216 all the additional switches are also taken into account. Thus,
9217 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9218 @option{--GCC="bar -x -y -z -t"}.
9219
9220 @item --GNATBIND=@var{binder_name}
9221 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9222 Program used for binding. The default is `@code{gnatbind}'. You need to
9223 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9224 or other separator characters. As an example @option{--GNATBIND="bar -x
9225 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9226 binder. Binder switches that are normally appended by @command{gnatmake}
9227 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9228 A limitation of this syntax is that the name and path name of the executable
9229 itself must not include any embedded spaces.
9230
9231 @item --GNATLINK=@var{linker_name}
9232 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9233 Program used for linking. The default is `@command{gnatlink}'. You need to
9234 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9235 or other separator characters. As an example @option{--GNATLINK="lan -x
9236 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9237 linker. Linker switches that are normally appended by @command{gnatmake} to
9238 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9239 A limitation of this syntax is that the name and path name of the executable
9240 itself must not include any embedded spaces.
9241
9242 @end ifclear
9243
9244 @item ^--subdirs^/SUBDIRS^=subdir
9245 Actual object directory of each project file is the subdirectory subdir of the
9246 object directory specified or defaulted in the project file.
9247
9248 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9249 Disallow simultaneous compilations in the same object directory when
9250 project files are used.
9251
9252 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9253 By default, shared library projects are not allowed to import static library
9254 projects. When this switch is used on the command line, this restriction is
9255 relaxed.
9256
9257 @ifclear vms
9258 @item --create-map-file
9259 When linking an executable, create a map file. The name of the map file
9260 has the same name as the executable with extension ".map".
9261
9262 @item --create-map-file=mapfile
9263 When linking an executable, create a map file. The name of the map file is
9264 "mapfile".
9265
9266 @end ifclear
9267
9268 @item ^-a^/ALL_FILES^
9269 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9270 Consider all files in the make process, even the GNAT internal system
9271 files (for example, the predefined Ada library files), as well as any
9272 locked files. Locked files are files whose ALI file is write-protected.
9273 By default,
9274 @command{gnatmake} does not check these files,
9275 because the assumption is that the GNAT internal files are properly up
9276 to date, and also that any write protected ALI files have been properly
9277 installed. Note that if there is an installation problem, such that one
9278 of these files is not up to date, it will be properly caught by the
9279 binder.
9280 You may have to specify this switch if you are working on GNAT
9281 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9282 in conjunction with @option{^-f^/FORCE_COMPILE^}
9283 if you need to recompile an entire application,
9284 including run-time files, using special configuration pragmas,
9285 such as a @code{Normalize_Scalars} pragma.
9286
9287 By default
9288 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9289 internal files with
9290 @ifclear vms
9291 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9292 @end ifclear
9293 @ifset vms
9294 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9295 @end ifset
9296
9297 @item ^-b^/ACTIONS=BIND^
9298 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9299 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9300 compilation and binding, but no link.
9301 Can be combined with @option{^-l^/ACTIONS=LINK^}
9302 to do binding and linking. When not combined with
9303 @option{^-c^/ACTIONS=COMPILE^}
9304 all the units in the closure of the main program must have been previously
9305 compiled and must be up to date. The root unit specified by @var{file_name}
9306 may be given without extension, with the source extension or, if no GNAT
9307 Project File is specified, with the ALI file extension.
9308
9309 @item ^-c^/ACTIONS=COMPILE^
9310 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9311 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9312 is also specified. Do not perform linking, except if both
9313 @option{^-b^/ACTIONS=BIND^} and
9314 @option{^-l^/ACTIONS=LINK^} are also specified.
9315 If the root unit specified by @var{file_name} is not a main unit, this is the
9316 default. Otherwise @command{gnatmake} will attempt binding and linking
9317 unless all objects are up to date and the executable is more recent than
9318 the objects.
9319
9320 @item ^-C^/MAPPING^
9321 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9322 Use a temporary mapping file. A mapping file is a way to communicate
9323 to the compiler two mappings: from unit names to file names (without
9324 any directory information) and from file names to path names (with
9325 full directory information). A mapping file can make the compiler's
9326 file searches faster, especially if there are many source directories,
9327 or the sources are read over a slow network connection. If
9328 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9329 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9330 is initially populated based on the project file. If
9331 @option{^-C^/MAPPING^} is used without
9332 @option{^-P^/PROJECT_FILE^},
9333 the mapping file is initially empty. Each invocation of the compiler
9334 will add any newly accessed sources to the mapping file.
9335
9336 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9337 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9338 Use a specific mapping file. The file, specified as a path name (absolute or
9339 relative) by this switch, should already exist, otherwise the switch is
9340 ineffective. The specified mapping file will be communicated to the compiler.
9341 This switch is not compatible with a project file
9342 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9343 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9344
9345 @item ^-d^/DISPLAY_PROGRESS^
9346 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9347 Display progress for each source, up to date or not, as a single line
9348
9349 @smallexample
9350 completed x out of y (zz%)
9351 @end smallexample
9352
9353 If the file needs to be compiled this is displayed after the invocation of
9354 the compiler. These lines are displayed even in quiet output mode.
9355
9356 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9357 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9358 Put all object files and ALI file in directory @var{dir}.
9359 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9360 and ALI files go in the current working directory.
9361
9362 This switch cannot be used when using a project file.
9363
9364 @ifclear vms
9365 @item -eL
9366 @cindex @option{-eL} (@command{gnatmake})
9367 @cindex symbolic links
9368 Follow all symbolic links when processing project files.
9369 This should be used if your project uses symbolic links for files or
9370 directories, but is not needed in other cases.
9371
9372 @cindex naming scheme
9373 This also assumes that no directory matches the naming scheme for files (for
9374 instance that you do not have a directory called "sources.ads" when using the
9375 default GNAT naming scheme).
9376
9377 When you do not have to use this switch (ie by default), gnatmake is able to
9378 save a lot of system calls (several per source file and object file), which
9379 can result in a significant speed up to load and manipulate a project file,
9380 especially when using source files from a remote system.
9381
9382 @end ifclear
9383
9384 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9385 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9386 Output the commands for the compiler, the binder and the linker
9387 on ^standard output^SYS$OUTPUT^,
9388 instead of ^standard error^SYS$ERROR^.
9389
9390 @item ^-f^/FORCE_COMPILE^
9391 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9392 Force recompilations. Recompile all sources, even though some object
9393 files may be up to date, but don't recompile predefined or GNAT internal
9394 files or locked files (files with a write-protected ALI file),
9395 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9396
9397 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9398 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9399 When using project files, if some errors or warnings are detected during
9400 parsing and verbose mode is not in effect (no use of switch
9401 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9402 file, rather than its simple file name.
9403
9404 @item ^-g^/DEBUG^
9405 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9406 Enable debugging. This switch is simply passed to the compiler and to the
9407 linker.
9408
9409 @item ^-i^/IN_PLACE^
9410 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9411 In normal mode, @command{gnatmake} compiles all object files and ALI files
9412 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9413 then instead object files and ALI files that already exist are overwritten
9414 in place. This means that once a large project is organized into separate
9415 directories in the desired manner, then @command{gnatmake} will automatically
9416 maintain and update this organization. If no ALI files are found on the
9417 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9418 the new object and ALI files are created in the
9419 directory containing the source being compiled. If another organization
9420 is desired, where objects and sources are kept in different directories,
9421 a useful technique is to create dummy ALI files in the desired directories.
9422 When detecting such a dummy file, @command{gnatmake} will be forced to
9423 recompile the corresponding source file, and it will be put the resulting
9424 object and ALI files in the directory where it found the dummy file.
9425
9426 @item ^-j^/PROCESSES=^@var{n}
9427 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9428 @cindex Parallel make
9429 Use @var{n} processes to carry out the (re)compilations. On a
9430 multiprocessor machine compilations will occur in parallel. In the
9431 event of compilation errors, messages from various compilations might
9432 get interspersed (but @command{gnatmake} will give you the full ordered
9433 list of failing compiles at the end). If this is problematic, rerun
9434 the make process with n set to 1 to get a clean list of messages.
9435
9436 @item ^-k^/CONTINUE_ON_ERROR^
9437 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9438 Keep going. Continue as much as possible after a compilation error. To
9439 ease the programmer's task in case of compilation errors, the list of
9440 sources for which the compile fails is given when @command{gnatmake}
9441 terminates.
9442
9443 If @command{gnatmake} is invoked with several @file{file_names} and with this
9444 switch, if there are compilation errors when building an executable,
9445 @command{gnatmake} will not attempt to build the following executables.
9446
9447 @item ^-l^/ACTIONS=LINK^
9448 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9449 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9450 and linking. Linking will not be performed if combined with
9451 @option{^-c^/ACTIONS=COMPILE^}
9452 but not with @option{^-b^/ACTIONS=BIND^}.
9453 When not combined with @option{^-b^/ACTIONS=BIND^}
9454 all the units in the closure of the main program must have been previously
9455 compiled and must be up to date, and the main program needs to have been bound.
9456 The root unit specified by @var{file_name}
9457 may be given without extension, with the source extension or, if no GNAT
9458 Project File is specified, with the ALI file extension.
9459
9460 @item ^-m^/MINIMAL_RECOMPILATION^
9461 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9462 Specify that the minimum necessary amount of recompilations
9463 be performed. In this mode @command{gnatmake} ignores time
9464 stamp differences when the only
9465 modifications to a source file consist in adding/removing comments,
9466 empty lines, spaces or tabs. This means that if you have changed the
9467 comments in a source file or have simply reformatted it, using this
9468 switch will tell @command{gnatmake} not to recompile files that depend on it
9469 (provided other sources on which these files depend have undergone no
9470 semantic modifications). Note that the debugging information may be
9471 out of date with respect to the sources if the @option{-m} switch causes
9472 a compilation to be switched, so the use of this switch represents a
9473 trade-off between compilation time and accurate debugging information.
9474
9475 @item ^-M^/DEPENDENCIES_LIST^
9476 @cindex Dependencies, producing list
9477 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9478 Check if all objects are up to date. If they are, output the object
9479 dependences to @file{stdout} in a form that can be directly exploited in
9480 a @file{Makefile}. By default, each source file is prefixed with its
9481 (relative or absolute) directory name. This name is whatever you
9482 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9483 and @option{^-I^/SEARCH^} switches. If you use
9484 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9485 @option{^-q^/QUIET^}
9486 (see below), only the source file names,
9487 without relative paths, are output. If you just specify the
9488 @option{^-M^/DEPENDENCIES_LIST^}
9489 switch, dependencies of the GNAT internal system files are omitted. This
9490 is typically what you want. If you also specify
9491 the @option{^-a^/ALL_FILES^} switch,
9492 dependencies of the GNAT internal files are also listed. Note that
9493 dependencies of the objects in external Ada libraries (see switch
9494 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9495 are never reported.
9496
9497 @item ^-n^/DO_OBJECT_CHECK^
9498 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9499 Don't compile, bind, or link. Checks if all objects are up to date.
9500 If they are not, the full name of the first file that needs to be
9501 recompiled is printed.
9502 Repeated use of this option, followed by compiling the indicated source
9503 file, will eventually result in recompiling all required units.
9504
9505 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9506 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9507 Output executable name. The name of the final executable program will be
9508 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9509 name for the executable will be the name of the input file in appropriate form
9510 for an executable file on the host system.
9511
9512 This switch cannot be used when invoking @command{gnatmake} with several
9513 @file{file_names}.
9514
9515 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9516 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9517 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9518 automatically missing object directories, library directories and exec
9519 directories.
9520
9521 @item ^-P^/PROJECT_FILE=^@var{project}
9522 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9523 Use project file @var{project}. Only one such switch can be used.
9524 @xref{gnatmake and Project Files}.
9525
9526 @item ^-q^/QUIET^
9527 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9528 Quiet. When this flag is not set, the commands carried out by
9529 @command{gnatmake} are displayed.
9530
9531 @item ^-s^/SWITCH_CHECK/^
9532 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9533 Recompile if compiler switches have changed since last compilation.
9534 All compiler switches but -I and -o are taken into account in the
9535 following way:
9536 orders between different ``first letter'' switches are ignored, but
9537 orders between same switches are taken into account. For example,
9538 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9539 is equivalent to @option{-O -g}.
9540
9541 This switch is recommended when Integrated Preprocessing is used.
9542
9543 @item ^-u^/UNIQUE^
9544 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9545 Unique. Recompile at most the main files. It implies -c. Combined with
9546 -f, it is equivalent to calling the compiler directly. Note that using
9547 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9548 (@pxref{Project Files and Main Subprograms}).
9549
9550 @item ^-U^/ALL_PROJECTS^
9551 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9552 When used without a project file or with one or several mains on the command
9553 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9554 on the command line, all sources of all project files are checked and compiled
9555 if not up to date, and libraries are rebuilt, if necessary.
9556
9557 @item ^-v^/REASONS^
9558 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9559 Verbose. Display the reason for all recompilations @command{gnatmake}
9560 decides are necessary, with the highest verbosity level.
9561
9562 @item ^-vl^/LOW_VERBOSITY^
9563 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9564 Verbosity level Low. Display fewer lines than in verbosity Medium.
9565
9566 @item ^-vm^/MEDIUM_VERBOSITY^
9567 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9568 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9569
9570 @item ^-vh^/HIGH_VERBOSITY^
9571 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9572 Verbosity level High. Equivalent to ^-v^/REASONS^.
9573
9574 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9575 Indicate the verbosity of the parsing of GNAT project files.
9576 @xref{Switches Related to Project Files}.
9577
9578 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9579 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9580 Indicate that sources that are not part of any Project File may be compiled.
9581 Normally, when using Project Files, only sources that are part of a Project
9582 File may be compile. When this switch is used, a source outside of all Project
9583 Files may be compiled. The ALI file and the object file will be put in the
9584 object directory of the main Project. The compilation switches used will only
9585 be those specified on the command line. Even when
9586 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9587 command line need to be sources of a project file.
9588
9589 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9590 Indicate that external variable @var{name} has the value @var{value}.
9591 The Project Manager will use this value for occurrences of
9592 @code{external(name)} when parsing the project file.
9593 @xref{Switches Related to Project Files}.
9594
9595 @item ^-z^/NOMAIN^
9596 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9597 No main subprogram. Bind and link the program even if the unit name
9598 given on the command line is a package name. The resulting executable
9599 will execute the elaboration routines of the package and its closure,
9600 then the finalization routines.
9601
9602 @end table
9603
9604 @table @asis
9605 @item @command{gcc} @asis{switches}
9606 @ifclear vms
9607 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9608 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9609 @end ifclear
9610 @ifset vms
9611 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9612 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9613 automatically treated as a compiler switch, and passed on to all
9614 compilations that are carried out.
9615 @end ifset
9616 @end table
9617
9618 @noindent
9619 Source and library search path switches:
9620
9621 @table @option
9622 @c !sort!
9623 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9624 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9625 When looking for source files also look in directory @var{dir}.
9626 The order in which source files search is undertaken is
9627 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9628
9629 @item ^-aL^/SKIP_MISSING=^@var{dir}
9630 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9631 Consider @var{dir} as being an externally provided Ada library.
9632 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9633 files have been located in directory @var{dir}. This allows you to have
9634 missing bodies for the units in @var{dir} and to ignore out of date bodies
9635 for the same units. You still need to specify
9636 the location of the specs for these units by using the switches
9637 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9638 or @option{^-I^/SEARCH=^@var{dir}}.
9639 Note: this switch is provided for compatibility with previous versions
9640 of @command{gnatmake}. The easier method of causing standard libraries
9641 to be excluded from consideration is to write-protect the corresponding
9642 ALI files.
9643
9644 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9645 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9646 When searching for library and object files, look in directory
9647 @var{dir}. The order in which library files are searched is described in
9648 @ref{Search Paths for gnatbind}.
9649
9650 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9651 @cindex Search paths, for @command{gnatmake}
9652 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9653 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9654 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9655
9656 @item ^-I^/SEARCH=^@var{dir}
9657 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9658 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9659 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9660
9661 @item ^-I-^/NOCURRENT_DIRECTORY^
9662 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9663 @cindex Source files, suppressing search
9664 Do not look for source files in the directory containing the source
9665 file named in the command line.
9666 Do not look for ALI or object files in the directory
9667 where @command{gnatmake} was invoked.
9668
9669 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9670 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9671 @cindex Linker libraries
9672 Add directory @var{dir} to the list of directories in which the linker
9673 will search for libraries. This is equivalent to
9674 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9675 @ifclear vms
9676 Furthermore, under Windows, the sources pointed to by the libraries path
9677 set in the registry are not searched for.
9678 @end ifclear
9679
9680 @item -nostdinc
9681 @cindex @option{-nostdinc} (@command{gnatmake})
9682 Do not look for source files in the system default directory.
9683
9684 @item -nostdlib
9685 @cindex @option{-nostdlib} (@command{gnatmake})
9686 Do not look for library files in the system default directory.
9687
9688 @item --RTS=@var{rts-path}
9689 @cindex @option{--RTS} (@command{gnatmake})
9690 Specifies the default location of the runtime library. GNAT looks for the
9691 runtime
9692 in the following directories, and stops as soon as a valid runtime is found
9693 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9694 @file{ada_object_path} present):
9695
9696 @itemize @bullet
9697 @item <current directory>/$rts_path
9698
9699 @item <default-search-dir>/$rts_path
9700
9701 @item <default-search-dir>/rts-$rts_path
9702 @end itemize
9703
9704 @noindent
9705 The selected path is handled like a normal RTS path.
9706
9707 @end table
9708
9709 @node Mode Switches for gnatmake
9710 @section Mode Switches for @command{gnatmake}
9711
9712 @noindent
9713 The mode switches (referred to as @code{mode_switches}) allow the
9714 inclusion of switches that are to be passed to the compiler itself, the
9715 binder or the linker. The effect of a mode switch is to cause all
9716 subsequent switches up to the end of the switch list, or up to the next
9717 mode switch, to be interpreted as switches to be passed on to the
9718 designated component of GNAT.
9719
9720 @table @option
9721 @c !sort!
9722 @item -cargs @var{switches}
9723 @cindex @option{-cargs} (@command{gnatmake})
9724 Compiler switches. Here @var{switches} is a list of switches
9725 that are valid switches for @command{gcc}. They will be passed on to
9726 all compile steps performed by @command{gnatmake}.
9727
9728 @item -bargs @var{switches}
9729 @cindex @option{-bargs} (@command{gnatmake})
9730 Binder switches. Here @var{switches} is a list of switches
9731 that are valid switches for @code{gnatbind}. They will be passed on to
9732 all bind steps performed by @command{gnatmake}.
9733
9734 @item -largs @var{switches}
9735 @cindex @option{-largs} (@command{gnatmake})
9736 Linker switches. Here @var{switches} is a list of switches
9737 that are valid switches for @command{gnatlink}. They will be passed on to
9738 all link steps performed by @command{gnatmake}.
9739
9740 @item -margs @var{switches}
9741 @cindex @option{-margs} (@command{gnatmake})
9742 Make switches. The switches are directly interpreted by @command{gnatmake},
9743 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9744 or @option{-largs}.
9745 @end table
9746
9747 @node Notes on the Command Line
9748 @section Notes on the Command Line
9749
9750 @noindent
9751 This section contains some additional useful notes on the operation
9752 of the @command{gnatmake} command.
9753
9754 @itemize @bullet
9755 @item
9756 @cindex Recompilation, by @command{gnatmake}
9757 If @command{gnatmake} finds no ALI files, it recompiles the main program
9758 and all other units required by the main program.
9759 This means that @command{gnatmake}
9760 can be used for the initial compile, as well as during subsequent steps of
9761 the development cycle.
9762
9763 @item
9764 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9765 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9766 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9767 warning.
9768
9769 @item
9770 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9771 is used to specify both source and
9772 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9773 instead if you just want to specify
9774 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9775 if you want to specify library paths
9776 only.
9777
9778 @item
9779 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9780 This may conveniently be used to exclude standard libraries from
9781 consideration and in particular it means that the use of the
9782 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9783 unless @option{^-a^/ALL_FILES^} is also specified.
9784
9785 @item
9786 @command{gnatmake} has been designed to make the use of Ada libraries
9787 particularly convenient. Assume you have an Ada library organized
9788 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9789 of your Ada compilation units,
9790 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9791 specs of these units, but no bodies. Then to compile a unit
9792 stored in @code{main.adb}, which uses this Ada library you would just type
9793
9794 @smallexample
9795 @ifclear vms
9796 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9797 @end ifclear
9798 @ifset vms
9799 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9800            /SKIP_MISSING=@i{[OBJ_DIR]} main
9801 @end ifset
9802 @end smallexample
9803
9804 @item
9805 Using @command{gnatmake} along with the
9806 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9807 switch provides a mechanism for avoiding unnecessary recompilations. Using
9808 this switch,
9809 you can update the comments/format of your
9810 source files without having to recompile everything. Note, however, that
9811 adding or deleting lines in a source files may render its debugging
9812 info obsolete. If the file in question is a spec, the impact is rather
9813 limited, as that debugging info will only be useful during the
9814 elaboration phase of your program. For bodies the impact can be more
9815 significant. In all events, your debugger will warn you if a source file
9816 is more recent than the corresponding object, and alert you to the fact
9817 that the debugging information may be out of date.
9818 @end itemize
9819
9820 @node How gnatmake Works
9821 @section How @command{gnatmake} Works
9822
9823 @noindent
9824 Generally @command{gnatmake} automatically performs all necessary
9825 recompilations and you don't need to worry about how it works. However,
9826 it may be useful to have some basic understanding of the @command{gnatmake}
9827 approach and in particular to understand how it uses the results of
9828 previous compilations without incorrectly depending on them.
9829
9830 First a definition: an object file is considered @dfn{up to date} if the
9831 corresponding ALI file exists and if all the source files listed in the
9832 dependency section of this ALI file have time stamps matching those in
9833 the ALI file. This means that neither the source file itself nor any
9834 files that it depends on have been modified, and hence there is no need
9835 to recompile this file.
9836
9837 @command{gnatmake} works by first checking if the specified main unit is up
9838 to date. If so, no compilations are required for the main unit. If not,
9839 @command{gnatmake} compiles the main program to build a new ALI file that
9840 reflects the latest sources. Then the ALI file of the main unit is
9841 examined to find all the source files on which the main program depends,
9842 and @command{gnatmake} recursively applies the above procedure on all these
9843 files.
9844
9845 This process ensures that @command{gnatmake} only trusts the dependencies
9846 in an existing ALI file if they are known to be correct. Otherwise it
9847 always recompiles to determine a new, guaranteed accurate set of
9848 dependencies. As a result the program is compiled ``upside down'' from what may
9849 be more familiar as the required order of compilation in some other Ada
9850 systems. In particular, clients are compiled before the units on which
9851 they depend. The ability of GNAT to compile in any order is critical in
9852 allowing an order of compilation to be chosen that guarantees that
9853 @command{gnatmake} will recompute a correct set of new dependencies if
9854 necessary.
9855
9856 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9857 imported by several of the executables, it will be recompiled at most once.
9858
9859 Note: when using non-standard naming conventions
9860 (@pxref{Using Other File Names}), changing through a configuration pragmas
9861 file the version of a source and invoking @command{gnatmake} to recompile may
9862 have no effect, if the previous version of the source is still accessible
9863 by @command{gnatmake}. It may be necessary to use the switch
9864 ^-f^/FORCE_COMPILE^.
9865
9866 @node Examples of gnatmake Usage
9867 @section Examples of @command{gnatmake} Usage
9868
9869 @table @code
9870 @item gnatmake hello.adb
9871 Compile all files necessary to bind and link the main program
9872 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9873 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9874
9875 @item gnatmake main1 main2 main3
9876 Compile all files necessary to bind and link the main programs
9877 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9878 (containing unit @code{Main2}) and @file{main3.adb}
9879 (containing unit @code{Main3}) and bind and link the resulting object files
9880 to generate three executable files @file{^main1^MAIN1.EXE^},
9881 @file{^main2^MAIN2.EXE^}
9882 and @file{^main3^MAIN3.EXE^}.
9883
9884 @ifclear vms
9885 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9886 @end ifclear
9887
9888 @ifset vms
9889 @item gnatmake Main_Unit /QUIET
9890 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9891 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9892 @end ifset
9893 Compile all files necessary to bind and link the main program unit
9894 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9895 be done with optimization level 2 and the order of elaboration will be
9896 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9897 displaying commands it is executing.
9898 @end table
9899
9900 @c *************************
9901 @node Improving Performance
9902 @chapter Improving Performance
9903 @cindex Improving performance
9904
9905 @noindent
9906 This chapter presents several topics related to program performance.
9907 It first describes some of the tradeoffs that need to be considered
9908 and some of the techniques for making your program run faster.
9909 It then documents the @command{gnatelim} tool and unused subprogram/data
9910 elimination feature, which can reduce the size of program executables.
9911
9912 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9913 driver (see @ref{The GNAT Driver and Project Files}).
9914
9915 @ifnottex
9916 @menu
9917 * Performance Considerations::
9918 * Text_IO Suggestions::
9919 * Reducing Size of Ada Executables with gnatelim::
9920 * Reducing Size of Executables with unused subprogram/data elimination::
9921 @end menu
9922 @end ifnottex
9923
9924 @c *****************************
9925 @node Performance Considerations
9926 @section Performance Considerations
9927
9928 @noindent
9929 The GNAT system provides a number of options that allow a trade-off
9930 between
9931
9932 @itemize @bullet
9933 @item
9934 performance of the generated code
9935
9936 @item
9937 speed of compilation
9938
9939 @item
9940 minimization of dependences and recompilation
9941
9942 @item
9943 the degree of run-time checking.
9944 @end itemize
9945
9946 @noindent
9947 The defaults (if no options are selected) aim at improving the speed
9948 of compilation and minimizing dependences, at the expense of performance
9949 of the generated code:
9950
9951 @itemize @bullet
9952 @item
9953 no optimization
9954
9955 @item
9956 no inlining of subprogram calls
9957
9958 @item
9959 all run-time checks enabled except overflow and elaboration checks
9960 @end itemize
9961
9962 @noindent
9963 These options are suitable for most program development purposes. This
9964 chapter describes how you can modify these choices, and also provides
9965 some guidelines on debugging optimized code.
9966
9967 @menu
9968 * Controlling Run-Time Checks::
9969 * Use of Restrictions::
9970 * Optimization Levels::
9971 * Debugging Optimized Code::
9972 * Inlining of Subprograms::
9973 * Other Optimization Switches::
9974 * Optimization and Strict Aliasing::
9975
9976 @ifset vms
9977 * Coverage Analysis::
9978 @end ifset
9979 @end menu
9980
9981 @node Controlling Run-Time Checks
9982 @subsection Controlling Run-Time Checks
9983
9984 @noindent
9985 By default, GNAT generates all run-time checks, except integer overflow
9986 checks, stack overflow checks, and checks for access before elaboration on
9987 subprogram calls. The latter are not required in default mode, because all
9988 necessary checking is done at compile time.
9989 @cindex @option{-gnatp} (@command{gcc})
9990 @cindex @option{-gnato} (@command{gcc})
9991 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9992 be modified. @xref{Run-Time Checks}.
9993
9994 Our experience is that the default is suitable for most development
9995 purposes.
9996
9997 We treat integer overflow specially because these
9998 are quite expensive and in our experience are not as important as other
9999 run-time checks in the development process. Note that division by zero
10000 is not considered an overflow check, and divide by zero checks are
10001 generated where required by default.
10002
10003 Elaboration checks are off by default, and also not needed by default, since
10004 GNAT uses a static elaboration analysis approach that avoids the need for
10005 run-time checking. This manual contains a full chapter discussing the issue
10006 of elaboration checks, and if the default is not satisfactory for your use,
10007 you should read this chapter.
10008
10009 For validity checks, the minimal checks required by the Ada Reference
10010 Manual (for case statements and assignments to array elements) are on
10011 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10012 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10013 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10014 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10015 are also suppressed entirely if @option{-gnatp} is used.
10016
10017 @cindex Overflow checks
10018 @cindex Checks, overflow
10019 @findex Suppress
10020 @findex Unsuppress
10021 @cindex pragma Suppress
10022 @cindex pragma Unsuppress
10023 Note that the setting of the switches controls the default setting of
10024 the checks. They may be modified using either @code{pragma Suppress} (to
10025 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10026 checks) in the program source.
10027
10028 @node Use of Restrictions
10029 @subsection Use of Restrictions
10030
10031 @noindent
10032 The use of pragma Restrictions allows you to control which features are
10033 permitted in your program. Apart from the obvious point that if you avoid
10034 relatively expensive features like finalization (enforceable by the use
10035 of pragma Restrictions (No_Finalization), the use of this pragma does not
10036 affect the generated code in most cases.
10037
10038 One notable exception to this rule is that the possibility of task abort
10039 results in some distributed overhead, particularly if finalization or
10040 exception handlers are used. The reason is that certain sections of code
10041 have to be marked as non-abortable.
10042
10043 If you use neither the @code{abort} statement, nor asynchronous transfer
10044 of control (@code{select @dots{} then abort}), then this distributed overhead
10045 is removed, which may have a general positive effect in improving
10046 overall performance.  Especially code involving frequent use of tasking
10047 constructs and controlled types will show much improved performance.
10048 The relevant restrictions pragmas are
10049
10050 @smallexample @c ada
10051    pragma Restrictions (No_Abort_Statements);
10052    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10053 @end smallexample
10054
10055 @noindent
10056 It is recommended that these restriction pragmas be used if possible. Note
10057 that this also means that you can write code without worrying about the
10058 possibility of an immediate abort at any point.
10059
10060 @node Optimization Levels
10061 @subsection Optimization Levels
10062 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10063
10064 @noindent
10065 Without any optimization ^option,^qualifier,^
10066 the compiler's goal is to reduce the cost of
10067 compilation and to make debugging produce the expected results.
10068 Statements are independent: if you stop the program with a breakpoint between
10069 statements, you can then assign a new value to any variable or change
10070 the program counter to any other statement in the subprogram and get exactly
10071 the results you would expect from the source code.
10072
10073 Turning on optimization makes the compiler attempt to improve the
10074 performance and/or code size at the expense of compilation time and
10075 possibly the ability to debug the program.
10076
10077 If you use multiple
10078 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10079 the last such option is the one that is effective.
10080
10081 @noindent
10082 The default is optimization off. This results in the fastest compile
10083 times, but GNAT makes absolutely no attempt to optimize, and the
10084 generated programs are considerably larger and slower than when
10085 optimization is enabled. You can use the
10086 @ifclear vms
10087 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10088 @option{-O2}, @option{-O3}, and @option{-Os})
10089 @end ifclear
10090 @ifset vms
10091 @code{OPTIMIZE} qualifier
10092 @end ifset
10093 to @command{gcc} to control the optimization level:
10094
10095 @table @option
10096 @item ^-O0^/OPTIMIZE=NONE^
10097 No optimization (the default);
10098 generates unoptimized code but has
10099 the fastest compilation time.
10100
10101 Note that many other compilers do fairly extensive optimization
10102 even if ``no optimization'' is specified. With gcc, it is
10103 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10104 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10105 really does mean no optimization at all. This difference between
10106 gcc and other compilers should be kept in mind when doing
10107 performance comparisons.
10108
10109 @item ^-O1^/OPTIMIZE=SOME^
10110 Moderate optimization;
10111 optimizes reasonably well but does not
10112 degrade compilation time significantly.
10113
10114 @item ^-O2^/OPTIMIZE=ALL^
10115 @ifset vms
10116 @itemx /OPTIMIZE=DEVELOPMENT
10117 @end ifset
10118 Full optimization;
10119 generates highly optimized code and has
10120 the slowest compilation time.
10121
10122 @item ^-O3^/OPTIMIZE=INLINING^
10123 Full optimization as in @option{-O2};
10124 also uses more aggressive automatic inlining of subprograms within a unit
10125 (@pxref{Inlining of Subprograms}) and attemps to vectorize loops.
10126
10127 @item ^-Os^/OPTIMIZE=SPACE^
10128 Optimize space usage (code and data) of resulting program.
10129 @end table
10130
10131 @noindent
10132 Higher optimization levels perform more global transformations on the
10133 program and apply more expensive analysis algorithms in order to generate
10134 faster and more compact code. The price in compilation time, and the
10135 resulting improvement in execution time,
10136 both depend on the particular application and the hardware environment.
10137 You should experiment to find the best level for your application.
10138
10139 Since the precise set of optimizations done at each level will vary from
10140 release to release (and sometime from target to target), it is best to think
10141 of the optimization settings in general terms.
10142 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10143 the GNU Compiler Collection (GCC)}, for details about
10144 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10145 individually enable or disable specific optimizations.
10146
10147 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10148 been tested extensively at all optimization levels. There are some bugs
10149 which appear only with optimization turned on, but there have also been
10150 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10151 level of optimization does not improve the reliability of the code
10152 generator, which in practice is highly reliable at all optimization
10153 levels.
10154
10155 Note regarding the use of @option{-O3}: The use of this optimization level
10156 is generally discouraged with GNAT, since it often results in larger
10157 executables which may run more slowly. See further discussion of this point
10158 in @ref{Inlining of Subprograms}.
10159
10160 @node Debugging Optimized Code
10161 @subsection Debugging Optimized Code
10162 @cindex Debugging optimized code
10163 @cindex Optimization and debugging
10164
10165 @noindent
10166 Although it is possible to do a reasonable amount of debugging at
10167 @ifclear vms
10168 nonzero optimization levels,
10169 the higher the level the more likely that
10170 @end ifclear
10171 @ifset vms
10172 @option{/OPTIMIZE} settings other than @code{NONE},
10173 such settings will make it more likely that
10174 @end ifset
10175 source-level constructs will have been eliminated by optimization.
10176 For example, if a loop is strength-reduced, the loop
10177 control variable may be completely eliminated and thus cannot be
10178 displayed in the debugger.
10179 This can only happen at @option{-O2} or @option{-O3}.
10180 Explicit temporary variables that you code might be eliminated at
10181 ^level^setting^ @option{-O1} or higher.
10182
10183 The use of the @option{^-g^/DEBUG^} switch,
10184 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10185 which is needed for source-level debugging,
10186 affects the size of the program executable on disk,
10187 and indeed the debugging information can be quite large.
10188 However, it has no effect on the generated code (and thus does not
10189 degrade performance)
10190
10191 Since the compiler generates debugging tables for a compilation unit before
10192 it performs optimizations, the optimizing transformations may invalidate some
10193 of the debugging data.  You therefore need to anticipate certain
10194 anomalous situations that may arise while debugging optimized code.
10195 These are the most common cases:
10196
10197 @enumerate
10198 @item
10199 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10200 commands show
10201 the PC bouncing back and forth in the code.  This may result from any of
10202 the following optimizations:
10203
10204 @itemize @bullet
10205 @item
10206 @i{Common subexpression elimination:} using a single instance of code for a
10207 quantity that the source computes several times.  As a result you
10208 may not be able to stop on what looks like a statement.
10209
10210 @item
10211 @i{Invariant code motion:} moving an expression that does not change within a
10212 loop, to the beginning of the loop.
10213
10214 @item
10215 @i{Instruction scheduling:} moving instructions so as to
10216 overlap loads and stores (typically) with other code, or in
10217 general to move computations of values closer to their uses. Often
10218 this causes you to pass an assignment statement without the assignment
10219 happening and then later bounce back to the statement when the
10220 value is actually needed.  Placing a breakpoint on a line of code
10221 and then stepping over it may, therefore, not always cause all the
10222 expected side-effects.
10223 @end itemize
10224
10225 @item
10226 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10227 two identical pieces of code are merged and the program counter suddenly
10228 jumps to a statement that is not supposed to be executed, simply because
10229 it (and the code following) translates to the same thing as the code
10230 that @emph{was} supposed to be executed.  This effect is typically seen in
10231 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10232 a @code{break} in a C @code{^switch^switch^} statement.
10233
10234 @item
10235 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10236 There are various reasons for this effect:
10237
10238 @itemize @bullet
10239 @item
10240 In a subprogram prologue, a parameter may not yet have been moved to its
10241 ``home''.
10242
10243 @item
10244 A variable may be dead, and its register re-used.  This is
10245 probably the most common cause.
10246
10247 @item
10248 As mentioned above, the assignment of a value to a variable may
10249 have been moved.
10250
10251 @item
10252 A variable may be eliminated entirely by value propagation or
10253 other means.  In this case, GCC may incorrectly generate debugging
10254 information for the variable
10255 @end itemize
10256
10257 @noindent
10258 In general, when an unexpected value appears for a local variable or parameter
10259 you should first ascertain if that value was actually computed by
10260 your program, as opposed to being incorrectly reported by the debugger.
10261 Record fields or
10262 array elements in an object designated by an access value
10263 are generally less of a problem, once you have ascertained that the access
10264 value is sensible.
10265 Typically, this means checking variables in the preceding code and in the
10266 calling subprogram to verify that the value observed is explainable from other
10267 values (one must apply the procedure recursively to those
10268 other values); or re-running the code and stopping a little earlier
10269 (perhaps before the call) and stepping to better see how the variable obtained
10270 the value in question; or continuing to step @emph{from} the point of the
10271 strange value to see if code motion had simply moved the variable's
10272 assignments later.
10273 @end enumerate
10274
10275 @noindent
10276 In light of such anomalies, a recommended technique is to use @option{-O0}
10277 early in the software development cycle, when extensive debugging capabilities
10278 are most needed, and then move to @option{-O1} and later @option{-O2} as
10279 the debugger becomes less critical.
10280 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10281 a release management issue.
10282 @ifclear vms
10283 Note that if you use @option{-g} you can then use the @command{strip} program
10284 on the resulting executable,
10285 which removes both debugging information and global symbols.
10286 @end ifclear
10287
10288 @node Inlining of Subprograms
10289 @subsection Inlining of Subprograms
10290
10291 @noindent
10292 A call to a subprogram in the current unit is inlined if all the
10293 following conditions are met:
10294
10295 @itemize @bullet
10296 @item
10297 The optimization level is at least @option{-O1}.
10298
10299 @item
10300 The called subprogram is suitable for inlining: It must be small enough
10301 and not contain something that @command{gcc} cannot support in inlined
10302 subprograms.
10303
10304 @item
10305 @cindex pragma Inline
10306 @findex Inline
10307 Either @code{pragma Inline} applies to the subprogram, or it is local to
10308 the unit and called once from within it, or it is small and optimization
10309 level @option{-O2} is specified, or automatic inlining (optimization level
10310 @option{-O3}) is specified.
10311 @end itemize
10312
10313 @noindent
10314 Calls to subprograms in @code{with}'ed units are normally not inlined.
10315 To achieve actual inlining (that is, replacement of the call by the code
10316 in the body of the subprogram), the following conditions must all be true.
10317
10318 @itemize @bullet
10319 @item
10320 The optimization level is at least @option{-O1}.
10321
10322 @item
10323 The called subprogram is suitable for inlining: It must be small enough
10324 and not contain something that @command{gcc} cannot support in inlined
10325 subprograms.
10326
10327 @item
10328 The call appears in a body (not in a package spec).
10329
10330 @item
10331 There is a @code{pragma Inline} for the subprogram.
10332
10333 @item
10334 @cindex @option{-gnatn} (@command{gcc})
10335 The @option{^-gnatn^/INLINE^} switch
10336 is used in the @command{gcc} command line
10337 @end itemize
10338
10339 Even if all these conditions are met, it may not be possible for
10340 the compiler to inline the call, due to the length of the body,
10341 or features in the body that make it impossible for the compiler
10342 to do the inlining.
10343
10344 Note that specifying the @option{-gnatn} switch causes additional
10345 compilation dependencies. Consider the following:
10346
10347 @smallexample @c ada
10348 @cartouche
10349 package R is
10350    procedure Q;
10351    pragma Inline (Q);
10352 end R;
10353 package body R is
10354    @dots{}
10355 end R;
10356
10357 with R;
10358 procedure Main is
10359 begin
10360    @dots{}
10361    R.Q;
10362 end Main;
10363 @end cartouche
10364 @end smallexample
10365
10366 @noindent
10367 With the default behavior (no @option{-gnatn} switch specified), the
10368 compilation of the @code{Main} procedure depends only on its own source,
10369 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10370 means that editing the body of @code{R} does not require recompiling
10371 @code{Main}.
10372
10373 On the other hand, the call @code{R.Q} is not inlined under these
10374 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10375 is compiled, the call will be inlined if the body of @code{Q} is small
10376 enough, but now @code{Main} depends on the body of @code{R} in
10377 @file{r.adb} as well as on the spec. This means that if this body is edited,
10378 the main program must be recompiled. Note that this extra dependency
10379 occurs whether or not the call is in fact inlined by @command{gcc}.
10380
10381 The use of front end inlining with @option{-gnatN} generates similar
10382 additional dependencies.
10383
10384 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10385 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10386 can be used to prevent
10387 all inlining. This switch overrides all other conditions and ensures
10388 that no inlining occurs. The extra dependences resulting from
10389 @option{-gnatn} will still be active, even if
10390 this switch is used to suppress the resulting inlining actions.
10391
10392 @cindex @option{-fno-inline-functions} (@command{gcc})
10393 Note: The @option{-fno-inline-functions} switch can be used to prevent
10394 automatic inlining of subprograms if @option{-O3} is used.
10395
10396 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10397 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10398 automatic inlining of small subprograms if @option{-O2} is used.
10399
10400 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10401 Note: The @option{-fno-inline-functions-called-once} switch
10402 can be used to prevent inlining of subprograms local to the unit
10403 and called once from within it if @option{-O1} is used.
10404
10405 Note regarding the use of @option{-O3}: There is no difference in inlining
10406 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10407 pragma @code{Inline} assuming the use of @option{-gnatn}
10408 or @option{-gnatN} (the switches that activate inlining). If you have used
10409 pragma @code{Inline} in appropriate cases, then it is usually much better
10410 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10411 in this case only has the effect of inlining subprograms you did not
10412 think should be inlined. We often find that the use of @option{-O3} slows
10413 down code by performing excessive inlining, leading to increased instruction
10414 cache pressure from the increased code size. So the bottom line here is
10415 that you should not automatically assume that @option{-O3} is better than
10416 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10417 it actually improves performance.
10418
10419 @node Other Optimization Switches
10420 @subsection Other Optimization Switches
10421 @cindex Optimization Switches
10422
10423 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10424 @command{gcc} optimization switches are potentially usable. These switches
10425 have not been extensively tested with GNAT but can generally be expected
10426 to work. Examples of switches in this category are
10427 @option{-funroll-loops} and
10428 the various target-specific @option{-m} options (in particular, it has been
10429 observed that @option{-march=pentium4} can significantly improve performance
10430 on appropriate machines). For full details of these switches, see
10431 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10432 the GNU Compiler Collection (GCC)}.
10433
10434 @node Optimization and Strict Aliasing
10435 @subsection Optimization and Strict Aliasing
10436 @cindex Aliasing
10437 @cindex Strict Aliasing
10438 @cindex No_Strict_Aliasing
10439
10440 @noindent
10441 The strong typing capabilities of Ada allow an optimizer to generate
10442 efficient code in situations where other languages would be forced to
10443 make worst case assumptions preventing such optimizations. Consider
10444 the following example:
10445
10446 @smallexample @c ada
10447 @cartouche
10448 procedure R is
10449    type Int1 is new Integer;
10450    type Int2 is new Integer;
10451    type Int1A is access Int1;
10452    type Int2A is access Int2;
10453    Int1V : Int1A;
10454    Int2V : Int2A;
10455    @dots{}
10456
10457 begin
10458    @dots{}
10459    for J in Data'Range loop
10460       if Data (J) = Int1V.all then
10461          Int2V.all := Int2V.all + 1;
10462       end if;
10463    end loop;
10464    @dots{}
10465 end R;
10466 @end cartouche
10467 @end smallexample
10468
10469 @noindent
10470 In this example, since the variable @code{Int1V} can only access objects
10471 of type @code{Int1}, and @code{Int2V} can only access objects of type
10472 @code{Int2}, there is no possibility that the assignment to
10473 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10474 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10475 for all iterations of the loop and avoid the extra memory reference
10476 required to dereference it each time through the loop.
10477
10478 This kind of optimization, called strict aliasing analysis, is
10479 triggered by specifying an optimization level of @option{-O2} or
10480 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10481 when access values are involved.
10482
10483 However, although this optimization is always correct in terms of
10484 the formal semantics of the Ada Reference Manual, difficulties can
10485 arise if features like @code{Unchecked_Conversion} are used to break
10486 the typing system. Consider the following complete program example:
10487
10488 @smallexample @c ada
10489 @cartouche
10490 package p1 is
10491    type int1 is new integer;
10492    type int2 is new integer;
10493    type a1 is access int1;
10494    type a2 is access int2;
10495 end p1;
10496
10497 with p1; use p1;
10498 package p2 is
10499    function to_a2 (Input : a1) return a2;
10500 end p2;
10501
10502 with Unchecked_Conversion;
10503 package body p2 is
10504    function to_a2 (Input : a1) return a2 is
10505       function to_a2u is
10506         new Unchecked_Conversion (a1, a2);
10507    begin
10508       return to_a2u (Input);
10509    end to_a2;
10510 end p2;
10511
10512 with p2; use p2;
10513 with p1; use p1;
10514 with Text_IO; use Text_IO;
10515 procedure m is
10516    v1 : a1 := new int1;
10517    v2 : a2 := to_a2 (v1);
10518 begin
10519    v1.all := 1;
10520    v2.all := 0;
10521    put_line (int1'image (v1.all));
10522 end;
10523 @end cartouche
10524 @end smallexample
10525
10526 @noindent
10527 This program prints out 0 in @option{-O0} or @option{-O1}
10528 mode, but it prints out 1 in @option{-O2} mode. That's
10529 because in strict aliasing mode, the compiler can and
10530 does assume that the assignment to @code{v2.all} could not
10531 affect the value of @code{v1.all}, since different types
10532 are involved.
10533
10534 This behavior is not a case of non-conformance with the standard, since
10535 the Ada RM specifies that an unchecked conversion where the resulting
10536 bit pattern is not a correct value of the target type can result in an
10537 abnormal value and attempting to reference an abnormal value makes the
10538 execution of a program erroneous.  That's the case here since the result
10539 does not point to an object of type @code{int2}.  This means that the
10540 effect is entirely unpredictable.
10541
10542 However, although that explanation may satisfy a language
10543 lawyer, in practice an applications programmer expects an
10544 unchecked conversion involving pointers to create true
10545 aliases and the behavior of printing 1 seems plain wrong.
10546 In this case, the strict aliasing optimization is unwelcome.
10547
10548 Indeed the compiler recognizes this possibility, and the
10549 unchecked conversion generates a warning:
10550
10551 @smallexample
10552 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10553 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10554 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10555 @end smallexample
10556
10557 @noindent
10558 Unfortunately the problem is recognized when compiling the body of
10559 package @code{p2}, but the actual "bad" code is generated while
10560 compiling the body of @code{m} and this latter compilation does not see
10561 the suspicious @code{Unchecked_Conversion}.
10562
10563 As implied by the warning message, there are approaches you can use to
10564 avoid the unwanted strict aliasing optimization in a case like this.
10565
10566 One possibility is to simply avoid the use of @option{-O2}, but
10567 that is a bit drastic, since it throws away a number of useful
10568 optimizations that do not involve strict aliasing assumptions.
10569
10570 A less drastic approach is to compile the program using the
10571 option @option{-fno-strict-aliasing}. Actually it is only the
10572 unit containing the dereferencing of the suspicious pointer
10573 that needs to be compiled. So in this case, if we compile
10574 unit @code{m} with this switch, then we get the expected
10575 value of zero printed. Analyzing which units might need
10576 the switch can be painful, so a more reasonable approach
10577 is to compile the entire program with options @option{-O2}
10578 and @option{-fno-strict-aliasing}. If the performance is
10579 satisfactory with this combination of options, then the
10580 advantage is that the entire issue of possible "wrong"
10581 optimization due to strict aliasing is avoided.
10582
10583 To avoid the use of compiler switches, the configuration
10584 pragma @code{No_Strict_Aliasing} with no parameters may be
10585 used to specify that for all access types, the strict
10586 aliasing optimization should be suppressed.
10587
10588 However, these approaches are still overkill, in that they causes
10589 all manipulations of all access values to be deoptimized. A more
10590 refined approach is to concentrate attention on the specific
10591 access type identified as problematic.
10592
10593 First, if a careful analysis of uses of the pointer shows
10594 that there are no possible problematic references, then
10595 the warning can be suppressed by bracketing the
10596 instantiation of @code{Unchecked_Conversion} to turn
10597 the warning off:
10598
10599 @smallexample @c ada
10600    pragma Warnings (Off);
10601    function to_a2u is
10602      new Unchecked_Conversion (a1, a2);
10603    pragma Warnings (On);
10604 @end smallexample
10605
10606 @noindent
10607 Of course that approach is not appropriate for this particular
10608 example, since indeed there is a problematic reference. In this
10609 case we can take one of two other approaches.
10610
10611 The first possibility is to move the instantiation of unchecked
10612 conversion to the unit in which the type is declared. In
10613 this example, we would move the instantiation of
10614 @code{Unchecked_Conversion} from the body of package
10615 @code{p2} to the spec of package @code{p1}. Now the
10616 warning disappears. That's because any use of the
10617 access type knows there is a suspicious unchecked
10618 conversion, and the strict aliasing optimization
10619 is automatically suppressed for the type.
10620
10621 If it is not practical to move the unchecked conversion to the same unit
10622 in which the destination access type is declared (perhaps because the
10623 source type is not visible in that unit), you may use pragma
10624 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10625 same declarative sequence as the declaration of the access type:
10626
10627 @smallexample @c ada
10628    type a2 is access int2;
10629    pragma No_Strict_Aliasing (a2);
10630 @end smallexample
10631
10632 @noindent
10633 Here again, the compiler now knows that the strict aliasing optimization
10634 should be suppressed for any reference to type @code{a2} and the
10635 expected behavior is obtained.
10636
10637 Finally, note that although the compiler can generate warnings for
10638 simple cases of unchecked conversions, there are tricker and more
10639 indirect ways of creating type incorrect aliases which the compiler
10640 cannot detect. Examples are the use of address overlays and unchecked
10641 conversions involving composite types containing access types as
10642 components. In such cases, no warnings are generated, but there can
10643 still be aliasing problems. One safe coding practice is to forbid the
10644 use of address clauses for type overlaying, and to allow unchecked
10645 conversion only for primitive types. This is not really a significant
10646 restriction since any possible desired effect can be achieved by
10647 unchecked conversion of access values.
10648
10649 The aliasing analysis done in strict aliasing mode can certainly
10650 have significant benefits. We have seen cases of large scale
10651 application code where the time is increased by up to 5% by turning
10652 this optimization off. If you have code that includes significant
10653 usage of unchecked conversion, you might want to just stick with
10654 @option{-O1} and avoid the entire issue. If you get adequate
10655 performance at this level of optimization level, that's probably
10656 the safest approach. If tests show that you really need higher
10657 levels of optimization, then you can experiment with @option{-O2}
10658 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10659 has on size and speed of the code. If you really need to use
10660 @option{-O2} with strict aliasing in effect, then you should
10661 review any uses of unchecked conversion of access types,
10662 particularly if you are getting the warnings described above.
10663
10664 @ifset vms
10665 @node Coverage Analysis
10666 @subsection Coverage Analysis
10667
10668 @noindent
10669 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10670 the user to determine the distribution of execution time across a program,
10671 @pxref{Profiling} for details of usage.
10672 @end ifset
10673
10674
10675 @node Text_IO Suggestions
10676 @section @code{Text_IO} Suggestions
10677 @cindex @code{Text_IO} and performance
10678
10679 @noindent
10680 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10681 the requirement of maintaining page and line counts. If performance
10682 is critical, a recommendation is to use @code{Stream_IO} instead of
10683 @code{Text_IO} for volume output, since this package has less overhead.
10684
10685 If @code{Text_IO} must be used, note that by default output to the standard
10686 output and standard error files is unbuffered (this provides better
10687 behavior when output statements are used for debugging, or if the
10688 progress of a program is observed by tracking the output, e.g. by
10689 using the Unix @command{tail -f} command to watch redirected output.
10690
10691 If you are generating large volumes of output with @code{Text_IO} and
10692 performance is an important factor, use a designated file instead
10693 of the standard output file, or change the standard output file to
10694 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10695
10696
10697
10698 @node Reducing Size of Ada Executables with gnatelim
10699 @section Reducing Size of Ada Executables with @code{gnatelim}
10700 @findex gnatelim
10701
10702 @noindent
10703 This section describes @command{gnatelim}, a tool which detects unused
10704 subprograms and helps the compiler to create a smaller executable for your
10705 program.
10706
10707 @menu
10708 * About gnatelim::
10709 * Running gnatelim::
10710 * Processing Precompiled Libraries::
10711 * Correcting the List of Eliminate Pragmas::
10712 * Making Your Executables Smaller::
10713 * Summary of the gnatelim Usage Cycle::
10714 @end menu
10715
10716 @node About gnatelim
10717 @subsection About @code{gnatelim}
10718
10719 @noindent
10720 When a program shares a set of Ada
10721 packages with other programs, it may happen that this program uses
10722 only a fraction of the subprograms defined in these packages. The code
10723 created for these unused subprograms increases the size of the executable.
10724
10725 @code{gnatelim} tracks unused subprograms in an Ada program and
10726 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10727 subprograms that are declared but never called. By placing the list of
10728 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10729 recompiling your program, you may decrease the size of its executable,
10730 because the compiler will not generate the code for 'eliminated' subprograms.
10731 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10732 information about this pragma.
10733
10734 @code{gnatelim} needs as its input data the name of the main subprogram.
10735
10736 If a set of source files is specified as @code{gnatelim} arguments, it
10737 treats these files as a complete set of sources making up a program to
10738 analyse, and analyses only these sources.
10739
10740 After a full successful build of the main subprogram @code{gnatelim} can be
10741 called without  specifying sources to analyse, in this case it computes
10742 the source closure of the main unit from the @file{ALI} files.
10743
10744 The following command will create the set of @file{ALI} files needed for
10745 @code{gnatelim}:
10746
10747 @smallexample
10748 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10749 @end smallexample
10750
10751 Note that @code{gnatelim} does not need object files.
10752
10753 @node Running gnatelim
10754 @subsection Running @code{gnatelim}
10755
10756 @noindent
10757 @code{gnatelim} has the following command-line interface:
10758
10759 @smallexample
10760 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10761 @end smallexample
10762
10763 @noindent
10764 @var{main_unit_name} should be a name of a source file that contains the main
10765 subprogram of a program (partition).
10766
10767 Each @var{filename} is the name (including the extension) of a source
10768 file to process. ``Wildcards'' are allowed, and
10769 the file name may contain path information.
10770
10771 @samp{@var{gcc_switches}} is a list of switches for
10772 @command{gcc}. They will be passed on to all compiler invocations made by
10773 @command{gnatelim} to generate the ASIS trees. Here you can provide
10774 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10775 use the @option{-gnatec} switch to set the configuration file,
10776 use the @option{-gnat05} switch if sources should be compiled in
10777 Ada 2005 mode etc.
10778
10779 @code{gnatelim} has the following switches:
10780
10781 @table @option
10782 @c !sort!
10783 @item ^-files^/FILES^=@var{filename}
10784 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10785 Take the argument source files from the specified file. This file should be an
10786 ordinary text file containing file names separated by spaces or
10787 line breaks. You can use this switch more than once in the same call to
10788 @command{gnatelim}. You also can combine this switch with
10789 an explicit list of files.
10790
10791 @item ^-log^/LOG^
10792 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10793 Duplicate all the output sent to @file{stderr} into a log file. The log file
10794 is named @file{gnatelim.log} and is located in the current directory.
10795
10796 @item ^-log^/LOGFILE^=@var{filename}
10797 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10798 Duplicate all the output sent to @file{stderr} into a specified log file.
10799
10800 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10801 @item ^--no-elim-dispatch^/NO_DISPATCH^
10802 Do not generate pragmas for dispatching operations.
10803
10804 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10805 @item ^-o^/OUTPUT^=@var{report_file}
10806 Put @command{gnatelim} output into a specified file. If this file already exists,
10807 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10808 into @file{stderr}
10809
10810 @item ^-q^/QUIET^
10811 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10812 Quiet mode: by default @code{gnatelim} outputs to the standard error
10813 stream the number of program units left to be processed. This option turns
10814 this trace off.
10815
10816 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10817 @item ^-t^/TIME^
10818 Print out execution time.
10819
10820 @item ^-v^/VERBOSE^
10821 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10822 Verbose mode: @code{gnatelim} version information is printed as Ada
10823 comments to the standard output stream. Also, in addition to the number of
10824 program units left @code{gnatelim} will output the name of the current unit
10825 being processed.
10826
10827 @item ^-wq^/WARNINGS=QUIET^
10828 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10829 Quet warning mode - some warnings are suppressed. In particular warnings that
10830 indicate that the analysed set of sources is incomplete to make up a
10831 partition and that some subprogram bodies are missing are not generated.
10832 @end table
10833
10834 @node Processing Precompiled Libraries
10835 @subsection Processing Precompiled Libraries
10836
10837 @noindent
10838 If some program uses a precompiled Ada library, it can be processed by
10839 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10840 Eliminate pragma for a subprogram if the body of this subprogram has not
10841 been analysed, this is a typical case for subprograms from precompiled
10842 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10843 warnings about missing source files and non-analyzed subprogram bodies
10844 that can be generated when processing precompiled Ada libraries.
10845
10846 @node Correcting the List of Eliminate Pragmas
10847 @subsection Correcting the List of Eliminate Pragmas
10848
10849 @noindent
10850 In some rare cases @code{gnatelim} may try to eliminate
10851 subprograms that are actually called in the program. In this case, the
10852 compiler will generate an error message of the form:
10853
10854 @smallexample
10855 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10856 @end smallexample
10857
10858 @noindent
10859 You will need to manually remove the wrong @code{Eliminate} pragmas from
10860 the configuration file indicated in the error message. You should recompile
10861 your program from scratch after that, because you need a consistent
10862 configuration file(s) during the entire compilation.
10863
10864 @node Making Your Executables Smaller
10865 @subsection Making Your Executables Smaller
10866
10867 @noindent
10868 In order to get a smaller executable for your program you now have to
10869 recompile the program completely with the configuration file containing
10870 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10871 @file{gnat.adc} file located in your current directory, just do:
10872
10873 @smallexample
10874 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10875 @end smallexample
10876
10877 @noindent
10878 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10879 recompile everything
10880 with the set of pragmas @code{Eliminate} that you have obtained with
10881 @command{gnatelim}).
10882
10883 Be aware that the set of @code{Eliminate} pragmas is specific to each
10884 program. It is not recommended to merge sets of @code{Eliminate}
10885 pragmas created for different programs in one configuration file.
10886
10887 @node Summary of the gnatelim Usage Cycle
10888 @subsection Summary of the @code{gnatelim} Usage Cycle
10889
10890 @noindent
10891 Here is a quick summary of the steps to be taken in order to reduce
10892 the size of your executables with @code{gnatelim}. You may use
10893 other GNAT options to control the optimization level,
10894 to produce the debugging information, to set search path, etc.
10895
10896 @enumerate
10897 @item
10898 Create a complete set of @file{ALI} files (if the program has not been
10899 built already)
10900
10901 @smallexample
10902 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10903 @end smallexample
10904
10905 @item
10906 Generate a list of @code{Eliminate} pragmas in default configuration file
10907 @file{gnat.adc} in the current directory
10908 @smallexample
10909 @ifset vms
10910 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10911 @end ifset
10912 @ifclear vms
10913 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10914 @end ifclear
10915 @end smallexample
10916
10917 @item
10918 Recompile the application
10919
10920 @smallexample
10921 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10922 @end smallexample
10923
10924 @end enumerate
10925
10926 @node Reducing Size of Executables with unused subprogram/data elimination
10927 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10928 @findex unused subprogram/data elimination
10929
10930 @noindent
10931 This section describes how you can eliminate unused subprograms and data from
10932 your executable just by setting options at compilation time.
10933
10934 @menu
10935 * About unused subprogram/data elimination::
10936 * Compilation options::
10937 * Example of unused subprogram/data elimination::
10938 @end menu
10939
10940 @node About unused subprogram/data elimination
10941 @subsection About unused subprogram/data elimination
10942
10943 @noindent
10944 By default, an executable contains all code and data of its composing objects
10945 (directly linked or coming from statically linked libraries), even data or code
10946 never used by this executable.
10947
10948 This feature will allow you to eliminate such unused code from your
10949 executable, making it smaller (in disk and in memory).
10950
10951 This functionality is available on all Linux platforms except for the IA-64
10952 architecture and on all cross platforms using the ELF binary file format.
10953 In both cases GNU binutils version 2.16 or later are required to enable it.
10954
10955 @node Compilation options
10956 @subsection Compilation options
10957
10958 @noindent
10959 The operation of eliminating the unused code and data from the final executable
10960 is directly performed by the linker.
10961
10962 In order to do this, it has to work with objects compiled with the
10963 following options:
10964 @option{-ffunction-sections} @option{-fdata-sections}.
10965 @cindex @option{-ffunction-sections} (@command{gcc})
10966 @cindex @option{-fdata-sections} (@command{gcc})
10967 These options are usable with C and Ada files.
10968 They will place respectively each
10969 function or data in a separate section in the resulting object file.
10970
10971 Once the objects and static libraries are created with these options, the
10972 linker can perform the dead code elimination. You can do this by setting
10973 the @option{-Wl,--gc-sections} option to gcc command or in the
10974 @option{-largs} section of @command{gnatmake}. This will perform a
10975 garbage collection of code and data never referenced.
10976
10977 If the linker performs a partial link (@option{-r} ld linker option), then you
10978 will need to provide one or several entry point using the
10979 @option{-e} / @option{--entry} ld option.
10980
10981 Note that objects compiled without the @option{-ffunction-sections} and
10982 @option{-fdata-sections} options can still be linked with the executable.
10983 However, no dead code elimination will be performed on those objects (they will
10984 be linked as is).
10985
10986 The GNAT static library is now compiled with -ffunction-sections and
10987 -fdata-sections on some platforms. This allows you to eliminate the unused code
10988 and data of the GNAT library from your executable.
10989
10990 @node Example of unused subprogram/data elimination
10991 @subsection Example of unused subprogram/data elimination
10992
10993 @noindent
10994 Here is a simple example:
10995
10996 @smallexample @c ada
10997 with Aux;
10998
10999 procedure Test is
11000 begin
11001    Aux.Used (10);
11002 end Test;
11003
11004 package Aux is
11005    Used_Data   : Integer;
11006    Unused_Data : Integer;
11007
11008    procedure Used   (Data : Integer);
11009    procedure Unused (Data : Integer);
11010 end Aux;
11011
11012 package body Aux is
11013    procedure Used (Data : Integer) is
11014    begin
11015       Used_Data := Data;
11016    end Used;
11017
11018    procedure Unused (Data : Integer) is
11019    begin
11020       Unused_Data := Data;
11021    end Unused;
11022 end Aux;
11023 @end smallexample
11024
11025 @noindent
11026 @code{Unused} and @code{Unused_Data} are never referenced in this code
11027 excerpt, and hence they may be safely removed from the final executable.
11028
11029 @smallexample
11030 $ gnatmake test
11031
11032 $ nm test | grep used
11033 020015f0 T aux__unused
11034 02005d88 B aux__unused_data
11035 020015cc T aux__used
11036 02005d84 B aux__used_data
11037
11038 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11039      -largs -Wl,--gc-sections
11040
11041 $ nm test | grep used
11042 02005350 T aux__used
11043 0201ffe0 B aux__used_data
11044 @end smallexample
11045
11046 @noindent
11047 It can be observed that the procedure @code{Unused} and the object
11048 @code{Unused_Data} are removed by the linker when using the
11049 appropriate options.
11050
11051 @c ********************************
11052 @node Renaming Files Using gnatchop
11053 @chapter Renaming Files Using @code{gnatchop}
11054 @findex gnatchop
11055
11056 @noindent
11057 This chapter discusses how to handle files with multiple units by using
11058 the @code{gnatchop} utility. This utility is also useful in renaming
11059 files to meet the standard GNAT default file naming conventions.
11060
11061 @menu
11062 * Handling Files with Multiple Units::
11063 * Operating gnatchop in Compilation Mode::
11064 * Command Line for gnatchop::
11065 * Switches for gnatchop::
11066 * Examples of gnatchop Usage::
11067 @end menu
11068
11069 @node Handling Files with Multiple Units
11070 @section Handling Files with Multiple Units
11071
11072 @noindent
11073 The basic compilation model of GNAT requires that a file submitted to the
11074 compiler have only one unit and there be a strict correspondence
11075 between the file name and the unit name.
11076
11077 The @code{gnatchop} utility allows both of these rules to be relaxed,
11078 allowing GNAT to process files which contain multiple compilation units
11079 and files with arbitrary file names. @code{gnatchop}
11080 reads the specified file and generates one or more output files,
11081 containing one unit per file. The unit and the file name correspond,
11082 as required by GNAT.
11083
11084 If you want to permanently restructure a set of ``foreign'' files so that
11085 they match the GNAT rules, and do the remaining development using the
11086 GNAT structure, you can simply use @command{gnatchop} once, generate the
11087 new set of files and work with them from that point on.
11088
11089 Alternatively, if you want to keep your files in the ``foreign'' format,
11090 perhaps to maintain compatibility with some other Ada compilation
11091 system, you can set up a procedure where you use @command{gnatchop} each
11092 time you compile, regarding the source files that it writes as temporary
11093 files that you throw away.
11094
11095 Note that if your file containing multiple units starts with a byte order
11096 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11097 will each start with a copy of this BOM, meaning that they can be compiled
11098 automatically in UTF-8 mode without needing to specify an explicit encoding.
11099
11100 @node Operating gnatchop in Compilation Mode
11101 @section Operating gnatchop in Compilation Mode
11102
11103 @noindent
11104 The basic function of @code{gnatchop} is to take a file with multiple units
11105 and split it into separate files. The boundary between files is reasonably
11106 clear, except for the issue of comments and pragmas. In default mode, the
11107 rule is that any pragmas between units belong to the previous unit, except
11108 that configuration pragmas always belong to the following unit. Any comments
11109 belong to the following unit. These rules
11110 almost always result in the right choice of
11111 the split point without needing to mark it explicitly and most users will
11112 find this default to be what they want. In this default mode it is incorrect to
11113 submit a file containing only configuration pragmas, or one that ends in
11114 configuration pragmas, to @code{gnatchop}.
11115
11116 However, using a special option to activate ``compilation mode'',
11117 @code{gnatchop}
11118 can perform another function, which is to provide exactly the semantics
11119 required by the RM for handling of configuration pragmas in a compilation.
11120 In the absence of configuration pragmas (at the main file level), this
11121 option has no effect, but it causes such configuration pragmas to be handled
11122 in a quite different manner.
11123
11124 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11125 only configuration pragmas, then this file is appended to the
11126 @file{gnat.adc} file in the current directory. This behavior provides
11127 the required behavior described in the RM for the actions to be taken
11128 on submitting such a file to the compiler, namely that these pragmas
11129 should apply to all subsequent compilations in the same compilation
11130 environment. Using GNAT, the current directory, possibly containing a
11131 @file{gnat.adc} file is the representation
11132 of a compilation environment. For more information on the
11133 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11134
11135 Second, in compilation mode, if @code{gnatchop}
11136 is given a file that starts with
11137 configuration pragmas, and contains one or more units, then these
11138 configuration pragmas are prepended to each of the chopped files. This
11139 behavior provides the required behavior described in the RM for the
11140 actions to be taken on compiling such a file, namely that the pragmas
11141 apply to all units in the compilation, but not to subsequently compiled
11142 units.
11143
11144 Finally, if configuration pragmas appear between units, they are appended
11145 to the previous unit. This results in the previous unit being illegal,
11146 since the compiler does not accept configuration pragmas that follow
11147 a unit. This provides the required RM behavior that forbids configuration
11148 pragmas other than those preceding the first compilation unit of a
11149 compilation.
11150
11151 For most purposes, @code{gnatchop} will be used in default mode. The
11152 compilation mode described above is used only if you need exactly
11153 accurate behavior with respect to compilations, and you have files
11154 that contain multiple units and configuration pragmas. In this
11155 circumstance the use of @code{gnatchop} with the compilation mode
11156 switch provides the required behavior, and is for example the mode
11157 in which GNAT processes the ACVC tests.
11158
11159 @node Command Line for gnatchop
11160 @section Command Line for @code{gnatchop}
11161
11162 @noindent
11163 The @code{gnatchop} command has the form:
11164
11165 @smallexample
11166 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11167 @c      @ovar{directory}
11168 @c Expanding @ovar macro inline (explanation in macro def comments)
11169 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11170       @r{[}@var{directory}@r{]}
11171 @end smallexample
11172
11173 @noindent
11174 The only required argument is the file name of the file to be chopped.
11175 There are no restrictions on the form of this file name. The file itself
11176 contains one or more Ada units, in normal GNAT format, concatenated
11177 together. As shown, more than one file may be presented to be chopped.
11178
11179 When run in default mode, @code{gnatchop} generates one output file in
11180 the current directory for each unit in each of the files.
11181
11182 @var{directory}, if specified, gives the name of the directory to which
11183 the output files will be written. If it is not specified, all files are
11184 written to the current directory.
11185
11186 For example, given a
11187 file called @file{hellofiles} containing
11188
11189 @smallexample @c ada
11190 @group
11191 @cartouche
11192 procedure hello;
11193
11194 with Text_IO; use Text_IO;
11195 procedure hello is
11196 begin
11197    Put_Line ("Hello");
11198 end hello;
11199 @end cartouche
11200 @end group
11201 @end smallexample
11202
11203 @noindent
11204 the command
11205
11206 @smallexample
11207 $ gnatchop ^hellofiles^HELLOFILES.^
11208 @end smallexample
11209
11210 @noindent
11211 generates two files in the current directory, one called
11212 @file{hello.ads} containing the single line that is the procedure spec,
11213 and the other called @file{hello.adb} containing the remaining text. The
11214 original file is not affected. The generated files can be compiled in
11215 the normal manner.
11216
11217 @noindent
11218 When gnatchop is invoked on a file that is empty or that contains only empty
11219 lines and/or comments, gnatchop will not fail, but will not produce any
11220 new sources.
11221
11222 For example, given a
11223 file called @file{toto.txt} containing
11224
11225 @smallexample @c ada
11226 @group
11227 @cartouche
11228 --  Just a comment
11229 @end cartouche
11230 @end group
11231 @end smallexample
11232
11233 @noindent
11234 the command
11235
11236 @smallexample
11237 $ gnatchop ^toto.txt^TOT.TXT^
11238 @end smallexample
11239
11240 @noindent
11241 will not produce any new file and will result in the following warnings:
11242
11243 @smallexample
11244 toto.txt:1:01: warning: empty file, contains no compilation units
11245 no compilation units found
11246 no source files written
11247 @end smallexample
11248
11249 @node Switches for gnatchop
11250 @section Switches for @code{gnatchop}
11251
11252 @noindent
11253 @command{gnatchop} recognizes the following switches:
11254
11255 @table @option
11256 @c !sort!
11257
11258 @item --version
11259 @cindex @option{--version} @command{gnatchop}
11260 Display Copyright and version, then exit disregarding all other options.
11261
11262 @item --help
11263 @cindex @option{--help} @command{gnatchop}
11264 If @option{--version} was not used, display usage, then exit disregarding
11265 all other options.
11266
11267 @item ^-c^/COMPILATION^
11268 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11269 Causes @code{gnatchop} to operate in compilation mode, in which
11270 configuration pragmas are handled according to strict RM rules. See
11271 previous section for a full description of this mode.
11272
11273 @ifclear vms
11274 @item -gnat@var{xxx}
11275 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11276 used to parse the given file. Not all @var{xxx} options make sense,
11277 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11278 process a source file that uses Latin-2 coding for identifiers.
11279 @end ifclear
11280
11281 @item ^-h^/HELP^
11282 Causes @code{gnatchop} to generate a brief help summary to the standard
11283 output file showing usage information.
11284
11285 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11286 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11287 Limit generated file names to the specified number @code{mm}
11288 of characters.
11289 This is useful if the
11290 resulting set of files is required to be interoperable with systems
11291 which limit the length of file names.
11292 @ifset vms
11293 If no value is given, or
11294 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11295 a default of 39, suitable for OpenVMS Alpha
11296 Systems, is assumed
11297 @end ifset
11298 @ifclear vms
11299 No space is allowed between the @option{-k} and the numeric value. The numeric
11300 value may be omitted in which case a default of @option{-k8},
11301 suitable for use
11302 with DOS-like file systems, is used. If no @option{-k} switch
11303 is present then
11304 there is no limit on the length of file names.
11305 @end ifclear
11306
11307 @item ^-p^/PRESERVE^
11308 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11309 Causes the file ^modification^creation^ time stamp of the input file to be
11310 preserved and used for the time stamp of the output file(s). This may be
11311 useful for preserving coherency of time stamps in an environment where
11312 @code{gnatchop} is used as part of a standard build process.
11313
11314 @item ^-q^/QUIET^
11315 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11316 Causes output of informational messages indicating the set of generated
11317 files to be suppressed. Warnings and error messages are unaffected.
11318
11319 @item ^-r^/REFERENCE^
11320 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11321 @findex Source_Reference
11322 Generate @code{Source_Reference} pragmas. Use this switch if the output
11323 files are regarded as temporary and development is to be done in terms
11324 of the original unchopped file. This switch causes
11325 @code{Source_Reference} pragmas to be inserted into each of the
11326 generated files to refers back to the original file name and line number.
11327 The result is that all error messages refer back to the original
11328 unchopped file.
11329 In addition, the debugging information placed into the object file (when
11330 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11331 specified)
11332 also refers back to this original file so that tools like profilers and
11333 debuggers will give information in terms of the original unchopped file.
11334
11335 If the original file to be chopped itself contains
11336 a @code{Source_Reference}
11337 pragma referencing a third file, then gnatchop respects
11338 this pragma, and the generated @code{Source_Reference} pragmas
11339 in the chopped file refer to the original file, with appropriate
11340 line numbers. This is particularly useful when @code{gnatchop}
11341 is used in conjunction with @code{gnatprep} to compile files that
11342 contain preprocessing statements and multiple units.
11343
11344 @item ^-v^/VERBOSE^
11345 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11346 Causes @code{gnatchop} to operate in verbose mode. The version
11347 number and copyright notice are output, as well as exact copies of
11348 the gnat1 commands spawned to obtain the chop control information.
11349
11350 @item ^-w^/OVERWRITE^
11351 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11352 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11353 fatal error if there is already a file with the same name as a
11354 file it would otherwise output, in other words if the files to be
11355 chopped contain duplicated units. This switch bypasses this
11356 check, and causes all but the last instance of such duplicated
11357 units to be skipped.
11358
11359 @ifclear vms
11360 @item --GCC=@var{xxxx}
11361 @cindex @option{--GCC=} (@code{gnatchop})
11362 Specify the path of the GNAT parser to be used. When this switch is used,
11363 no attempt is made to add the prefix to the GNAT parser executable.
11364 @end ifclear
11365 @end table
11366
11367 @node Examples of gnatchop Usage
11368 @section Examples of @code{gnatchop} Usage
11369
11370 @table @code
11371 @ifset vms
11372 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11373 @end ifset
11374 @ifclear vms
11375 @item gnatchop -w hello_s.ada prerelease/files
11376 @end ifclear
11377
11378 Chops the source file @file{hello_s.ada}. The output files will be
11379 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11380 overwriting any
11381 files with matching names in that directory (no files in the current
11382 directory are modified).
11383
11384 @item gnatchop ^archive^ARCHIVE.^
11385 Chops the source file @file{^archive^ARCHIVE.^}
11386 into the current directory. One
11387 useful application of @code{gnatchop} is in sending sets of sources
11388 around, for example in email messages. The required sources are simply
11389 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11390 command), and then
11391 @command{gnatchop} is used at the other end to reconstitute the original
11392 file names.
11393
11394 @item gnatchop file1 file2 file3 direc
11395 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11396 the resulting files in the directory @file{direc}. Note that if any units
11397 occur more than once anywhere within this set of files, an error message
11398 is generated, and no files are written. To override this check, use the
11399 @option{^-w^/OVERWRITE^} switch,
11400 in which case the last occurrence in the last file will
11401 be the one that is output, and earlier duplicate occurrences for a given
11402 unit will be skipped.
11403 @end table
11404
11405 @node Configuration Pragmas
11406 @chapter Configuration Pragmas
11407 @cindex Configuration pragmas
11408 @cindex Pragmas, configuration
11409
11410 @noindent
11411 Configuration pragmas include those pragmas described as
11412 such in the Ada Reference Manual, as well as
11413 implementation-dependent pragmas that are configuration pragmas.
11414 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11415 for details on these additional GNAT-specific configuration pragmas.
11416 Most notably, the pragma @code{Source_File_Name}, which allows
11417 specifying non-default names for source files, is a configuration
11418 pragma. The following is a complete list of configuration pragmas
11419 recognized by GNAT:
11420
11421 @smallexample
11422    Ada_83
11423    Ada_95
11424    Ada_05
11425    Ada_2005
11426    Ada_12
11427    Ada_2012
11428    Assertion_Policy
11429    Assume_No_Invalid_Values
11430    C_Pass_By_Copy
11431    Check_Name
11432    Check_Policy
11433    Compile_Time_Error
11434    Compile_Time_Warning
11435    Compiler_Unit
11436    Component_Alignment
11437    Convention_Identifier
11438    Debug_Policy
11439    Detect_Blocking
11440    Discard_Names
11441    Elaboration_Checks
11442    Eliminate
11443    Extend_System
11444    Extensions_Allowed
11445    External_Name_Casing
11446    Fast_Math
11447    Favor_Top_Level
11448    Float_Representation
11449    Implicit_Packing
11450    Initialize_Scalars
11451    Interrupt_State
11452    License
11453    Locking_Policy
11454    Long_Float
11455    No_Run_Time
11456    No_Strict_Aliasing
11457    Normalize_Scalars
11458    Optimize_Alignment
11459    Persistent_BSS
11460    Polling
11461    Priority_Specific_Dispatching
11462    Profile
11463    Profile_Warnings
11464    Propagate_Exceptions
11465    Queuing_Policy
11466    Ravenscar
11467    Restricted_Run_Time
11468    Restrictions
11469    Restrictions_Warnings
11470    Reviewable
11471    Short_Circuit_And_Or
11472    Source_File_Name
11473    Source_File_Name_Project
11474    Style_Checks
11475    Suppress
11476    Suppress_Exception_Locations
11477    Task_Dispatching_Policy
11478    Universal_Data
11479    Unsuppress
11480    Use_VADS_Size
11481    Validity_Checks
11482    Warnings
11483    Wide_Character_Encoding
11484
11485 @end smallexample
11486
11487 @menu
11488 * Handling of Configuration Pragmas::
11489 * The Configuration Pragmas Files::
11490 @end menu
11491
11492 @node Handling of Configuration Pragmas
11493 @section Handling of Configuration Pragmas
11494
11495 Configuration pragmas may either appear at the start of a compilation
11496 unit, in which case they apply only to that unit, or they may apply to
11497 all compilations performed in a given compilation environment.
11498
11499 GNAT also provides the @code{gnatchop} utility to provide an automatic
11500 way to handle configuration pragmas following the semantics for
11501 compilations (that is, files with multiple units), described in the RM.
11502 See @ref{Operating gnatchop in Compilation Mode} for details.
11503 However, for most purposes, it will be more convenient to edit the
11504 @file{gnat.adc} file that contains configuration pragmas directly,
11505 as described in the following section.
11506
11507 @node The Configuration Pragmas Files
11508 @section The Configuration Pragmas Files
11509 @cindex @file{gnat.adc}
11510
11511 @noindent
11512 In GNAT a compilation environment is defined by the current
11513 directory at the time that a compile command is given. This current
11514 directory is searched for a file whose name is @file{gnat.adc}. If
11515 this file is present, it is expected to contain one or more
11516 configuration pragmas that will be applied to the current compilation.
11517 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11518 considered.
11519
11520 Configuration pragmas may be entered into the @file{gnat.adc} file
11521 either by running @code{gnatchop} on a source file that consists only of
11522 configuration pragmas, or more conveniently  by
11523 direct editing of the @file{gnat.adc} file, which is a standard format
11524 source file.
11525
11526 In addition to @file{gnat.adc}, additional files containing configuration
11527 pragmas may be applied to the current compilation using the switch
11528 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11529 contains only configuration pragmas. These configuration pragmas are
11530 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11531 is present and switch @option{-gnatA} is not used).
11532
11533 It is allowed to specify several switches @option{-gnatec}, all of which
11534 will be taken into account.
11535
11536 If you are using project file, a separate mechanism is provided using
11537 project attributes, see @ref{Specifying Configuration Pragmas} for more
11538 details.
11539
11540 @ifset vms
11541 Of special interest to GNAT OpenVMS Alpha is the following
11542 configuration pragma:
11543
11544 @smallexample @c ada
11545 @cartouche
11546 pragma Extend_System (Aux_DEC);
11547 @end cartouche
11548 @end smallexample
11549
11550 @noindent
11551 In the presence of this pragma, GNAT adds to the definition of the
11552 predefined package SYSTEM all the additional types and subprograms that are
11553 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11554 @end ifset
11555
11556 @node Handling Arbitrary File Naming Conventions Using gnatname
11557 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11558 @cindex Arbitrary File Naming Conventions
11559
11560 @menu
11561 * Arbitrary File Naming Conventions::
11562 * Running gnatname::
11563 * Switches for gnatname::
11564 * Examples of gnatname Usage::
11565 @end menu
11566
11567 @node Arbitrary File Naming Conventions
11568 @section Arbitrary File Naming Conventions
11569
11570 @noindent
11571 The GNAT compiler must be able to know the source file name of a compilation
11572 unit.  When using the standard GNAT default file naming conventions
11573 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11574 does not need additional information.
11575
11576 @noindent
11577 When the source file names do not follow the standard GNAT default file naming
11578 conventions, the GNAT compiler must be given additional information through
11579 a configuration pragmas file (@pxref{Configuration Pragmas})
11580 or a project file.
11581 When the non-standard file naming conventions are well-defined,
11582 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11583 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11584 if the file naming conventions are irregular or arbitrary, a number
11585 of pragma @code{Source_File_Name} for individual compilation units
11586 must be defined.
11587 To help maintain the correspondence between compilation unit names and
11588 source file names within the compiler,
11589 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11590 set of files.
11591
11592 @node Running gnatname
11593 @section Running @code{gnatname}
11594
11595 @noindent
11596 The usual form of the @code{gnatname} command is
11597
11598 @smallexample
11599 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11600 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11601 @c Expanding @ovar macro inline (explanation in macro def comments)
11602 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11603       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11604 @end smallexample
11605
11606 @noindent
11607 All of the arguments are optional. If invoked without any argument,
11608 @code{gnatname} will display its usage.
11609
11610 @noindent
11611 When used with at least one naming pattern, @code{gnatname} will attempt to
11612 find all the compilation units in files that follow at least one of the
11613 naming patterns. To find these compilation units,
11614 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11615 regular files.
11616
11617 @noindent
11618 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11619 Each Naming Pattern is enclosed between double quotes (or single
11620 quotes on Windows).
11621 A Naming Pattern is a regular expression similar to the wildcard patterns
11622 used in file names by the Unix shells or the DOS prompt.
11623
11624 @noindent
11625 @code{gnatname} may be called with several sections of directories/patterns.
11626 Sections are separated by switch @code{--and}. In each section, there must be
11627 at least one pattern. If no directory is specified in a section, the current
11628 directory (or the project directory is @code{-P} is used) is implied.
11629 The options other that the directory switches and the patterns apply globally
11630 even if they are in different sections.
11631
11632 @noindent
11633 Examples of Naming Patterns are
11634
11635 @smallexample
11636    "*.[12].ada"
11637    "*.ad[sb]*"
11638    "body_*"    "spec_*"
11639 @end smallexample
11640
11641 @noindent
11642 For a more complete description of the syntax of Naming Patterns,
11643 see the second kind of regular expressions described in @file{g-regexp.ads}
11644 (the ``Glob'' regular expressions).
11645
11646 @noindent
11647 When invoked with no switch @code{-P}, @code{gnatname} will create a
11648 configuration pragmas file @file{gnat.adc} in the current working directory,
11649 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11650 unit.
11651
11652 @node Switches for gnatname
11653 @section Switches for @code{gnatname}
11654
11655 @noindent
11656 Switches for @code{gnatname} must precede any specified Naming Pattern.
11657
11658 @noindent
11659 You may specify any of the following switches to @code{gnatname}:
11660
11661 @table @option
11662 @c !sort!
11663
11664 @item --version
11665 @cindex @option{--version} @command{gnatname}
11666 Display Copyright and version, then exit disregarding all other options.
11667
11668 @item --help
11669 @cindex @option{--help} @command{gnatname}
11670 If @option{--version} was not used, display usage, then exit disregarding
11671 all other options.
11672
11673 @item --and
11674 Start another section of directories/patterns.
11675
11676 @item ^-c^/CONFIG_FILE=^@file{file}
11677 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11678 Create a configuration pragmas file @file{file} (instead of the default
11679 @file{gnat.adc}).
11680 @ifclear vms
11681 There may be zero, one or more space between @option{-c} and
11682 @file{file}.
11683 @end ifclear
11684 @file{file} may include directory information. @file{file} must be
11685 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11686 When a switch @option{^-c^/CONFIG_FILE^} is
11687 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11688
11689 @item ^-d^/SOURCE_DIRS=^@file{dir}
11690 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11691 Look for source files in directory @file{dir}. There may be zero, one or more
11692 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11693 When a switch @option{^-d^/SOURCE_DIRS^}
11694 is specified, the current working directory will not be searched for source
11695 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11696 or @option{^-D^/DIR_FILES^} switch.
11697 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11698 If @file{dir} is a relative path, it is relative to the directory of
11699 the configuration pragmas file specified with switch
11700 @option{^-c^/CONFIG_FILE^},
11701 or to the directory of the project file specified with switch
11702 @option{^-P^/PROJECT_FILE^} or,
11703 if neither switch @option{^-c^/CONFIG_FILE^}
11704 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11705 current working directory. The directory
11706 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11707
11708 @item ^-D^/DIRS_FILE=^@file{file}
11709 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11710 Look for source files in all directories listed in text file @file{file}.
11711 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11712 and @file{file}.
11713 @file{file} must be an existing, readable text file.
11714 Each nonempty line in @file{file} must be a directory.
11715 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11716 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11717 @file{file}.
11718
11719 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11720 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11721 Foreign patterns. Using this switch, it is possible to add sources of languages
11722 other than Ada to the list of sources of a project file.
11723 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11724 For example,
11725 @smallexample
11726 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11727 @end smallexample
11728 @noindent
11729 will look for Ada units in all files with the @file{.ada} extension,
11730 and will add to the list of file for project @file{prj.gpr} the C files
11731 with extension @file{.^c^C^}.
11732
11733 @item ^-h^/HELP^
11734 @cindex @option{^-h^/HELP^} (@code{gnatname})
11735 Output usage (help) information. The output is written to @file{stdout}.
11736
11737 @item ^-P^/PROJECT_FILE=^@file{proj}
11738 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11739 Create or update project file @file{proj}. There may be zero, one or more space
11740 between @option{-P} and @file{proj}. @file{proj} may include directory
11741 information. @file{proj} must be writable.
11742 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11743 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11744 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11745
11746 @item ^-v^/VERBOSE^
11747 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11748 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11749 This includes name of the file written, the name of the directories to search
11750 and, for each file in those directories whose name matches at least one of
11751 the Naming Patterns, an indication of whether the file contains a unit,
11752 and if so the name of the unit.
11753
11754 @item ^-v -v^/VERBOSE /VERBOSE^
11755 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11756 Very Verbose mode. In addition to the output produced in verbose mode,
11757 for each file in the searched directories whose name matches none of
11758 the Naming Patterns, an indication is given that there is no match.
11759
11760 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11761 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11762 Excluded patterns. Using this switch, it is possible to exclude some files
11763 that would match the name patterns. For example,
11764 @smallexample
11765 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11766 @end smallexample
11767 @noindent
11768 will look for Ada units in all files with the @file{.ada} extension,
11769 except those whose names end with @file{_nt.ada}.
11770
11771 @end table
11772
11773 @node Examples of gnatname Usage
11774 @section Examples of @code{gnatname} Usage
11775
11776 @ifset vms
11777 @smallexample
11778 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11779 @end smallexample
11780 @end ifset
11781
11782 @ifclear vms
11783 @smallexample
11784 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11785 @end smallexample
11786 @end ifclear
11787
11788 @noindent
11789 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11790 and be writable. In addition, the directory
11791 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11792 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11793
11794 @ifclear vms
11795 Note the optional spaces after @option{-c} and @option{-d}.
11796 @end ifclear
11797
11798 @smallexample
11799 @ifclear vms
11800 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11801   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11802 @end ifclear
11803 @ifset vms
11804 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11805   /EXCLUDED_PATTERN=*_nt_body.ada
11806   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11807   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11808 @end ifset
11809 @end smallexample
11810
11811 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11812 even in conjunction with one or several switches
11813 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11814 are used in this example.
11815
11816 @c *****************************************
11817 @c * G N A T  P r o j e c t  M a n a g e r *
11818 @c *****************************************
11819
11820 @c ------ macros for projects.texi
11821 @c These macros are needed when building the gprbuild documentation, but
11822 @c should have no effect in the gnat user's guide
11823
11824 @macro CODESAMPLE{TXT}
11825 @smallexample
11826 @group
11827 \TXT\
11828 @end group
11829 @end smallexample
11830 @end macro
11831
11832 @macro PROJECTFILE{TXT}
11833 @CODESAMPLE{\TXT\}
11834 @end macro
11835
11836 @c simulates a newline when in a @CODESAMPLE
11837 @macro NL{}
11838 @end macro
11839
11840 @macro TIP{TXT}
11841 @quotation
11842 @noindent
11843 \TXT\
11844 @end quotation
11845 @end macro
11846
11847 @macro TIPHTML{TXT}
11848 \TXT\
11849 @end macro
11850
11851 @macro IMPORTANT{TXT}
11852 @quotation
11853 @noindent
11854 \TXT\
11855 @end quotation
11856
11857 @end macro
11858
11859 @macro NOTE{TXT}
11860 @quotation
11861 @noindent
11862 \TXT\
11863 @end quotation
11864 @end macro
11865
11866 @include projects.texi
11867
11868 @c *****************************************
11869 @c * Cross-referencing tools
11870 @c *****************************************
11871
11872 @node The Cross-Referencing Tools gnatxref and gnatfind
11873 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11874 @findex gnatxref
11875 @findex gnatfind
11876
11877 @noindent
11878 The compiler generates cross-referencing information (unless
11879 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11880 This information indicates where in the source each entity is declared and
11881 referenced. Note that entities in package Standard are not included, but
11882 entities in all other predefined units are included in the output.
11883
11884 Before using any of these two tools, you need to compile successfully your
11885 application, so that GNAT gets a chance to generate the cross-referencing
11886 information.
11887
11888 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11889 information to provide the user with the capability to easily locate the
11890 declaration and references to an entity. These tools are quite similar,
11891 the difference being that @code{gnatfind} is intended for locating
11892 definitions and/or references to a specified entity or entities, whereas
11893 @code{gnatxref} is oriented to generating a full report of all
11894 cross-references.
11895
11896 To use these tools, you must not compile your application using the
11897 @option{-gnatx} switch on the @command{gnatmake} command line
11898 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11899 information will not be generated.
11900
11901 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11902 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11903
11904 @menu
11905 * Switches for gnatxref::
11906 * Switches for gnatfind::
11907 * Project Files for gnatxref and gnatfind::
11908 * Regular Expressions in gnatfind and gnatxref::
11909 * Examples of gnatxref Usage::
11910 * Examples of gnatfind Usage::
11911 @end menu
11912
11913 @node Switches for gnatxref
11914 @section @code{gnatxref} Switches
11915
11916 @noindent
11917 The command invocation for @code{gnatxref} is:
11918 @smallexample
11919 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11920 @c Expanding @ovar macro inline (explanation in macro def comments)
11921 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11922 @end smallexample
11923
11924 @noindent
11925 where
11926
11927 @table @var
11928 @item sourcefile1
11929 @itemx sourcefile2
11930 identifies the source files for which a report is to be generated. The
11931 ``with''ed units will be processed too. You must provide at least one file.
11932
11933 These file names are considered to be regular expressions, so for instance
11934 specifying @file{source*.adb} is the same as giving every file in the current
11935 directory whose name starts with @file{source} and whose extension is
11936 @file{adb}.
11937
11938 You shouldn't specify any directory name, just base names. @command{gnatxref}
11939 and @command{gnatfind} will be able to locate these files by themselves using
11940 the source path. If you specify directories, no result is produced.
11941
11942 @end table
11943
11944 @noindent
11945 The switches can be:
11946 @table @option
11947 @c !sort!
11948 @item --version
11949 @cindex @option{--version} @command{gnatxref}
11950 Display Copyright and version, then exit disregarding all other options.
11951
11952 @item --help
11953 @cindex @option{--help} @command{gnatxref}
11954 If @option{--version} was not used, display usage, then exit disregarding
11955 all other options.
11956
11957 @item ^-a^/ALL_FILES^
11958 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
11959 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
11960 the read-only files found in the library search path. Otherwise, these files
11961 will be ignored. This option can be used to protect Gnat sources or your own
11962 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
11963 much faster, and their output much smaller. Read-only here refers to access
11964 or permissions status in the file system for the current user.
11965
11966 @item -aIDIR
11967 @cindex @option{-aIDIR} (@command{gnatxref})
11968 When looking for source files also look in directory DIR. The order in which
11969 source file search is undertaken is the same as for @command{gnatmake}.
11970
11971 @item -aODIR
11972 @cindex @option{-aODIR} (@command{gnatxref})
11973 When searching for library and object files, look in directory
11974 DIR. The order in which library files are searched is the same as for
11975 @command{gnatmake}.
11976
11977 @item -nostdinc
11978 @cindex @option{-nostdinc} (@command{gnatxref})
11979 Do not look for sources in the system default directory.
11980
11981 @item -nostdlib
11982 @cindex @option{-nostdlib} (@command{gnatxref})
11983 Do not look for library files in the system default directory.
11984
11985 @item --ext=@var{extension}
11986 @cindex @option{--ext} (@command{gnatxref})
11987 Specify an alternate ali file extension. The default is @code{ali} and other
11988 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
11989 switch. Note that if this switch overrides the default, which means that only
11990 the new extension will be considered.
11991
11992 @item --RTS=@var{rts-path}
11993 @cindex @option{--RTS} (@command{gnatxref})
11994 Specifies the default location of the runtime library. Same meaning as the
11995 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
11996
11997 @item ^-d^/DERIVED_TYPES^
11998 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
11999 If this switch is set @code{gnatxref} will output the parent type
12000 reference for each matching derived types.
12001
12002 @item ^-f^/FULL_PATHNAME^
12003 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12004 If this switch is set, the output file names will be preceded by their
12005 directory (if the file was found in the search path). If this switch is
12006 not set, the directory will not be printed.
12007
12008 @item ^-g^/IGNORE_LOCALS^
12009 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12010 If this switch is set, information is output only for library-level
12011 entities, ignoring local entities. The use of this switch may accelerate
12012 @code{gnatfind} and @code{gnatxref}.
12013
12014 @item -IDIR
12015 @cindex @option{-IDIR} (@command{gnatxref})
12016 Equivalent to @samp{-aODIR -aIDIR}.
12017
12018 @item -pFILE
12019 @cindex @option{-pFILE} (@command{gnatxref})
12020 Specify a project file to use @xref{GNAT Project Manager}.
12021 If you need to use the @file{.gpr}
12022 project files, you should use gnatxref through the GNAT driver
12023 (@command{gnat xref -Pproject}).
12024
12025 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12026 project file in the current directory.
12027
12028 If a project file is either specified or found by the tools, then the content
12029 of the source directory and object directory lines are added as if they
12030 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12031 and @samp{^-aO^OBJECT_SEARCH^}.
12032 @item ^-u^/UNUSED^
12033 Output only unused symbols. This may be really useful if you give your
12034 main compilation unit on the command line, as @code{gnatxref} will then
12035 display every unused entity and 'with'ed package.
12036
12037 @ifclear vms
12038 @item -v
12039 Instead of producing the default output, @code{gnatxref} will generate a
12040 @file{tags} file that can be used by vi. For examples how to use this
12041 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12042 to the standard output, thus you will have to redirect it to a file.
12043 @end ifclear
12044
12045 @end table
12046
12047 @noindent
12048 All these switches may be in any order on the command line, and may even
12049 appear after the file names. They need not be separated by spaces, thus
12050 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12051 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12052
12053 @node Switches for gnatfind
12054 @section @code{gnatfind} Switches
12055
12056 @noindent
12057 The command line for @code{gnatfind} is:
12058
12059 @smallexample
12060 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12061 @c       @r{[}@var{file1} @var{file2} @dots{}]
12062 @c Expanding @ovar macro inline (explanation in macro def comments)
12063 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12064       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12065 @end smallexample
12066
12067 @noindent
12068 where
12069
12070 @table @var
12071 @item pattern
12072 An entity will be output only if it matches the regular expression found
12073 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12074
12075 Omitting the pattern is equivalent to specifying @samp{*}, which
12076 will match any entity. Note that if you do not provide a pattern, you
12077 have to provide both a sourcefile and a line.
12078
12079 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12080 for matching purposes. At the current time there is no support for
12081 8-bit codes other than Latin-1, or for wide characters in identifiers.
12082
12083 @item sourcefile
12084 @code{gnatfind} will look for references, bodies or declarations
12085 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12086 and column @var{column}. See @ref{Examples of gnatfind Usage}
12087 for syntax examples.
12088
12089 @item line
12090 is a decimal integer identifying the line number containing
12091 the reference to the entity (or entities) to be located.
12092
12093 @item column
12094 is a decimal integer identifying the exact location on the
12095 line of the first character of the identifier for the
12096 entity reference. Columns are numbered from 1.
12097
12098 @item file1 file2 @dots{}
12099 The search will be restricted to these source files. If none are given, then
12100 the search will be done for every library file in the search path.
12101 These file must appear only after the pattern or sourcefile.
12102
12103 These file names are considered to be regular expressions, so for instance
12104 specifying @file{source*.adb} is the same as giving every file in the current
12105 directory whose name starts with @file{source} and whose extension is
12106 @file{adb}.
12107
12108 The location of the spec of the entity will always be displayed, even if it
12109 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12110 occurrences of the entity in the separate units of the ones given on the
12111 command line will also be displayed.
12112
12113 Note that if you specify at least one file in this part, @code{gnatfind} may
12114 sometimes not be able to find the body of the subprograms.
12115
12116 @end table
12117
12118 @noindent
12119 At least one of 'sourcefile' or 'pattern' has to be present on
12120 the command line.
12121
12122 The following switches are available:
12123 @table @option
12124 @c !sort!
12125
12126 @cindex @option{--version} @command{gnatfind}
12127 Display Copyright and version, then exit disregarding all other options.
12128
12129 @item --help
12130 @cindex @option{--help} @command{gnatfind}
12131 If @option{--version} was not used, display usage, then exit disregarding
12132 all other options.
12133
12134 @item ^-a^/ALL_FILES^
12135 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12136 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12137 the read-only files found in the library search path. Otherwise, these files
12138 will be ignored. This option can be used to protect Gnat sources or your own
12139 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12140 much faster, and their output much smaller. Read-only here refers to access
12141 or permission status in the file system for the current user.
12142
12143 @item -aIDIR
12144 @cindex @option{-aIDIR} (@command{gnatfind})
12145 When looking for source files also look in directory DIR. The order in which
12146 source file search is undertaken is the same as for @command{gnatmake}.
12147
12148 @item -aODIR
12149 @cindex @option{-aODIR} (@command{gnatfind})
12150 When searching for library and object files, look in directory
12151 DIR. The order in which library files are searched is the same as for
12152 @command{gnatmake}.
12153
12154 @item -nostdinc
12155 @cindex @option{-nostdinc} (@command{gnatfind})
12156 Do not look for sources in the system default directory.
12157
12158 @item -nostdlib
12159 @cindex @option{-nostdlib} (@command{gnatfind})
12160 Do not look for library files in the system default directory.
12161
12162 @item --ext=@var{extension}
12163 @cindex @option{--ext} (@command{gnatfind})
12164 Specify an alternate ali file extension. The default is @code{ali} and other
12165 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12166 switch. Note that if this switch overrides the default, which means that only
12167 the new extension will be considered.
12168
12169 @item --RTS=@var{rts-path}
12170 @cindex @option{--RTS} (@command{gnatfind})
12171 Specifies the default location of the runtime library. Same meaning as the
12172 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12173
12174 @item ^-d^/DERIVED_TYPE_INFORMATION^
12175 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12176 If this switch is set, then @code{gnatfind} will output the parent type
12177 reference for each matching derived types.
12178
12179 @item ^-e^/EXPRESSIONS^
12180 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12181 By default, @code{gnatfind} accept the simple regular expression set for
12182 @samp{pattern}. If this switch is set, then the pattern will be
12183 considered as full Unix-style regular expression.
12184
12185 @item ^-f^/FULL_PATHNAME^
12186 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12187 If this switch is set, the output file names will be preceded by their
12188 directory (if the file was found in the search path). If this switch is
12189 not set, the directory will not be printed.
12190
12191 @item ^-g^/IGNORE_LOCALS^
12192 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12193 If this switch is set, information is output only for library-level
12194 entities, ignoring local entities. The use of this switch may accelerate
12195 @code{gnatfind} and @code{gnatxref}.
12196
12197 @item -IDIR
12198 @cindex @option{-IDIR} (@command{gnatfind})
12199 Equivalent to @samp{-aODIR -aIDIR}.
12200
12201 @item -pFILE
12202 @cindex @option{-pFILE} (@command{gnatfind})
12203 Specify a project file (@pxref{GNAT Project Manager}) to use.
12204 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12205 project file in the current directory.
12206
12207 If a project file is either specified or found by the tools, then the content
12208 of the source directory and object directory lines are added as if they
12209 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12210 @samp{^-aO^/OBJECT_SEARCH^}.
12211
12212 @item ^-r^/REFERENCES^
12213 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12214 By default, @code{gnatfind} will output only the information about the
12215 declaration, body or type completion of the entities. If this switch is
12216 set, the @code{gnatfind} will locate every reference to the entities in
12217 the files specified on the command line (or in every file in the search
12218 path if no file is given on the command line).
12219
12220 @item ^-s^/PRINT_LINES^
12221 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12222 If this switch is set, then @code{gnatfind} will output the content
12223 of the Ada source file lines were the entity was found.
12224
12225 @item ^-t^/TYPE_HIERARCHY^
12226 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12227 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12228 the specified type. It act like -d option but recursively from parent
12229 type to parent type. When this switch is set it is not possible to
12230 specify more than one file.
12231
12232 @end table
12233
12234 @noindent
12235 All these switches may be in any order on the command line, and may even
12236 appear after the file names. They need not be separated by spaces, thus
12237 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12238 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12239
12240 As stated previously, gnatfind will search in every directory in the
12241 search path. You can force it to look only in the current directory if
12242 you specify @code{*} at the end of the command line.
12243
12244 @node Project Files for gnatxref and gnatfind
12245 @section Project Files for @command{gnatxref} and @command{gnatfind}
12246
12247 @noindent
12248 Project files allow a programmer to specify how to compile its
12249 application, where to find sources, etc.  These files are used
12250 @ifclear vms
12251 primarily by GPS, but they can also be used
12252 @end ifclear
12253 by the two tools
12254 @code{gnatxref} and @code{gnatfind}.
12255
12256 A project file name must end with @file{.gpr}. If a single one is
12257 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12258 extract the information from it. If multiple project files are found, none of
12259 them is read, and you have to use the @samp{-p} switch to specify the one
12260 you want to use.
12261
12262 The following lines can be included, even though most of them have default
12263 values which can be used in most cases.
12264 The lines can be entered in any order in the file.
12265 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12266 each line. If you have multiple instances, only the last one is taken into
12267 account.
12268
12269 @table @code
12270 @item src_dir=DIR
12271 [default: @code{"^./^[]^"}]
12272 specifies a directory where to look for source files. Multiple @code{src_dir}
12273 lines can be specified and they will be searched in the order they
12274 are specified.
12275
12276 @item obj_dir=DIR
12277 [default: @code{"^./^[]^"}]
12278 specifies a directory where to look for object and library files. Multiple
12279 @code{obj_dir} lines can be specified, and they will be searched in the order
12280 they are specified
12281
12282 @item comp_opt=SWITCHES
12283 [default: @code{""}]
12284 creates a variable which can be referred to subsequently by using
12285 the @code{$@{comp_opt@}} notation. This is intended to store the default
12286 switches given to @command{gnatmake} and @command{gcc}.
12287
12288 @item bind_opt=SWITCHES
12289 [default: @code{""}]
12290 creates a variable which can be referred to subsequently by using
12291 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12292 switches given to @command{gnatbind}.
12293
12294 @item link_opt=SWITCHES
12295 [default: @code{""}]
12296 creates a variable which can be referred to subsequently by using
12297 the @samp{$@{link_opt@}} notation. This is intended to store the default
12298 switches given to @command{gnatlink}.
12299
12300 @item main=EXECUTABLE
12301 [default: @code{""}]
12302 specifies the name of the executable for the application. This variable can
12303 be referred to in the following lines by using the @samp{$@{main@}} notation.
12304
12305 @ifset vms
12306 @item comp_cmd=COMMAND
12307 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12308 @end ifset
12309 @ifclear vms
12310 @item comp_cmd=COMMAND
12311 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12312 @end ifclear
12313 specifies the command used to compile a single file in the application.
12314
12315 @ifset vms
12316 @item make_cmd=COMMAND
12317 [default: @code{"GNAT MAKE $@{main@}
12318 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12319 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12320 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12321 @end ifset
12322 @ifclear vms
12323 @item make_cmd=COMMAND
12324 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12325 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12326 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12327 @end ifclear
12328 specifies the command used to recompile the whole application.
12329
12330 @item run_cmd=COMMAND
12331 [default: @code{"$@{main@}"}]
12332 specifies the command used to run the application.
12333
12334 @item debug_cmd=COMMAND
12335 [default: @code{"gdb $@{main@}"}]
12336 specifies the command used to debug the application
12337
12338 @end table
12339
12340 @noindent
12341 @command{gnatxref} and @command{gnatfind} only take into account the
12342 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12343
12344 @node Regular Expressions in gnatfind and gnatxref
12345 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12346
12347 @noindent
12348 As specified in the section about @command{gnatfind}, the pattern can be a
12349 regular expression. Actually, there are to set of regular expressions
12350 which are recognized by the program:
12351
12352 @table @code
12353 @item globbing patterns
12354 These are the most usual regular expression. They are the same that you
12355 generally used in a Unix shell command line, or in a DOS session.
12356
12357 Here is a more formal grammar:
12358 @smallexample
12359 @group
12360 @iftex
12361 @leftskip=.5cm
12362 @end iftex
12363 regexp ::= term
12364 term   ::= elmt            -- matches elmt
12365 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12366 term   ::= *               -- any string of 0 or more characters
12367 term   ::= ?               -- matches any character
12368 term   ::= [char @{char@}]   -- matches any character listed
12369 term   ::= [char - char]   -- matches any character in range
12370 @end group
12371 @end smallexample
12372
12373 @item full regular expression
12374 The second set of regular expressions is much more powerful. This is the
12375 type of regular expressions recognized by utilities such a @file{grep}.
12376
12377 The following is the form of a regular expression, expressed in Ada
12378 reference manual style BNF is as follows
12379
12380 @smallexample
12381 @iftex
12382 @leftskip=.5cm
12383 @end iftex
12384 @group
12385 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12386
12387 term ::= item @{item@}       -- concatenation (item then item)
12388
12389 item ::= elmt              -- match elmt
12390 item ::= elmt *            -- zero or more elmt's
12391 item ::= elmt +            -- one or more elmt's
12392 item ::= elmt ?            -- matches elmt or nothing
12393 @end group
12394 @group
12395 elmt ::= nschar            -- matches given character
12396 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12397 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12398 elmt ::= [char - char]     -- matches chars in given range
12399 elmt ::= \ char            -- matches given character
12400 elmt ::= .                 -- matches any single character
12401 elmt ::= ( regexp )        -- parens used for grouping
12402
12403 char ::= any character, including special characters
12404 nschar ::= any character except ()[].*+?^^^
12405 @end group
12406 @end smallexample
12407
12408 Following are a few examples:
12409
12410 @table @samp
12411 @item abcde|fghi
12412 will match any of the two strings @samp{abcde} and @samp{fghi},
12413
12414 @item abc*d
12415 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12416 @samp{abcccd}, and so on,
12417
12418 @item [a-z]+
12419 will match any string which has only lowercase characters in it (and at
12420 least one character.
12421
12422 @end table
12423 @end table
12424
12425 @node Examples of gnatxref Usage
12426 @section Examples of @code{gnatxref} Usage
12427
12428 @subsection General Usage
12429
12430 @noindent
12431 For the following examples, we will consider the following units:
12432
12433 @smallexample @c ada
12434 @group
12435 @cartouche
12436 main.ads:
12437 1: with Bar;
12438 2: package Main is
12439 3:     procedure Foo (B : in Integer);
12440 4:     C : Integer;
12441 5: private
12442 6:     D : Integer;
12443 7: end Main;
12444
12445 main.adb:
12446 1: package body Main is
12447 2:     procedure Foo (B : in Integer) is
12448 3:     begin
12449 4:        C := B;
12450 5:        D := B;
12451 6:        Bar.Print (B);
12452 7:        Bar.Print (C);
12453 8:     end Foo;
12454 9: end Main;
12455
12456 bar.ads:
12457 1: package Bar is
12458 2:     procedure Print (B : Integer);
12459 3: end bar;
12460 @end cartouche
12461 @end group
12462 @end smallexample
12463
12464 @table @code
12465
12466 @noindent
12467 The first thing to do is to recompile your application (for instance, in
12468 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12469 the cross-referencing information.
12470 You can then issue any of the following commands:
12471
12472 @item gnatxref main.adb
12473 @code{gnatxref} generates cross-reference information for main.adb
12474 and every unit 'with'ed by main.adb.
12475
12476 The output would be:
12477 @smallexample
12478 @iftex
12479 @leftskip=0cm
12480 @end iftex
12481 B                                                      Type: Integer
12482   Decl: bar.ads           2:22
12483 B                                                      Type: Integer
12484   Decl: main.ads          3:20
12485   Body: main.adb          2:20
12486   Ref:  main.adb          4:13     5:13     6:19
12487 Bar                                                    Type: Unit
12488   Decl: bar.ads           1:9
12489   Ref:  main.adb          6:8      7:8
12490        main.ads           1:6
12491 C                                                      Type: Integer
12492   Decl: main.ads          4:5
12493   Modi: main.adb          4:8
12494   Ref:  main.adb          7:19
12495 D                                                      Type: Integer
12496   Decl: main.ads          6:5
12497   Modi: main.adb          5:8
12498 Foo                                                    Type: Unit
12499   Decl: main.ads          3:15
12500   Body: main.adb          2:15
12501 Main                                                    Type: Unit
12502   Decl: main.ads          2:9
12503   Body: main.adb          1:14
12504 Print                                                   Type: Unit
12505   Decl: bar.ads           2:15
12506   Ref:  main.adb          6:12     7:12
12507 @end smallexample
12508
12509 @noindent
12510 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12511 its body is in main.adb, line 1, column 14 and is not referenced any where.
12512
12513 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12514 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12515
12516 @item gnatxref package1.adb package2.ads
12517 @code{gnatxref} will generates cross-reference information for
12518 package1.adb, package2.ads and any other package 'with'ed by any
12519 of these.
12520
12521 @end table
12522
12523 @ifclear vms
12524 @subsection Using gnatxref with vi
12525
12526 @code{gnatxref} can generate a tags file output, which can be used
12527 directly from @command{vi}. Note that the standard version of @command{vi}
12528 will not work properly with overloaded symbols. Consider using another
12529 free implementation of @command{vi}, such as @command{vim}.
12530
12531 @smallexample
12532 $ gnatxref -v gnatfind.adb > tags
12533 @end smallexample
12534
12535 @noindent
12536 will generate the tags file for @code{gnatfind} itself (if the sources
12537 are in the search path!).
12538
12539 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12540 (replacing @var{entity} by whatever you are looking for), and vi will
12541 display a new file with the corresponding declaration of entity.
12542 @end ifclear
12543
12544 @node Examples of gnatfind Usage
12545 @section Examples of @code{gnatfind} Usage
12546
12547 @table @code
12548
12549 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12550 Find declarations for all entities xyz referenced at least once in
12551 main.adb. The references are search in every library file in the search
12552 path.
12553
12554 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12555 switch is set)
12556
12557 The output will look like:
12558 @smallexample
12559 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12560 ^directory/^[directory]^main.adb:24:10: xyz <= body
12561 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12562 @end smallexample
12563
12564 @noindent
12565 that is to say, one of the entities xyz found in main.adb is declared at
12566 line 12 of main.ads (and its body is in main.adb), and another one is
12567 declared at line 45 of foo.ads
12568
12569 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12570 This is the same command as the previous one, instead @code{gnatfind} will
12571 display the content of the Ada source file lines.
12572
12573 The output will look like:
12574
12575 @smallexample
12576 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12577    procedure xyz;
12578 ^directory/^[directory]^main.adb:24:10: xyz <= body
12579    procedure xyz is
12580 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12581    xyz : Integer;
12582 @end smallexample
12583
12584 @noindent
12585 This can make it easier to find exactly the location your are looking
12586 for.
12587
12588 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12589 Find references to all entities containing an x that are
12590 referenced on line 123 of main.ads.
12591 The references will be searched only in main.ads and foo.adb.
12592
12593 @item gnatfind main.ads:123
12594 Find declarations and bodies for all entities that are referenced on
12595 line 123 of main.ads.
12596
12597 This is the same as @code{gnatfind "*":main.adb:123}.
12598
12599 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12600 Find the declaration for the entity referenced at column 45 in
12601 line 123 of file main.adb in directory mydir. Note that it
12602 is usual to omit the identifier name when the column is given,
12603 since the column position identifies a unique reference.
12604
12605 The column has to be the beginning of the identifier, and should not
12606 point to any character in the middle of the identifier.
12607
12608 @end table
12609
12610 @c *********************************
12611 @node The GNAT Pretty-Printer gnatpp
12612 @chapter The GNAT Pretty-Printer @command{gnatpp}
12613 @findex gnatpp
12614 @cindex Pretty-Printer
12615
12616 @noindent
12617 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12618 for source reformatting / pretty-printing.
12619 It takes an Ada source file as input and generates a reformatted
12620 version as output.
12621 You can specify various style directives via switches; e.g.,
12622 identifier case conventions, rules of indentation, and comment layout.
12623
12624 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12625 tree for the input source and thus requires the input to be syntactically and
12626 semantically legal.
12627 If this condition is not met, @command{gnatpp} will terminate with an
12628 error message; no output file will be generated.
12629
12630 If the source files presented to @command{gnatpp} contain
12631 preprocessing directives, then the output file will
12632 correspond to the generated source after all
12633 preprocessing is carried out. There is no way
12634 using @command{gnatpp} to obtain pretty printed files that
12635 include the preprocessing directives.
12636
12637 If the compilation unit
12638 contained in the input source depends semantically upon units located
12639 outside the current directory, you have to provide the source search path
12640 when invoking @command{gnatpp}, if these units are contained in files with
12641 names that do not follow the GNAT file naming rules, you have to provide
12642 the configuration file describing the corresponding naming scheme;
12643 see the description of the @command{gnatpp}
12644 switches below. Another possibility is to use a project file and to
12645 call @command{gnatpp} through the @command{gnat} driver
12646
12647 The @command{gnatpp} command has the form
12648
12649 @smallexample
12650 @c $ gnatpp @ovar{switches} @var{filename}
12651 @c Expanding @ovar macro inline (explanation in macro def comments)
12652 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12653 @end smallexample
12654
12655 @noindent
12656 where
12657 @itemize @bullet
12658 @item
12659 @var{switches} is an optional sequence of switches defining such properties as
12660 the formatting rules, the source search path, and the destination for the
12661 output source file
12662
12663 @item
12664 @var{filename} is the name (including the extension) of the source file to
12665 reformat; ``wildcards'' or several file names on the same gnatpp command are
12666 allowed.  The file name may contain path information; it does not have to
12667 follow the GNAT file naming rules
12668
12669 @item
12670 @samp{@var{gcc_switches}} is a list of switches for
12671 @command{gcc}. They will be passed on to all compiler invocations made by
12672 @command{gnatelim} to generate the ASIS trees. Here you can provide
12673 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12674 use the @option{-gnatec} switch to set the configuration file,
12675 use the @option{-gnat05} switch if sources should be compiled in
12676 Ada 2005 mode  etc.
12677 @end itemize
12678
12679 @menu
12680 * Switches for gnatpp::
12681 * Formatting Rules::
12682 @end menu
12683
12684 @node Switches for gnatpp
12685 @section Switches for @command{gnatpp}
12686
12687 @noindent
12688 The following subsections describe the various switches accepted by
12689 @command{gnatpp}, organized by category.
12690
12691 @ifclear vms
12692 You specify a switch by supplying a name and generally also a value.
12693 In many cases the values for a switch with a given name are incompatible with
12694 each other
12695 (for example the switch that controls the casing of a reserved word may have
12696 exactly one value: upper case, lower case, or
12697 mixed case) and thus exactly one such switch can be in effect for an
12698 invocation of @command{gnatpp}.
12699 If more than one is supplied, the last one is used.
12700 However, some values for the same switch are mutually compatible.
12701 You may supply several such switches to @command{gnatpp}, but then
12702 each must be specified in full, with both the name and the value.
12703 Abbreviated forms (the name appearing once, followed by each value) are
12704 not permitted.
12705 For example, to set
12706 the alignment of the assignment delimiter both in declarations and in
12707 assignment statements, you must write @option{-A2A3}
12708 (or @option{-A2 -A3}), but not @option{-A23}.
12709 @end ifclear
12710
12711 @ifset vms
12712 In many cases the set of options for a given qualifier are incompatible with
12713 each other (for example the qualifier that controls the casing of a reserved
12714 word may have exactly one option, which specifies either upper case, lower
12715 case, or mixed case), and thus exactly one such option can be in effect for
12716 an invocation of @command{gnatpp}.
12717 If more than one is supplied, the last one is used.
12718 However, some qualifiers have options that are mutually compatible,
12719 and then you may then supply several such options when invoking
12720 @command{gnatpp}.
12721 @end ifset
12722
12723 In most cases, it is obvious whether or not the
12724 ^values for a switch with a given name^options for a given qualifier^
12725 are compatible with each other.
12726 When the semantics might not be evident, the summaries below explicitly
12727 indicate the effect.
12728
12729 @menu
12730 * Alignment Control::
12731 * Casing Control::
12732 * Construct Layout Control::
12733 * General Text Layout Control::
12734 * Other Formatting Options::
12735 * Setting the Source Search Path::
12736 * Output File Control::
12737 * Other gnatpp Switches::
12738 @end menu
12739
12740 @node Alignment Control
12741 @subsection Alignment Control
12742 @cindex Alignment control in @command{gnatpp}
12743
12744 @noindent
12745 Programs can be easier to read if certain constructs are vertically aligned.
12746 By default all alignments are set ON.
12747 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12748 OFF, and then use one or more of the other
12749 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12750 to activate alignment for specific constructs.
12751
12752 @table @option
12753 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12754
12755 @ifset vms
12756 @item /ALIGN=ON
12757 Set all alignments to ON
12758 @end ifset
12759
12760 @item ^-A0^/ALIGN=OFF^
12761 Set all alignments to OFF
12762
12763 @item ^-A1^/ALIGN=COLONS^
12764 Align @code{:} in declarations
12765
12766 @item ^-A2^/ALIGN=DECLARATIONS^
12767 Align @code{:=} in initializations in declarations
12768
12769 @item ^-A3^/ALIGN=STATEMENTS^
12770 Align @code{:=} in assignment statements
12771
12772 @item ^-A4^/ALIGN=ARROWS^
12773 Align @code{=>} in associations
12774
12775 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12776 Align @code{at} keywords in the component clauses in record
12777 representation clauses
12778 @end table
12779
12780 @noindent
12781 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12782 is allowed.
12783
12784 @node Casing Control
12785 @subsection Casing Control
12786 @cindex Casing control in @command{gnatpp}
12787
12788 @noindent
12789 @command{gnatpp} allows you to specify the casing for reserved words,
12790 pragma names, attribute designators and identifiers.
12791 For identifiers you may define a
12792 general rule for name casing but also override this rule
12793 via a set of dictionary files.
12794
12795 Three types of casing are supported: lower case, upper case, and mixed case.
12796 Lower and upper case are self-explanatory (but since some letters in
12797 Latin1 and other GNAT-supported character sets
12798 exist only in lower-case form, an upper case conversion will have no
12799 effect on them.)
12800 ``Mixed case'' means that the first letter, and also each letter immediately
12801 following an underscore, are converted to their uppercase forms;
12802 all the other letters are converted to their lowercase forms.
12803
12804 @table @option
12805 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12806 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12807 Attribute designators are lower case
12808
12809 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12810 Attribute designators are upper case
12811
12812 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12813 Attribute designators are mixed case (this is the default)
12814
12815 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12816 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12817 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12818 lower case (this is the default)
12819
12820 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12821 Keywords are upper case
12822
12823 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12824 @item ^-nD^/NAME_CASING=AS_DECLARED^
12825 Name casing for defining occurrences are as they appear in the source file
12826 (this is the default)
12827
12828 @item ^-nU^/NAME_CASING=UPPER_CASE^
12829 Names are in upper case
12830
12831 @item ^-nL^/NAME_CASING=LOWER_CASE^
12832 Names are in lower case
12833
12834 @item ^-nM^/NAME_CASING=MIXED_CASE^
12835 Names are in mixed case
12836
12837 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12838 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12839 Pragma names are lower case
12840
12841 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12842 Pragma names are upper case
12843
12844 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12845 Pragma names are mixed case (this is the default)
12846
12847 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12848 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12849 Use @var{file} as a @emph{dictionary file} that defines
12850 the casing for a set of specified names,
12851 thereby overriding the effect on these names by
12852 any explicit or implicit
12853 ^-n^/NAME_CASING^ switch.
12854 To supply more than one dictionary file,
12855 use ^several @option{-D} switches^a list of files as options^.
12856
12857 @noindent
12858 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12859 to define the casing for the Ada predefined names and
12860 the names declared in the GNAT libraries.
12861
12862 @item ^-D-^/SPECIFIC_CASING^
12863 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12864 Do not use the default dictionary file;
12865 instead, use the casing
12866 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12867 dictionary file(s)
12868 @end table
12869
12870 @noindent
12871 The structure of a dictionary file, and details on the conventions
12872 used in the default dictionary file, are defined in @ref{Name Casing}.
12873
12874 The @option{^-D-^/SPECIFIC_CASING^} and
12875 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12876 compatible.
12877
12878 @node Construct Layout Control
12879 @subsection Construct Layout Control
12880 @cindex Layout control in @command{gnatpp}
12881
12882 @noindent
12883 This group of @command{gnatpp} switches controls the layout of comments and
12884 complex syntactic constructs.  See @ref{Formatting Comments} for details
12885 on their effect.
12886
12887 @table @option
12888 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12889 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12890 All the comments remain unchanged
12891
12892 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12893 GNAT-style comment line indentation (this is the default).
12894
12895 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12896 Reference-manual comment line indentation.
12897
12898 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12899 GNAT-style comment beginning
12900
12901 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12902 Reformat comment blocks
12903
12904 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12905 Keep unchanged special form comments
12906
12907 Reformat comment blocks
12908
12909 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12910 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12911 GNAT-style layout (this is the default)
12912
12913 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12914 Compact layout
12915
12916 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12917 Uncompact layout
12918
12919 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12920 @item ^-N^/NOTABS^
12921 All the VT characters are removed from the comment text. All the HT characters
12922 are expanded with the sequences of space characters to get to the next tab
12923 stops.
12924
12925 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12926 @item ^--no-separate-is^/NO_SEPARATE_IS^
12927 Do not place the keyword @code{is} on a separate line in a subprogram body in
12928 case if the spec occupies more then one line.
12929
12930 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12931 @item ^--separate-label^/SEPARATE_LABEL^
12932 Place statement label(s) on a separate line, with the following statement
12933 on the next line.
12934
12935 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12936 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12937 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12938 keyword @code{then} in IF statements on a separate line.
12939
12940 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12941 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12942 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12943 keyword @code{then} in IF statements on a separate line. This option is
12944 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12945
12946 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12947 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
12948 Start each USE clause in a context clause from a separate line.
12949
12950 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
12951 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
12952 Use a separate line for a loop or block statement name, but do not use an extra
12953 indentation level for the statement itself.
12954
12955 @end table
12956
12957 @ifclear vms
12958 @noindent
12959 The @option{-c1} and @option{-c2} switches are incompatible.
12960 The @option{-c3} and @option{-c4} switches are compatible with each other and
12961 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
12962 the other comment formatting switches.
12963
12964 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
12965 @end ifclear
12966
12967 @ifset vms
12968 @noindent
12969 For the @option{/COMMENTS_LAYOUT} qualifier:
12970 @itemize @bullet
12971 @item
12972 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
12973 @item
12974 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
12975 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
12976 @end itemize
12977
12978 @noindent
12979 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
12980 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
12981 @end ifset
12982
12983 @node General Text Layout Control
12984 @subsection General Text Layout Control
12985
12986 @noindent
12987 These switches allow control over line length and indentation.
12988
12989 @table @option
12990 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
12991 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
12992 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
12993
12994 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
12995 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
12996 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
12997
12998 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
12999 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13000 Indentation level for continuation lines (relative to the line being
13001 continued), @var{nnn} from 1@dots{}9.
13002 The default
13003 value is one less then the (normal) indentation level, unless the
13004 indentation is set to 1 (in which case the default value for continuation
13005 line indentation is also 1)
13006 @end table
13007
13008 @node Other Formatting Options
13009 @subsection Other Formatting Options
13010
13011 @noindent
13012 These switches control the inclusion of missing end/exit labels, and
13013 the indentation level in @b{case} statements.
13014
13015 @table @option
13016 @item ^-e^/NO_MISSED_LABELS^
13017 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13018 Do not insert missing end/exit labels. An end label is the name of
13019 a construct that may optionally be repeated at the end of the
13020 construct's declaration;
13021 e.g., the names of packages, subprograms, and tasks.
13022 An exit label is the name of a loop that may appear as target
13023 of an exit statement within the loop.
13024 By default, @command{gnatpp} inserts these end/exit labels when
13025 they are absent from the original source. This option suppresses such
13026 insertion, so that the formatted source reflects the original.
13027
13028 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13029 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13030 Insert a Form Feed character after a pragma Page.
13031
13032 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13033 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13034 Do not use an additional indentation level for @b{case} alternatives
13035 and variants if there are @var{nnn} or more (the default
13036 value is 10).
13037 If @var{nnn} is 0, an additional indentation level is
13038 used for @b{case} alternatives and variants regardless of their number.
13039 @end table
13040
13041 @node Setting the Source Search Path
13042 @subsection Setting the Source Search Path
13043
13044 @noindent
13045 To define the search path for the input source file, @command{gnatpp}
13046 uses the same switches as the GNAT compiler, with the same effects.
13047
13048 @table @option
13049 @item ^-I^/SEARCH=^@var{dir}
13050 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13051 The same as the corresponding gcc switch
13052
13053 @item ^-I-^/NOCURRENT_DIRECTORY^
13054 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13055 The same as the corresponding gcc switch
13056
13057 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13058 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13059 The same as the corresponding gcc switch
13060
13061 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13062 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13063 The same as the corresponding gcc switch
13064
13065 @end table
13066
13067 @node Output File Control
13068 @subsection Output File Control
13069
13070 @noindent
13071 By default the output is sent to the file whose name is obtained by appending
13072 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13073 (if the file with this name already exists, it is unconditionally overwritten).
13074 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13075 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13076 as output file.
13077 The output may be redirected by the following switches:
13078
13079 @table @option
13080 @item ^-pipe^/STANDARD_OUTPUT^
13081 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13082 Send the output to @code{Standard_Output}
13083
13084 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13085 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13086 Write the output into @var{output_file}.
13087 If @var{output_file} already exists, @command{gnatpp} terminates without
13088 reading or processing the input file.
13089
13090 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13091 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13092 Write the output into @var{output_file}, overwriting the existing file
13093 (if one is present).
13094
13095 @item ^-r^/REPLACE^
13096 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13097 Replace the input source file with the reformatted output, and copy the
13098 original input source into the file whose name is obtained by appending the
13099 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13100 If a file with this name already exists, @command{gnatpp} terminates without
13101 reading or processing the input file.
13102
13103 @item ^-rf^/OVERRIDING_REPLACE^
13104 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13105 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13106 already exists, it is overwritten.
13107
13108 @item ^-rnb^/REPLACE_NO_BACKUP^
13109 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13110 Replace the input source file with the reformatted output without
13111 creating any backup copy of the input source.
13112
13113 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13114 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13115 Specifies the format of the reformatted output file. The @var{xxx}
13116 ^string specified with the switch^option^ may be either
13117 @itemize @bullet
13118 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13119 @item ``@option{^crlf^CRLF^}''
13120 the same as @option{^crlf^CRLF^}
13121 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13122 @item ``@option{^lf^LF^}''
13123 the same as @option{^unix^UNIX^}
13124 @end itemize
13125
13126 @item ^-W^/RESULT_ENCODING=^@var{e}
13127 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13128 Specify the wide character encoding method used to write the code in the
13129 result file
13130 @var{e} is one of the following:
13131
13132 @itemize @bullet
13133
13134 @item ^h^HEX^
13135 Hex encoding
13136
13137 @item ^u^UPPER^
13138 Upper half encoding
13139
13140 @item ^s^SHIFT_JIS^
13141 Shift/JIS encoding
13142
13143 @item ^e^EUC^
13144 EUC encoding
13145
13146 @item ^8^UTF8^
13147 UTF-8 encoding
13148
13149 @item ^b^BRACKETS^
13150 Brackets encoding (default value)
13151 @end itemize
13152
13153 @end table
13154
13155 @noindent
13156 Options @option{^-pipe^/STANDARD_OUTPUT^},
13157 @option{^-o^/OUTPUT^} and
13158 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13159 contains only one file to reformat.
13160 Option
13161 @option{^--eol^/END_OF_LINE^}
13162 and
13163 @option{^-W^/RESULT_ENCODING^}
13164 cannot be used together
13165 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13166
13167 @node Other gnatpp Switches
13168 @subsection Other @code{gnatpp} Switches
13169
13170 @noindent
13171 The additional @command{gnatpp} switches are defined in this subsection.
13172
13173 @table @option
13174 @item ^-files @var{filename}^/FILES=@var{filename}^
13175 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13176 Take the argument source files from the specified file. This file should be an
13177 ordinary text file containing file names separated by spaces or
13178 line breaks. You can use this switch more than once in the same call to
13179 @command{gnatpp}. You also can combine this switch with an explicit list of
13180 files.
13181
13182 @item ^-v^/VERBOSE^
13183 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13184 Verbose mode;
13185 @command{gnatpp} generates version information and then
13186 a trace of the actions it takes to produce or obtain the ASIS tree.
13187
13188 @item ^-w^/WARNINGS^
13189 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13190 Warning mode;
13191 @command{gnatpp} generates a warning whenever it cannot provide
13192 a required layout in the result source.
13193 @end table
13194
13195 @node Formatting Rules
13196 @section Formatting Rules
13197
13198 @noindent
13199 The following subsections show how @command{gnatpp} treats ``white space'',
13200 comments, program layout, and name casing.
13201 They provide the detailed descriptions of the switches shown above.
13202
13203 @menu
13204 * White Space and Empty Lines::
13205 * Formatting Comments::
13206 * Construct Layout::
13207 * Name Casing::
13208 @end menu
13209
13210 @node White Space and Empty Lines
13211 @subsection White Space and Empty Lines
13212
13213 @noindent
13214 @command{gnatpp} does not have an option to control space characters.
13215 It will add or remove spaces according to the style illustrated by the
13216 examples in the @cite{Ada Reference Manual}.
13217
13218 The only format effectors
13219 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13220 that will appear in the output file are platform-specific line breaks,
13221 and also format effectors within (but not at the end of) comments.
13222 In particular, each horizontal tab character that is not inside
13223 a comment will be treated as a space and thus will appear in the
13224 output file as zero or more spaces depending on
13225 the reformatting of the line in which it appears.
13226 The only exception is a Form Feed character, which is inserted after a
13227 pragma @code{Page} when @option{-ff} is set.
13228
13229 The output file will contain no lines with trailing ``white space'' (spaces,
13230 format effectors).
13231
13232 Empty lines in the original source are preserved
13233 only if they separate declarations or statements.
13234 In such contexts, a
13235 sequence of two or more empty lines is replaced by exactly one empty line.
13236 Note that a blank line will be removed if it separates two ``comment blocks''
13237 (a comment block is a sequence of whole-line comments).
13238 In order to preserve a visual separation between comment blocks, use an
13239 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13240 Likewise, if for some reason you wish to have a sequence of empty lines,
13241 use a sequence of empty comments instead.
13242
13243 @node Formatting Comments
13244 @subsection Formatting Comments
13245
13246 @noindent
13247 Comments in Ada code are of two kinds:
13248 @itemize @bullet
13249 @item
13250 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13251 ``white space'') on a line
13252
13253 @item
13254 an @emph{end-of-line comment}, which follows some other Ada lexical element
13255 on the same line.
13256 @end itemize
13257
13258 @noindent
13259 The indentation of a whole-line comment is that of either
13260 the preceding or following line in
13261 the formatted source, depending on switch settings as will be described below.
13262
13263 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13264 between the end of the preceding Ada lexical element and the beginning
13265 of the comment as appear in the original source,
13266 unless either the comment has to be split to
13267 satisfy the line length limitation, or else the next line contains a
13268 whole line comment that is considered a continuation of this end-of-line
13269 comment (because it starts at the same position).
13270 In the latter two
13271 cases, the start of the end-of-line comment is moved right to the nearest
13272 multiple of the indentation level.
13273 This may result in a ``line overflow'' (the right-shifted comment extending
13274 beyond the maximum line length), in which case the comment is split as
13275 described below.
13276
13277 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13278 (GNAT-style comment line indentation)
13279 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13280 (reference-manual comment line indentation).
13281 With reference-manual style, a whole-line comment is indented as if it
13282 were a declaration or statement at the same place
13283 (i.e., according to the indentation of the preceding line(s)).
13284 With GNAT style, a whole-line comment that is immediately followed by an
13285 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13286 word @b{begin}, is indented based on the construct that follows it.
13287
13288 For example:
13289 @smallexample @c ada
13290 @cartouche
13291 if A then
13292     null;
13293        -- some comment
13294 else
13295    null;
13296 end if;
13297 @end cartouche
13298 @end smallexample
13299
13300 @noindent
13301 Reference-manual indentation produces:
13302
13303 @smallexample @c ada
13304 @cartouche
13305 if A then
13306    null;
13307    --  some comment
13308 else
13309    null;
13310 end if;
13311 @end cartouche
13312 @end smallexample
13313
13314 @noindent
13315 while GNAT-style indentation produces:
13316
13317 @smallexample @c ada
13318 @cartouche
13319 if A then
13320    null;
13321 --  some comment
13322 else
13323    null;
13324 end if;
13325 @end cartouche
13326 @end smallexample
13327
13328 @noindent
13329 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13330 (GNAT style comment beginning) has the following
13331 effect:
13332
13333 @itemize @bullet
13334 @item
13335 For each whole-line comment that does not end with two hyphens,
13336 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13337 to ensure that there are at least two spaces between these hyphens and the
13338 first non-blank character of the comment.
13339 @end itemize
13340
13341 @noindent
13342 For an end-of-line comment, if in the original source the next line is a
13343 whole-line comment that starts at the same position
13344 as the end-of-line comment,
13345 then the whole-line comment (and all whole-line comments
13346 that follow it and that start at the same position)
13347 will start at this position in the output file.
13348
13349 @noindent
13350 That is, if in the original source we have:
13351
13352 @smallexample @c ada
13353 @cartouche
13354 begin
13355 A := B + C;            --  B must be in the range Low1..High1
13356                        --  C must be in the range Low2..High2
13357              --B+C will be in the range Low1+Low2..High1+High2
13358 X := X + 1;
13359 @end cartouche
13360 @end smallexample
13361
13362 @noindent
13363 Then in the formatted source we get
13364
13365 @smallexample @c ada
13366 @cartouche
13367 begin
13368    A := B + C;            --  B must be in the range Low1..High1
13369                           --  C must be in the range Low2..High2
13370    --  B+C will be in the range Low1+Low2..High1+High2
13371    X := X + 1;
13372 @end cartouche
13373 @end smallexample
13374
13375 @noindent
13376 A comment that exceeds the line length limit will be split.
13377 Unless switch
13378 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13379 the line belongs to a reformattable block, splitting the line generates a
13380 @command{gnatpp} warning.
13381 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13382 comments may be reformatted in typical
13383 word processor style (that is, moving words between lines and putting as
13384 many words in a line as possible).
13385
13386 @noindent
13387 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13388 that has a special format (that is, a character that is neither a letter nor digit
13389 not white space nor line break immediately following the leading @code{--} of
13390 the comment) should be without any change moved from the argument source
13391 into reformatted source. This switch allows to preserve comments that are used
13392 as a special marks in the code (e.g.@: SPARK annotation).
13393
13394 @node Construct Layout
13395 @subsection Construct Layout
13396
13397 @noindent
13398 In several cases the suggested layout in the Ada Reference Manual includes
13399 an extra level of indentation that many programmers prefer to avoid. The
13400 affected cases include:
13401
13402 @itemize @bullet
13403
13404 @item Record type declaration (RM 3.8)
13405
13406 @item Record representation clause (RM 13.5.1)
13407
13408 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13409
13410 @item Block statement in case if a block has a statement identifier (RM 5.6)
13411 @end itemize
13412
13413 @noindent
13414 In compact mode (when GNAT style layout or compact layout is set),
13415 the pretty printer uses one level of indentation instead
13416 of two. This is achieved in the record definition and record representation
13417 clause cases by putting the @code{record} keyword on the same line as the
13418 start of the declaration or representation clause, and in the block and loop
13419 case by putting the block or loop header on the same line as the statement
13420 identifier.
13421
13422 @noindent
13423 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13424 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13425 layout on the one hand, and uncompact layout
13426 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13427 can be illustrated by the following examples:
13428
13429 @iftex
13430 @cartouche
13431 @multitable @columnfractions .5 .5
13432 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13433
13434 @item
13435 @smallexample @c ada
13436 type q is record
13437    a : integer;
13438    b : integer;
13439 end record;
13440 @end smallexample
13441 @tab
13442 @smallexample @c ada
13443 type q is
13444    record
13445       a : integer;
13446       b : integer;
13447    end record;
13448 @end smallexample
13449
13450 @item
13451 @smallexample @c ada
13452 for q use record
13453    a at 0 range  0 .. 31;
13454    b at 4 range  0 .. 31;
13455 end record;
13456 @end smallexample
13457 @tab
13458 @smallexample @c ada
13459 for q use
13460    record
13461       a at 0 range  0 .. 31;
13462       b at 4 range  0 .. 31;
13463    end record;
13464 @end smallexample
13465
13466 @item
13467 @smallexample @c ada
13468 Block : declare
13469    A : Integer := 3;
13470 begin
13471    Proc (A, A);
13472 end Block;
13473 @end smallexample
13474 @tab
13475 @smallexample @c ada
13476 Block :
13477    declare
13478       A : Integer := 3;
13479    begin
13480       Proc (A, A);
13481    end Block;
13482 @end smallexample
13483
13484 @item
13485 @smallexample @c ada
13486 Clear : for J in 1 .. 10 loop
13487    A (J) := 0;
13488 end loop Clear;
13489 @end smallexample
13490 @tab
13491 @smallexample @c ada
13492 Clear :
13493    for J in 1 .. 10 loop
13494       A (J) := 0;
13495    end loop Clear;
13496 @end smallexample
13497 @end multitable
13498 @end cartouche
13499 @end iftex
13500
13501 @ifnottex
13502 @smallexample
13503 @cartouche
13504 GNAT style, compact layout              Uncompact layout
13505
13506 type q is record                        type q is
13507    a : integer;                            record
13508    b : integer;                               a : integer;
13509 end record;                                   b : integer;
13510                                            end record;
13511
13512 for q use record                        for q use
13513    a at 0 range  0 .. 31;                  record
13514    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13515 end record;                                   b at 4 range  0 .. 31;
13516                                            end record;
13517
13518 Block : declare                         Block :
13519    A : Integer := 3;                       declare
13520 begin                                         A : Integer := 3;
13521    Proc (A, A);                            begin
13522 end Block;                                    Proc (A, A);
13523                                            end Block;
13524
13525 Clear : for J in 1 .. 10 loop           Clear :
13526    A (J) := 0;                             for J in 1 .. 10 loop
13527 end loop Clear;                               A (J) := 0;
13528                                            end loop Clear;
13529 @end cartouche
13530 @end smallexample
13531 @end ifnottex
13532
13533 @noindent
13534 A further difference between GNAT style layout and compact layout is that
13535 GNAT style layout inserts empty lines as separation for
13536 compound statements, return statements and bodies.
13537
13538 Note that the layout specified by
13539 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13540 for named block and loop statements overrides the layout defined by these
13541 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13542 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13543 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13544
13545 @node Name Casing
13546 @subsection Name Casing
13547
13548 @noindent
13549 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13550 the same casing as the corresponding defining identifier.
13551
13552 You control the casing for defining occurrences via the
13553 @option{^-n^/NAME_CASING^} switch.
13554 @ifclear vms
13555 With @option{-nD} (``as declared'', which is the default),
13556 @end ifclear
13557 @ifset vms
13558 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13559 @end ifset
13560 defining occurrences appear exactly as in the source file
13561 where they are declared.
13562 The other ^values for this switch^options for this qualifier^ ---
13563 @option{^-nU^UPPER_CASE^},
13564 @option{^-nL^LOWER_CASE^},
13565 @option{^-nM^MIXED_CASE^} ---
13566 result in
13567 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13568 If @command{gnatpp} changes the casing of a defining
13569 occurrence, it analogously changes the casing of all the
13570 usage occurrences of this name.
13571
13572 If the defining occurrence of a name is not in the source compilation unit
13573 currently being processed by @command{gnatpp}, the casing of each reference to
13574 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13575 switch (subject to the dictionary file mechanism described below).
13576 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13577 had affected the
13578 casing for the defining occurrence of the name.
13579
13580 Some names may need to be spelled with casing conventions that are not
13581 covered by the upper-, lower-, and mixed-case transformations.
13582 You can arrange correct casing by placing such names in a
13583 @emph{dictionary file},
13584 and then supplying a @option{^-D^/DICTIONARY^} switch.
13585 The casing of names from dictionary files overrides
13586 any @option{^-n^/NAME_CASING^} switch.
13587
13588 To handle the casing of Ada predefined names and the names from GNAT libraries,
13589 @command{gnatpp} assumes a default dictionary file.
13590 The name of each predefined entity is spelled with the same casing as is used
13591 for the entity in the @cite{Ada Reference Manual}.
13592 The name of each entity in the GNAT libraries is spelled with the same casing
13593 as is used in the declaration of that entity.
13594
13595 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13596 default dictionary file.
13597 Instead, the casing for predefined and GNAT-defined names will be established
13598 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13599 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13600 will appear as just shown,
13601 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13602 To ensure that even such names are rendered in uppercase,
13603 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13604 (or else, less conveniently, place these names in upper case in a dictionary
13605 file).
13606
13607 A dictionary file is
13608 a plain text file; each line in this file can be either a blank line
13609 (containing only space characters and ASCII.HT characters), an Ada comment
13610 line, or the specification of exactly one @emph{casing schema}.
13611
13612 A casing schema is a string that has the following syntax:
13613
13614 @smallexample
13615 @cartouche
13616   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13617
13618   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13619 @end cartouche
13620 @end smallexample
13621
13622 @noindent
13623 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13624 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13625
13626 The casing schema string can be followed by white space and/or an Ada-style
13627 comment; any amount of white space is allowed before the string.
13628
13629 If a dictionary file is passed as
13630 @ifclear vms
13631 the value of a @option{-D@var{file}} switch
13632 @end ifclear
13633 @ifset vms
13634 an option to the @option{/DICTIONARY} qualifier
13635 @end ifset
13636 then for every
13637 simple name and every identifier, @command{gnatpp} checks if the dictionary
13638 defines the casing for the name or for some of its parts (the term ``subword''
13639 is used below to denote the part of a name which is delimited by ``_'' or by
13640 the beginning or end of the word and which does not contain any ``_'' inside):
13641
13642 @itemize @bullet
13643 @item
13644 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13645 the casing defined by the dictionary; no subwords are checked for this word
13646
13647 @item
13648 for every subword @command{gnatpp} checks if the dictionary contains the
13649 corresponding string of the form @code{*@var{simple_identifier}*},
13650 and if it does, the casing of this @var{simple_identifier} is used
13651 for this subword
13652
13653 @item
13654 if the whole name does not contain any ``_'' inside, and if for this name
13655 the dictionary contains two entries - one of the form @var{identifier},
13656 and another - of the form *@var{simple_identifier}*, then the first one
13657 is applied to define the casing of this name
13658
13659 @item
13660 if more than one dictionary file is passed as @command{gnatpp} switches, each
13661 dictionary adds new casing exceptions and overrides all the existing casing
13662 exceptions set by the previous dictionaries
13663
13664 @item
13665 when @command{gnatpp} checks if the word or subword is in the dictionary,
13666 this check is not case sensitive
13667 @end itemize
13668
13669 @noindent
13670 For example, suppose we have the following source to reformat:
13671
13672 @smallexample @c ada
13673 @cartouche
13674 procedure test is
13675    name1 : integer := 1;
13676    name4_name3_name2 : integer := 2;
13677    name2_name3_name4 : Boolean;
13678    name1_var : Float;
13679 begin
13680    name2_name3_name4 := name4_name3_name2 > name1;
13681 end;
13682 @end cartouche
13683 @end smallexample
13684
13685 @noindent
13686 And suppose we have two dictionaries:
13687
13688 @smallexample
13689 @cartouche
13690 @i{dict1:}
13691    NAME1
13692    *NaMe3*
13693    *Name1*
13694 @end cartouche
13695
13696 @cartouche
13697 @i{dict2:}
13698   *NAME3*
13699 @end cartouche
13700 @end smallexample
13701
13702 @noindent
13703 If @command{gnatpp} is called with the following switches:
13704
13705 @smallexample
13706 @ifclear vms
13707 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13708 @end ifclear
13709 @ifset vms
13710 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13711 @end ifset
13712 @end smallexample
13713
13714 @noindent
13715 then we will get the following name casing in the @command{gnatpp} output:
13716
13717 @smallexample @c ada
13718 @cartouche
13719 procedure Test is
13720    NAME1             : Integer := 1;
13721    Name4_NAME3_Name2 : Integer := 2;
13722    Name2_NAME3_Name4 : Boolean;
13723    Name1_Var         : Float;
13724 begin
13725    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13726 end Test;
13727 @end cartouche
13728 @end smallexample
13729
13730 @c *********************************
13731 @node The GNAT Metric Tool gnatmetric
13732 @chapter The GNAT Metric Tool @command{gnatmetric}
13733 @findex gnatmetric
13734 @cindex Metric tool
13735
13736 @noindent
13737 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13738 for computing various program metrics.
13739 It takes an Ada source file as input and generates a file containing the
13740 metrics data as output. Various switches control which
13741 metrics are computed and output.
13742
13743 @command{gnatmetric} generates and uses the ASIS
13744 tree for the input source and thus requires the input to be syntactically and
13745 semantically legal.
13746 If this condition is not met, @command{gnatmetric} will generate
13747 an error message; no metric information for this file will be
13748 computed and reported.
13749
13750 If the compilation unit contained in the input source depends semantically
13751 upon units in files located outside the current directory, you have to provide
13752 the source search path when invoking @command{gnatmetric}.
13753 If it depends semantically upon units that are contained
13754 in files with names that do not follow the GNAT file naming rules, you have to
13755 provide the configuration file describing the corresponding naming scheme (see
13756 the description of the @command{gnatmetric} switches below.)
13757 Alternatively, you may use a project file and invoke @command{gnatmetric}
13758 through the @command{gnat} driver.
13759
13760 The @command{gnatmetric} command has the form
13761
13762 @smallexample
13763 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13764 @c Expanding @ovar macro inline (explanation in macro def comments)
13765 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13766 @end smallexample
13767
13768 @noindent
13769 where
13770 @itemize @bullet
13771 @item
13772 @var{switches} specify the metrics to compute and define the destination for
13773 the output
13774
13775 @item
13776 Each @var{filename} is the name (including the extension) of a source
13777 file to process. ``Wildcards'' are allowed, and
13778 the file name may contain path information.
13779 If no @var{filename} is supplied, then the @var{switches} list must contain
13780 at least one
13781 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13782 Including both a @option{-files} switch and one or more
13783 @var{filename} arguments is permitted.
13784
13785 @item
13786 @samp{@var{gcc_switches}} is a list of switches for
13787 @command{gcc}. They will be passed on to all compiler invocations made by
13788 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13789 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13790 and use the @option{-gnatec} switch to set the configuration file,
13791 use the @option{-gnat05} switch if sources should be compiled in
13792 Ada 2005 mode etc.
13793 @end itemize
13794
13795 @menu
13796 * Switches for gnatmetric::
13797 @end menu
13798
13799 @node Switches for gnatmetric
13800 @section Switches for @command{gnatmetric}
13801
13802 @noindent
13803 The following subsections describe the various switches accepted by
13804 @command{gnatmetric}, organized by category.
13805
13806 @menu
13807 * Output Files Control::
13808 * Disable Metrics For Local Units::
13809 * Specifying a set of metrics to compute::
13810 * Other gnatmetric Switches::
13811 * Generate project-wide metrics::
13812 @end menu
13813
13814 @node Output Files Control
13815 @subsection Output File Control
13816 @cindex Output file control in @command{gnatmetric}
13817
13818 @noindent
13819 @command{gnatmetric} has two output formats. It can generate a
13820 textual (human-readable) form, and also XML. By default only textual
13821 output is generated.
13822
13823 When generating the output in textual form, @command{gnatmetric} creates
13824 for each Ada source file a corresponding text file
13825 containing the computed metrics, except for the case when the set of metrics
13826 specified by gnatmetric parameters consists only of metrics that are computed
13827 for the whole set of analyzed sources, but not for each Ada source.
13828 By default, this file is placed in the same directory as where the source
13829 file is located, and its name is obtained
13830 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13831 input file.
13832
13833 All the output information generated in XML format is placed in a single
13834 file. By default this file is placed in the current directory and has the
13835 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13836
13837 Some of the computed metrics are summed over the units passed to
13838 @command{gnatmetric}; for example, the total number of lines of code.
13839 By default this information is sent to @file{stdout}, but a file
13840 can be specified with the @option{-og} switch.
13841
13842 The following switches control the @command{gnatmetric} output:
13843
13844 @table @option
13845 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13846 @item ^-x^/XML^
13847 Generate the XML output
13848
13849 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13850 @item ^-xs^/XSD^
13851 Generate the XML output and the XML schema file that describes the structure
13852 of the XML metric report, this schema is assigned to the XML file. The schema
13853 file has the same name as the XML output file with @file{.xml} suffix replaced
13854 with @file{.xsd}
13855
13856 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13857 @item ^-nt^/NO_TEXT^
13858 Do not generate the output in text form (implies @option{^-x^/XML^})
13859
13860 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13861 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13862 Put text files with detailed metrics into @var{output_dir}
13863
13864 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13865 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13866 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13867 in the name of the output file.
13868
13869 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13870 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13871 Put global metrics into @var{file_name}
13872
13873 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13874 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13875 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13876
13877 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13878 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13879 Use ``short'' source file names in the output.  (The @command{gnatmetric}
13880 output includes the name(s) of the Ada source file(s) from which the metrics
13881 are computed.  By default each name includes the absolute path. The
13882 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13883 to exclude all directory information from the file names that are output.)
13884
13885 @end table
13886
13887 @node Disable Metrics For Local Units
13888 @subsection Disable Metrics For Local Units
13889 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13890
13891 @noindent
13892 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13893 one compilation
13894 unit per one source file. It computes line metrics for the whole source
13895 file, and it also computes syntax
13896 and complexity metrics for the file's outermost unit.
13897
13898 By default, @command{gnatmetric} will also compute all metrics for certain
13899 kinds of locally declared program units:
13900
13901 @itemize @bullet
13902 @item
13903 subprogram (and generic subprogram) bodies;
13904
13905 @item
13906 package (and generic package) specs and bodies;
13907
13908 @item
13909 task object and type specifications and bodies;
13910
13911 @item
13912 protected object and type specifications and bodies.
13913 @end itemize
13914
13915 @noindent
13916 These kinds of entities will be referred to as
13917 @emph{eligible local program units}, or simply @emph{eligible local units},
13918 @cindex Eligible local unit (for @command{gnatmetric})
13919 in the discussion below.
13920
13921 Note that a subprogram declaration, generic instantiation,
13922 or renaming declaration only receives metrics
13923 computation when it appear as the outermost entity
13924 in a source file.
13925
13926 Suppression of metrics computation for eligible local units can be
13927 obtained via the following switch:
13928
13929 @table @option
13930 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13931 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13932 Do not compute detailed metrics for eligible local program units
13933
13934 @end table
13935
13936 @node Specifying a set of metrics to compute
13937 @subsection Specifying a set of metrics to compute
13938
13939 @noindent
13940 By default all the metrics are computed and reported. The switches
13941 described in this subsection allow you to control, on an individual
13942 basis, whether metrics are computed and
13943 reported. If at least one positive metric
13944 switch is specified (that is, a switch that defines that a given
13945 metric or set of metrics is to be computed), then only
13946 explicitly specified metrics are reported.
13947
13948 @menu
13949 * Line Metrics Control::
13950 * Syntax Metrics Control::
13951 * Complexity Metrics Control::
13952 * Object-Oriented Metrics Control::
13953 @end menu
13954
13955 @node Line Metrics Control
13956 @subsubsection Line Metrics Control
13957 @cindex Line metrics control in @command{gnatmetric}
13958
13959 @noindent
13960 For any (legal) source file, and for each of its
13961 eligible local program units, @command{gnatmetric} computes the following
13962 metrics:
13963
13964 @itemize @bullet
13965 @item
13966 the total number of lines;
13967
13968 @item
13969 the total number of code lines (i.e., non-blank lines that are not comments)
13970
13971 @item
13972 the number of comment lines
13973
13974 @item
13975 the number of code lines containing end-of-line comments;
13976
13977 @item
13978 the comment percentage: the ratio between the number of lines that contain
13979 comments and the number of all non-blank lines, expressed as a percentage;
13980
13981 @item
13982 the number of empty lines and lines containing only space characters and/or
13983 format effectors (blank lines)
13984
13985 @item
13986 the average number of code lines in subprogram bodies, task bodies, entry
13987 bodies and statement sequences in package bodies (this metric is only computed
13988 across the whole set of the analyzed units)
13989
13990 @end itemize
13991
13992 @noindent
13993 @command{gnatmetric} sums the values of the line metrics for all the
13994 files being processed and then generates the cumulative results. The tool
13995 also computes for all the files being processed the average number of code
13996 lines in bodies.
13997
13998 You can use the following switches to select the specific line metrics
13999 to be computed and reported.
14000
14001 @table @option
14002 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14003
14004 @ifclear vms
14005 @cindex @option{--no-lines@var{x}}
14006 @end ifclear
14007
14008 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14009 Report all the line metrics
14010
14011 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14012 Do not report any of line metrics
14013
14014 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14015 Report the number of all lines
14016
14017 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14018 Do not report the number of all lines
14019
14020 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14021 Report the number of code lines
14022
14023 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14024 Do not report the number of code lines
14025
14026 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14027 Report the number of comment lines
14028
14029 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14030 Do not report the number of comment lines
14031
14032 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14033 Report the number of code lines containing
14034 end-of-line comments
14035
14036 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14037 Do not report the number of code lines containing
14038 end-of-line comments
14039
14040 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14041 Report the comment percentage in the program text
14042
14043 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14044 Do not report the comment percentage in the program text
14045
14046 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14047 Report the number of blank lines
14048
14049 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14050 Do not report the number of blank lines
14051
14052 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14053 Report the average number of code lines in subprogram bodies, task bodies,
14054 entry bodies and statement sequences in package bodies. The metric is computed
14055 and reported for the whole set of processed Ada sources only.
14056
14057 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14058 Do not report the average number of code lines in subprogram bodies,
14059 task bodies, entry bodies and statement sequences in package bodies.
14060
14061 @end table
14062
14063 @node Syntax Metrics Control
14064 @subsubsection Syntax Metrics Control
14065 @cindex Syntax metrics control in @command{gnatmetric}
14066
14067 @noindent
14068 @command{gnatmetric} computes various syntactic metrics for the
14069 outermost unit and for each eligible local unit:
14070
14071 @table @emph
14072 @item LSLOC (``Logical Source Lines Of Code'')
14073 The total number of declarations and the total number of statements
14074
14075 @item Maximal static nesting level of inner program units
14076 According to
14077 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14078 package, a task unit, a protected unit, a
14079 protected entry, a generic unit, or an explicitly declared subprogram other
14080 than an enumeration literal.''
14081
14082 @item Maximal nesting level of composite syntactic constructs
14083 This corresponds to the notion of the
14084 maximum nesting level in the GNAT built-in style checks
14085 (@pxref{Style Checking})
14086 @end table
14087
14088 @noindent
14089 For the outermost unit in the file, @command{gnatmetric} additionally computes
14090 the following metrics:
14091
14092 @table @emph
14093 @item Public subprograms
14094 This metric is computed for package specs. It is the
14095 number of subprograms and generic subprograms declared in the visible
14096 part (including the visible part of nested packages, protected objects, and
14097 protected types).
14098
14099 @item All subprograms
14100 This metric is computed for bodies and subunits. The
14101 metric is equal to a total number of subprogram bodies in the compilation
14102 unit.
14103 Neither generic instantiations nor renamings-as-a-body nor body stubs
14104 are counted. Any subprogram body is counted, independently of its nesting
14105 level and enclosing constructs. Generic bodies and bodies of protected
14106 subprograms are counted in the same way as ``usual'' subprogram bodies.
14107
14108 @item Public types
14109 This metric is computed for package specs and
14110 generic package declarations. It is the total number of types
14111 that can be referenced from outside this compilation unit, plus the
14112 number of types from all the visible parts of all the visible generic
14113 packages. Generic formal types are not counted.  Only types, not subtypes,
14114 are included.
14115
14116 @noindent
14117 Along with the total number of public types, the following
14118 types are counted and reported separately:
14119
14120 @itemize @bullet
14121 @item
14122 Abstract types
14123
14124 @item
14125 Root tagged types (abstract, non-abstract, private, non-private). Type
14126 extensions are @emph{not} counted
14127
14128 @item
14129 Private types (including private extensions)
14130
14131 @item
14132 Task types
14133
14134 @item
14135 Protected types
14136
14137 @end itemize
14138
14139 @item All types
14140 This metric is computed for any compilation unit. It is equal to the total
14141 number of the declarations of different types given in the compilation unit.
14142 The private and the corresponding full type declaration are counted as one
14143 type declaration. Incomplete type declarations and generic formal types
14144 are not counted.
14145 No distinction is made among different kinds of types (abstract,
14146 private etc.); the total number of types is computed and reported.
14147
14148 @end table
14149
14150 @noindent
14151 By default, all the syntax metrics are computed and reported. You can use the
14152 following switches to select specific syntax metrics.
14153
14154 @table @option
14155
14156 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14157
14158 @ifclear vms
14159 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14160 @end ifclear
14161
14162 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14163 Report all the syntax metrics
14164
14165 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14166 Do not report any of syntax metrics
14167
14168 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14169 Report the total number of declarations
14170
14171 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14172 Do not report the total number of declarations
14173
14174 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14175 Report the total number of statements
14176
14177 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14178 Do not report the total number of statements
14179
14180 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14181 Report the number of public subprograms in a compilation unit
14182
14183 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14184 Do not report the number of public subprograms in a compilation unit
14185
14186 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14187 Report the number of all the subprograms in a compilation unit
14188
14189 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14190 Do not report the number of all the subprograms in a compilation unit
14191
14192 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14193 Report the number of public types in a compilation unit
14194
14195 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14196 Do not report the number of public types in a compilation unit
14197
14198 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14199 Report the number of all the types in a compilation unit
14200
14201 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14202 Do not report the number of all the types in a compilation unit
14203
14204 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14205 Report the maximal program unit nesting level
14206
14207 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14208 Do not report the maximal program unit nesting level
14209
14210 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14211 Report the maximal construct nesting level
14212
14213 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14214 Do not report the maximal construct nesting level
14215
14216 @end table
14217
14218 @node Complexity Metrics Control
14219 @subsubsection Complexity Metrics Control
14220 @cindex Complexity metrics control in @command{gnatmetric}
14221
14222 @noindent
14223 For a program unit that is an executable body (a subprogram body (including
14224 generic bodies), task body, entry body or a package body containing
14225 its own statement sequence) @command{gnatmetric} computes the following
14226 complexity metrics:
14227
14228 @itemize @bullet
14229 @item
14230 McCabe cyclomatic complexity;
14231
14232 @item
14233 McCabe essential complexity;
14234
14235 @item
14236 maximal loop nesting level
14237
14238 @end itemize
14239
14240 @noindent
14241 The McCabe complexity metrics are defined
14242 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14243
14244 According to McCabe, both control statements and short-circuit control forms
14245 should be taken into account when computing cyclomatic complexity. For each
14246 body, we compute three metric values:
14247
14248 @itemize @bullet
14249 @item
14250 the complexity introduced by control
14251 statements only, without taking into account short-circuit forms,
14252
14253 @item
14254 the complexity introduced by short-circuit control forms only, and
14255
14256 @item
14257 the total
14258 cyclomatic complexity, which is the sum of these two values.
14259 @end itemize
14260
14261 @noindent
14262 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14263 the code in the exception handlers and in all the nested program units.
14264
14265 By default, all the complexity metrics are computed and reported.
14266 For more fine-grained control you can use
14267 the following switches:
14268
14269 @table @option
14270 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14271
14272 @ifclear vms
14273 @cindex @option{--no-complexity@var{x}}
14274 @end ifclear
14275
14276 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14277 Report all the complexity metrics
14278
14279 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14280 Do not report any of complexity metrics
14281
14282 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14283 Report the McCabe Cyclomatic Complexity
14284
14285 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14286 Do not report the McCabe Cyclomatic Complexity
14287
14288 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14289 Report the Essential Complexity
14290
14291 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14292 Do not report the Essential Complexity
14293
14294 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14295 Report maximal loop nesting level
14296
14297 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14298 Do not report maximal loop nesting level
14299
14300 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14301 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14302 task bodies, entry bodies and statement sequences in package bodies.
14303 The metric is computed and reported for whole set of processed Ada sources
14304 only.
14305
14306 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14307 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14308 bodies, task bodies, entry bodies and statement sequences in package bodies
14309
14310 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14311 @item ^-ne^/NO_EXITS_AS_GOTOS^
14312 Do not consider @code{exit} statements as @code{goto}s when
14313 computing Essential Complexity
14314
14315 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14316 Report the extra exit points for subprogram bodies. As an exit point, this
14317 metric counts @code{return} statements and raise statements in case when the
14318 raised exception is not handled in the same body. In case of a function this
14319 metric subtracts 1 from the number of exit points, because a function body
14320 must contain at least one @code{return} statement.
14321
14322 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14323 Do not report the extra exit points for subprogram bodies
14324 @end table
14325
14326
14327 @node Object-Oriented Metrics Control
14328 @subsubsection Object-Oriented Metrics Control
14329 @cindex Object-Oriented metrics control in @command{gnatmetric}
14330
14331 @noindent
14332 @cindex Coupling metrics (in in @command{gnatmetric})
14333 Coupling metrics are object-oriented metrics that measure the
14334 dependencies between a given class (or a group of classes) and the
14335 ``external world'' (that is, the other classes in the program). In this
14336 subsection the term ``class'' is used in its
14337 traditional object-oriented programming sense
14338 (an instantiable module that contains data and/or method members).
14339 A @emph{category} (of classes)
14340 is a group of closely related classes that are reused and/or
14341 modified together.
14342
14343 A class @code{K}'s @emph{efferent coupling} is the number of classes
14344 that @code{K} depends upon.
14345 A category's efferent coupling is the number of classes outside the
14346 category that the classes inside the category depend upon.
14347
14348 A class @code{K}'s @emph{afferent coupling} is the number of classes
14349 that depend upon @code{K}.
14350 A category's afferent coupling is the number of classes outside the
14351 category that depend on classes belonging to the category.
14352
14353 Ada's implementation of the object-oriented paradigm does not use the
14354 traditional class notion, so the definition of the coupling
14355 metrics for Ada maps the class and class category notions
14356 onto Ada constructs.
14357
14358 For the coupling metrics, several kinds of modules -- a library package,
14359 a library generic package, and a library generic package instantiation --
14360 that define a tagged type or an interface type are
14361 considered to be a class. A category consists of a library package (or
14362 a library generic package) that defines a tagged or an interface type,
14363 together with all its descendant (generic) packages that define tagged
14364 or interface types. For any package counted as a class,
14365 its body and subunits (if any) are considered
14366 together with its spec when counting the dependencies, and coupling
14367 metrics are reported for spec units only. For dependencies
14368 between classes, the Ada semantic dependencies are considered.
14369 For coupling metrics, only dependencies on units that are considered as
14370 classes, are considered.
14371
14372 When computing coupling metrics, @command{gnatmetric} counts only
14373 dependencies between units that are arguments of the gnatmetric call.
14374 Coupling metrics are program-wide (or project-wide) metrics, so to
14375 get a valid result, you should call @command{gnatmetric} for
14376 the whole set of sources that make up your program. It can be done
14377 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14378 option (see See @ref{The GNAT Driver and Project Files} for details.
14379
14380 By default, all the coupling metrics are disabled. You can use the following
14381 switches to specify the coupling metrics to be computed and reported:
14382
14383 @table @option
14384
14385 @ifclear vms
14386 @cindex @option{--package@var{x}} (@command{gnatmetric})
14387 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14388 @cindex @option{--category@var{x}} (@command{gnatmetric})
14389 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14390 @end ifclear
14391
14392 @ifset vms
14393 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14394 @end ifset
14395
14396 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14397 Report all the coupling metrics
14398
14399 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14400 Do not report any of  metrics
14401
14402 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14403 Report package efferent coupling
14404
14405 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14406 Do not report package efferent coupling
14407
14408 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14409 Report package afferent coupling
14410
14411 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14412 Do not report package afferent coupling
14413
14414 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14415 Report category efferent coupling
14416
14417 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14418 Do not report category efferent coupling
14419
14420 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14421 Report category afferent coupling
14422
14423 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14424 Do not report category afferent coupling
14425
14426 @end table
14427
14428 @node Other gnatmetric Switches
14429 @subsection Other @code{gnatmetric} Switches
14430
14431 @noindent
14432 Additional @command{gnatmetric} switches are as follows:
14433
14434 @table @option
14435 @item ^-files @var{filename}^/FILES=@var{filename}^
14436 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14437 Take the argument source files from the specified file. This file should be an
14438 ordinary text file containing file names separated by spaces or
14439 line breaks. You can use this switch more than once in the same call to
14440 @command{gnatmetric}. You also can combine this switch with
14441 an explicit list of files.
14442
14443 @item ^-v^/VERBOSE^
14444 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14445 Verbose mode;
14446 @command{gnatmetric} generates version information and then
14447 a trace of sources being processed.
14448
14449 @item ^-dv^/DEBUG_OUTPUT^
14450 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14451 Debug mode;
14452 @command{gnatmetric} generates various messages useful to understand what
14453 happens during the metrics computation
14454
14455 @item ^-q^/QUIET^
14456 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14457 Quiet mode.
14458 @end table
14459
14460 @node Generate project-wide metrics
14461 @subsection Generate project-wide metrics
14462
14463 In order to compute metrics on all units of a given project, you can use
14464 the @command{gnat} driver along with the @option{-P} option:
14465 @smallexample
14466    gnat metric -Pproj
14467 @end smallexample
14468
14469 @noindent
14470 If the project @code{proj} depends upon other projects, you can compute
14471 the metrics on the project closure using the @option{-U} option:
14472 @smallexample
14473    gnat metric -Pproj -U
14474 @end smallexample
14475
14476 @noindent
14477 Finally, if not all the units are relevant to a particular main
14478 program in the project closure, you can generate metrics for the set
14479 of units needed to create a given main program (unit closure) using
14480 the @option{-U} option followed by the name of the main unit:
14481 @smallexample
14482    gnat metric -Pproj -U main
14483 @end smallexample
14484
14485
14486 @c ***********************************
14487 @node File Name Krunching Using gnatkr
14488 @chapter File Name Krunching Using @code{gnatkr}
14489 @findex gnatkr
14490
14491 @noindent
14492 This chapter discusses the method used by the compiler to shorten
14493 the default file names chosen for Ada units so that they do not
14494 exceed the maximum length permitted. It also describes the
14495 @code{gnatkr} utility that can be used to determine the result of
14496 applying this shortening.
14497 @menu
14498 * About gnatkr::
14499 * Using gnatkr::
14500 * Krunching Method::
14501 * Examples of gnatkr Usage::
14502 @end menu
14503
14504 @node About gnatkr
14505 @section About @code{gnatkr}
14506
14507 @noindent
14508 The default file naming rule in GNAT
14509 is that the file name must be derived from
14510 the unit name. The exact default rule is as follows:
14511 @itemize @bullet
14512 @item
14513 Take the unit name and replace all dots by hyphens.
14514 @item
14515 If such a replacement occurs in the
14516 second character position of a name, and the first character is
14517 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14518 then replace the dot by the character
14519 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14520 instead of a minus.
14521 @end itemize
14522 The reason for this exception is to avoid clashes
14523 with the standard names for children of System, Ada, Interfaces,
14524 and GNAT, which use the prefixes
14525 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14526 respectively.
14527
14528 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14529 switch of the compiler activates a ``krunching''
14530 circuit that limits file names to nn characters (where nn is a decimal
14531 integer). For example, using OpenVMS,
14532 where the maximum file name length is
14533 39, the value of nn is usually set to 39, but if you want to generate
14534 a set of files that would be usable if ported to a system with some
14535 different maximum file length, then a different value can be specified.
14536 The default value of 39 for OpenVMS need not be specified.
14537
14538 The @code{gnatkr} utility can be used to determine the krunched name for
14539 a given file, when krunched to a specified maximum length.
14540
14541 @node Using gnatkr
14542 @section Using @code{gnatkr}
14543
14544 @noindent
14545 The @code{gnatkr} command has the form
14546
14547 @ifclear vms
14548 @smallexample
14549 @c $ gnatkr @var{name} @ovar{length}
14550 @c Expanding @ovar macro inline (explanation in macro def comments)
14551 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14552 @end smallexample
14553 @end ifclear
14554
14555 @ifset vms
14556 @smallexample
14557 $ gnatkr @var{name} /COUNT=nn
14558 @end smallexample
14559 @end ifset
14560
14561 @noindent
14562 @var{name} is the uncrunched file name, derived from the name of the unit
14563 in the standard manner described in the previous section (i.e., in particular
14564 all dots are replaced by hyphens). The file name may or may not have an
14565 extension (defined as a suffix of the form period followed by arbitrary
14566 characters other than period). If an extension is present then it will
14567 be preserved in the output. For example, when krunching @file{hellofile.ads}
14568 to eight characters, the result will be hellofil.ads.
14569
14570 Note: for compatibility with previous versions of @code{gnatkr} dots may
14571 appear in the name instead of hyphens, but the last dot will always be
14572 taken as the start of an extension. So if @code{gnatkr} is given an argument
14573 such as @file{Hello.World.adb} it will be treated exactly as if the first
14574 period had been a hyphen, and for example krunching to eight characters
14575 gives the result @file{hellworl.adb}.
14576
14577 Note that the result is always all lower case (except on OpenVMS where it is
14578 all upper case). Characters of the other case are folded as required.
14579
14580 @var{length} represents the length of the krunched name. The default
14581 when no argument is given is ^8^39^ characters. A length of zero stands for
14582 unlimited, in other words do not chop except for system files where the
14583 implied crunching length is always eight characters.
14584
14585 @noindent
14586 The output is the krunched name. The output has an extension only if the
14587 original argument was a file name with an extension.
14588
14589 @node Krunching Method
14590 @section Krunching Method
14591
14592 @noindent
14593 The initial file name is determined by the name of the unit that the file
14594 contains. The name is formed by taking the full expanded name of the
14595 unit and replacing the separating dots with hyphens and
14596 using ^lowercase^uppercase^
14597 for all letters, except that a hyphen in the second character position is
14598 replaced by a ^tilde^dollar sign^ if the first character is
14599 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14600 The extension is @code{.ads} for a
14601 spec and @code{.adb} for a body.
14602 Krunching does not affect the extension, but the file name is shortened to
14603 the specified length by following these rules:
14604
14605 @itemize @bullet
14606 @item
14607 The name is divided into segments separated by hyphens, tildes or
14608 underscores and all hyphens, tildes, and underscores are
14609 eliminated. If this leaves the name short enough, we are done.
14610
14611 @item
14612 If the name is too long, the longest segment is located (left-most
14613 if there are two of equal length), and shortened by dropping
14614 its last character. This is repeated until the name is short enough.
14615
14616 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14617 to fit the name into 8 characters as required by some operating systems.
14618
14619 @smallexample
14620 our-strings-wide_fixed 22
14621 our strings wide fixed 19
14622 our string  wide fixed 18
14623 our strin   wide fixed 17
14624 our stri    wide fixed 16
14625 our stri    wide fixe  15
14626 our str     wide fixe  14
14627 our str     wid  fixe  13
14628 our str     wid  fix   12
14629 ou  str     wid  fix   11
14630 ou  st      wid  fix   10
14631 ou  st      wi   fix   9
14632 ou  st      wi   fi    8
14633 Final file name: oustwifi.adb
14634 @end smallexample
14635
14636 @item
14637 The file names for all predefined units are always krunched to eight
14638 characters. The krunching of these predefined units uses the following
14639 special prefix replacements:
14640
14641 @table @file
14642 @item ada-
14643 replaced by @file{^a^A^-}
14644
14645 @item gnat-
14646 replaced by @file{^g^G^-}
14647
14648 @item interfaces-
14649 replaced by @file{^i^I^-}
14650
14651 @item system-
14652 replaced by @file{^s^S^-}
14653 @end table
14654
14655 These system files have a hyphen in the second character position. That
14656 is why normal user files replace such a character with a
14657 ^tilde^dollar sign^, to
14658 avoid confusion with system file names.
14659
14660 As an example of this special rule, consider
14661 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14662
14663 @smallexample
14664 ada-strings-wide_fixed 22
14665 a-  strings wide fixed 18
14666 a-  string  wide fixed 17
14667 a-  strin   wide fixed 16
14668 a-  stri    wide fixed 15
14669 a-  stri    wide fixe  14
14670 a-  str     wide fixe  13
14671 a-  str     wid  fixe  12
14672 a-  str     wid  fix   11
14673 a-  st      wid  fix   10
14674 a-  st      wi   fix   9
14675 a-  st      wi   fi    8
14676 Final file name: a-stwifi.adb
14677 @end smallexample
14678 @end itemize
14679
14680 Of course no file shortening algorithm can guarantee uniqueness over all
14681 possible unit names, and if file name krunching is used then it is your
14682 responsibility to ensure that no name clashes occur. The utility
14683 program @code{gnatkr} is supplied for conveniently determining the
14684 krunched name of a file.
14685
14686 @node Examples of gnatkr Usage
14687 @section Examples of @code{gnatkr} Usage
14688
14689 @smallexample
14690 @iftex
14691 @leftskip=0cm
14692 @end iftex
14693 @ifclear vms
14694 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14695 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14696 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14697 $ gnatkr grandparent-parent-child     --> grparchi
14698 @end ifclear
14699 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14700 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14701 @end smallexample
14702
14703 @node Preprocessing Using gnatprep
14704 @chapter Preprocessing Using @code{gnatprep}
14705 @findex gnatprep
14706
14707 @noindent
14708 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14709 preprocessing.
14710 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14711 special GNAT features.
14712 For further discussion of conditional compilation in general, see
14713 @ref{Conditional Compilation}.
14714
14715 @menu
14716 * Preprocessing Symbols::
14717 * Using gnatprep::
14718 * Switches for gnatprep::
14719 * Form of Definitions File::
14720 * Form of Input Text for gnatprep::
14721 @end menu
14722
14723 @node Preprocessing Symbols
14724 @section Preprocessing Symbols
14725
14726 @noindent
14727 Preprocessing symbols are defined in definition files and referred to in
14728 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14729 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14730 all characters need to be in the ASCII set (no accented letters).
14731
14732 @node Using gnatprep
14733 @section Using @code{gnatprep}
14734
14735 @noindent
14736 To call @code{gnatprep} use
14737
14738 @smallexample
14739 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14740 @c Expanding @ovar macro inline (explanation in macro def comments)
14741 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14742 @end smallexample
14743
14744 @noindent
14745 where
14746 @table @var
14747 @item switches
14748 is an optional sequence of switches as described in the next section.
14749
14750 @item infile
14751 is the full name of the input file, which is an Ada source
14752 file containing preprocessor directives.
14753
14754 @item outfile
14755 is the full name of the output file, which is an Ada source
14756 in standard Ada form. When used with GNAT, this file name will
14757 normally have an ads or adb suffix.
14758
14759 @item deffile
14760 is the full name of a text file containing definitions of
14761 preprocessing symbols to be referenced by the preprocessor. This argument is
14762 optional, and can be replaced by the use of the @option{-D} switch.
14763
14764 @end table
14765
14766 @node Switches for gnatprep
14767 @section Switches for @code{gnatprep}
14768
14769 @table @option
14770 @c !sort!
14771
14772 @item ^-b^/BLANK_LINES^
14773 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14774 Causes both preprocessor lines and the lines deleted by
14775 preprocessing to be replaced by blank lines in the output source file,
14776 preserving line numbers in the output file.
14777
14778 @item ^-c^/COMMENTS^
14779 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14780 Causes both preprocessor lines and the lines deleted
14781 by preprocessing to be retained in the output source as comments marked
14782 with the special string @code{"--! "}. This option will result in line numbers
14783 being preserved in the output file.
14784
14785 @item ^-C^/REPLACE_IN_COMMENTS^
14786 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14787 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14788 If this option is specified, then comments are scanned and any $symbol
14789 substitutions performed as in program text. This is particularly useful
14790 when structured comments are used (e.g., when writing programs in the
14791 SPARK dialect of Ada). Note that this switch is not available when
14792 doing integrated preprocessing (it would be useless in this context
14793 since comments are ignored by the compiler in any case).
14794
14795 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14796 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14797 Defines a new preprocessing symbol, associated with value. If no value is given
14798 on the command line, then symbol is considered to be @code{True}. This switch
14799 can be used in place of a definition file.
14800
14801 @ifset vms
14802 @item /REMOVE
14803 @cindex @option{/REMOVE} (@command{gnatprep})
14804 This is the default setting which causes lines deleted by preprocessing
14805 to be entirely removed from the output file.
14806 @end ifset
14807
14808 @item ^-r^/REFERENCE^
14809 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14810 Causes a @code{Source_Reference} pragma to be generated that
14811 references the original input file, so that error messages will use
14812 the file name of this original file. The use of this switch implies
14813 that preprocessor lines are not to be removed from the file, so its
14814 use will force @option{^-b^/BLANK_LINES^} mode if
14815 @option{^-c^/COMMENTS^}
14816 has not been specified explicitly.
14817
14818 Note that if the file to be preprocessed contains multiple units, then
14819 it will be necessary to @code{gnatchop} the output file from
14820 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14821 in the preprocessed file, it will be respected by
14822 @code{gnatchop ^-r^/REFERENCE^}
14823 so that the final chopped files will correctly refer to the original
14824 input source file for @code{gnatprep}.
14825
14826 @item ^-s^/SYMBOLS^
14827 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14828 Causes a sorted list of symbol names and values to be
14829 listed on the standard output file.
14830
14831 @item ^-u^/UNDEFINED^
14832 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14833 Causes undefined symbols to be treated as having the value FALSE in the context
14834 of a preprocessor test. In the absence of this option, an undefined symbol in
14835 a @code{#if} or @code{#elsif} test will be treated as an error.
14836
14837 @end table
14838
14839 @ifclear vms
14840 @noindent
14841 Note: if neither @option{-b} nor @option{-c} is present,
14842 then preprocessor lines and
14843 deleted lines are completely removed from the output, unless -r is
14844 specified, in which case -b is assumed.
14845 @end ifclear
14846
14847 @node Form of Definitions File
14848 @section Form of Definitions File
14849
14850 @noindent
14851 The definitions file contains lines of the form
14852
14853 @smallexample
14854 symbol := value
14855 @end smallexample
14856
14857 @noindent
14858 where symbol is a preprocessing symbol, and value is one of the following:
14859
14860 @itemize @bullet
14861 @item
14862 Empty, corresponding to a null substitution
14863 @item
14864 A string literal using normal Ada syntax
14865 @item
14866 Any sequence of characters from the set
14867 (letters, digits, period, underline).
14868 @end itemize
14869
14870 @noindent
14871 Comment lines may also appear in the definitions file, starting with
14872 the usual @code{--},
14873 and comments may be added to the definitions lines.
14874
14875 @node Form of Input Text for gnatprep
14876 @section Form of Input Text for @code{gnatprep}
14877
14878 @noindent
14879 The input text may contain preprocessor conditional inclusion lines,
14880 as well as general symbol substitution sequences.
14881
14882 The preprocessor conditional inclusion commands have the form
14883
14884 @smallexample
14885 @group
14886 @cartouche
14887 #if @i{expression} @r{[}then@r{]}
14888    lines
14889 #elsif @i{expression} @r{[}then@r{]}
14890    lines
14891 #elsif @i{expression} @r{[}then@r{]}
14892    lines
14893 @dots{}
14894 #else
14895    lines
14896 #end if;
14897 @end cartouche
14898 @end group
14899 @end smallexample
14900
14901 @noindent
14902 In this example, @i{expression} is defined by the following grammar:
14903 @smallexample
14904 @i{expression} ::=  <symbol>
14905 @i{expression} ::=  <symbol> = "<value>"
14906 @i{expression} ::=  <symbol> = <symbol>
14907 @i{expression} ::=  <symbol> 'Defined
14908 @i{expression} ::=  not @i{expression}
14909 @i{expression} ::=  @i{expression} and @i{expression}
14910 @i{expression} ::=  @i{expression} or @i{expression}
14911 @i{expression} ::=  @i{expression} and then @i{expression}
14912 @i{expression} ::=  @i{expression} or else @i{expression}
14913 @i{expression} ::=  ( @i{expression} )
14914 @end smallexample
14915
14916 The following restriction exists: it is not allowed to have "and" or "or"
14917 following "not" in the same expression without parentheses. For example, this
14918 is not allowed:
14919
14920 @smallexample
14921    not X or Y
14922 @end smallexample
14923
14924 This should be one of the following:
14925
14926 @smallexample
14927    (not X) or Y
14928    not (X or Y)
14929 @end smallexample
14930
14931 @noindent
14932 For the first test (@i{expression} ::= <symbol>) the symbol must have
14933 either the value true or false, that is to say the right-hand of the
14934 symbol definition must be one of the (case-insensitive) literals
14935 @code{True} or @code{False}. If the value is true, then the
14936 corresponding lines are included, and if the value is false, they are
14937 excluded.
14938
14939 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14940 the symbol has been defined in the definition file or by a @option{-D}
14941 switch on the command line. Otherwise, the test is false.
14942
14943 The equality tests are case insensitive, as are all the preprocessor lines.
14944
14945 If the symbol referenced is not defined in the symbol definitions file,
14946 then the effect depends on whether or not switch @option{-u}
14947 is specified. If so, then the symbol is treated as if it had the value
14948 false and the test fails. If this switch is not specified, then
14949 it is an error to reference an undefined symbol. It is also an error to
14950 reference a symbol that is defined with a value other than @code{True}
14951 or @code{False}.
14952
14953 The use of the @code{not} operator inverts the sense of this logical test.
14954 The @code{not} operator cannot be combined with the @code{or} or @code{and}
14955 operators, without parentheses. For example, "if not X or Y then" is not
14956 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
14957
14958 The @code{then} keyword is optional as shown
14959
14960 The @code{#} must be the first non-blank character on a line, but
14961 otherwise the format is free form. Spaces or tabs may appear between
14962 the @code{#} and the keyword. The keywords and the symbols are case
14963 insensitive as in normal Ada code. Comments may be used on a
14964 preprocessor line, but other than that, no other tokens may appear on a
14965 preprocessor line. Any number of @code{elsif} clauses can be present,
14966 including none at all. The @code{else} is optional, as in Ada.
14967
14968 The @code{#} marking the start of a preprocessor line must be the first
14969 non-blank character on the line, i.e., it must be preceded only by
14970 spaces or horizontal tabs.
14971
14972 Symbol substitution outside of preprocessor lines is obtained by using
14973 the sequence
14974
14975 @smallexample
14976 $symbol
14977 @end smallexample
14978
14979 @noindent
14980 anywhere within a source line, except in a comment or within a
14981 string literal. The identifier
14982 following the @code{$} must match one of the symbols defined in the symbol
14983 definition file, and the result is to substitute the value of the
14984 symbol in place of @code{$symbol} in the output file.
14985
14986 Note that although the substitution of strings within a string literal
14987 is not possible, it is possible to have a symbol whose defined value is
14988 a string literal. So instead of setting XYZ to @code{hello} and writing:
14989
14990 @smallexample
14991 Header : String := "$XYZ";
14992 @end smallexample
14993
14994 @noindent
14995 you should set XYZ to @code{"hello"} and write:
14996
14997 @smallexample
14998 Header : String := $XYZ;
14999 @end smallexample
15000
15001 @noindent
15002 and then the substitution will occur as desired.
15003
15004 @node The GNAT Library Browser gnatls
15005 @chapter The GNAT Library Browser @code{gnatls}
15006 @findex gnatls
15007 @cindex Library browser
15008
15009 @noindent
15010 @code{gnatls} is a tool that outputs information about compiled
15011 units. It gives the relationship between objects, unit names and source
15012 files. It can also be used to check the source dependencies of a unit
15013 as well as various characteristics.
15014
15015 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15016 driver (see @ref{The GNAT Driver and Project Files}).
15017
15018 @menu
15019 * Running gnatls::
15020 * Switches for gnatls::
15021 * Examples of gnatls Usage::
15022 @end menu
15023
15024 @node Running gnatls
15025 @section Running @code{gnatls}
15026
15027 @noindent
15028 The @code{gnatls} command has the form
15029
15030 @smallexample
15031 $ gnatls switches @var{object_or_ali_file}
15032 @end smallexample
15033
15034 @noindent
15035 The main argument is the list of object or @file{ali} files
15036 (@pxref{The Ada Library Information Files})
15037 for which information is requested.
15038
15039 In normal mode, without additional option, @code{gnatls} produces a
15040 four-column listing. Each line represents information for a specific
15041 object. The first column gives the full path of the object, the second
15042 column gives the name of the principal unit in this object, the third
15043 column gives the status of the source and the fourth column gives the
15044 full path of the source representing this unit.
15045 Here is a simple example of use:
15046
15047 @smallexample
15048 $ gnatls *.o
15049 ^./^[]^demo1.o            demo1            DIF demo1.adb
15050 ^./^[]^demo2.o            demo2             OK demo2.adb
15051 ^./^[]^hello.o            h1                OK hello.adb
15052 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15053 ^./^[]^instr.o            instr             OK instr.adb
15054 ^./^[]^tef.o              tef              DIF tef.adb
15055 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15056 ^./^[]^tgef.o             tgef             DIF tgef.adb
15057 @end smallexample
15058
15059 @noindent
15060 The first line can be interpreted as follows: the main unit which is
15061 contained in
15062 object file @file{demo1.o} is demo1, whose main source is in
15063 @file{demo1.adb}. Furthermore, the version of the source used for the
15064 compilation of demo1 has been modified (DIF). Each source file has a status
15065 qualifier which can be:
15066
15067 @table @code
15068 @item OK (unchanged)
15069 The version of the source file used for the compilation of the
15070 specified unit corresponds exactly to the actual source file.
15071
15072 @item MOK (slightly modified)
15073 The version of the source file used for the compilation of the
15074 specified unit differs from the actual source file but not enough to
15075 require recompilation. If you use gnatmake with the qualifier
15076 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15077 MOK will not be recompiled.
15078
15079 @item DIF (modified)
15080 No version of the source found on the path corresponds to the source
15081 used to build this object.
15082
15083 @item ??? (file not found)
15084 No source file was found for this unit.
15085
15086 @item HID (hidden,  unchanged version not first on PATH)
15087 The version of the source that corresponds exactly to the source used
15088 for compilation has been found on the path but it is hidden by another
15089 version of the same source that has been modified.
15090
15091 @end table
15092
15093 @node Switches for gnatls
15094 @section Switches for @code{gnatls}
15095
15096 @noindent
15097 @code{gnatls} recognizes the following switches:
15098
15099 @table @option
15100 @c !sort!
15101 @cindex @option{--version} @command{gnatls}
15102 Display Copyright and version, then exit disregarding all other options.
15103
15104 @item --help
15105 @cindex @option{--help} @command{gnatls}
15106 If @option{--version} was not used, display usage, then exit disregarding
15107 all other options.
15108
15109 @item ^-a^/ALL_UNITS^
15110 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15111 Consider all units, including those of the predefined Ada library.
15112 Especially useful with @option{^-d^/DEPENDENCIES^}.
15113
15114 @item ^-d^/DEPENDENCIES^
15115 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15116 List sources from which specified units depend on.
15117
15118 @item ^-h^/OUTPUT=OPTIONS^
15119 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15120 Output the list of options.
15121
15122 @item ^-o^/OUTPUT=OBJECTS^
15123 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15124 Only output information about object files.
15125
15126 @item ^-s^/OUTPUT=SOURCES^
15127 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15128 Only output information about source files.
15129
15130 @item ^-u^/OUTPUT=UNITS^
15131 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15132 Only output information about compilation units.
15133
15134 @item ^-files^/FILES^=@var{file}
15135 @cindex @option{^-files^/FILES^} (@code{gnatls})
15136 Take as arguments the files listed in text file @var{file}.
15137 Text file @var{file} may contain empty lines that are ignored.
15138 Each nonempty line should contain the name of an existing file.
15139 Several such switches may be specified simultaneously.
15140
15141 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15142 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15143 @itemx ^-I^/SEARCH=^@var{dir}
15144 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15145 @itemx -nostdinc
15146 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15147 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15148 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15149 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15150 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15151 flags (@pxref{Switches for gnatmake}).
15152
15153 @item --RTS=@var{rts-path}
15154 @cindex @option{--RTS} (@code{gnatls})
15155 Specifies the default location of the runtime library. Same meaning as the
15156 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15157
15158 @item ^-v^/OUTPUT=VERBOSE^
15159 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15160 Verbose mode. Output the complete source, object and project paths. Do not use
15161 the default column layout but instead use long format giving as much as
15162 information possible on each requested units, including special
15163 characteristics such as:
15164
15165 @table @code
15166 @item  Preelaborable
15167 The unit is preelaborable in the Ada sense.
15168
15169 @item No_Elab_Code
15170 No elaboration code has been produced by the compiler for this unit.
15171
15172 @item Pure
15173 The unit is pure in the Ada sense.
15174
15175 @item Elaborate_Body
15176 The unit contains a pragma Elaborate_Body.
15177
15178 @item Remote_Types
15179 The unit contains a pragma Remote_Types.
15180
15181 @item Shared_Passive
15182 The unit contains a pragma Shared_Passive.
15183
15184 @item Predefined
15185 This unit is part of the predefined environment and cannot be modified
15186 by the user.
15187
15188 @item Remote_Call_Interface
15189 The unit contains a pragma Remote_Call_Interface.
15190
15191 @end table
15192
15193 @end table
15194
15195 @node Examples of gnatls Usage
15196 @section Example of @code{gnatls} Usage
15197 @ifclear vms
15198
15199 @noindent
15200 Example of using the verbose switch. Note how the source and
15201 object paths are affected by the -I switch.
15202
15203 @smallexample
15204 $ gnatls -v -I.. demo1.o
15205
15206 GNATLS 5.03w (20041123-34)
15207 Copyright 1997-2004 Free Software Foundation, Inc.
15208
15209 Source Search Path:
15210    <Current_Directory>
15211    ../
15212    /home/comar/local/adainclude/
15213
15214 Object Search Path:
15215    <Current_Directory>
15216    ../
15217    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15218
15219 Project Search Path:
15220    <Current_Directory>
15221    /home/comar/local/lib/gnat/
15222
15223 ./demo1.o
15224    Unit =>
15225      Name   => demo1
15226      Kind   => subprogram body
15227      Flags  => No_Elab_Code
15228      Source => demo1.adb    modified
15229 @end smallexample
15230
15231 @noindent
15232 The following is an example of use of the dependency list.
15233 Note the use of the -s switch
15234 which gives a straight list of source files. This can be useful for
15235 building specialized scripts.
15236
15237 @smallexample
15238 $ gnatls -d demo2.o
15239 ./demo2.o   demo2        OK demo2.adb
15240                          OK gen_list.ads
15241                          OK gen_list.adb
15242                          OK instr.ads
15243                          OK instr-child.ads
15244
15245 $ gnatls -d -s -a demo1.o
15246 demo1.adb
15247 /home/comar/local/adainclude/ada.ads
15248 /home/comar/local/adainclude/a-finali.ads
15249 /home/comar/local/adainclude/a-filico.ads
15250 /home/comar/local/adainclude/a-stream.ads
15251 /home/comar/local/adainclude/a-tags.ads
15252 gen_list.ads
15253 gen_list.adb
15254 /home/comar/local/adainclude/gnat.ads
15255 /home/comar/local/adainclude/g-io.ads
15256 instr.ads
15257 /home/comar/local/adainclude/system.ads
15258 /home/comar/local/adainclude/s-exctab.ads
15259 /home/comar/local/adainclude/s-finimp.ads
15260 /home/comar/local/adainclude/s-finroo.ads
15261 /home/comar/local/adainclude/s-secsta.ads
15262 /home/comar/local/adainclude/s-stalib.ads
15263 /home/comar/local/adainclude/s-stoele.ads
15264 /home/comar/local/adainclude/s-stratt.ads
15265 /home/comar/local/adainclude/s-tasoli.ads
15266 /home/comar/local/adainclude/s-unstyp.ads
15267 /home/comar/local/adainclude/unchconv.ads
15268 @end smallexample
15269 @end ifclear
15270
15271 @ifset vms
15272 @smallexample
15273 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15274
15275 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15276 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15277 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15278 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15279 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15280 demo1.adb
15281 gen_list.ads
15282 gen_list.adb
15283 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15284 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15285 instr.ads
15286 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15287 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15288 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15289 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15290 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15291 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15292 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15293 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15294 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15295 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15296 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15297 @end smallexample
15298 @end ifset
15299
15300 @node Cleaning Up Using gnatclean
15301 @chapter Cleaning Up Using @code{gnatclean}
15302 @findex gnatclean
15303 @cindex Cleaning tool
15304
15305 @noindent
15306 @code{gnatclean} is a tool that allows the deletion of files produced by the
15307 compiler, binder and linker, including ALI files, object files, tree files,
15308 expanded source files, library files, interface copy source files, binder
15309 generated files and executable files.
15310
15311 @menu
15312 * Running gnatclean::
15313 * Switches for gnatclean::
15314 @c * Examples of gnatclean Usage::
15315 @end menu
15316
15317 @node Running gnatclean
15318 @section Running @code{gnatclean}
15319
15320 @noindent
15321 The @code{gnatclean} command has the form:
15322
15323 @smallexample
15324 $ gnatclean switches @var{names}
15325 @end smallexample
15326
15327 @noindent
15328 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15329 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15330 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15331
15332 @noindent
15333 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15334 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15335 the linker. In informative-only mode, specified by switch
15336 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15337 normal mode is listed, but no file is actually deleted.
15338
15339 @node Switches for gnatclean
15340 @section Switches for @code{gnatclean}
15341
15342 @noindent
15343 @code{gnatclean} recognizes the following switches:
15344
15345 @table @option
15346 @c !sort!
15347 @cindex @option{--version} @command{gnatclean}
15348 Display Copyright and version, then exit disregarding all other options.
15349
15350 @item --help
15351 @cindex @option{--help} @command{gnatclean}
15352 If @option{--version} was not used, display usage, then exit disregarding
15353 all other options.
15354
15355 @item ^--subdirs^/SUBDIRS^=subdir
15356 Actual object directory of each project file is the subdirectory subdir of the
15357 object directory specified or defauted in the project file.
15358
15359 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15360 By default, shared library projects are not allowed to import static library
15361 projects. When this switch is used on the command line, this restriction is
15362 relaxed.
15363
15364 @item ^-c^/COMPILER_FILES_ONLY^
15365 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15366 Only attempt to delete the files produced by the compiler, not those produced
15367 by the binder or the linker. The files that are not to be deleted are library
15368 files, interface copy files, binder generated files and executable files.
15369
15370 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15371 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15372 Indicate that ALI and object files should normally be found in directory
15373 @var{dir}.
15374
15375 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15376 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15377 When using project files, if some errors or warnings are detected during
15378 parsing and verbose mode is not in effect (no use of switch
15379 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15380 file, rather than its simple file name.
15381
15382 @item ^-h^/HELP^
15383 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15384 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15385
15386 @item ^-n^/NODELETE^
15387 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15388 Informative-only mode. Do not delete any files. Output the list of the files
15389 that would have been deleted if this switch was not specified.
15390
15391 @item ^-P^/PROJECT_FILE=^@var{project}
15392 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15393 Use project file @var{project}. Only one such switch can be used.
15394 When cleaning a project file, the files produced by the compilation of the
15395 immediate sources or inherited sources of the project files are to be
15396 deleted. This is not depending on the presence or not of executable names
15397 on the command line.
15398
15399 @item ^-q^/QUIET^
15400 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15401 Quiet output. If there are no errors, do not output anything, except in
15402 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15403 (switch ^-n^/NODELETE^).
15404
15405 @item ^-r^/RECURSIVE^
15406 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15407 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15408 clean all imported and extended project files, recursively. If this switch
15409 is not specified, only the files related to the main project file are to be
15410 deleted. This switch has no effect if no project file is specified.
15411
15412 @item ^-v^/VERBOSE^
15413 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15414 Verbose mode.
15415
15416 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15417 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15418 Indicates the verbosity of the parsing of GNAT project files.
15419 @xref{Switches Related to Project Files}.
15420
15421 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15422 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15423 Indicates that external variable @var{name} has the value @var{value}.
15424 The Project Manager will use this value for occurrences of
15425 @code{external(name)} when parsing the project file.
15426 @xref{Switches Related to Project Files}.
15427
15428 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15429 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15430 When searching for ALI and object files, look in directory
15431 @var{dir}.
15432
15433 @item ^-I^/SEARCH=^@var{dir}
15434 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15435 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15436
15437 @item ^-I-^/NOCURRENT_DIRECTORY^
15438 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15439 @cindex Source files, suppressing search
15440 Do not look for ALI or object files in the directory
15441 where @code{gnatclean} was invoked.
15442
15443 @end table
15444
15445 @c @node Examples of gnatclean Usage
15446 @c @section Examples of @code{gnatclean} Usage
15447
15448 @ifclear vms
15449 @node GNAT and Libraries
15450 @chapter GNAT and Libraries
15451 @cindex Library, building, installing, using
15452
15453 @noindent
15454 This chapter describes how to build and use libraries with GNAT, and also shows
15455 how to recompile the GNAT run-time library. You should be familiar with the
15456 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15457 chapter.
15458
15459 @menu
15460 * Introduction to Libraries in GNAT::
15461 * General Ada Libraries::
15462 * Stand-alone Ada Libraries::
15463 * Rebuilding the GNAT Run-Time Library::
15464 @end menu
15465
15466 @node Introduction to Libraries in GNAT
15467 @section Introduction to Libraries in GNAT
15468
15469 @noindent
15470 A library is, conceptually, a collection of objects which does not have its
15471 own main thread of execution, but rather provides certain services to the
15472 applications that use it. A library can be either statically linked with the
15473 application, in which case its code is directly included in the application,
15474 or, on platforms that support it, be dynamically linked, in which case
15475 its code is shared by all applications making use of this library.
15476
15477 GNAT supports both types of libraries.
15478 In the static case, the compiled code can be provided in different ways. The
15479 simplest approach is to provide directly the set of objects resulting from
15480 compilation of the library source files. Alternatively, you can group the
15481 objects into an archive using whatever commands are provided by the operating
15482 system. For the latter case, the objects are grouped into a shared library.
15483
15484 In the GNAT environment, a library has three types of components:
15485 @itemize @bullet
15486 @item
15487 Source files.
15488 @item
15489 @file{ALI} files.
15490 @xref{The Ada Library Information Files}.
15491 @item
15492 Object files, an archive or a shared library.
15493 @end itemize
15494
15495 @noindent
15496 A GNAT library may expose all its source files, which is useful for
15497 documentation purposes. Alternatively, it may expose only the units needed by
15498 an external user to make use of the library. That is to say, the specs
15499 reflecting the library services along with all the units needed to compile
15500 those specs, which can include generic bodies or any body implementing an
15501 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15502 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15503
15504 All compilation units comprising an application, including those in a library,
15505 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15506 computes the elaboration order from the @file{ALI} files and this is why they
15507 constitute a mandatory part of GNAT libraries.
15508 @emph{Stand-alone libraries} are the exception to this rule because a specific
15509 library elaboration routine is produced independently of the application(s)
15510 using the library.
15511
15512 @node General Ada Libraries
15513 @section General Ada Libraries
15514
15515 @menu
15516 * Building a library::
15517 * Installing a library::
15518 * Using a library::
15519 @end menu
15520
15521 @node Building a library
15522 @subsection Building a library
15523
15524 @noindent
15525 The easiest way to build a library is to use the Project Manager,
15526 which supports a special type of project called a @emph{Library Project}
15527 (@pxref{Library Projects}).
15528
15529 A project is considered a library project, when two project-level attributes
15530 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15531 control different aspects of library configuration, additional optional
15532 project-level attributes can be specified:
15533 @table @code
15534 @item Library_Kind
15535 This attribute controls whether the library is to be static or dynamic
15536
15537 @item Library_Version
15538 This attribute specifies the library version; this value is used
15539 during dynamic linking of shared libraries to determine if the currently
15540 installed versions of the binaries are compatible.
15541
15542 @item Library_Options
15543 @item Library_GCC
15544 These attributes specify additional low-level options to be used during
15545 library generation, and redefine the actual application used to generate
15546 library.
15547 @end table
15548
15549 @noindent
15550 The GNAT Project Manager takes full care of the library maintenance task,
15551 including recompilation of the source files for which objects do not exist
15552 or are not up to date, assembly of the library archive, and installation of
15553 the library (i.e., copying associated source, object and @file{ALI} files
15554 to the specified location).
15555
15556 Here is a simple library project file:
15557 @smallexample @c ada
15558 project My_Lib is
15559    for Source_Dirs use ("src1", "src2");
15560    for Object_Dir use "obj";
15561    for Library_Name use "mylib";
15562    for Library_Dir use "lib";
15563    for Library_Kind use "dynamic";
15564 end My_lib;
15565 @end smallexample
15566
15567 @noindent
15568 and the compilation command to build and install the library:
15569
15570 @smallexample @c ada
15571   $ gnatmake -Pmy_lib
15572 @end smallexample
15573
15574 @noindent
15575 It is not entirely trivial to perform manually all the steps required to
15576 produce a library. We recommend that you use the GNAT Project Manager
15577 for this task. In special cases where this is not desired, the necessary
15578 steps are discussed below.
15579
15580 There are various possibilities for compiling the units that make up the
15581 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15582 with a conventional script. For simple libraries, it is also possible to create
15583 a dummy main program which depends upon all the packages that comprise the
15584 interface of the library. This dummy main program can then be given to
15585 @command{gnatmake}, which will ensure that all necessary objects are built.
15586
15587 After this task is accomplished, you should follow the standard procedure
15588 of the underlying operating system to produce the static or shared library.
15589
15590 Here is an example of such a dummy program:
15591 @smallexample @c ada
15592 @group
15593 with My_Lib.Service1;
15594 with My_Lib.Service2;
15595 with My_Lib.Service3;
15596 procedure My_Lib_Dummy is
15597 begin
15598    null;
15599 end;
15600 @end group
15601 @end smallexample
15602
15603 @noindent
15604 Here are the generic commands that will build an archive or a shared library.
15605
15606 @smallexample
15607 # compiling the library
15608 $ gnatmake -c my_lib_dummy.adb
15609
15610 # we don't need the dummy object itself
15611 $ rm my_lib_dummy.o my_lib_dummy.ali
15612
15613 # create an archive with the remaining objects
15614 $ ar rc libmy_lib.a *.o
15615 # some systems may require "ranlib" to be run as well
15616
15617 # or create a shared library
15618 $ gcc -shared -o libmy_lib.so *.o
15619 # some systems may require the code to have been compiled with -fPIC
15620
15621 # remove the object files that are now in the library
15622 $ rm *.o
15623
15624 # Make the ALI files read-only so that gnatmake will not try to
15625 # regenerate the objects that are in the library
15626 $ chmod -w *.ali
15627 @end smallexample
15628
15629 @noindent
15630 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15631 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15632 be accessed by the directive @option{-l@var{xxx}} at link time.
15633
15634 @node Installing a library
15635 @subsection Installing a library
15636 @cindex @code{ADA_PROJECT_PATH}
15637 @cindex @code{GPR_PROJECT_PATH}
15638
15639 @noindent
15640 If you use project files, library installation is part of the library build
15641 process (@pxref{Installing a library with project files}).
15642
15643 When project files are not an option, it is also possible, but not recommended,
15644 to install the library so that the sources needed to use the library are on the
15645 Ada source path and the ALI files & libraries be on the Ada Object path (see
15646 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15647 administrator can place general-purpose libraries in the default compiler
15648 paths, by specifying the libraries' location in the configuration files
15649 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15650 must be located in the GNAT installation tree at the same place as the gcc spec
15651 file. The location of the gcc spec file can be determined as follows:
15652 @smallexample
15653 $ gcc -v
15654 @end smallexample
15655
15656 @noindent
15657 The configuration files mentioned above have a simple format: each line
15658 must contain one unique directory name.
15659 Those names are added to the corresponding path
15660 in their order of appearance in the file. The names can be either absolute
15661 or relative; in the latter case, they are relative to where theses files
15662 are located.
15663
15664 The files @file{ada_source_path} and @file{ada_object_path} might not be
15665 present in a
15666 GNAT installation, in which case, GNAT will look for its run-time library in
15667 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15668 objects and @file{ALI} files). When the files exist, the compiler does not
15669 look in @file{adainclude} and @file{adalib}, and thus the
15670 @file{ada_source_path} file
15671 must contain the location for the GNAT run-time sources (which can simply
15672 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15673 contain the location for the GNAT run-time objects (which can simply
15674 be @file{adalib}).
15675
15676 You can also specify a new default path to the run-time library at compilation
15677 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15678 the run-time library you want your program to be compiled with. This switch is
15679 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15680 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15681
15682 It is possible to install a library before or after the standard GNAT
15683 library, by reordering the lines in the configuration files. In general, a
15684 library must be installed before the GNAT library if it redefines
15685 any part of it.
15686
15687 @node Using a library
15688 @subsection Using a library
15689
15690 @noindent Once again, the project facility greatly simplifies the use of
15691 libraries. In this context, using a library is just a matter of adding a
15692 @code{with} clause in the user project. For instance, to make use of the
15693 library @code{My_Lib} shown in examples in earlier sections, you can
15694 write:
15695
15696 @smallexample @c projectfile
15697 with "my_lib";
15698 project My_Proj is
15699   @dots{}
15700 end My_Proj;
15701 @end smallexample
15702
15703 Even if you have a third-party, non-Ada library, you can still use GNAT's
15704 Project Manager facility to provide a wrapper for it. For example, the
15705 following project, when @code{with}ed by your main project, will link with the
15706 third-party library @file{liba.a}:
15707
15708 @smallexample @c projectfile
15709 @group
15710 project Liba is
15711    for Externally_Built use "true";
15712    for Source_Files use ();
15713    for Library_Dir use "lib";
15714    for Library_Name use "a";
15715    for Library_Kind use "static";
15716 end Liba;
15717 @end group
15718 @end smallexample
15719 This is an alternative to the use of @code{pragma Linker_Options}. It is
15720 especially interesting in the context of systems with several interdependent
15721 static libraries where finding a proper linker order is not easy and best be
15722 left to the tools having visibility over project dependence information.
15723
15724 @noindent
15725 In order to use an Ada library manually, you need to make sure that this
15726 library is on both your source and object path
15727 (see @ref{Search Paths and the Run-Time Library (RTL)}
15728 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15729 in an archive or a shared library, you need to specify the desired
15730 library at link time.
15731
15732 For example, you can use the library @file{mylib} installed in
15733 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15734
15735 @smallexample
15736 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15737   -largs -lmy_lib
15738 @end smallexample
15739
15740 @noindent
15741 This can be expressed more simply:
15742 @smallexample
15743 $ gnatmake my_appl
15744 @end smallexample
15745 @noindent
15746 when the following conditions are met:
15747 @itemize @bullet
15748 @item
15749 @file{/dir/my_lib_src} has been added by the user to the environment
15750 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15751 @file{ada_source_path}
15752 @item
15753 @file{/dir/my_lib_obj} has been added by the user to the environment
15754 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15755 @file{ada_object_path}
15756 @item
15757 a pragma @code{Linker_Options} has been added to one of the sources.
15758 For example:
15759
15760 @smallexample @c ada
15761 pragma Linker_Options ("-lmy_lib");
15762 @end smallexample
15763 @end itemize
15764
15765 @node Stand-alone Ada Libraries
15766 @section Stand-alone Ada Libraries
15767 @cindex Stand-alone library, building, using
15768
15769 @menu
15770 * Introduction to Stand-alone Libraries::
15771 * Building a Stand-alone Library::
15772 * Creating a Stand-alone Library to be used in a non-Ada context::
15773 * Restrictions in Stand-alone Libraries::
15774 @end menu
15775
15776 @node Introduction to Stand-alone Libraries
15777 @subsection Introduction to Stand-alone Libraries
15778
15779 @noindent
15780 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15781 necessary code to
15782 elaborate the Ada units that are included in the library. In contrast with
15783 an ordinary library, which consists of all sources, objects and @file{ALI}
15784 files of the
15785 library, a SAL may specify a restricted subset of compilation units
15786 to serve as a library interface. In this case, the fully
15787 self-sufficient set of files will normally consist of an objects
15788 archive, the sources of interface units' specs, and the @file{ALI}
15789 files of interface units.
15790 If an interface spec contains a generic unit or an inlined subprogram,
15791 the body's
15792 source must also be provided; if the units that must be provided in the source
15793 form depend on other units, the source and @file{ALI} files of those must
15794 also be provided.
15795
15796 The main purpose of a SAL is to minimize the recompilation overhead of client
15797 applications when a new version of the library is installed. Specifically,
15798 if the interface sources have not changed, client applications do not need to
15799 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15800 version, controlled by @code{Library_Version} attribute, is not changed,
15801 then the clients do not need to be relinked.
15802
15803 SALs also allow the library providers to minimize the amount of library source
15804 text exposed to the clients.  Such ``information hiding'' might be useful or
15805 necessary for various reasons.
15806
15807 Stand-alone libraries are also well suited to be used in an executable whose
15808 main routine is not written in Ada.
15809
15810 @node Building a Stand-alone Library
15811 @subsection Building a Stand-alone Library
15812
15813 @noindent
15814 GNAT's Project facility provides a simple way of building and installing
15815 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15816 To be a Stand-alone Library Project, in addition to the two attributes
15817 that make a project a Library Project (@code{Library_Name} and
15818 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15819 @code{Library_Interface} must be defined.  For example:
15820
15821 @smallexample @c projectfile
15822 @group
15823    for Library_Dir use "lib_dir";
15824    for Library_Name use "dummy";
15825    for Library_Interface use ("int1", "int1.child");
15826 @end group
15827 @end smallexample
15828
15829 @noindent
15830 Attribute @code{Library_Interface} has a non-empty string list value,
15831 each string in the list designating a unit contained in an immediate source
15832 of the project file.
15833
15834 When a Stand-alone Library is built, first the binder is invoked to build
15835 a package whose name depends on the library name
15836 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15837 This binder-generated package includes initialization and
15838 finalization procedures whose
15839 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15840 in the example
15841 above). The object corresponding to this package is included in the library.
15842
15843 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15844 calling of these procedures if a static SAL is built, or if a shared SAL
15845 is built
15846 with the project-level attribute @code{Library_Auto_Init} set to
15847 @code{"false"}.
15848
15849 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15850 (those that are listed in attribute @code{Library_Interface}) are copied to
15851 the Library Directory. As a consequence, only the Interface Units may be
15852 imported from Ada units outside of the library. If other units are imported,
15853 the binding phase will fail.
15854
15855 The attribute @code{Library_Src_Dir} may be specified for a
15856 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15857 single string value. Its value must be the path (absolute or relative to the
15858 project directory) of an existing directory. This directory cannot be the
15859 object directory or one of the source directories, but it can be the same as
15860 the library directory. The sources of the Interface
15861 Units of the library that are needed by an Ada client of the library will be
15862 copied to the designated directory, called the Interface Copy directory.
15863 These sources include the specs of the Interface Units, but they may also
15864 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15865 are used, or when there is a generic unit in the spec. Before the sources
15866 are copied to the Interface Copy directory, an attempt is made to delete all
15867 files in the Interface Copy directory.
15868
15869 Building stand-alone libraries by hand is somewhat tedious, but for those
15870 occasions when it is necessary here are the steps that you need to perform:
15871 @itemize @bullet
15872 @item
15873 Compile all library sources.
15874
15875 @item
15876 Invoke the binder with the switch @option{-n} (No Ada main program),
15877 with all the @file{ALI} files of the interfaces, and
15878 with the switch @option{-L} to give specific names to the @code{init}
15879 and @code{final} procedures.  For example:
15880 @smallexample
15881   gnatbind -n int1.ali int2.ali -Lsal1
15882 @end smallexample
15883
15884 @item
15885 Compile the binder generated file:
15886 @smallexample
15887   gcc -c b~int2.adb
15888 @end smallexample
15889
15890 @item
15891 Link the dynamic library with all the necessary object files,
15892 indicating to the linker the names of the @code{init} (and possibly
15893 @code{final}) procedures for automatic initialization (and finalization).
15894 The built library should be placed in a directory different from
15895 the object directory.
15896
15897 @item
15898 Copy the @code{ALI} files of the interface to the library directory,
15899 add in this copy an indication that it is an interface to a SAL
15900 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15901 with letter ``P'') and make the modified copy of the @file{ALI} file
15902 read-only.
15903 @end itemize
15904
15905 @noindent
15906 Using SALs is not different from using other libraries
15907 (see @ref{Using a library}).
15908
15909 @node Creating a Stand-alone Library to be used in a non-Ada context
15910 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15911
15912 @noindent
15913 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15914 a non-Ada context.
15915
15916 The only extra step required is to ensure that library interface subprograms
15917 are compatible with the main program, by means of @code{pragma Export}
15918 or @code{pragma Convention}.
15919
15920 Here is an example of simple library interface for use with C main program:
15921
15922 @smallexample @c ada
15923 package My_Package is
15924
15925    procedure Do_Something;
15926    pragma Export (C, Do_Something, "do_something");
15927
15928    procedure Do_Something_Else;
15929    pragma Export (C, Do_Something_Else, "do_something_else");
15930
15931 end My_Package;
15932 @end smallexample
15933
15934 @noindent
15935 On the foreign language side, you must provide a ``foreign'' view of the
15936 library interface; remember that it should contain elaboration routines in
15937 addition to interface subprograms.
15938
15939 The example below shows the content of @code{mylib_interface.h} (note
15940 that there is no rule for the naming of this file, any name can be used)
15941 @smallexample
15942 /* the library elaboration procedure */
15943 extern void mylibinit (void);
15944
15945 /* the library finalization procedure */
15946 extern void mylibfinal (void);
15947
15948 /* the interface exported by the library */
15949 extern void do_something (void);
15950 extern void do_something_else (void);
15951 @end smallexample
15952
15953 @noindent
15954 Libraries built as explained above can be used from any program, provided
15955 that the elaboration procedures (named @code{mylibinit} in the previous
15956 example) are called before the library services are used. Any number of
15957 libraries can be used simultaneously, as long as the elaboration
15958 procedure of each library is called.
15959
15960 Below is an example of a C program that uses the @code{mylib} library.
15961
15962 @smallexample
15963 #include "mylib_interface.h"
15964
15965 int
15966 main (void)
15967 @{
15968    /* First, elaborate the library before using it */
15969    mylibinit ();
15970
15971    /* Main program, using the library exported entities */
15972    do_something ();
15973    do_something_else ();
15974
15975    /* Library finalization at the end of the program */
15976    mylibfinal ();
15977    return 0;
15978 @}
15979 @end smallexample
15980
15981 @noindent
15982 Note that invoking any library finalization procedure generated by
15983 @code{gnatbind} shuts down the Ada run-time environment.
15984 Consequently, the
15985 finalization of all Ada libraries must be performed at the end of the program.
15986 No call to these libraries or to the Ada run-time library should be made
15987 after the finalization phase.
15988
15989 @node Restrictions in Stand-alone Libraries
15990 @subsection Restrictions in Stand-alone Libraries
15991
15992 @noindent
15993 The pragmas listed below should be used with caution inside libraries,
15994 as they can create incompatibilities with other Ada libraries:
15995 @itemize @bullet
15996 @item pragma @code{Locking_Policy}
15997 @item pragma @code{Queuing_Policy}
15998 @item pragma @code{Task_Dispatching_Policy}
15999 @item pragma @code{Unreserve_All_Interrupts}
16000 @end itemize
16001
16002 @noindent
16003 When using a library that contains such pragmas, the user must make sure
16004 that all libraries use the same pragmas with the same values. Otherwise,
16005 @code{Program_Error} will
16006 be raised during the elaboration of the conflicting
16007 libraries. The usage of these pragmas and its consequences for the user
16008 should therefore be well documented.
16009
16010 Similarly, the traceback in the exception occurrence mechanism should be
16011 enabled or disabled in a consistent manner across all libraries.
16012 Otherwise, Program_Error will be raised during the elaboration of the
16013 conflicting libraries.
16014
16015 If the @code{Version} or @code{Body_Version}
16016 attributes are used inside a library, then you need to
16017 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16018 libraries, so that version identifiers can be properly computed.
16019 In practice these attributes are rarely used, so this is unlikely
16020 to be a consideration.
16021
16022 @node  Rebuilding the GNAT Run-Time Library
16023 @section Rebuilding the GNAT Run-Time Library
16024 @cindex GNAT Run-Time Library, rebuilding
16025 @cindex Building the GNAT Run-Time Library
16026 @cindex Rebuilding the GNAT Run-Time Library
16027 @cindex Run-Time Library, rebuilding
16028
16029 @noindent
16030 It may be useful to recompile the GNAT library in various contexts, the
16031 most important one being the use of partition-wide configuration pragmas
16032 such as @code{Normalize_Scalars}. A special Makefile called
16033 @code{Makefile.adalib} is provided to that effect and can be found in
16034 the directory containing the GNAT library. The location of this
16035 directory depends on the way the GNAT environment has been installed and can
16036 be determined by means of the command:
16037
16038 @smallexample
16039 $ gnatls -v
16040 @end smallexample
16041
16042 @noindent
16043 The last entry in the object search path usually contains the
16044 gnat library. This Makefile contains its own documentation and in
16045 particular the set of instructions needed to rebuild a new library and
16046 to use it.
16047
16048 @node Using the GNU make Utility
16049 @chapter Using the GNU @code{make} Utility
16050 @findex make
16051
16052 @noindent
16053 This chapter offers some examples of makefiles that solve specific
16054 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16055 make, make, GNU @code{make}}), nor does it try to replace the
16056 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16057
16058 All the examples in this section are specific to the GNU version of
16059 make. Although @command{make} is a standard utility, and the basic language
16060 is the same, these examples use some advanced features found only in
16061 @code{GNU make}.
16062
16063 @menu
16064 * Using gnatmake in a Makefile::
16065 * Automatically Creating a List of Directories::
16066 * Generating the Command Line Switches::
16067 * Overcoming Command Line Length Limits::
16068 @end menu
16069
16070 @node Using gnatmake in a Makefile
16071 @section Using gnatmake in a Makefile
16072 @findex makefile
16073 @cindex GNU make
16074
16075 @noindent
16076 Complex project organizations can be handled in a very powerful way by
16077 using GNU make combined with gnatmake. For instance, here is a Makefile
16078 which allows you to build each subsystem of a big project into a separate
16079 shared library. Such a makefile allows you to significantly reduce the link
16080 time of very big applications while maintaining full coherence at
16081 each step of the build process.
16082
16083 The list of dependencies are handled automatically by
16084 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16085 the appropriate directories.
16086
16087 Note that you should also read the example on how to automatically
16088 create the list of directories
16089 (@pxref{Automatically Creating a List of Directories})
16090 which might help you in case your project has a lot of subdirectories.
16091
16092 @smallexample
16093 @iftex
16094 @leftskip=0cm
16095 @font@heightrm=cmr8
16096 @heightrm
16097 @end iftex
16098 ## This Makefile is intended to be used with the following directory
16099 ## configuration:
16100 ##  - The sources are split into a series of csc (computer software components)
16101 ##    Each of these csc is put in its own directory.
16102 ##    Their name are referenced by the directory names.
16103 ##    They will be compiled into shared library (although this would also work
16104 ##    with static libraries
16105 ##  - The main program (and possibly other packages that do not belong to any
16106 ##    csc is put in the top level directory (where the Makefile is).
16107 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16108 ##                    \_ second_csc (sources) __ lib (will contain the library)
16109 ##                    \_ @dots{}
16110 ## Although this Makefile is build for shared library, it is easy to modify
16111 ## to build partial link objects instead (modify the lines with -shared and
16112 ## gnatlink below)
16113 ##
16114 ## With this makefile, you can change any file in the system or add any new
16115 ## file, and everything will be recompiled correctly (only the relevant shared
16116 ## objects will be recompiled, and the main program will be re-linked).
16117
16118 # The list of computer software component for your project. This might be
16119 # generated automatically.
16120 CSC_LIST=aa bb cc
16121
16122 # Name of the main program (no extension)
16123 MAIN=main
16124
16125 # If we need to build objects with -fPIC, uncomment the following line
16126 #NEED_FPIC=-fPIC
16127
16128 # The following variable should give the directory containing libgnat.so
16129 # You can get this directory through 'gnatls -v'. This is usually the last
16130 # directory in the Object_Path.
16131 GLIB=@dots{}
16132
16133 # The directories for the libraries
16134 # (This macro expands the list of CSC to the list of shared libraries, you
16135 # could simply use the expanded form:
16136 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16137 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16138
16139 $@{MAIN@}: objects $@{LIB_DIR@}
16140     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16141     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16142
16143 objects::
16144     # recompile the sources
16145     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16146
16147 # Note: In a future version of GNAT, the following commands will be simplified
16148 # by a new tool, gnatmlib
16149 $@{LIB_DIR@}:
16150     mkdir -p $@{dir $@@ @}
16151     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16152     cd $@{dir $@@ @} && cp -f ../*.ali .
16153
16154 # The dependencies for the modules
16155 # Note that we have to force the expansion of *.o, since in some cases
16156 # make won't be able to do it itself.
16157 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16158 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16159 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16160
16161 # Make sure all of the shared libraries are in the path before starting the
16162 # program
16163 run::
16164     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16165
16166 clean::
16167     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16168     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16169     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16170     $@{RM@} *.o *.ali $@{MAIN@}
16171 @end smallexample
16172
16173 @node Automatically Creating a List of Directories
16174 @section Automatically Creating a List of Directories
16175
16176 @noindent
16177 In most makefiles, you will have to specify a list of directories, and
16178 store it in a variable. For small projects, it is often easier to
16179 specify each of them by hand, since you then have full control over what
16180 is the proper order for these directories, which ones should be
16181 included.
16182
16183 However, in larger projects, which might involve hundreds of
16184 subdirectories, it might be more convenient to generate this list
16185 automatically.
16186
16187 The example below presents two methods. The first one, although less
16188 general, gives you more control over the list. It involves wildcard
16189 characters, that are automatically expanded by @command{make}. Its
16190 shortcoming is that you need to explicitly specify some of the
16191 organization of your project, such as for instance the directory tree
16192 depth, whether some directories are found in a separate tree, @enddots{}
16193
16194 The second method is the most general one. It requires an external
16195 program, called @command{find}, which is standard on all Unix systems. All
16196 the directories found under a given root directory will be added to the
16197 list.
16198
16199 @smallexample
16200 @iftex
16201 @leftskip=0cm
16202 @font@heightrm=cmr8
16203 @heightrm
16204 @end iftex
16205 # The examples below are based on the following directory hierarchy:
16206 # All the directories can contain any number of files
16207 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16208 #                       ->  ab
16209 #                       ->  ac
16210 #                ->  b  ->  ba  ->  baa
16211 #                       ->  bb
16212 #                       ->  bc
16213 # This Makefile creates a variable called DIRS, that can be reused any time
16214 # you need this list (see the other examples in this section)
16215
16216 # The root of your project's directory hierarchy
16217 ROOT_DIRECTORY=.
16218
16219 ####
16220 # First method: specify explicitly the list of directories
16221 # This allows you to specify any subset of all the directories you need.
16222 ####
16223
16224 DIRS := a/aa/ a/ab/ b/ba/
16225
16226 ####
16227 # Second method: use wildcards
16228 # Note that the argument(s) to wildcard below should end with a '/'.
16229 # Since wildcards also return file names, we have to filter them out
16230 # to avoid duplicate directory names.
16231 # We thus use make's @code{dir} and @code{sort} functions.
16232 # It sets DIRs to the following value (note that the directories aaa and baa
16233 # are not given, unless you change the arguments to wildcard).
16234 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16235 ####
16236
16237 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16238                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16239
16240 ####
16241 # Third method: use an external program
16242 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16243 # This is the most complete command: it sets DIRs to the following value:
16244 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16245 ####
16246
16247 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16248
16249 @end smallexample
16250
16251 @node Generating the Command Line Switches
16252 @section Generating the Command Line Switches
16253
16254 @noindent
16255 Once you have created the list of directories as explained in the
16256 previous section (@pxref{Automatically Creating a List of Directories}),
16257 you can easily generate the command line arguments to pass to gnatmake.
16258
16259 For the sake of completeness, this example assumes that the source path
16260 is not the same as the object path, and that you have two separate lists
16261 of directories.
16262
16263 @smallexample
16264 # see "Automatically creating a list of directories" to create
16265 # these variables
16266 SOURCE_DIRS=
16267 OBJECT_DIRS=
16268
16269 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16270 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16271
16272 all:
16273         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16274 @end smallexample
16275
16276 @node Overcoming Command Line Length Limits
16277 @section Overcoming Command Line Length Limits
16278
16279 @noindent
16280 One problem that might be encountered on big projects is that many
16281 operating systems limit the length of the command line. It is thus hard to give
16282 gnatmake the list of source and object directories.
16283
16284 This example shows how you can set up environment variables, which will
16285 make @command{gnatmake} behave exactly as if the directories had been
16286 specified on the command line, but have a much higher length limit (or
16287 even none on most systems).
16288
16289 It assumes that you have created a list of directories in your Makefile,
16290 using one of the methods presented in
16291 @ref{Automatically Creating a List of Directories}.
16292 For the sake of completeness, we assume that the object
16293 path (where the ALI files are found) is different from the sources patch.
16294
16295 Note a small trick in the Makefile below: for efficiency reasons, we
16296 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16297 expanded immediately by @code{make}. This way we overcome the standard
16298 make behavior which is to expand the variables only when they are
16299 actually used.
16300
16301 On Windows, if you are using the standard Windows command shell, you must
16302 replace colons with semicolons in the assignments to these variables.
16303
16304 @smallexample
16305 @iftex
16306 @leftskip=0cm
16307 @font@heightrm=cmr8
16308 @heightrm
16309 @end iftex
16310 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16311 # This is the same thing as putting the -I arguments on the command line.
16312 # (the equivalent of using -aI on the command line would be to define
16313 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16314 # You can of course have different values for these variables.
16315 #
16316 # Note also that we need to keep the previous values of these variables, since
16317 # they might have been set before running 'make' to specify where the GNAT
16318 # library is installed.
16319
16320 # see "Automatically creating a list of directories" to create these
16321 # variables
16322 SOURCE_DIRS=
16323 OBJECT_DIRS=
16324
16325 empty:=
16326 space:=$@{empty@} $@{empty@}
16327 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16328 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16329 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16330 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16331 export ADA_INCLUDE_PATH
16332 export ADA_OBJECT_PATH
16333
16334 all:
16335         gnatmake main_unit
16336 @end smallexample
16337 @end ifclear
16338
16339 @node Memory Management Issues
16340 @chapter Memory Management Issues
16341
16342 @noindent
16343 This chapter describes some useful memory pools provided in the GNAT library
16344 and in particular the GNAT Debug Pool facility, which can be used to detect
16345 incorrect uses of access values (including ``dangling references'').
16346 @ifclear vms
16347 It also describes the @command{gnatmem} tool, which can be used to track down
16348 ``memory leaks''.
16349 @end ifclear
16350
16351 @menu
16352 * Some Useful Memory Pools::
16353 * The GNAT Debug Pool Facility::
16354 @ifclear vms
16355 * The gnatmem Tool::
16356 @end ifclear
16357 @end menu
16358
16359 @node Some Useful Memory Pools
16360 @section Some Useful Memory Pools
16361 @findex Memory Pool
16362 @cindex storage, pool
16363
16364 @noindent
16365 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16366 storage pool. Allocations use the standard system call @code{malloc} while
16367 deallocations use the standard system call @code{free}. No reclamation is
16368 performed when the pool goes out of scope. For performance reasons, the
16369 standard default Ada allocators/deallocators do not use any explicit storage
16370 pools but if they did, they could use this storage pool without any change in
16371 behavior. That is why this storage pool is used  when the user
16372 manages to make the default implicit allocator explicit as in this example:
16373 @smallexample @c ada
16374    type T1 is access Something;
16375     -- no Storage pool is defined for T2
16376    type T2 is access Something_Else;
16377    for T2'Storage_Pool use T1'Storage_Pool;
16378    -- the above is equivalent to
16379    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16380 @end smallexample
16381
16382 @noindent
16383 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16384 pool. The allocation strategy is similar to @code{Pool_Local}'s
16385 except that the all
16386 storage allocated with this pool is reclaimed when the pool object goes out of
16387 scope. This pool provides a explicit mechanism similar to the implicit one
16388 provided by several Ada 83 compilers for allocations performed through a local
16389 access type and whose purpose was to reclaim memory when exiting the
16390 scope of a given local access. As an example, the following program does not
16391 leak memory even though it does not perform explicit deallocation:
16392
16393 @smallexample @c ada
16394 with System.Pool_Local;
16395 procedure Pooloc1 is
16396    procedure Internal is
16397       type A is access Integer;
16398       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16399       for A'Storage_Pool use X;
16400       v : A;
16401    begin
16402       for I in  1 .. 50 loop
16403          v := new Integer;
16404       end loop;
16405    end Internal;
16406 begin
16407    for I in  1 .. 100 loop
16408       Internal;
16409    end loop;
16410 end Pooloc1;
16411 @end smallexample
16412
16413 @noindent
16414 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16415 @code{Storage_Size} is specified for an access type.
16416 The whole storage for the pool is
16417 allocated at once, usually on the stack at the point where the access type is
16418 elaborated. It is automatically reclaimed when exiting the scope where the
16419 access type is defined. This package is not intended to be used directly by the
16420 user and it is implicitly used for each such declaration:
16421
16422 @smallexample @c ada
16423    type T1 is access Something;
16424    for T1'Storage_Size use 10_000;
16425 @end smallexample
16426
16427 @node The GNAT Debug Pool Facility
16428 @section The GNAT Debug Pool Facility
16429 @findex Debug Pool
16430 @cindex storage, pool, memory corruption
16431
16432 @noindent
16433 The use of unchecked deallocation and unchecked conversion can easily
16434 lead to incorrect memory references. The problems generated by such
16435 references are usually difficult to tackle because the symptoms can be
16436 very remote from the origin of the problem. In such cases, it is
16437 very helpful to detect the problem as early as possible. This is the
16438 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16439
16440 In order to use the GNAT specific debugging pool, the user must
16441 associate a debug pool object with each of the access types that may be
16442 related to suspected memory problems. See Ada Reference Manual 13.11.
16443 @smallexample @c ada
16444 type Ptr is access Some_Type;
16445 Pool : GNAT.Debug_Pools.Debug_Pool;
16446 for Ptr'Storage_Pool use Pool;
16447 @end smallexample
16448
16449 @noindent
16450 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16451 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16452 allow the user to redefine allocation and deallocation strategies. They
16453 also provide a checkpoint for each dereference, through the use of
16454 the primitive operation @code{Dereference} which is implicitly called at
16455 each dereference of an access value.
16456
16457 Once an access type has been associated with a debug pool, operations on
16458 values of the type may raise four distinct exceptions,
16459 which correspond to four potential kinds of memory corruption:
16460 @itemize @bullet
16461 @item
16462 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16463 @item
16464 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16465 @item
16466 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16467 @item
16468 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16469 @end itemize
16470
16471 @noindent
16472 For types associated with a Debug_Pool, dynamic allocation is performed using
16473 the standard GNAT allocation routine. References to all allocated chunks of
16474 memory are kept in an internal dictionary. Several deallocation strategies are
16475 provided, whereupon the user can choose to release the memory to the system,
16476 keep it allocated for further invalid access checks, or fill it with an easily
16477 recognizable pattern for debug sessions. The memory pattern is the old IBM
16478 hexadecimal convention: @code{16#DEADBEEF#}.
16479
16480 See the documentation in the file g-debpoo.ads for more information on the
16481 various strategies.
16482
16483 Upon each dereference, a check is made that the access value denotes a
16484 properly allocated memory location. Here is a complete example of use of
16485 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16486 @smallexample @c ada
16487 @iftex
16488 @leftskip=0cm
16489 @end iftex
16490 with Gnat.Io; use Gnat.Io;
16491 with Unchecked_Deallocation;
16492 with Unchecked_Conversion;
16493 with GNAT.Debug_Pools;
16494 with System.Storage_Elements;
16495 with Ada.Exceptions; use Ada.Exceptions;
16496 procedure Debug_Pool_Test is
16497
16498    type T is access Integer;
16499    type U is access all T;
16500
16501    P : GNAT.Debug_Pools.Debug_Pool;
16502    for T'Storage_Pool use P;
16503
16504    procedure Free is new Unchecked_Deallocation (Integer, T);
16505    function UC is new Unchecked_Conversion (U, T);
16506    A, B : aliased T;
16507
16508    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16509
16510 begin
16511    Info (P);
16512    A := new Integer;
16513    B := new Integer;
16514    B := A;
16515    Info (P);
16516    Free (A);
16517    begin
16518       Put_Line (Integer'Image(B.all));
16519    exception
16520       when E : others => Put_Line ("raised: " & Exception_Name (E));
16521    end;
16522    begin
16523       Free (B);
16524    exception
16525       when E : others => Put_Line ("raised: " & Exception_Name (E));
16526    end;
16527    B := UC(A'Access);
16528    begin
16529       Put_Line (Integer'Image(B.all));
16530    exception
16531       when E : others => Put_Line ("raised: " & Exception_Name (E));
16532    end;
16533    begin
16534       Free (B);
16535    exception
16536       when E : others => Put_Line ("raised: " & Exception_Name (E));
16537    end;
16538    Info (P);
16539 end Debug_Pool_Test;
16540 @end smallexample
16541
16542 @noindent
16543 The debug pool mechanism provides the following precise diagnostics on the
16544 execution of this erroneous program:
16545 @smallexample
16546 Debug Pool info:
16547   Total allocated bytes :  0
16548   Total deallocated bytes :  0
16549   Current Water Mark:  0
16550   High Water Mark:  0
16551
16552 Debug Pool info:
16553   Total allocated bytes :  8
16554   Total deallocated bytes :  0
16555   Current Water Mark:  8
16556   High Water Mark:  8
16557
16558 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16559 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16560 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16561 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16562 Debug Pool info:
16563   Total allocated bytes :  8
16564   Total deallocated bytes :  4
16565   Current Water Mark:  4
16566   High Water Mark:  8
16567 @end smallexample
16568
16569 @ifclear vms
16570 @node The gnatmem Tool
16571 @section The @command{gnatmem} Tool
16572 @findex gnatmem
16573
16574 @noindent
16575 The @code{gnatmem} utility monitors dynamic allocation and
16576 deallocation activity in a program, and displays information about
16577 incorrect deallocations and possible sources of memory leaks.
16578 It is designed to work in association with a static runtime library
16579 only and in this context provides three types of information:
16580 @itemize @bullet
16581 @item
16582 General information concerning memory management, such as the total
16583 number of allocations and deallocations, the amount of allocated
16584 memory and the high water mark, i.e.@: the largest amount of allocated
16585 memory in the course of program execution.
16586
16587 @item
16588 Backtraces for all incorrect deallocations, that is to say deallocations
16589 which do not correspond to a valid allocation.
16590
16591 @item
16592 Information on each allocation that is potentially the origin of a memory
16593 leak.
16594 @end itemize
16595
16596 @menu
16597 * Running gnatmem::
16598 * Switches for gnatmem::
16599 * Example of gnatmem Usage::
16600 @end menu
16601
16602 @node Running gnatmem
16603 @subsection Running @code{gnatmem}
16604
16605 @noindent
16606 @code{gnatmem} makes use of the output created by the special version of
16607 allocation and deallocation routines that record call information. This
16608 allows to obtain accurate dynamic memory usage history at a minimal cost to
16609 the execution speed. Note however, that @code{gnatmem} is not supported on
16610 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16611 Solaris and Windows NT/2000/XP (x86).
16612
16613 @noindent
16614 The @code{gnatmem} command has the form
16615
16616 @smallexample
16617 @c    $ gnatmem @ovar{switches} user_program
16618 @c Expanding @ovar macro inline (explanation in macro def comments)
16619       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16620 @end smallexample
16621
16622 @noindent
16623 The program must have been linked with the instrumented version of the
16624 allocation and deallocation routines. This is done by linking with the
16625 @file{libgmem.a} library. For correct symbolic backtrace information,
16626 the user program should be compiled with debugging options
16627 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16628
16629 @smallexample
16630 $ gnatmake -g my_program -largs -lgmem
16631 @end smallexample
16632
16633 @noindent
16634 As library @file{libgmem.a} contains an alternate body for package
16635 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16636 when an executable is linked with library @file{libgmem.a}. It is then not
16637 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16638
16639 @noindent
16640 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16641 This file contains information about all allocations and deallocations
16642 performed by the program. It is produced by the instrumented allocations and
16643 deallocations routines and will be used by @code{gnatmem}.
16644
16645 In order to produce symbolic backtrace information for allocations and
16646 deallocations performed by the GNAT run-time library, you need to use a
16647 version of that library that has been compiled with the @option{-g} switch
16648 (see @ref{Rebuilding the GNAT Run-Time Library}).
16649
16650 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16651 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16652 @option{-i} switch, gnatmem will assume that this file can be found in the
16653 current directory. For example, after you have executed @file{my_program},
16654 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16655
16656 @smallexample
16657 $ gnatmem my_program
16658 @end smallexample
16659
16660 @noindent
16661 This will produce the output with the following format:
16662
16663 *************** debut cc
16664 @smallexample
16665 $ gnatmem my_program
16666
16667 Global information
16668 ------------------
16669    Total number of allocations        :  45
16670    Total number of deallocations      :   6
16671    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16672    High Water Mark                    :  11.40 Kilobytes
16673
16674 .
16675 .
16676 .
16677 Allocation Root # 2
16678 -------------------
16679  Number of non freed allocations    :  11
16680  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16681  High Water Mark                    :   1.27 Kilobytes
16682  Backtrace                          :
16683    my_program.adb:23 my_program.alloc
16684 .
16685 .
16686 .
16687 @end smallexample
16688
16689 The first block of output gives general information. In this case, the
16690 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16691 Unchecked_Deallocation routine occurred.
16692
16693 @noindent
16694 Subsequent paragraphs display  information on all allocation roots.
16695 An allocation root is a specific point in the execution of the program
16696 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16697 construct. This root is represented by an execution backtrace (or subprogram
16698 call stack). By default the backtrace depth for allocations roots is 1, so
16699 that a root corresponds exactly to a source location. The backtrace can
16700 be made deeper, to make the root more specific.
16701
16702 @node Switches for gnatmem
16703 @subsection Switches for @code{gnatmem}
16704
16705 @noindent
16706 @code{gnatmem} recognizes the following switches:
16707
16708 @table @option
16709
16710 @item -q
16711 @cindex @option{-q} (@code{gnatmem})
16712 Quiet. Gives the minimum output needed to identify the origin of the
16713 memory leaks. Omits statistical information.
16714
16715 @item @var{N}
16716 @cindex @var{N} (@code{gnatmem})
16717 N is an integer literal (usually between 1 and 10) which controls the
16718 depth of the backtraces defining allocation root. The default value for
16719 N is 1. The deeper the backtrace, the more precise the localization of
16720 the root. Note that the total number of roots can depend on this
16721 parameter. This parameter must be specified @emph{before} the name of the
16722 executable to be analyzed, to avoid ambiguity.
16723
16724 @item -b n
16725 @cindex @option{-b} (@code{gnatmem})
16726 This switch has the same effect as just depth parameter.
16727
16728 @item -i @var{file}
16729 @cindex @option{-i} (@code{gnatmem})
16730 Do the @code{gnatmem} processing starting from @file{file}, rather than
16731 @file{gmem.out} in the current directory.
16732
16733 @item -m n
16734 @cindex @option{-m} (@code{gnatmem})
16735 This switch causes @code{gnatmem} to mask the allocation roots that have less
16736 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16737 examine even the roots that didn't result in leaks.
16738
16739 @item -s order
16740 @cindex @option{-s} (@code{gnatmem})
16741 This switch causes @code{gnatmem} to sort the allocation roots according to the
16742 specified order of sort criteria, each identified by a single letter. The
16743 currently supported criteria are @code{n, h, w} standing respectively for
16744 number of unfreed allocations, high watermark, and final watermark
16745 corresponding to a specific root. The default order is @code{nwh}.
16746
16747 @end table
16748
16749 @node Example of gnatmem Usage
16750 @subsection Example of @code{gnatmem} Usage
16751
16752 @noindent
16753 The following example shows the use of @code{gnatmem}
16754 on a simple memory-leaking program.
16755 Suppose that we have the following Ada program:
16756
16757 @smallexample @c ada
16758 @group
16759 @cartouche
16760 with Unchecked_Deallocation;
16761 procedure Test_Gm is
16762
16763    type T is array (1..1000) of Integer;
16764    type Ptr is access T;
16765    procedure Free is new Unchecked_Deallocation (T, Ptr);
16766    A : Ptr;
16767
16768    procedure My_Alloc is
16769    begin
16770       A := new T;
16771    end My_Alloc;
16772
16773    procedure My_DeAlloc is
16774       B : Ptr := A;
16775    begin
16776       Free (B);
16777    end My_DeAlloc;
16778
16779 begin
16780    My_Alloc;
16781    for I in 1 .. 5 loop
16782       for J in I .. 5 loop
16783          My_Alloc;
16784       end loop;
16785       My_Dealloc;
16786    end loop;
16787 end;
16788 @end cartouche
16789 @end group
16790 @end smallexample
16791
16792 @noindent
16793 The program needs to be compiled with debugging option and linked with
16794 @code{gmem} library:
16795
16796 @smallexample
16797 $ gnatmake -g test_gm -largs -lgmem
16798 @end smallexample
16799
16800 @noindent
16801 Then we execute the program as usual:
16802
16803 @smallexample
16804 $ test_gm
16805 @end smallexample
16806
16807 @noindent
16808 Then @code{gnatmem} is invoked simply with
16809 @smallexample
16810 $ gnatmem test_gm
16811 @end smallexample
16812
16813 @noindent
16814 which produces the following output (result may vary on different platforms):
16815
16816 @smallexample
16817 Global information
16818 ------------------
16819    Total number of allocations        :  18
16820    Total number of deallocations      :   5
16821    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16822    High Water Mark                    :  56.90 Kilobytes
16823
16824 Allocation Root # 1
16825 -------------------
16826  Number of non freed allocations    :  11
16827  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16828  High Water Mark                    :  46.88 Kilobytes
16829  Backtrace                          :
16830    test_gm.adb:11 test_gm.my_alloc
16831
16832 Allocation Root # 2
16833 -------------------
16834  Number of non freed allocations    :   1
16835  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16836  High Water Mark                    :  10.02 Kilobytes
16837  Backtrace                          :
16838    s-secsta.adb:81 system.secondary_stack.ss_init
16839
16840 Allocation Root # 3
16841 -------------------
16842  Number of non freed allocations    :   1
16843  Final Water Mark (non freed mem)   :  12 Bytes
16844  High Water Mark                    :  12 Bytes
16845  Backtrace                          :
16846    s-secsta.adb:181 system.secondary_stack.ss_init
16847 @end smallexample
16848
16849 @noindent
16850 Note that the GNAT run time contains itself a certain number of
16851 allocations that have no  corresponding deallocation,
16852 as shown here for root #2 and root
16853 #3. This is a normal behavior when the number of non-freed allocations
16854 is one, it allocates dynamic data structures that the run time needs for
16855 the complete lifetime of the program. Note also that there is only one
16856 allocation root in the user program with a single line back trace:
16857 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16858 program shows that 'My_Alloc' is called at 2 different points in the
16859 source (line 21 and line 24). If those two allocation roots need to be
16860 distinguished, the backtrace depth parameter can be used:
16861
16862 @smallexample
16863 $ gnatmem 3 test_gm
16864 @end smallexample
16865
16866 @noindent
16867 which will give the following output:
16868
16869 @smallexample
16870 Global information
16871 ------------------
16872    Total number of allocations        :  18
16873    Total number of deallocations      :   5
16874    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16875    High Water Mark                    :  56.90 Kilobytes
16876
16877 Allocation Root # 1
16878 -------------------
16879  Number of non freed allocations    :  10
16880  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16881  High Water Mark                    :  42.97 Kilobytes
16882  Backtrace                          :
16883    test_gm.adb:11 test_gm.my_alloc
16884    test_gm.adb:24 test_gm
16885    b_test_gm.c:52 main
16886
16887 Allocation Root # 2
16888 -------------------
16889  Number of non freed allocations    :   1
16890  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16891  High Water Mark                    :  10.02 Kilobytes
16892  Backtrace                          :
16893    s-secsta.adb:81  system.secondary_stack.ss_init
16894    s-secsta.adb:283 <system__secondary_stack___elabb>
16895    b_test_gm.c:33   adainit
16896
16897 Allocation Root # 3
16898 -------------------
16899  Number of non freed allocations    :   1
16900  Final Water Mark (non freed mem)   :   3.91 Kilobytes
16901  High Water Mark                    :   3.91 Kilobytes
16902  Backtrace                          :
16903    test_gm.adb:11 test_gm.my_alloc
16904    test_gm.adb:21 test_gm
16905    b_test_gm.c:52 main
16906
16907 Allocation Root # 4
16908 -------------------
16909  Number of non freed allocations    :   1
16910  Final Water Mark (non freed mem)   :  12 Bytes
16911  High Water Mark                    :  12 Bytes
16912  Backtrace                          :
16913    s-secsta.adb:181 system.secondary_stack.ss_init
16914    s-secsta.adb:283 <system__secondary_stack___elabb>
16915    b_test_gm.c:33   adainit
16916 @end smallexample
16917
16918 @noindent
16919 The allocation root #1 of the first example has been split in 2 roots #1
16920 and #3 thanks to the more precise associated backtrace.
16921
16922 @end ifclear
16923
16924 @node Stack Related Facilities
16925 @chapter Stack Related Facilities
16926
16927 @noindent
16928 This chapter describes some useful tools associated with stack
16929 checking and analysis. In
16930 particular, it deals with dynamic and static stack usage measurements.
16931
16932 @menu
16933 * Stack Overflow Checking::
16934 * Static Stack Usage Analysis::
16935 * Dynamic Stack Usage Analysis::
16936 @end menu
16937
16938 @node Stack Overflow Checking
16939 @section Stack Overflow Checking
16940 @cindex Stack Overflow Checking
16941 @cindex -fstack-check
16942
16943 @noindent
16944 For most operating systems, @command{gcc} does not perform stack overflow
16945 checking by default. This means that if the main environment task or
16946 some other task exceeds the available stack space, then unpredictable
16947 behavior will occur. Most native systems offer some level of protection by
16948 adding a guard page at the end of each task stack. This mechanism is usually
16949 not enough for dealing properly with stack overflow situations because
16950 a large local variable could ``jump'' above the guard page.
16951 Furthermore, when the
16952 guard page is hit, there may not be any space left on the stack for executing
16953 the exception propagation code. Enabling stack checking avoids
16954 such situations.
16955
16956 To activate stack checking, compile all units with the gcc option
16957 @option{-fstack-check}. For example:
16958
16959 @smallexample
16960 gcc -c -fstack-check package1.adb
16961 @end smallexample
16962
16963 @noindent
16964 Units compiled with this option will generate extra instructions to check
16965 that any use of the stack (for procedure calls or for declaring local
16966 variables in declare blocks) does not exceed the available stack space.
16967 If the space is exceeded, then a @code{Storage_Error} exception is raised.
16968
16969 For declared tasks, the stack size is controlled by the size
16970 given in an applicable @code{Storage_Size} pragma or by the value specified
16971 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
16972 the default size as defined in the GNAT runtime otherwise.
16973
16974 For the environment task, the stack size depends on
16975 system defaults and is unknown to the compiler. Stack checking
16976 may still work correctly if a fixed
16977 size stack is allocated, but this cannot be guaranteed.
16978 @ifclear vms
16979 To ensure that a clean exception is signalled for stack
16980 overflow, set the environment variable
16981 @env{GNAT_STACK_LIMIT} to indicate the maximum
16982 stack area that can be used, as in:
16983 @cindex GNAT_STACK_LIMIT
16984
16985 @smallexample
16986 SET GNAT_STACK_LIMIT 1600
16987 @end smallexample
16988
16989 @noindent
16990 The limit is given in kilobytes, so the above declaration would
16991 set the stack limit of the environment task to 1.6 megabytes.
16992 Note that the only purpose of this usage is to limit the amount
16993 of stack used by the environment task. If it is necessary to
16994 increase the amount of stack for the environment task, then this
16995 is an operating systems issue, and must be addressed with the
16996 appropriate operating systems commands.
16997 @end ifclear
16998 @ifset vms
16999 To have a fixed size stack in the environment task, the stack must be put
17000 in the P0 address space and its size specified.  Use these switches to
17001 create a p0 image:
17002
17003 @smallexample
17004 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17005 @end smallexample
17006
17007 @noindent
17008 The quotes are required to keep case.  The number after @samp{STACK=} is the
17009 size of the environmental task stack in pagelets (512 bytes).  In this example
17010 the stack size is about 2 megabytes.
17011
17012 @noindent
17013 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17014 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17015 more details about the @option{/p0image} qualifier and the @option{stack}
17016 option.
17017 @end ifset
17018
17019 @node Static Stack Usage Analysis
17020 @section Static Stack Usage Analysis
17021 @cindex Static Stack Usage Analysis
17022 @cindex -fstack-usage
17023
17024 @noindent
17025 A unit compiled with @option{-fstack-usage} will generate an extra file
17026 that specifies
17027 the maximum amount of stack used, on a per-function basis.
17028 The file has the same
17029 basename as the target object file with a @file{.su} extension.
17030 Each line of this file is made up of three fields:
17031
17032 @itemize
17033 @item
17034 The name of the function.
17035 @item
17036 A number of bytes.
17037 @item
17038 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17039 @end itemize
17040
17041 The second field corresponds to the size of the known part of the function
17042 frame.
17043
17044 The qualifier @code{static} means that the function frame size
17045 is purely static.
17046 It usually means that all local variables have a static size.
17047 In this case, the second field is a reliable measure of the function stack
17048 utilization.
17049
17050 The qualifier @code{dynamic} means that the function frame size is not static.
17051 It happens mainly when some local variables have a dynamic size. When this
17052 qualifier appears alone, the second field is not a reliable measure
17053 of the function stack analysis. When it is qualified with  @code{bounded}, it
17054 means that the second field is a reliable maximum of the function stack
17055 utilization.
17056
17057 @node Dynamic Stack Usage Analysis
17058 @section Dynamic Stack Usage Analysis
17059
17060 @noindent
17061 It is possible to measure the maximum amount of stack used by a task, by
17062 adding a switch to @command{gnatbind}, as:
17063
17064 @smallexample
17065 $ gnatbind -u0 file
17066 @end smallexample
17067
17068 @noindent
17069 With this option, at each task termination, its stack usage is  output on
17070 @file{stderr}.
17071 It is not always convenient to output the stack usage when the program
17072 is still running. Hence, it is possible to delay this output until program
17073 termination. for a given number of tasks specified as the argument of the
17074 @option{-u} option. For instance:
17075
17076 @smallexample
17077 $ gnatbind -u100 file
17078 @end smallexample
17079
17080 @noindent
17081 will buffer the stack usage information of the first 100 tasks to terminate and
17082 output this info at program termination. Results are displayed in four
17083 columns:
17084
17085 @noindent
17086 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17087
17088 @noindent
17089 where:
17090
17091 @table @emph
17092 @item Index
17093 is a number associated with each task.
17094
17095 @item Task Name
17096 is the name of the task analyzed.
17097
17098 @item Stack Size
17099 is the maximum size for the stack.
17100
17101 @item Stack Usage
17102 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17103 is not entirely analyzed, and it's not possible to know exactly how
17104 much has actually been used. The report thus contains the theoretical stack usage
17105 (Value) and the possible variation (Variation) around this value.
17106
17107 @end table
17108
17109 @noindent
17110 The environment task stack, e.g., the stack that contains the main unit, is
17111 only processed when the environment variable GNAT_STACK_LIMIT is set.
17112
17113
17114 @c *********************************
17115 @c *            GNATCHECK          *
17116 @c *********************************
17117 @node Verifying Properties Using gnatcheck
17118 @chapter Verifying Properties Using @command{gnatcheck}
17119 @findex gnatcheck
17120 @cindex @command{gnatcheck}
17121
17122 @noindent
17123 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17124 of Ada source files according to a given set of semantic rules.
17125 @cindex ASIS
17126
17127 In order to check compliance with a given rule, @command{gnatcheck} has to
17128 semantically analyze the Ada sources.
17129 Therefore, checks can only be performed on
17130 legal Ada units. Moreover, when a unit depends semantically upon units located
17131 outside the current directory, the source search path has to be provided when
17132 calling @command{gnatcheck}, either through a specified project file or
17133 through @command{gnatcheck} switches as described below.
17134
17135 A number of rules are predefined in @command{gnatcheck} and are described
17136 later in this chapter.
17137 You can also add new rules, by modifying the @command{gnatcheck} code and
17138 rebuilding the tool. In order to add a simple rule making some local checks,
17139 a small amount of straightforward ASIS-based programming is usually needed.
17140
17141 Project support for @command{gnatcheck} is provided by the GNAT
17142 driver (see @ref{The GNAT Driver and Project Files}).
17143
17144 Invoking @command{gnatcheck} on the command line has the form:
17145
17146 @smallexample
17147 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
17148 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17149 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17150 @c Expanding @ovar macro inline (explanation in macro def comments)
17151 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
17152       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17153       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17154 @end smallexample
17155
17156 @noindent
17157 where
17158 @itemize @bullet
17159 @item
17160 @var{switches} specify the general tool options
17161
17162 @item
17163 Each @var{filename} is the name (including the extension) of a source
17164 file to process. ``Wildcards'' are allowed, and
17165 the file name may contain path information.
17166
17167 @item
17168 Each @var{arg_list_filename} is the name (including the extension) of a text
17169 file containing the names of the source files to process, separated by spaces
17170 or line breaks.
17171
17172 @item
17173 @var{gcc_switches} is a list of switches for
17174 @command{gcc}. They will be passed on to all compiler invocations made by
17175 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17176 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17177 and use the @option{-gnatec} switch to set the configuration file,
17178 use the @option{-gnat05} switch if sources should be compiled in
17179 Ada 2005 mode etc.
17180
17181 @item
17182 @var{rule_options} is a list of options for controlling a set of
17183 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17184 @end itemize
17185
17186 @noindent
17187 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17188 supplied.
17189
17190 @menu
17191 * Format of the Report File::
17192 * General gnatcheck Switches::
17193 * gnatcheck Rule Options::
17194 * Adding the Results of Compiler Checks to gnatcheck Output::
17195 * Project-Wide Checks::
17196 * Rule exemption::
17197 * Predefined Rules::
17198 * Example of gnatcheck Usage::
17199 @end menu
17200
17201 @node Format of the Report File
17202 @section Format of the Report File
17203 @cindex Report file (for @code{gnatcheck})
17204
17205 @noindent
17206 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17207 rule violations.
17208 It also creates a text file  that
17209 contains the complete report of the last gnatcheck run. By default this file
17210 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17211 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17212 name and/or location of the report file. This report contains:
17213 @itemize @bullet
17214 @item date and time of @command{gnatcheck} run, the version of
17215 the tool that has generated this report and the full parameters
17216 of the  @command{gnatcheck} invocation;
17217 @item list of enabled rules;
17218 @item total number of detected violations;
17219 @item list of source files where rule violations have been detected;
17220 @item list of source files where no violations have been detected.
17221 @end itemize
17222
17223 @node General gnatcheck Switches
17224 @section General @command{gnatcheck} Switches
17225
17226 @noindent
17227 The following switches control the general @command{gnatcheck} behavior
17228
17229 @table @option
17230 @c !sort!
17231 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17232 @item ^-a^/ALL^
17233 Process all units including those with read-only ALI files such as
17234 those from the GNAT Run-Time library.
17235
17236 @ifclear vms
17237 @ignore
17238 @cindex @option{-d} (@command{gnatcheck})
17239 @item -d
17240 Debug mode
17241 @end ignore
17242
17243 @cindex @option{-dd} (@command{gnatcheck})
17244 @item -dd
17245 Progress indicator mode (for use in GPS).
17246 @end ifclear
17247
17248 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17249 @item ^-h^/HELP^
17250 List the predefined and user-defined rules. For more details see
17251 @ref{Predefined Rules}.
17252
17253 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17254 @item ^-l^/LOCS^
17255 Use full source locations references in the report file. For a construct from
17256 a generic instantiation a full source location is a chain from the location
17257 of this construct in the generic unit to the place where this unit is
17258 instantiated.
17259
17260 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17261 @item ^-log^/LOG^
17262 Duplicate all the output sent to @file{stderr} into a log file. The log file
17263 is named @file{gnatcheck.log} and is located in the current directory.
17264
17265 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17266 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17267 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17268 the range 0@dots{}1000;
17269 the default value is 500. Zero means that there is no limitation on
17270 the number of diagnostic messages to be output.
17271
17272 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17273 @item ^-q^/QUIET^
17274 Quiet mode. All the diagnostics about rule violations are placed in the
17275 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17276
17277 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17278 @item ^-s^/SHORT^
17279 Short format of the report file (no version information, no list of applied
17280 rules, no list of checked sources is included)
17281
17282 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17283 @item ^--include-file^/INCLUDE_FILE^
17284 Append the content of the specified text file to the report file
17285
17286 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17287 @item ^-t^/TIME^
17288 Print out execution time.
17289
17290 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17291 @item ^-v^/VERBOSE^
17292 Verbose mode; @command{gnatcheck} generates version information and then
17293 a trace of sources being processed.
17294
17295 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17296 @item ^-o ^/OUTPUT=^@var{report_file}
17297 Set name of report file file to @var{report_file} .
17298
17299 @end table
17300
17301 @node gnatcheck Rule Options
17302 @section @command{gnatcheck} Rule Options
17303
17304 @noindent
17305 The following options control the processing performed by
17306 @command{gnatcheck}.
17307
17308 @table @option
17309 @cindex @option{+ALL} (@command{gnatcheck})
17310 @item +ALL
17311 Turn all the rule checks ON.
17312
17313 @cindex @option{-ALL} (@command{gnatcheck})
17314 @item -ALL
17315 Turn all the rule checks OFF.
17316
17317 @cindex @option{+R} (@command{gnatcheck})
17318 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17319 Turn on the check for a specified rule with the specified parameter, if any.
17320 @var{rule_id} must be the identifier of one of the currently implemented rules
17321 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17322 are not case-sensitive. The @var{param} item must
17323 be a string representing a valid parameter(s) for the specified rule.
17324 If it contains any space characters then this string must be enclosed in
17325 quotation marks.
17326
17327 @cindex @option{-R} (@command{gnatcheck})
17328 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17329 Turn off the check for a specified rule with the specified parameter, if any.
17330
17331 @cindex @option{-from} (@command{gnatcheck})
17332 @item -from=@var{rule_option_filename}
17333 Read the rule options from the text file @var{rule_option_filename}, referred
17334 to as a ``coding standard file'' below.
17335
17336 @end table
17337
17338 @noindent
17339 The default behavior is that all the rule checks are disabled.
17340
17341 A coding standard file is a text file that contains a set of rule options
17342 described above.
17343 @cindex Coding standard file (for @code{gnatcheck})
17344 The file may contain empty lines and Ada-style comments (comment
17345 lines and end-of-line comments). There can be several rule options on a
17346 single line (separated by a space).
17347
17348 A coding standard file may reference other coding standard files by including
17349 more @option{-from=@var{rule_option_filename}}
17350 options, each such option being replaced with the content of the
17351 corresponding coding standard file during processing. In case a
17352 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17353 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17354 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17355 processing fails with an error message.
17356
17357
17358 @node Adding the Results of Compiler Checks to gnatcheck Output
17359 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17360
17361 @noindent
17362 The @command{gnatcheck} tool can include in the generated diagnostic messages
17363 and in
17364 the report file the results of the checks performed by the compiler. Though
17365 disabled by default, this effect may be obtained by using @option{+R} with
17366 the following rule identifiers and parameters:
17367
17368 @table @option
17369 @item Restrictions
17370 To record restrictions violations (which are performed by the compiler if the
17371 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17372 use the @code{Restrictions} rule
17373 with the same parameters as pragma
17374 @code{Restrictions} or @code{Restriction_Warnings}.
17375
17376 @item Style_Checks
17377 To record compiler style checks (@pxref{Style Checking}), use the
17378 @code{Style_Checks} rule.
17379 This rule takes a parameter in one of the following forms:
17380 @itemize
17381 @item
17382 @code{All_Checks},
17383 which enables the standard style checks corresponding to the @option{-gnatyy}
17384 GNAT style check option, or
17385
17386 @item
17387 a string with the same
17388 structure and semantics as the @code{string_LITERAL} parameter of the
17389 GNAT pragma @code{Style_Checks}
17390 (for further information about this pragma,
17391 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17392 @end itemize
17393
17394 @noindent
17395 For example, the
17396 @code{+RStyle_Checks:O} rule option activates
17397 the compiler style check that corresponds to
17398 @code{-gnatyO} style check option.
17399
17400 @item Warnings
17401 To record compiler warnings (@pxref{Warning Message Control}), use the
17402 @code{Warnings} rule with a parameter that is a valid
17403 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17404 (for further information about this pragma,
17405 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17406 Note that in case of gnatcheck
17407 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17408 all the specific warnings, but not suppresses the warning mode,
17409 and 'e' parameter, corresponding to @option{-gnatwe} that means
17410 "treat warnings as errors", does not have any effect.
17411
17412 @end table
17413
17414 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17415 option with the corresponding restriction name as a parameter. @code{-R} is
17416 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17417 warnings and style checks, use the corresponding warning and style options.
17418
17419 @node Project-Wide Checks
17420 @section Project-Wide Checks
17421 @cindex Project-wide checks (for @command{gnatcheck})
17422
17423 @noindent
17424 In order to perform checks on all units of a given project, you can use
17425 the GNAT driver along with the @option{-P} option:
17426 @smallexample
17427    gnat check -Pproj -rules -from=my_rules
17428 @end smallexample
17429
17430 @noindent
17431 If the project @code{proj} depends upon other projects, you can perform
17432 checks on the project closure using the @option{-U} option:
17433 @smallexample
17434    gnat check -Pproj -U -rules -from=my_rules
17435 @end smallexample
17436
17437 @noindent
17438 Finally, if not all the units are relevant to a particular main
17439 program in the project closure, you can perform checks for the set
17440 of units needed to create a given main program (unit closure) using
17441 the @option{-U} option followed by the name of the main unit:
17442 @smallexample
17443    gnat check -Pproj -U main -rules -from=my_rules
17444 @end smallexample
17445
17446
17447 @node Rule exemption
17448 @section Rule exemption
17449 @cindex Rule exemption (for @command{gnatcheck})
17450
17451 @noindent
17452 One of the most useful applications of @command{gnatcheck} is to
17453 automate the enforcement of project-specific coding standards,
17454 for example in safety-critical systems where particular features
17455 must be restricted in order to simplify the certification effort.
17456 However, it may sometimes be appropriate to violate a coding standard rule,
17457 and in such cases the rationale for the violation should be provided
17458 in the source program itself so that the individuals
17459 reviewing or maintaining the program can immediately understand the intent.
17460
17461 The @command{gnatcheck} tool supports this practice with the notion of
17462 a ``rule exemption'' covering a specific source code section. Normally
17463 rule violation messages are issued both on @file{stderr}
17464 and in a report file. In contrast, exempted violations are not listed on
17465 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17466 (e.g. in its GPS interface) do not need to pay attention to known and
17467 justified violations. However, exempted violations along with their
17468 justification are documented in a special section of the report file that
17469 @command{gnatcheck} generates.
17470
17471 @menu
17472 * Using pragma Annotate to Control Rule Exemption::
17473 * gnatcheck Annotations Rules::
17474 @end menu
17475
17476 @node Using pragma Annotate to Control Rule Exemption
17477 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17478 @cindex Using pragma Annotate to control rule exemption
17479
17480 @noindent
17481 Rule exemption is controlled by pragma @code{Annotate} when its first
17482 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17483 exemption control annotations is as follows:
17484
17485 @smallexample @c ada
17486 @group
17487 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17488
17489 @i{exemption_control} ::= Exempt_On | Exempt_Off
17490
17491 @i{Rule_Name}         ::= string_literal
17492
17493 @i{justification}     ::= string_literal
17494 @end group
17495 @end smallexample
17496
17497 @noindent
17498 When a @command{gnatcheck} annotation has more then four arguments,
17499 @command{gnatcheck} issues a warning and ignores the additional arguments.
17500 If the additional arguments do not follow the syntax above,
17501 @command{gnatcheck} emits a warning and ignores the annotation.
17502
17503 The @i{@code{Rule_Name}} argument should be the name of some existing
17504 @command{gnatcheck} rule.
17505 Otherwise a warning message is generated and the pragma is
17506 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17507 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17508
17509 A source code section where an exemption is active for a given rule is
17510 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17511
17512 @smallexample @c ada
17513 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17514 -- source code section
17515 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17516 @end smallexample
17517
17518
17519 @node gnatcheck Annotations Rules
17520 @subsection @command{gnatcheck} Annotations Rules
17521 @cindex @command{gnatcheck} annotations rules
17522
17523 @itemize @bullet
17524
17525 @item
17526 An ``Exempt_Off'' annotation can only appear after a corresponding
17527 ``Exempt_On'' annotation.
17528
17529 @item
17530 Exempted source code sections are only based on the source location of the
17531 annotations. Any source construct between the two
17532 annotations is part of the exempted source code section.
17533
17534 @item
17535 Exempted source code sections for different rules are independent. They can
17536 be nested or intersect with one another without limitation.
17537 Creating nested or intersecting source code sections for the same rule is
17538 not allowed.
17539
17540 @item
17541 Malformed exempted source code sections are reported by a warning, and
17542 the corresponding rule exemptions are ignored.
17543
17544 @item
17545 When an exempted source code section does not contain at least one violation
17546 of the exempted rule, a warning is emitted on @file{stderr}.
17547
17548 @item
17549 If an ``Exempt_On'' annotation pragma does not have a matching
17550 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17551 exemption for the given rule is ignored and a warning is issued.
17552 @end itemize
17553
17554
17555 @node Predefined Rules
17556 @section Predefined Rules
17557 @cindex Predefined rules (for @command{gnatcheck})
17558
17559 @ignore
17560 @c (Jan 2007) Since the global rules are still under development and are not
17561 @c documented, there is no point in explaining the difference between
17562 @c global and local rules
17563 @noindent
17564 A rule in @command{gnatcheck} is either local or global.
17565 A @emph{local rule} is a rule that applies to a well-defined section
17566 of a program and that can be checked by analyzing only this section.
17567 A @emph{global rule} requires analysis of some global properties of the
17568 whole program (mostly related to the program call graph).
17569 As of @value{NOW}, the implementation of global rules should be
17570 considered to be at a preliminary stage. You can use the
17571 @option{+GLOBAL} option to enable all the global rules, and the
17572 @option{-GLOBAL} rule option to disable all the global rules.
17573
17574 All the global rules in the list below are
17575 so indicated by marking them ``GLOBAL''.
17576 This +GLOBAL and -GLOBAL options are not
17577 included in the list of gnatcheck options above, because at the moment they
17578 are considered as a temporary debug options.
17579
17580 @command{gnatcheck} performs rule checks for generic
17581 instances only for global rules.  This limitation may be relaxed in a later
17582 release.
17583 @end ignore
17584
17585 @noindent
17586 The predefined rules implemented in @command{gnatcheck}
17587 are described in a companion document,
17588 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17589 The rule identifier is
17590 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17591 switches.
17592
17593
17594 @node Example of gnatcheck Usage
17595 @section Example of @command{gnatcheck} Usage
17596
17597 @noindent
17598 Here is a simple example. Suppose that in the current directory we have a
17599 project file named @file{gnatcheck_example.gpr} with the following content:
17600
17601 @smallexample @c projectfile
17602 project Gnatcheck_Example is
17603
17604    for Source_Dirs use ("src");
17605    for Object_Dir use "obj";
17606    for Main use ("main.adb");
17607
17608    package Check is
17609       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17610    end Check;
17611
17612 end Gnatcheck_Example;
17613 @end smallexample
17614
17615 @noindent
17616 And the file named @file{coding_standard} is also located in the current
17617 directory and has the following content:
17618
17619 @smallexample
17620 -----------------------------------------------------
17621 -- This is a sample gnatcheck coding standard file --
17622 -----------------------------------------------------
17623
17624 --  First, turning on rules, that are directly implemented in gnatcheck
17625 +RAbstract_Type_Declarations
17626 +RAnonymous_Arrays
17627 +RLocal_Packages
17628 +RFloat_Equality_Checks
17629 +REXIT_Statements_With_No_Loop_Name
17630
17631 --  Then, activating compiler checks of interest:
17632 +RStyle_Checks:e
17633 --  This style check checks if a unit name is present on END keyword that
17634 --  is the end of the unit declaration
17635 @end smallexample
17636
17637 @noindent
17638 And the subdirectory @file{src} contains the following Ada sources:
17639
17640 @file{pack.ads}:
17641
17642 @smallexample @c ada
17643 package Pack is
17644    type T is abstract tagged private;
17645    procedure P (X : T) is abstract;
17646
17647    package Inner is
17648       type My_Float is digits 8;
17649       function Is_Equal (L, R : My_Float) return Boolean;
17650    end Inner;
17651 private
17652    type T is abstract tagged null record;
17653 end;
17654 @end smallexample
17655
17656 @noindent
17657 @file{pack.adb}:
17658
17659 @smallexample @c ada
17660 package body Pack is
17661    package body Inner is
17662       function Is_Equal (L, R : My_Float) return Boolean is
17663       begin
17664          return L = R;
17665       end;
17666    end Inner;
17667 end Pack;
17668 @end smallexample
17669
17670 @noindent
17671 and @file{main.adb}
17672
17673 @smallexample @c ada
17674 with Pack; use Pack;
17675 procedure Main is
17676
17677    pragma Annotate
17678      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17679    Float_Array : array (1 .. 10) of Inner.My_Float;
17680    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17681
17682    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17683
17684    use Inner;
17685
17686    B : Boolean := False;
17687
17688 begin
17689    for J in Float_Array'Range loop
17690       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17691          B := True;
17692          exit;
17693       end if;
17694    end loop;
17695 end Main;
17696 @end smallexample
17697
17698 @noindent
17699 And suppose we call @command{gnatcheck} from the current directory using
17700 the @command{gnat} driver:
17701
17702 @smallexample
17703    gnat check -Pgnatcheck_example.gpr
17704 @end smallexample
17705
17706 @noindent
17707 As a result, @command{gnatcheck} is called to check all the files from the
17708 project @file{gnatcheck_example.gpr} using the coding standard defined by
17709 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17710 report file named @file{gnatcheck.out} will be created in the current
17711 directory, and it will have the following content:
17712
17713 @smallexample
17714 RULE CHECKING REPORT
17715
17716 1. OVERVIEW
17717
17718 Date and time of execution: 2009.10.28 14:17
17719 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17720 Command line:
17721
17722 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17723
17724 Coding standard (applied rules):
17725    Abstract_Type_Declarations
17726    Anonymous_Arrays
17727    EXIT_Statements_With_No_Loop_Name
17728    Float_Equality_Checks
17729    Local_Packages
17730
17731    Compiler style checks: -gnatye
17732
17733 Number of coding standard violations: 6
17734 Number of exempted coding standard violations: 1
17735
17736 2. DETECTED RULE VIOLATIONS
17737
17738 2.1. NON-EXEMPTED VIOLATIONS
17739
17740 Source files with non-exempted violations
17741    pack.ads
17742    pack.adb
17743    main.adb
17744
17745 List of violations grouped by files, and ordered by increasing source location:
17746
17747 pack.ads:2:4: declaration of abstract type
17748 pack.ads:5:4: declaration of local package
17749 pack.ads:10:30: declaration of abstract type
17750 pack.ads:11:1: (style) "end Pack" required
17751 pack.adb:5:19: use of equality operation for float values
17752 pack.adb:6:7: (style) "end Is_Equal" required
17753 main.adb:9:26: anonymous array type
17754 main.adb:19:10: exit statement with no loop name
17755
17756 2.2. EXEMPTED VIOLATIONS
17757
17758 Source files with exempted violations
17759    main.adb
17760
17761 List of violations grouped by files, and ordered by increasing source location:
17762
17763 main.adb:6:18: anonymous array type
17764    (this one is fine)
17765
17766 2.3. SOURCE FILES WITH NO VIOLATION
17767
17768    No files without violations
17769
17770 END OF REPORT
17771 @end smallexample
17772
17773
17774 @c *********************************
17775 @node Creating Sample Bodies Using gnatstub
17776 @chapter Creating Sample Bodies Using @command{gnatstub}
17777 @findex gnatstub
17778
17779 @noindent
17780 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17781 for library unit declarations.
17782
17783 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17784 driver (see @ref{The GNAT Driver and Project Files}).
17785
17786 To create a body stub, @command{gnatstub} has to compile the library
17787 unit declaration. Therefore, bodies can be created only for legal
17788 library units. Moreover, if a library unit depends semantically upon
17789 units located outside the current directory, you have to provide
17790 the source search path when calling @command{gnatstub}, see the description
17791 of @command{gnatstub} switches below.
17792
17793 By default, all the program unit body stubs generated by @code{gnatstub}
17794 raise the predefined @code{Program_Error} exception, which will catch
17795 accidental calls of generated stubs. This behavior can be changed with
17796 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17797
17798 @menu
17799 * Running gnatstub::
17800 * Switches for gnatstub::
17801 @end menu
17802
17803 @node Running gnatstub
17804 @section Running @command{gnatstub}
17805
17806 @noindent
17807 @command{gnatstub} has the command-line interface of the form
17808
17809 @smallexample
17810 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17811 @c Expanding @ovar macro inline (explanation in macro def comments)
17812 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17813 @end smallexample
17814
17815 @noindent
17816 where
17817 @table @var
17818 @item filename
17819 is the name of the source file that contains a library unit declaration
17820 for which a body must be created. The file name may contain the path
17821 information.
17822 The file name does not have to follow the GNAT file name conventions. If the
17823 name
17824 does not follow GNAT file naming conventions, the name of the body file must
17825 be provided
17826 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17827 If the file name follows the GNAT file naming
17828 conventions and the name of the body file is not provided,
17829 @command{gnatstub}
17830 creates the name
17831 of the body file from the argument file name by replacing the @file{.ads}
17832 suffix
17833 with the @file{.adb} suffix.
17834
17835 @item directory
17836 indicates the directory in which the body stub is to be placed (the default
17837 is the
17838 current directory)
17839
17840 @item @samp{@var{gcc_switches}} is a list of switches for
17841 @command{gcc}. They will be passed on to all compiler invocations made by
17842 @command{gnatelim} to generate the ASIS trees. Here you can provide
17843 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17844 use the @option{-gnatec} switch to set the configuration file,
17845 use the @option{-gnat05} switch if sources should be compiled in
17846 Ada 2005 mode etc.
17847
17848 @item switches
17849 is an optional sequence of switches as described in the next section
17850 @end table
17851
17852 @node Switches for gnatstub
17853 @section Switches for @command{gnatstub}
17854
17855 @table @option
17856 @c !sort!
17857
17858 @item ^-f^/FULL^
17859 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17860 If the destination directory already contains a file with the name of the
17861 body file
17862 for the argument spec file, replace it with the generated body stub.
17863
17864 @item ^-hs^/HEADER=SPEC^
17865 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17866 Put the comment header (i.e., all the comments preceding the
17867 compilation unit) from the source of the library unit declaration
17868 into the body stub.
17869
17870 @item ^-hg^/HEADER=GENERAL^
17871 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17872 Put a sample comment header into the body stub.
17873
17874 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17875 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17876 Use the content of the file as the comment header for a generated body stub.
17877
17878 @ifclear vms
17879 @item -IDIR
17880 @cindex @option{-IDIR} (@command{gnatstub})
17881 @itemx -I-
17882 @cindex @option{-I-} (@command{gnatstub})
17883 @end ifclear
17884 @ifset vms
17885 @item /NOCURRENT_DIRECTORY
17886 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17887 @end ifset
17888 ^These switches have ^This switch has^ the same meaning as in calls to
17889 @command{gcc}.
17890 ^They define ^It defines ^ the source search path in the call to
17891 @command{gcc} issued
17892 by @command{gnatstub} to compile an argument source file.
17893
17894 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17895 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17896 This switch has the same meaning as in calls to @command{gcc}.
17897 It defines the additional configuration file to be passed to the call to
17898 @command{gcc} issued
17899 by @command{gnatstub} to compile an argument source file.
17900
17901 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17902 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17903 (@var{n} is a non-negative integer). Set the maximum line length in the
17904 body stub to @var{n}; the default is 79. The maximum value that can be
17905 specified is 32767. Note that in the special case of configuration
17906 pragma files, the maximum is always 32767 regardless of whether or
17907 not this switch appears.
17908
17909 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17910 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17911 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17912 the generated body sample to @var{n}.
17913 The default indentation is 3.
17914
17915 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17916 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17917 Order local bodies alphabetically. (By default local bodies are ordered
17918 in the same way as the corresponding local specs in the argument spec file.)
17919
17920 @item ^-i^/INDENTATION=^@var{n}
17921 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17922 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17923
17924 @item ^-k^/TREE_FILE=SAVE^
17925 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17926 Do not remove the tree file (i.e., the snapshot of the compiler internal
17927 structures used by @command{gnatstub}) after creating the body stub.
17928
17929 @item ^-l^/LINE_LENGTH=^@var{n}
17930 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17931 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17932
17933 @item ^--no-exception^/NO_EXCEPTION^
17934 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17935 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17936 This is not always possible for function stubs.
17937
17938 @item ^--no-local-header^/NO_LOCAL_HEADER^
17939 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17940 Do not place local comment header with unit name before body stub for a
17941 unit.
17942
17943 @item ^-o ^/BODY=^@var{body-name}
17944 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17945 Body file name.  This should be set if the argument file name does not
17946 follow
17947 the GNAT file naming
17948 conventions. If this switch is omitted the default name for the body will be
17949 obtained
17950 from the argument file name according to the GNAT file naming conventions.
17951
17952 @item ^-q^/QUIET^
17953 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17954 Quiet mode: do not generate a confirmation when a body is
17955 successfully created, and do not generate a message when a body is not
17956 required for an
17957 argument unit.
17958
17959 @item ^-r^/TREE_FILE=REUSE^
17960 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17961 Reuse the tree file (if it exists) instead of creating it.  Instead of
17962 creating the tree file for the library unit declaration, @command{gnatstub}
17963 tries to find it in the current directory and use it for creating
17964 a body. If the tree file is not found, no body is created. This option
17965 also implies @option{^-k^/SAVE^}, whether or not
17966 the latter is set explicitly.
17967
17968 @item ^-t^/TREE_FILE=OVERWRITE^
17969 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17970 Overwrite the existing tree file.  If the current directory already
17971 contains the file which, according to the GNAT file naming rules should
17972 be considered as a tree file for the argument source file,
17973 @command{gnatstub}
17974 will refuse to create the tree file needed to create a sample body
17975 unless this option is set.
17976
17977 @item ^-v^/VERBOSE^
17978 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17979 Verbose mode: generate version information.
17980
17981 @end table
17982
17983 @c *********************************
17984 @node Generating Ada Bindings for C and C++ headers
17985 @chapter Generating Ada Bindings for C and C++ headers
17986 @findex binding
17987
17988 @noindent
17989 GNAT now comes with a binding generator for C and C++ headers which is
17990 intended to do 95% of the tedious work of generating Ada specs from C
17991 or C++ header files.
17992
17993 Note that this capability is not intended to generate 100% correct Ada specs,
17994 and will is some cases require manual adjustments, although it can often
17995 be used out of the box in practice.
17996
17997 Some of the known limitations include:
17998
17999 @itemize @bullet
18000 @item only very simple character constant macros are translated into Ada
18001 constants. Function macros (macros with arguments) are partially translated
18002 as comments, to be completed manually if needed.
18003 @item some extensions (e.g. vector types) are not supported
18004 @item pointers to pointers or complex structures are mapped to System.Address
18005 @end itemize
18006
18007 The code generated is using the Ada 2005 syntax, which makes it
18008 easier to interface with other languages than previous versions of Ada.
18009
18010 @menu
18011 * Running the binding generator::
18012 * Generating bindings for C++ headers::
18013 * Switches::
18014 @end menu
18015
18016 @node Running the binding generator
18017 @section Running the binding generator
18018
18019 @noindent
18020 The binding generator is part of the @command{gcc} compiler and can be
18021 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18022 spec files for the header files specified on the command line, and all
18023 header files needed by these files transitivitely. For example:
18024
18025 @smallexample
18026 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18027 $ gcc -c -gnat05 *.ads
18028 @end smallexample
18029
18030 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18031 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18032 correspond to the files @file{/usr/include/time.h},
18033 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18034 mode these Ada specs.
18035
18036 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18037 and will attempt to generate corresponding Ada comments.
18038
18039 If you want to generate a single Ada file and not the transitive closure, you
18040 can use instead the @option{-fdump-ada-spec-slim} switch.
18041
18042 Note that we recommend when possible to use the @command{g++} driver to
18043 generate bindings, even for most C headers, since this will in general
18044 generate better Ada specs. For generating bindings for C++ headers, it is
18045 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18046 is equivalent in this case. If @command{g++} cannot work on your C headers
18047 because of incompatibilities between C and C++, then you can fallback to
18048 @command{gcc} instead.
18049
18050 For an example of better bindings generated from the C++ front-end,
18051 the name of the parameters (when available) are actually ignored by the C
18052 front-end. Consider the following C header:
18053
18054 @smallexample
18055 extern void foo (int variable);
18056 @end smallexample
18057
18058 with the C front-end, @code{variable} is ignored, and the above is handled as:
18059
18060 @smallexample
18061 extern void foo (int);
18062 @end smallexample
18063
18064 generating a generic:
18065
18066 @smallexample
18067 procedure foo (param1 : int);
18068 @end smallexample
18069
18070 with the C++ front-end, the name is available, and we generate:
18071
18072 @smallexample
18073 procedure foo (variable : int);
18074 @end smallexample
18075
18076 In some cases, the generated bindings will be more complete or more meaningful
18077 when defining some macros, which you can do via the @option{-D} switch. This
18078 is for example the case with @file{Xlib.h} under GNU/Linux:
18079
18080 @smallexample
18081 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18082 @end smallexample
18083
18084 The above will generate more complete bindings than a straight call without
18085 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18086
18087 In other cases, it is not possible to parse a header file in a stand alone
18088 manner, because other include files need to be included first. In this
18089 case, the solution is to create a small header file including the needed
18090 @code{#include} and possible @code{#define} directives. For example, to
18091 generate Ada bindings for @file{readline/readline.h}, you need to first
18092 include @file{stdio.h}, so you can create a file with the following two
18093 lines in e.g. @file{readline1.h}:
18094
18095 @smallexample
18096 #include <stdio.h>
18097 #include <readline/readline.h>
18098 @end smallexample
18099
18100 and then generate Ada bindings from this file:
18101
18102 @smallexample
18103 $ g++ -c -fdump-ada-spec readline1.h
18104 @end smallexample
18105
18106 @node Generating bindings for C++ headers
18107 @section Generating bindings for C++ headers
18108
18109 @noindent
18110 Generating bindings for C++ headers is done using the same options, always
18111 with the @command{g++} compiler.
18112
18113 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18114 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18115 multiple inheritance of abstract classes will be mapped to Ada interfaces
18116 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18117 information on interfacing to C++).
18118
18119 For example, given the following C++ header file:
18120
18121 @smallexample
18122 @group
18123 @cartouche
18124 class Carnivore @{
18125 public:
18126    virtual int Number_Of_Teeth () = 0;
18127 @};
18128
18129 class Domestic @{
18130 public:
18131    virtual void Set_Owner (char* Name) = 0;
18132 @};
18133
18134 class Animal @{
18135 public:
18136   int Age_Count;
18137   virtual void Set_Age (int New_Age);
18138 @};
18139
18140 class Dog : Animal, Carnivore, Domestic @{
18141  public:
18142   int  Tooth_Count;
18143   char *Owner;
18144
18145   virtual int  Number_Of_Teeth ();
18146   virtual void Set_Owner (char* Name);
18147
18148   Dog();
18149 @};
18150 @end cartouche
18151 @end group
18152 @end smallexample
18153
18154 The corresponding Ada code is generated:
18155
18156 @smallexample @c ada
18157 @group
18158 @cartouche
18159   package Class_Carnivore is
18160     type Carnivore is limited interface;
18161     pragma Import (CPP, Carnivore);
18162
18163     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18164   end;
18165   use Class_Carnivore;
18166
18167   package Class_Domestic is
18168     type Domestic is limited interface;
18169     pragma Import (CPP, Domestic);
18170
18171     procedure Set_Owner
18172       (this : access Domestic;
18173        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18174   end;
18175   use Class_Domestic;
18176
18177   package Class_Animal is
18178     type Animal is tagged limited record
18179       Age_Count : aliased int;
18180     end record;
18181     pragma Import (CPP, Animal);
18182
18183     procedure Set_Age (this : access Animal; New_Age : int);
18184     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18185   end;
18186   use Class_Animal;
18187
18188   package Class_Dog is
18189     type Dog is new Animal and Carnivore and Domestic with record
18190       Tooth_Count : aliased int;
18191       Owner : Interfaces.C.Strings.chars_ptr;
18192     end record;
18193     pragma Import (CPP, Dog);
18194
18195     function Number_Of_Teeth (this : access Dog) return int;
18196     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18197
18198     procedure Set_Owner
18199       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18200     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18201
18202     function New_Dog return Dog;
18203     pragma CPP_Constructor (New_Dog);
18204     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18205   end;
18206   use Class_Dog;
18207 @end cartouche
18208 @end group
18209 @end smallexample
18210
18211 @node Switches
18212 @section Switches
18213
18214 @table @option
18215 @item -fdump-ada-spec
18216 @cindex @option{-fdump-ada-spec} (@command{gcc})
18217 Generate Ada spec files for the given header files transitively (including
18218 all header files that these headers depend upon).
18219
18220 @item -fdump-ada-spec-slim
18221 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18222 Generate Ada spec files for the header files specified on the command line
18223 only.
18224
18225 @item -C
18226 @cindex @option{-C} (@command{gcc})
18227 Extract comments from headers and generate Ada comments in the Ada spec files.
18228 @end table
18229
18230 @node Other Utility Programs
18231 @chapter Other Utility Programs
18232
18233 @noindent
18234 This chapter discusses some other utility programs available in the Ada
18235 environment.
18236
18237 @menu
18238 * Using Other Utility Programs with GNAT::
18239 * The External Symbol Naming Scheme of GNAT::
18240 * Converting Ada Files to html with gnathtml::
18241 * Installing gnathtml::
18242 @ifset vms
18243 * LSE::
18244 * Profiling::
18245 @end ifset
18246 @end menu
18247
18248 @node Using Other Utility Programs with GNAT
18249 @section Using Other Utility Programs with GNAT
18250
18251 @noindent
18252 The object files generated by GNAT are in standard system format and in
18253 particular the debugging information uses this format. This means
18254 programs generated by GNAT can be used with existing utilities that
18255 depend on these formats.
18256
18257 @ifclear vms
18258 In general, any utility program that works with C will also often work with
18259 Ada programs generated by GNAT. This includes software utilities such as
18260 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18261 as Purify.
18262 @end ifclear
18263
18264 @node The External Symbol Naming Scheme of GNAT
18265 @section The External Symbol Naming Scheme of GNAT
18266
18267 @noindent
18268 In order to interpret the output from GNAT, when using tools that are
18269 originally intended for use with other languages, it is useful to
18270 understand the conventions used to generate link names from the Ada
18271 entity names.
18272
18273 All link names are in all lowercase letters. With the exception of library
18274 procedure names, the mechanism used is simply to use the full expanded
18275 Ada name with dots replaced by double underscores. For example, suppose
18276 we have the following package spec:
18277
18278 @smallexample @c ada
18279 @group
18280 @cartouche
18281 package QRS is
18282    MN : Integer;
18283 end QRS;
18284 @end cartouche
18285 @end group
18286 @end smallexample
18287
18288 @noindent
18289 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18290 the corresponding link name is @code{qrs__mn}.
18291 @findex Export
18292 Of course if a @code{pragma Export} is used this may be overridden:
18293
18294 @smallexample @c ada
18295 @group
18296 @cartouche
18297 package Exports is
18298    Var1 : Integer;
18299    pragma Export (Var1, C, External_Name => "var1_name");
18300    Var2 : Integer;
18301    pragma Export (Var2, C, Link_Name => "var2_link_name");
18302 end Exports;
18303 @end cartouche
18304 @end group
18305 @end smallexample
18306
18307 @noindent
18308 In this case, the link name for @var{Var1} is whatever link name the
18309 C compiler would assign for the C function @var{var1_name}. This typically
18310 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18311 system conventions, but other possibilities exist. The link name for
18312 @var{Var2} is @var{var2_link_name}, and this is not operating system
18313 dependent.
18314
18315 @findex _main
18316 One exception occurs for library level procedures. A potential ambiguity
18317 arises between the required name @code{_main} for the C main program,
18318 and the name we would otherwise assign to an Ada library level procedure
18319 called @code{Main} (which might well not be the main program).
18320
18321 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18322 names. So if we have a library level procedure such as
18323
18324 @smallexample @c ada
18325 @group
18326 @cartouche
18327 procedure Hello (S : String);
18328 @end cartouche
18329 @end group
18330 @end smallexample
18331
18332 @noindent
18333 the external name of this procedure will be @var{_ada_hello}.
18334
18335
18336 @node Converting Ada Files to html with gnathtml
18337 @section Converting Ada Files to HTML with @code{gnathtml}
18338
18339 @noindent
18340 This @code{Perl} script allows Ada source files to be browsed using
18341 standard Web browsers. For installation procedure, see the section
18342 @xref{Installing gnathtml}.
18343
18344 Ada reserved keywords are highlighted in a bold font and Ada comments in
18345 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18346 switch to suppress the generation of cross-referencing information, user
18347 defined variables and types will appear in a different color; you will
18348 be able to click on any identifier and go to its declaration.
18349
18350 The command line is as follow:
18351 @smallexample
18352 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18353 @c Expanding @ovar macro inline (explanation in macro def comments)
18354 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18355 @end smallexample
18356
18357 @noindent
18358 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18359 an html file for every ada file, and a global file called @file{index.htm}.
18360 This file is an index of every identifier defined in the files.
18361
18362 The available ^switches^options^ are the following ones:
18363
18364 @table @option
18365 @item -83
18366 @cindex @option{-83} (@code{gnathtml})
18367 Only the Ada 83 subset of keywords will be highlighted.
18368
18369 @item -cc @var{color}
18370 @cindex @option{-cc} (@code{gnathtml})
18371 This option allows you to change the color used for comments. The default
18372 value is green. The color argument can be any name accepted by html.
18373
18374 @item -d
18375 @cindex @option{-d} (@code{gnathtml})
18376 If the Ada files depend on some other files (for instance through
18377 @code{with} clauses, the latter files will also be converted to html.
18378 Only the files in the user project will be converted to html, not the files
18379 in the run-time library itself.
18380
18381 @item -D
18382 @cindex @option{-D} (@code{gnathtml})
18383 This command is the same as @option{-d} above, but @command{gnathtml} will
18384 also look for files in the run-time library, and generate html files for them.
18385
18386 @item -ext @var{extension}
18387 @cindex @option{-ext} (@code{gnathtml})
18388 This option allows you to change the extension of the generated HTML files.
18389 If you do not specify an extension, it will default to @file{htm}.
18390
18391 @item -f
18392 @cindex @option{-f} (@code{gnathtml})
18393 By default, gnathtml will generate html links only for global entities
18394 ('with'ed units, global variables and types,@dots{}).  If you specify
18395 @option{-f} on the command line, then links will be generated for local
18396 entities too.
18397
18398 @item -l @var{number}
18399 @cindex @option{-l} (@code{gnathtml})
18400 If this ^switch^option^ is provided and @var{number} is not 0, then
18401 @code{gnathtml} will number the html files every @var{number} line.
18402
18403 @item -I @var{dir}
18404 @cindex @option{-I} (@code{gnathtml})
18405 Specify a directory to search for library files (@file{.ALI} files) and
18406 source files. You can provide several -I switches on the command line,
18407 and the directories will be parsed in the order of the command line.
18408
18409 @item -o @var{dir}
18410 @cindex @option{-o} (@code{gnathtml})
18411 Specify the output directory for html files. By default, gnathtml will
18412 saved the generated html files in a subdirectory named @file{html/}.
18413
18414 @item -p @var{file}
18415 @cindex @option{-p} (@code{gnathtml})
18416 If you are using Emacs and the most recent Emacs Ada mode, which provides
18417 a full Integrated Development Environment for compiling, checking,
18418 running and debugging applications, you may use @file{.gpr} files
18419 to give the directories where Emacs can find sources and object files.
18420
18421 Using this ^switch^option^, you can tell gnathtml to use these files.
18422 This allows you to get an html version of your application, even if it
18423 is spread over multiple directories.
18424
18425 @item -sc @var{color}
18426 @cindex @option{-sc} (@code{gnathtml})
18427 This ^switch^option^ allows you to change the color used for symbol
18428 definitions.
18429 The default value is red. The color argument can be any name accepted by html.
18430
18431 @item -t @var{file}
18432 @cindex @option{-t} (@code{gnathtml})
18433 This ^switch^option^ provides the name of a file. This file contains a list of
18434 file names to be converted, and the effect is exactly as though they had
18435 appeared explicitly on the command line. This
18436 is the recommended way to work around the command line length limit on some
18437 systems.
18438
18439 @end table
18440
18441 @node Installing gnathtml
18442 @section Installing @code{gnathtml}
18443
18444 @noindent
18445 @code{Perl} needs to be installed on your machine to run this script.
18446 @code{Perl} is freely available for almost every architecture and
18447 Operating System via the Internet.
18448
18449 On Unix systems, you  may want to modify  the  first line of  the script
18450 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18451 is. The syntax of this line is:
18452 @smallexample
18453 #!full_path_name_to_perl
18454 @end smallexample
18455
18456 @noindent
18457 Alternatively, you may run the script using the following command line:
18458
18459 @smallexample
18460 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18461 @c Expanding @ovar macro inline (explanation in macro def comments)
18462 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18463 @end smallexample
18464
18465 @ifset vms
18466 @node LSE
18467 @section LSE
18468 @findex LSE
18469
18470 @noindent
18471 The GNAT distribution provides an Ada 95 template for the HP Language
18472 Sensitive Editor (LSE), a component of DECset. In order to
18473 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18474
18475 @node Profiling
18476 @section Profiling
18477 @findex PCA
18478
18479 @noindent
18480 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18481 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18482 the collection phase with the /DEBUG qualifier.
18483
18484 @smallexample
18485 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18486 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18487 $ RUN/DEBUG <PROGRAM_NAME>
18488 @end smallexample
18489 @noindent
18490 @end ifset
18491
18492 @ifclear vms
18493 @c ******************************
18494 @node Code Coverage and Profiling
18495 @chapter Code Coverage and Profiling
18496 @cindex Code Coverage
18497 @cindex Profiling
18498
18499 @noindent
18500 This chapter describes how to use @code{gcov} - coverage testing tool - and
18501 @code{gprof} - profiler tool - on your Ada programs.
18502
18503 @menu
18504 * Code Coverage of Ada Programs using gcov::
18505 * Profiling an Ada Program using gprof::
18506 @end menu
18507
18508 @node Code Coverage of Ada Programs using gcov
18509 @section Code Coverage of Ada Programs using gcov
18510 @cindex gcov
18511 @cindex -fprofile-arcs
18512 @cindex -ftest-coverage
18513 @cindex -coverage
18514 @cindex Code Coverage
18515
18516 @noindent
18517 @code{gcov} is a test coverage program: it analyzes the execution of a given
18518 program on selected tests, to help you determine the portions of the program
18519 that are still untested.
18520
18521 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18522 User's Guide. You can refer to this documentation for a more complete
18523 description.
18524
18525 This chapter provides a quick startup guide, and
18526 details some Gnat-specific features.
18527
18528 @menu
18529 * Quick startup guide::
18530 * Gnat specifics::
18531 @end menu
18532
18533 @node Quick startup guide
18534 @subsection Quick startup guide
18535
18536 In order to perform coverage analysis of a program using @code{gcov}, 3
18537 steps are needed:
18538
18539 @itemize @bullet
18540 @item
18541 Code instrumentation during the compilation process
18542 @item
18543 Execution of the instrumented program
18544 @item
18545 Execution of the @code{gcov} tool to generate the result.
18546 @end itemize
18547
18548 The code instrumentation needed by gcov is created at the object level:
18549 The source code is not modified in any way, because the instrumentation code is
18550 inserted by gcc during the compilation process. To compile your code with code
18551 coverage activated, you need to recompile your whole project using the
18552 switches
18553 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18554 @code{-fprofile-arcs}.
18555
18556 @smallexample
18557 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18558    -largs -fprofile-arcs
18559 @end smallexample
18560
18561 This compilation process will create @file{.gcno} files together with
18562 the usual object files.
18563
18564 Once the program is compiled with coverage instrumentation, you can
18565 run it as many times as needed - on portions of a test suite for
18566 example. The first execution will produce @file{.gcda} files at the
18567 same location as the @file{.gcno} files.  The following executions
18568 will update those files, so that a cumulative result of the covered
18569 portions of the program is generated.
18570
18571 Finally, you need to call the @code{gcov} tool. The different options of
18572 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18573
18574 This will create annotated source files with a @file{.gcov} extension:
18575 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18576
18577 @node Gnat specifics
18578 @subsection Gnat specifics
18579
18580 Because Ada semantics, portions of the source code may be shared among
18581 several object files. This is the case for example when generics are
18582 involved, when inlining is active  or when declarations generate  initialisation
18583 calls. In order to take
18584 into account this shared code, you need to call @code{gcov} on all
18585 source files of the tested program at once.
18586
18587 The list of source files might exceed the system's maximum command line
18588 length. In order to bypass this limitation, a new mechanism has been
18589 implemented in @code{gcov}: you can now list all your project's files into a
18590 text file, and provide this file to gcov as a parameter,  preceded by a @@
18591 (e.g. @samp{gcov @@mysrclist.txt}).
18592
18593 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18594 not supported as there can be unresolved symbols during the final link.
18595
18596 @node Profiling an Ada Program using gprof
18597 @section Profiling an Ada Program using gprof
18598 @cindex gprof
18599 @cindex -pg
18600 @cindex Profiling
18601
18602 @noindent
18603 This section is not meant to be an exhaustive documentation of @code{gprof}.
18604 Full documentation for it can be found in the GNU Profiler User's Guide
18605 documentation that is part of this GNAT distribution.
18606
18607 Profiling a program helps determine the parts of a program that are executed
18608 most often, and are therefore the most time-consuming.
18609
18610 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18611 better handle Ada programs and multitasking.
18612 It is currently supported on the following platforms
18613 @itemize @bullet
18614 @item
18615 linux x86/x86_64
18616 @item
18617 solaris sparc/sparc64/x86
18618 @item
18619 windows x86
18620 @end itemize
18621
18622 @noindent
18623 In order to profile a program using @code{gprof}, 3 steps are needed:
18624
18625 @itemize @bullet
18626 @item
18627 Code instrumentation, requiring a full recompilation of the project with the
18628 proper switches.
18629 @item
18630 Execution of the program under the analysis conditions, i.e. with the desired
18631 input.
18632 @item
18633 Analysis of the results using the @code{gprof} tool.
18634 @end itemize
18635
18636 @noindent
18637 The following sections detail the different steps, and indicate how
18638 to interpret the results:
18639 @menu
18640 * Compilation for profiling::
18641 * Program execution::
18642 * Running gprof::
18643 * Interpretation of profiling results::
18644 @end menu
18645
18646 @node Compilation for profiling
18647 @subsection Compilation for profiling
18648 @cindex -pg
18649 @cindex Profiling
18650
18651 In order to profile a program the first step is to tell the compiler
18652 to generate the necessary profiling information. The compiler switch to be used
18653 is @code{-pg}, which must be added to other compilation switches. This
18654 switch needs to be specified both during compilation and link stages, and can
18655 be specified once when using gnatmake:
18656
18657 @smallexample
18658 gnatmake -f -pg -P my_project
18659 @end smallexample
18660
18661 @noindent
18662 Note that only the objects that were compiled with the @samp{-pg} switch will
18663 be profiled; if you need to profile your whole project, use the @samp{-f}
18664 gnatmake switch to force full recompilation.
18665
18666 @node Program execution
18667 @subsection Program execution
18668
18669 @noindent
18670 Once the program has been compiled for profiling, you can run it as usual.
18671
18672 The only constraint imposed by profiling is that the program must terminate
18673 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18674 properly analyzed.
18675
18676 Once the program completes execution, a data file called @file{gmon.out} is
18677 generated in the directory where the program was launched from. If this file
18678 already exists, it will be overwritten.
18679
18680 @node Running gprof
18681 @subsection Running gprof
18682
18683 @noindent
18684 The @code{gprof} tool is called as follow:
18685
18686 @smallexample
18687 gprof my_prog gmon.out
18688 @end smallexample
18689
18690 @noindent
18691 or simpler:
18692
18693 @smallexample
18694 gprof my_prog
18695 @end smallexample
18696
18697 @noindent
18698 The complete form of the gprof command line is the following:
18699
18700 @smallexample
18701 gprof [^switches^options^] [executable [data-file]]
18702 @end smallexample
18703
18704 @noindent
18705 @code{gprof} supports numerous ^switch^options^. The order of these
18706 ^switch^options^ does not matter. The full list of options can be found in
18707 the GNU Profiler User's Guide documentation that comes with this documentation.
18708
18709 The following is the subset of those switches that is most relevant:
18710
18711 @table @option
18712
18713 @item --demangle[=@var{style}]
18714 @itemx --no-demangle
18715 @cindex @option{--demangle} (@code{gprof})
18716 These options control whether symbol names should be demangled when
18717 printing output.  The default is to demangle C++ symbols.  The
18718 @code{--no-demangle} option may be used to turn off demangling. Different
18719 compilers have different mangling styles.  The optional demangling style
18720 argument can be used to choose an appropriate demangling style for your
18721 compiler, in particular Ada symbols generated by GNAT can be demangled using
18722 @code{--demangle=gnat}.
18723
18724 @item -e @var{function_name}
18725 @cindex @option{-e} (@code{gprof})
18726 The @samp{-e @var{function}} option tells @code{gprof} not to print
18727 information about the function @var{function_name} (and its
18728 children@dots{}) in the call graph.  The function will still be listed
18729 as a child of any functions that call it, but its index number will be
18730 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18731 given; only one @var{function_name} may be indicated with each @samp{-e}
18732 option.
18733
18734 @item -E @var{function_name}
18735 @cindex @option{-E} (@code{gprof})
18736 The @code{-E @var{function}} option works like the @code{-e} option, but
18737 execution time spent in the function (and children who were not called from
18738 anywhere else), will not be used to compute the percentages-of-time for
18739 the call graph.  More than one @samp{-E} option may be given; only one
18740 @var{function_name} may be indicated with each @samp{-E} option.
18741
18742 @item -f @var{function_name}
18743 @cindex @option{-f} (@code{gprof})
18744 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18745 call graph to the function @var{function_name} and its children (and
18746 their children@dots{}).  More than one @samp{-f} option may be given;
18747 only one @var{function_name} may be indicated with each @samp{-f}
18748 option.
18749
18750 @item -F @var{function_name}
18751 @cindex @option{-F} (@code{gprof})
18752 The @samp{-F @var{function}} option works like the @code{-f} option, but
18753 only time spent in the function and its children (and their
18754 children@dots{}) will be used to determine total-time and
18755 percentages-of-time for the call graph.  More than one @samp{-F} option
18756 may be given; only one @var{function_name} may be indicated with each
18757 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18758
18759 @end table
18760
18761 @node Interpretation of profiling results
18762 @subsection Interpretation of profiling results
18763
18764 @noindent
18765
18766 The results of the profiling analysis are represented by two arrays: the
18767 'flat profile' and the 'call graph'. Full documentation of those outputs
18768 can be found in the GNU Profiler User's Guide.
18769
18770 The flat profile shows the time spent in each function of the program, and how
18771 many time it has been called. This allows you to locate easily the most
18772 time-consuming functions.
18773
18774 The call graph shows, for each subprogram, the subprograms that call it,
18775 and the subprograms that it calls. It also provides an estimate of the time
18776 spent in each of those callers/called subprograms.
18777 @end ifclear
18778
18779 @c ******************************
18780 @node Running and Debugging Ada Programs
18781 @chapter Running and Debugging Ada Programs
18782 @cindex Debugging
18783
18784 @noindent
18785 This chapter discusses how to debug Ada programs.
18786 @ifset vms
18787 It applies to GNAT on the Alpha OpenVMS platform;
18788 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18789 since HP has implemented Ada support in the OpenVMS debugger on I64.
18790 @end ifset
18791
18792 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18793
18794 @enumerate
18795 @item
18796 The illegality may be a violation of the static semantics of Ada. In
18797 that case GNAT diagnoses the constructs in the program that are illegal.
18798 It is then a straightforward matter for the user to modify those parts of
18799 the program.
18800
18801 @item
18802 The illegality may be a violation of the dynamic semantics of Ada. In
18803 that case the program compiles and executes, but may generate incorrect
18804 results, or may terminate abnormally with some exception.
18805
18806 @item
18807 When presented with a program that contains convoluted errors, GNAT
18808 itself may terminate abnormally without providing full diagnostics on
18809 the incorrect user program.
18810 @end enumerate
18811
18812 @menu
18813 * The GNAT Debugger GDB::
18814 * Running GDB::
18815 * Introduction to GDB Commands::
18816 * Using Ada Expressions::
18817 * Calling User-Defined Subprograms::
18818 * Using the Next Command in a Function::
18819 * Ada Exceptions::
18820 * Ada Tasks::
18821 * Debugging Generic Units::
18822 * Remote Debugging using gdbserver::
18823 * GNAT Abnormal Termination or Failure to Terminate::
18824 * Naming Conventions for GNAT Source Files::
18825 * Getting Internal Debugging Information::
18826 * Stack Traceback::
18827 @end menu
18828
18829 @cindex Debugger
18830 @findex gdb
18831
18832 @node The GNAT Debugger GDB
18833 @section The GNAT Debugger GDB
18834
18835 @noindent
18836 @code{GDB} is a general purpose, platform-independent debugger that
18837 can be used to debug mixed-language programs compiled with @command{gcc},
18838 and in particular is capable of debugging Ada programs compiled with
18839 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18840 complex Ada data structures.
18841
18842 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18843 @ifset vms
18844 located in the GNU:[DOCS] directory,
18845 @end ifset
18846 for full details on the usage of @code{GDB}, including a section on
18847 its usage on programs. This manual should be consulted for full
18848 details. The section that follows is a brief introduction to the
18849 philosophy and use of @code{GDB}.
18850
18851 When GNAT programs are compiled, the compiler optionally writes debugging
18852 information into the generated object file, including information on
18853 line numbers, and on declared types and variables. This information is
18854 separate from the generated code. It makes the object files considerably
18855 larger, but it does not add to the size of the actual executable that
18856 will be loaded into memory, and has no impact on run-time performance. The
18857 generation of debug information is triggered by the use of the
18858 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18859 used to carry out the compilations. It is important to emphasize that
18860 the use of these options does not change the generated code.
18861
18862 The debugging information is written in standard system formats that
18863 are used by many tools, including debuggers and profilers. The format
18864 of the information is typically designed to describe C types and
18865 semantics, but GNAT implements a translation scheme which allows full
18866 details about Ada types and variables to be encoded into these
18867 standard C formats. Details of this encoding scheme may be found in
18868 the file exp_dbug.ads in the GNAT source distribution. However, the
18869 details of this encoding are, in general, of no interest to a user,
18870 since @code{GDB} automatically performs the necessary decoding.
18871
18872 When a program is bound and linked, the debugging information is
18873 collected from the object files, and stored in the executable image of
18874 the program. Again, this process significantly increases the size of
18875 the generated executable file, but it does not increase the size of
18876 the executable program itself. Furthermore, if this program is run in
18877 the normal manner, it runs exactly as if the debug information were
18878 not present, and takes no more actual memory.
18879
18880 However, if the program is run under control of @code{GDB}, the
18881 debugger is activated.  The image of the program is loaded, at which
18882 point it is ready to run.  If a run command is given, then the program
18883 will run exactly as it would have if @code{GDB} were not present. This
18884 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18885 entirely non-intrusive until a breakpoint is encountered.  If no
18886 breakpoint is ever hit, the program will run exactly as it would if no
18887 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18888 the debugging information and can respond to user commands to inspect
18889 variables, and more generally to report on the state of execution.
18890
18891 @c **************
18892 @node Running GDB
18893 @section Running GDB
18894
18895 @noindent
18896 This section describes how to initiate the debugger.
18897 @c The above sentence is really just filler, but it was otherwise
18898 @c clumsy to get the first paragraph nonindented given the conditional
18899 @c nature of the description
18900
18901 @ifclear vms
18902 The debugger can be launched from a @code{GPS} menu or
18903 directly from the command line. The description below covers the latter use.
18904 All the commands shown can be used in the @code{GPS} debug console window,
18905 but there are usually more GUI-based ways to achieve the same effect.
18906 @end ifclear
18907
18908 The command to run @code{GDB} is
18909
18910 @smallexample
18911 $ ^gdb program^GDB PROGRAM^
18912 @end smallexample
18913
18914 @noindent
18915 where @code{^program^PROGRAM^} is the name of the executable file. This
18916 activates the debugger and results in a prompt for debugger commands.
18917 The simplest command is simply @code{run}, which causes the program to run
18918 exactly as if the debugger were not present. The following section
18919 describes some of the additional commands that can be given to @code{GDB}.
18920
18921 @c *******************************
18922 @node Introduction to GDB Commands
18923 @section Introduction to GDB Commands
18924
18925 @noindent
18926 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18927 Debugging with GDB, gdb, Debugging with GDB},
18928 @ifset vms
18929 located in the GNU:[DOCS] directory,
18930 @end ifset
18931 for extensive documentation on the use
18932 of these commands, together with examples of their use. Furthermore,
18933 the command @command{help} invoked from within GDB activates a simple help
18934 facility which summarizes the available commands and their options.
18935 In this section we summarize a few of the most commonly
18936 used commands to give an idea of what @code{GDB} is about. You should create
18937 a simple program with debugging information and experiment with the use of
18938 these @code{GDB} commands on the program as you read through the
18939 following section.
18940
18941 @table @code
18942 @item set args @var{arguments}
18943 The @var{arguments} list above is a list of arguments to be passed to
18944 the program on a subsequent run command, just as though the arguments
18945 had been entered on a normal invocation of the program. The @code{set args}
18946 command is not needed if the program does not require arguments.
18947
18948 @item run
18949 The @code{run} command causes execution of the program to start from
18950 the beginning. If the program is already running, that is to say if
18951 you are currently positioned at a breakpoint, then a prompt will ask
18952 for confirmation that you want to abandon the current execution and
18953 restart.
18954
18955 @item breakpoint @var{location}
18956 The breakpoint command sets a breakpoint, that is to say a point at which
18957 execution will halt and @code{GDB} will await further
18958 commands. @var{location} is
18959 either a line number within a file, given in the format @code{file:linenumber},
18960 or it is the name of a subprogram. If you request that a breakpoint be set on
18961 a subprogram that is overloaded, a prompt will ask you to specify on which of
18962 those subprograms you want to breakpoint. You can also
18963 specify that all of them should be breakpointed. If the program is run
18964 and execution encounters the breakpoint, then the program
18965 stops and @code{GDB} signals that the breakpoint was encountered by
18966 printing the line of code before which the program is halted.
18967
18968 @item catch exception @var{name}
18969 This command causes the program execution to stop whenever exception
18970 @var{name} is raised.  If @var{name} is omitted, then the execution is
18971 suspended when any exception is raised.
18972
18973 @item print @var{expression}
18974 This will print the value of the given expression. Most simple
18975 Ada expression formats are properly handled by @code{GDB}, so the expression
18976 can contain function calls, variables, operators, and attribute references.
18977
18978 @item continue
18979 Continues execution following a breakpoint, until the next breakpoint or the
18980 termination of the program.
18981
18982 @item step
18983 Executes a single line after a breakpoint. If the next statement
18984 is a subprogram call, execution continues into (the first statement of)
18985 the called subprogram.
18986
18987 @item next
18988 Executes a single line. If this line is a subprogram call, executes and
18989 returns from the call.
18990
18991 @item list
18992 Lists a few lines around the current source location. In practice, it
18993 is usually more convenient to have a separate edit window open with the
18994 relevant source file displayed. Successive applications of this command
18995 print subsequent lines. The command can be given an argument which is a
18996 line number, in which case it displays a few lines around the specified one.
18997
18998 @item backtrace
18999 Displays a backtrace of the call chain. This command is typically
19000 used after a breakpoint has occurred, to examine the sequence of calls that
19001 leads to the current breakpoint. The display includes one line for each
19002 activation record (frame) corresponding to an active subprogram.
19003
19004 @item up
19005 At a breakpoint, @code{GDB} can display the values of variables local
19006 to the current frame. The command @code{up} can be used to
19007 examine the contents of other active frames, by moving the focus up
19008 the stack, that is to say from callee to caller, one frame at a time.
19009
19010 @item down
19011 Moves the focus of @code{GDB} down from the frame currently being
19012 examined to the frame of its callee (the reverse of the previous command),
19013
19014 @item frame @var{n}
19015 Inspect the frame with the given number. The value 0 denotes the frame
19016 of the current breakpoint, that is to say the top of the call stack.
19017
19018 @end table
19019
19020 @noindent
19021 The above list is a very short introduction to the commands that
19022 @code{GDB} provides. Important additional capabilities, including conditional
19023 breakpoints, the ability to execute command sequences on a breakpoint,
19024 the ability to debug at the machine instruction level and many other
19025 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19026 Debugging with GDB}.  Note that most commands can be abbreviated
19027 (for example, c for continue, bt for backtrace).
19028
19029 @node Using Ada Expressions
19030 @section Using Ada Expressions
19031 @cindex Ada expressions
19032
19033 @noindent
19034 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19035 extensions. The philosophy behind the design of this subset is
19036
19037 @itemize @bullet
19038 @item
19039 That @code{GDB} should provide basic literals and access to operations for
19040 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19041 leaving more sophisticated computations to subprograms written into the
19042 program (which therefore may be called from @code{GDB}).
19043
19044 @item
19045 That type safety and strict adherence to Ada language restrictions
19046 are not particularly important to the @code{GDB} user.
19047
19048 @item
19049 That brevity is important to the @code{GDB} user.
19050 @end itemize
19051
19052 @noindent
19053 Thus, for brevity, the debugger acts as if there were
19054 implicit @code{with} and @code{use} clauses in effect for all user-written
19055 packages, thus making it unnecessary to fully qualify most names with
19056 their packages, regardless of context. Where this causes ambiguity,
19057 @code{GDB} asks the user's intent.
19058
19059 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19060 GDB, gdb, Debugging with GDB}.
19061
19062 @node Calling User-Defined Subprograms
19063 @section Calling User-Defined Subprograms
19064
19065 @noindent
19066 An important capability of @code{GDB} is the ability to call user-defined
19067 subprograms while debugging. This is achieved simply by entering
19068 a subprogram call statement in the form:
19069
19070 @smallexample
19071 call subprogram-name (parameters)
19072 @end smallexample
19073
19074 @noindent
19075 The keyword @code{call} can be omitted in the normal case where the
19076 @code{subprogram-name} does not coincide with any of the predefined
19077 @code{GDB} commands.
19078
19079 The effect is to invoke the given subprogram, passing it the
19080 list of parameters that is supplied. The parameters can be expressions and
19081 can include variables from the program being debugged. The
19082 subprogram must be defined
19083 at the library level within your program, and @code{GDB} will call the
19084 subprogram within the environment of your program execution (which
19085 means that the subprogram is free to access or even modify variables
19086 within your program).
19087
19088 The most important use of this facility is in allowing the inclusion of
19089 debugging routines that are tailored to particular data structures
19090 in your program. Such debugging routines can be written to provide a suitably
19091 high-level description of an abstract type, rather than a low-level dump
19092 of its physical layout. After all, the standard
19093 @code{GDB print} command only knows the physical layout of your
19094 types, not their abstract meaning. Debugging routines can provide information
19095 at the desired semantic level and are thus enormously useful.
19096
19097 For example, when debugging GNAT itself, it is crucial to have access to
19098 the contents of the tree nodes used to represent the program internally.
19099 But tree nodes are represented simply by an integer value (which in turn
19100 is an index into a table of nodes).
19101 Using the @code{print} command on a tree node would simply print this integer
19102 value, which is not very useful. But the PN routine (defined in file
19103 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19104 a useful high level representation of the tree node, which includes the
19105 syntactic category of the node, its position in the source, the integers
19106 that denote descendant nodes and parent node, as well as varied
19107 semantic information. To study this example in more detail, you might want to
19108 look at the body of the PN procedure in the stated file.
19109
19110 @node Using the Next Command in a Function
19111 @section Using the Next Command in a Function
19112
19113 @noindent
19114 When you use the @code{next} command in a function, the current source
19115 location will advance to the next statement as usual. A special case
19116 arises in the case of a @code{return} statement.
19117
19118 Part of the code for a return statement is the ``epilog'' of the function.
19119 This is the code that returns to the caller. There is only one copy of
19120 this epilog code, and it is typically associated with the last return
19121 statement in the function if there is more than one return. In some
19122 implementations, this epilog is associated with the first statement
19123 of the function.
19124
19125 The result is that if you use the @code{next} command from a return
19126 statement that is not the last return statement of the function you
19127 may see a strange apparent jump to the last return statement or to
19128 the start of the function. You should simply ignore this odd jump.
19129 The value returned is always that from the first return statement
19130 that was stepped through.
19131
19132 @node Ada Exceptions
19133 @section Stopping when Ada Exceptions are Raised
19134 @cindex Exceptions
19135
19136 @noindent
19137 You can set catchpoints that stop the program execution when your program
19138 raises selected exceptions.
19139
19140 @table @code
19141 @item catch exception
19142 Set a catchpoint that stops execution whenever (any task in the) program
19143 raises any exception.
19144
19145 @item catch exception @var{name}
19146 Set a catchpoint that stops execution whenever (any task in the) program
19147 raises the exception @var{name}.
19148
19149 @item catch exception unhandled
19150 Set a catchpoint that stops executino whenever (any task in the) program
19151 raises an exception for which there is no handler.
19152
19153 @item info exceptions
19154 @itemx info exceptions @var{regexp}
19155 The @code{info exceptions} command permits the user to examine all defined
19156 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19157 argument, prints out only those exceptions whose name matches @var{regexp}.
19158 @end table
19159
19160 @node Ada Tasks
19161 @section Ada Tasks
19162 @cindex Tasks
19163
19164 @noindent
19165 @code{GDB} allows the following task-related commands:
19166
19167 @table @code
19168 @item info tasks
19169 This command shows a list of current Ada tasks, as in the following example:
19170
19171 @smallexample
19172 @iftex
19173 @leftskip=0cm
19174 @end iftex
19175 (gdb) info tasks
19176   ID       TID P-ID   Thread Pri State                 Name
19177    1   8088000   0   807e000  15 Child Activation Wait main_task
19178    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19179    3   809a800   1   80a4800  15 Child Activation Wait a
19180 *  4   80ae800   3   80b8000  15 Running               c
19181 @end smallexample
19182
19183 @noindent
19184 In this listing, the asterisk before the first task indicates it to be the
19185 currently running task. The first column lists the task ID that is used
19186 to refer to tasks in the following commands.
19187
19188 @item break @var{linespec} task @var{taskid}
19189 @itemx break @var{linespec} task @var{taskid} if @dots{}
19190 @cindex Breakpoints and tasks
19191 These commands are like the @code{break @dots{} thread @dots{}}.
19192 @var{linespec} specifies source lines.
19193
19194 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19195 to specify that you only want @code{GDB} to stop the program when a
19196 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19197 numeric task identifiers assigned by @code{GDB}, shown in the first
19198 column of the @samp{info tasks} display.
19199
19200 If you do not specify @samp{task @var{taskid}} when you set a
19201 breakpoint, the breakpoint applies to @emph{all} tasks of your
19202 program.
19203
19204 You can use the @code{task} qualifier on conditional breakpoints as
19205 well; in this case, place @samp{task @var{taskid}} before the
19206 breakpoint condition (before the @code{if}).
19207
19208 @item task @var{taskno}
19209 @cindex Task switching
19210
19211 This command allows to switch to the task referred by @var{taskno}. In
19212 particular, This allows to browse the backtrace of the specified
19213 task. It is advised to switch back to the original task before
19214 continuing execution otherwise the scheduling of the program may be
19215 perturbed.
19216 @end table
19217
19218 @noindent
19219 For more detailed information on the tasking support,
19220 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19221
19222 @node Debugging Generic Units
19223 @section Debugging Generic Units
19224 @cindex Debugging Generic Units
19225 @cindex Generics
19226
19227 @noindent
19228 GNAT always uses code expansion for generic instantiation. This means that
19229 each time an instantiation occurs, a complete copy of the original code is
19230 made, with appropriate substitutions of formals by actuals.
19231
19232 It is not possible to refer to the original generic entities in
19233 @code{GDB}, but it is always possible to debug a particular instance of
19234 a generic, by using the appropriate expanded names. For example, if we have
19235
19236 @smallexample @c ada
19237 @group
19238 @cartouche
19239 procedure g is
19240
19241    generic package k is
19242       procedure kp (v1 : in out integer);
19243    end k;
19244
19245    package body k is
19246       procedure kp (v1 : in out integer) is
19247       begin
19248          v1 := v1 + 1;
19249       end kp;
19250    end k;
19251
19252    package k1 is new k;
19253    package k2 is new k;
19254
19255    var : integer := 1;
19256
19257 begin
19258    k1.kp (var);
19259    k2.kp (var);
19260    k1.kp (var);
19261    k2.kp (var);
19262 end;
19263 @end cartouche
19264 @end group
19265 @end smallexample
19266
19267 @noindent
19268 Then to break on a call to procedure kp in the k2 instance, simply
19269 use the command:
19270
19271 @smallexample
19272 (gdb) break g.k2.kp
19273 @end smallexample
19274
19275 @noindent
19276 When the breakpoint occurs, you can step through the code of the
19277 instance in the normal manner and examine the values of local variables, as for
19278 other units.
19279
19280 @node Remote Debugging using gdbserver
19281 @section Remote Debugging using gdbserver
19282 @cindex Remote Debugging using gdbserver
19283
19284 @noindent
19285 On platforms where gdbserver is supported, it is possible to use this tool
19286 to debug your application remotely.  This can be useful in situations
19287 where the program needs to be run on a target host that is different
19288 from the host used for development, particularly when the target has
19289 a limited amount of resources (either CPU and/or memory).
19290
19291 To do so, start your program using gdbserver on the target machine.
19292 gdbserver then automatically suspends the execution of your program
19293 at its entry point, waiting for a debugger to connect to it.  The
19294 following commands starts an application and tells gdbserver to
19295 wait for a connection with the debugger on localhost port 4444.
19296
19297 @smallexample
19298 $ gdbserver localhost:4444 program
19299 Process program created; pid = 5685
19300 Listening on port 4444
19301 @end smallexample
19302
19303 Once gdbserver has started listening, we can tell the debugger to establish
19304 a connection with this gdbserver, and then start the same debugging session
19305 as if the program was being debugged on the same host, directly under
19306 the control of GDB.
19307
19308 @smallexample
19309 $ gdb program
19310 (gdb) target remote targethost:4444
19311 Remote debugging using targethost:4444
19312 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19313 (gdb) b foo.adb:3
19314 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19315 (gdb) continue
19316 Continuing.
19317
19318 Breakpoint 1, foo () at foo.adb:4
19319 4       end foo;
19320 @end smallexample
19321
19322 It is also possible to use gdbserver to attach to an already running
19323 program, in which case the execution of that program is simply suspended
19324 until the connection between the debugger and gdbserver is established.
19325
19326 For more information on how to use gdbserver, @ref{Top, Server, Using
19327 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
19328 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19329
19330 @node GNAT Abnormal Termination or Failure to Terminate
19331 @section GNAT Abnormal Termination or Failure to Terminate
19332 @cindex GNAT Abnormal Termination or Failure to Terminate
19333
19334 @noindent
19335 When presented with programs that contain serious errors in syntax
19336 or semantics,
19337 GNAT may on rare occasions  experience problems in operation, such
19338 as aborting with a
19339 segmentation fault or illegal memory access, raising an internal
19340 exception, terminating abnormally, or failing to terminate at all.
19341 In such cases, you can activate
19342 various features of GNAT that can help you pinpoint the construct in your
19343 program that is the likely source of the problem.
19344
19345 The following strategies are presented in increasing order of
19346 difficulty, corresponding to your experience in using GNAT and your
19347 familiarity with compiler internals.
19348
19349 @enumerate
19350 @item
19351 Run @command{gcc} with the @option{-gnatf}. This first
19352 switch causes all errors on a given line to be reported. In its absence,
19353 only the first error on a line is displayed.
19354
19355 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19356 are encountered, rather than after compilation is terminated. If GNAT
19357 terminates prematurely or goes into an infinite loop, the last error
19358 message displayed may help to pinpoint the culprit.
19359
19360 @item
19361 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19362 mode, @command{gcc} produces ongoing information about the progress of the
19363 compilation and provides the name of each procedure as code is
19364 generated. This switch allows you to find which Ada procedure was being
19365 compiled when it encountered a code generation problem.
19366
19367 @item
19368 @cindex @option{-gnatdc} switch
19369 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19370 switch that does for the front-end what @option{^-v^VERBOSE^} does
19371 for the back end. The system prints the name of each unit,
19372 either a compilation unit or nested unit, as it is being analyzed.
19373 @item
19374 Finally, you can start
19375 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19376 front-end of GNAT, and can be run independently (normally it is just
19377 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19378 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19379 @code{where} command is the first line of attack; the variable
19380 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19381 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19382 which the execution stopped, and @code{input_file name} indicates the name of
19383 the source file.
19384 @end enumerate
19385
19386 @node Naming Conventions for GNAT Source Files
19387 @section Naming Conventions for GNAT Source Files
19388
19389 @noindent
19390 In order to examine the workings of the GNAT system, the following
19391 brief description of its organization may be helpful:
19392
19393 @itemize @bullet
19394 @item
19395 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19396
19397 @item
19398 All files prefixed with @file{^par^PAR^} are components of the parser. The
19399 numbers correspond to chapters of the Ada Reference Manual. For example,
19400 parsing of select statements can be found in @file{par-ch9.adb}.
19401
19402 @item
19403 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19404 numbers correspond to chapters of the Ada standard. For example, all
19405 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19406 addition, some features of the language require sufficient special processing
19407 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19408 dynamic dispatching, etc.
19409
19410 @item
19411 All files prefixed with @file{^exp^EXP^} perform normalization and
19412 expansion of the intermediate representation (abstract syntax tree, or AST).
19413 these files use the same numbering scheme as the parser and semantics files.
19414 For example, the construction of record initialization procedures is done in
19415 @file{exp_ch3.adb}.
19416
19417 @item
19418 The files prefixed with @file{^bind^BIND^} implement the binder, which
19419 verifies the consistency of the compilation, determines an order of
19420 elaboration, and generates the bind file.
19421
19422 @item
19423 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19424 data structures used by the front-end.
19425
19426 @item
19427 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19428 the abstract syntax tree as produced by the parser.
19429
19430 @item
19431 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19432 all entities, computed during semantic analysis.
19433
19434 @item
19435 Library management issues are dealt with in files with prefix
19436 @file{^lib^LIB^}.
19437
19438 @item
19439 @findex Ada
19440 @cindex Annex A
19441 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19442 defined in Annex A.
19443
19444 @item
19445 @findex Interfaces
19446 @cindex Annex B
19447 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19448 defined in Annex B.
19449
19450 @item
19451 @findex System
19452 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19453 both language-defined children and GNAT run-time routines.
19454
19455 @item
19456 @findex GNAT
19457 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19458 general-purpose packages, fully documented in their specs. All
19459 the other @file{.c} files are modifications of common @command{gcc} files.
19460 @end itemize
19461
19462 @node Getting Internal Debugging Information
19463 @section Getting Internal Debugging Information
19464
19465 @noindent
19466 Most compilers have internal debugging switches and modes. GNAT
19467 does also, except GNAT internal debugging switches and modes are not
19468 secret. A summary and full description of all the compiler and binder
19469 debug flags are in the file @file{debug.adb}. You must obtain the
19470 sources of the compiler to see the full detailed effects of these flags.
19471
19472 The switches that print the source of the program (reconstructed from
19473 the internal tree) are of general interest for user programs, as are the
19474 options to print
19475 the full internal tree, and the entity table (the symbol table
19476 information). The reconstructed source provides a readable version of the
19477 program after the front-end has completed analysis and  expansion,
19478 and is useful when studying the performance of specific constructs.
19479 For example, constraint checks are indicated, complex aggregates
19480 are replaced with loops and assignments, and tasking primitives
19481 are replaced with run-time calls.
19482
19483 @node Stack Traceback
19484 @section Stack Traceback
19485 @cindex traceback
19486 @cindex stack traceback
19487 @cindex stack unwinding
19488
19489 @noindent
19490 Traceback is a mechanism to display the sequence of subprogram calls that
19491 leads to a specified execution point in a program. Often (but not always)
19492 the execution point is an instruction at which an exception has been raised.
19493 This mechanism is also known as @i{stack unwinding} because it obtains
19494 its information by scanning the run-time stack and recovering the activation
19495 records of all active subprograms. Stack unwinding is one of the most
19496 important tools for program debugging.
19497
19498 The first entry stored in traceback corresponds to the deepest calling level,
19499 that is to say the subprogram currently executing the instruction
19500 from which we want to obtain the traceback.
19501
19502 Note that there is no runtime performance penalty when stack traceback
19503 is enabled, and no exception is raised during program execution.
19504
19505 @menu
19506 * Non-Symbolic Traceback::
19507 * Symbolic Traceback::
19508 @end menu
19509
19510 @node Non-Symbolic Traceback
19511 @subsection Non-Symbolic Traceback
19512 @cindex traceback, non-symbolic
19513
19514 @noindent
19515 Note: this feature is not supported on all platforms. See
19516 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19517 platforms.
19518
19519 @menu
19520 * Tracebacks From an Unhandled Exception::
19521 * Tracebacks From Exception Occurrences (non-symbolic)::
19522 * Tracebacks From Anywhere in a Program (non-symbolic)::
19523 @end menu
19524
19525 @node Tracebacks From an Unhandled Exception
19526 @subsubsection Tracebacks From an Unhandled Exception
19527
19528 @noindent
19529 A runtime non-symbolic traceback is a list of addresses of call instructions.
19530 To enable this feature you must use the @option{-E}
19531 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19532 of exception information. You can retrieve this information using the
19533 @code{addr2line} tool.
19534
19535 Here is a simple example:
19536
19537 @smallexample @c ada
19538 @cartouche
19539 procedure STB is
19540
19541    procedure P1 is
19542    begin
19543       raise Constraint_Error;
19544    end P1;
19545
19546    procedure P2 is
19547    begin
19548       P1;
19549    end P2;
19550
19551 begin
19552    P2;
19553 end STB;
19554 @end cartouche
19555 @end smallexample
19556
19557 @smallexample
19558 $ gnatmake stb -bargs -E
19559 $ stb
19560
19561 Execution terminated by unhandled exception
19562 Exception name: CONSTRAINT_ERROR
19563 Message: stb.adb:5
19564 Call stack traceback locations:
19565 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19566 @end smallexample
19567
19568 @noindent
19569 As we see the traceback lists a sequence of addresses for the unhandled
19570 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19571 guess that this exception come from procedure P1. To translate these
19572 addresses into the source lines where the calls appear, the
19573 @code{addr2line} tool, described below, is invaluable. The use of this tool
19574 requires the program to be compiled with debug information.
19575
19576 @smallexample
19577 $ gnatmake -g stb -bargs -E
19578 $ stb
19579
19580 Execution terminated by unhandled exception
19581 Exception name: CONSTRAINT_ERROR
19582 Message: stb.adb:5
19583 Call stack traceback locations:
19584 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19585
19586 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19587    0x4011f1 0x77e892a4
19588
19589 00401373 at d:/stb/stb.adb:5
19590 0040138B at d:/stb/stb.adb:10
19591 0040139C at d:/stb/stb.adb:14
19592 00401335 at d:/stb/b~stb.adb:104
19593 004011C4 at /build/@dots{}/crt1.c:200
19594 004011F1 at /build/@dots{}/crt1.c:222
19595 77E892A4 in ?? at ??:0
19596 @end smallexample
19597
19598 @noindent
19599 The @code{addr2line} tool has several other useful options:
19600
19601 @table @code
19602 @item --functions
19603 to get the function name corresponding to any location
19604
19605 @item --demangle=gnat
19606 to use the gnat decoding mode for the function names. Note that
19607 for binutils version 2.9.x the option is simply @option{--demangle}.
19608 @end table
19609
19610 @smallexample
19611 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19612    0x40139c 0x401335 0x4011c4 0x4011f1
19613
19614 00401373 in stb.p1 at d:/stb/stb.adb:5
19615 0040138B in stb.p2 at d:/stb/stb.adb:10
19616 0040139C in stb at d:/stb/stb.adb:14
19617 00401335 in main at d:/stb/b~stb.adb:104
19618 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19619 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19620 @end smallexample
19621
19622 @noindent
19623 From this traceback we can see that the exception was raised in
19624 @file{stb.adb} at line 5, which was reached from a procedure call in
19625 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19626 which contains the call to the main program.
19627 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19628 and the output will vary from platform to platform.
19629
19630 It is also possible to use @code{GDB} with these traceback addresses to debug
19631 the program. For example, we can break at a given code location, as reported
19632 in the stack traceback:
19633
19634 @smallexample
19635 $ gdb -nw stb
19636 @ifclear vms
19637 @noindent
19638 Furthermore, this feature is not implemented inside Windows DLL. Only
19639 the non-symbolic traceback is reported in this case.
19640 @end ifclear
19641
19642 (gdb) break *0x401373
19643 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19644 @end smallexample
19645
19646 @noindent
19647 It is important to note that the stack traceback addresses
19648 do not change when debug information is included. This is particularly useful
19649 because it makes it possible to release software without debug information (to
19650 minimize object size), get a field report that includes a stack traceback
19651 whenever an internal bug occurs, and then be able to retrieve the sequence
19652 of calls with the same program compiled with debug information.
19653
19654 @node Tracebacks From Exception Occurrences (non-symbolic)
19655 @subsubsection Tracebacks From Exception Occurrences
19656
19657 @noindent
19658 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19659 The stack traceback is attached to the exception information string, and can
19660 be retrieved in an exception handler within the Ada program, by means of the
19661 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19662
19663 @smallexample @c ada
19664 with Ada.Text_IO;
19665 with Ada.Exceptions;
19666
19667 procedure STB is
19668
19669    use Ada;
19670    use Ada.Exceptions;
19671
19672    procedure P1 is
19673       K : Positive := 1;
19674    begin
19675       K := K - 1;
19676    exception
19677       when E : others =>
19678          Text_IO.Put_Line (Exception_Information (E));
19679    end P1;
19680
19681    procedure P2 is
19682    begin
19683       P1;
19684    end P2;
19685
19686 begin
19687    P2;
19688 end STB;
19689 @end smallexample
19690
19691 @noindent
19692 This program will output:
19693
19694 @smallexample
19695 $ stb
19696
19697 Exception name: CONSTRAINT_ERROR
19698 Message: stb.adb:12
19699 Call stack traceback locations:
19700 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19701 @end smallexample
19702
19703 @node Tracebacks From Anywhere in a Program (non-symbolic)
19704 @subsubsection Tracebacks From Anywhere in a Program
19705
19706 @noindent
19707 It is also possible to retrieve a stack traceback from anywhere in a
19708 program. For this you need to
19709 use the @code{GNAT.Traceback} API. This package includes a procedure called
19710 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19711 display procedures described below. It is not necessary to use the
19712 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19713 is invoked explicitly.
19714
19715 @noindent
19716 In the following example we compute a traceback at a specific location in
19717 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19718 convert addresses to strings:
19719
19720 @smallexample @c ada
19721 with Ada.Text_IO;
19722 with GNAT.Traceback;
19723 with GNAT.Debug_Utilities;
19724
19725 procedure STB is
19726
19727    use Ada;
19728    use GNAT;
19729    use GNAT.Traceback;
19730
19731    procedure P1 is
19732       TB  : Tracebacks_Array (1 .. 10);
19733       --  We are asking for a maximum of 10 stack frames.
19734       Len : Natural;
19735       --  Len will receive the actual number of stack frames returned.
19736    begin
19737       Call_Chain (TB, Len);
19738
19739       Text_IO.Put ("In STB.P1 : ");
19740
19741       for K in 1 .. Len loop
19742          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19743          Text_IO.Put (' ');
19744       end loop;
19745
19746       Text_IO.New_Line;
19747    end P1;
19748
19749    procedure P2 is
19750    begin
19751       P1;
19752    end P2;
19753
19754 begin
19755    P2;
19756 end STB;
19757 @end smallexample
19758
19759 @smallexample
19760 $ gnatmake -g stb
19761 $ stb
19762
19763 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19764 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19765 @end smallexample
19766
19767 @noindent
19768 You can then get further information by invoking the @code{addr2line}
19769 tool as described earlier (note that the hexadecimal addresses
19770 need to be specified in C format, with a leading ``0x'').
19771
19772 @node Symbolic Traceback
19773 @subsection Symbolic Traceback
19774 @cindex traceback, symbolic
19775
19776 @noindent
19777 A symbolic traceback is a stack traceback in which procedure names are
19778 associated with each code location.
19779
19780 @noindent
19781 Note that this feature is not supported on all platforms. See
19782 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19783 list of currently supported platforms.
19784
19785 @noindent
19786 Note that the symbolic traceback requires that the program be compiled
19787 with debug information. If it is not compiled with debug information
19788 only the non-symbolic information will be valid.
19789
19790 @menu
19791 * Tracebacks From Exception Occurrences (symbolic)::
19792 * Tracebacks From Anywhere in a Program (symbolic)::
19793 @end menu
19794
19795 @node Tracebacks From Exception Occurrences (symbolic)
19796 @subsubsection Tracebacks From Exception Occurrences
19797
19798 @smallexample @c ada
19799 with Ada.Text_IO;
19800 with GNAT.Traceback.Symbolic;
19801
19802 procedure STB is
19803
19804    procedure P1 is
19805    begin
19806       raise Constraint_Error;
19807    end P1;
19808
19809    procedure P2 is
19810    begin
19811       P1;
19812    end P2;
19813
19814    procedure P3 is
19815    begin
19816       P2;
19817    end P3;
19818
19819 begin
19820    P3;
19821 exception
19822    when E : others =>
19823       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19824 end STB;
19825 @end smallexample
19826
19827 @smallexample
19828 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19829 $ stb
19830
19831 0040149F in stb.p1 at stb.adb:8
19832 004014B7 in stb.p2 at stb.adb:13
19833 004014CF in stb.p3 at stb.adb:18
19834 004015DD in ada.stb at stb.adb:22
19835 00401461 in main at b~stb.adb:168
19836 004011C4 in __mingw_CRTStartup at crt1.c:200
19837 004011F1 in mainCRTStartup at crt1.c:222
19838 77E892A4 in ?? at ??:0
19839 @end smallexample
19840
19841 @noindent
19842 In the above example the ``.\'' syntax in the @command{gnatmake} command
19843 is currently required by @command{addr2line} for files that are in
19844 the current working directory.
19845 Moreover, the exact sequence of linker options may vary from platform
19846 to platform.
19847 The above @option{-largs} section is for Windows platforms. By contrast,
19848 under Unix there is no need for the @option{-largs} section.
19849 Differences across platforms are due to details of linker implementation.
19850
19851 @node Tracebacks From Anywhere in a Program (symbolic)
19852 @subsubsection Tracebacks From Anywhere in a Program
19853
19854 @noindent
19855 It is possible to get a symbolic stack traceback
19856 from anywhere in a program, just as for non-symbolic tracebacks.
19857 The first step is to obtain a non-symbolic
19858 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19859 information. Here is an example:
19860
19861 @smallexample @c ada
19862 with Ada.Text_IO;
19863 with GNAT.Traceback;
19864 with GNAT.Traceback.Symbolic;
19865
19866 procedure STB is
19867
19868    use Ada;
19869    use GNAT.Traceback;
19870    use GNAT.Traceback.Symbolic;
19871
19872    procedure P1 is
19873       TB  : Tracebacks_Array (1 .. 10);
19874       --  We are asking for a maximum of 10 stack frames.
19875       Len : Natural;
19876       --  Len will receive the actual number of stack frames returned.
19877    begin
19878       Call_Chain (TB, Len);
19879       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19880    end P1;
19881
19882    procedure P2 is
19883    begin
19884       P1;
19885    end P2;
19886
19887 begin
19888    P2;
19889 end STB;
19890 @end smallexample
19891
19892 @c ******************************
19893 @ifset vms
19894 @node Compatibility with HP Ada
19895 @chapter Compatibility with HP Ada
19896 @cindex Compatibility
19897
19898 @noindent
19899 @cindex DEC Ada
19900 @cindex HP Ada
19901 @cindex Compatibility between GNAT and HP Ada
19902 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19903 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19904 GNAT is highly compatible
19905 with HP Ada, and it should generally be straightforward to port code
19906 from the HP Ada environment to GNAT. However, there are a few language
19907 and implementation differences of which the user must be aware. These
19908 differences are discussed in this chapter. In
19909 addition, the operating environment and command structure for the
19910 compiler are different, and these differences are also discussed.
19911
19912 For further details on these and other compatibility issues,
19913 see Appendix E of the HP publication
19914 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19915
19916 Except where otherwise indicated, the description of GNAT for OpenVMS
19917 applies to both the Alpha and I64 platforms.
19918
19919 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19920 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19921
19922 The discussion in this chapter addresses specifically the implementation
19923 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19924 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19925 GNAT always follows the Alpha implementation.
19926
19927 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19928 attributes are recognized, although only a subset of them can sensibly
19929 be implemented.  The description of pragmas in
19930 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19931 indicates whether or not they are applicable to non-VMS systems.
19932
19933 @menu
19934 * Ada Language Compatibility::
19935 * Differences in the Definition of Package System::
19936 * Language-Related Features::
19937 * The Package STANDARD::
19938 * The Package SYSTEM::
19939 * Tasking and Task-Related Features::
19940 * Pragmas and Pragma-Related Features::
19941 * Library of Predefined Units::
19942 * Bindings::
19943 * Main Program Definition::
19944 * Implementation-Defined Attributes::
19945 * Compiler and Run-Time Interfacing::
19946 * Program Compilation and Library Management::
19947 * Input-Output::
19948 * Implementation Limits::
19949 * Tools and Utilities::
19950 @end menu
19951
19952 @node Ada Language Compatibility
19953 @section Ada Language Compatibility
19954
19955 @noindent
19956 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19957 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19958 with Ada 83, and therefore Ada 83 programs will compile
19959 and run under GNAT with
19960 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19961 provides details on specific incompatibilities.
19962
19963 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19964 as well as the pragma @code{ADA_83}, to force the compiler to
19965 operate in Ada 83 mode. This mode does not guarantee complete
19966 conformance to Ada 83, but in practice is sufficient to
19967 eliminate most sources of incompatibilities.
19968 In particular, it eliminates the recognition of the
19969 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19970 in Ada 83 programs is legal, and handles the cases of packages
19971 with optional bodies, and generics that instantiate unconstrained
19972 types without the use of @code{(<>)}.
19973
19974 @node Differences in the Definition of Package System
19975 @section Differences in the Definition of Package @code{System}
19976
19977 @noindent
19978 An Ada compiler is allowed to add
19979 implementation-dependent declarations to package @code{System}.
19980 In normal mode,
19981 GNAT does not take advantage of this permission, and the version of
19982 @code{System} provided by GNAT exactly matches that defined in the Ada
19983 Reference Manual.
19984
19985 However, HP Ada adds an extensive set of declarations to package
19986 @code{System},
19987 as fully documented in the HP Ada manuals. To minimize changes required
19988 for programs that make use of these extensions, GNAT provides the pragma
19989 @code{Extend_System} for extending the definition of package System. By using:
19990 @cindex pragma @code{Extend_System}
19991 @cindex @code{Extend_System} pragma
19992
19993 @smallexample @c ada
19994 @group
19995 @cartouche
19996 pragma Extend_System (Aux_DEC);
19997 @end cartouche
19998 @end group
19999 @end smallexample
20000
20001 @noindent
20002 the set of definitions in @code{System} is extended to include those in
20003 package @code{System.Aux_DEC}.
20004 @cindex @code{System.Aux_DEC} package
20005 @cindex @code{Aux_DEC} package (child of @code{System})
20006 These definitions are incorporated directly into package @code{System},
20007 as though they had been declared there. For a
20008 list of the declarations added, see the spec of this package,
20009 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20010 @cindex @file{s-auxdec.ads} file
20011 The pragma @code{Extend_System} is a configuration pragma, which means that
20012 it can be placed in the file @file{gnat.adc}, so that it will automatically
20013 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20014 for further details.
20015
20016 An alternative approach that avoids the use of the non-standard
20017 @code{Extend_System} pragma is to add a context clause to the unit that
20018 references these facilities:
20019
20020 @smallexample @c ada
20021 @cartouche
20022 with System.Aux_DEC;
20023 use  System.Aux_DEC;
20024 @end cartouche
20025 @end smallexample
20026
20027 @noindent
20028 The effect is not quite semantically identical to incorporating
20029 the declarations directly into package @code{System},
20030 but most programs will not notice a difference
20031 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20032 to reference the entities directly in package @code{System}.
20033 For units containing such references,
20034 the prefixes must either be removed, or the pragma @code{Extend_System}
20035 must be used.
20036
20037 @node Language-Related Features
20038 @section Language-Related Features
20039
20040 @noindent
20041 The following sections highlight differences in types,
20042 representations of types, operations, alignment, and
20043 related topics.
20044
20045 @menu
20046 * Integer Types and Representations::
20047 * Floating-Point Types and Representations::
20048 * Pragmas Float_Representation and Long_Float::
20049 * Fixed-Point Types and Representations::
20050 * Record and Array Component Alignment::
20051 * Address Clauses::
20052 * Other Representation Clauses::
20053 @end menu
20054
20055 @node Integer Types and Representations
20056 @subsection Integer Types and Representations
20057
20058 @noindent
20059 The set of predefined integer types is identical in HP Ada and GNAT.
20060 Furthermore the representation of these integer types is also identical,
20061 including the capability of size clauses forcing biased representation.
20062
20063 In addition,
20064 HP Ada for OpenVMS Alpha systems has defined the
20065 following additional integer types in package @code{System}:
20066
20067 @itemize @bullet
20068
20069 @item
20070 @code{INTEGER_8}
20071
20072 @item
20073 @code{INTEGER_16}
20074
20075 @item
20076 @code{INTEGER_32}
20077
20078 @item
20079 @code{INTEGER_64}
20080
20081 @item
20082 @code{LARGEST_INTEGER}
20083 @end itemize
20084
20085 @noindent
20086 In GNAT, the first four of these types may be obtained from the
20087 standard Ada package @code{Interfaces}.
20088 Alternatively, by use of the pragma @code{Extend_System}, identical
20089 declarations can be referenced directly in package @code{System}.
20090 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20091
20092 @node Floating-Point Types and Representations
20093 @subsection Floating-Point Types and Representations
20094 @cindex Floating-Point types
20095
20096 @noindent
20097 The set of predefined floating-point types is identical in HP Ada and GNAT.
20098 Furthermore the representation of these floating-point
20099 types is also identical. One important difference is that the default
20100 representation for HP Ada is @code{VAX_Float}, but the default representation
20101 for GNAT is IEEE.
20102
20103 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20104 pragma @code{Float_Representation} as described in the HP Ada
20105 documentation.
20106 For example, the declarations:
20107
20108 @smallexample @c ada
20109 @cartouche
20110 type F_Float is digits 6;
20111 pragma Float_Representation (VAX_Float, F_Float);
20112 @end cartouche
20113 @end smallexample
20114
20115 @noindent
20116 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20117 format.
20118 This set of declarations actually appears in @code{System.Aux_DEC},
20119 which contains
20120 the full set of additional floating-point declarations provided in
20121 the HP Ada version of package @code{System}.
20122 This and similar declarations may be accessed in a user program
20123 by using pragma @code{Extend_System}. The use of this
20124 pragma, and the related pragma @code{Long_Float} is described in further
20125 detail in the following section.
20126
20127 @node Pragmas Float_Representation and Long_Float
20128 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20129
20130 @noindent
20131 HP Ada provides the pragma @code{Float_Representation}, which
20132 acts as a program library switch to allow control over
20133 the internal representation chosen for the predefined
20134 floating-point types declared in the package @code{Standard}.
20135 The format of this pragma is as follows:
20136
20137 @smallexample @c ada
20138 @cartouche
20139 pragma Float_Representation(VAX_Float | IEEE_Float);
20140 @end cartouche
20141 @end smallexample
20142
20143 @noindent
20144 This pragma controls the representation of floating-point
20145 types as follows:
20146
20147 @itemize @bullet
20148 @item
20149 @code{VAX_Float} specifies that floating-point
20150 types are represented by default with the VAX system hardware types
20151 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20152 Note that the @code{H-floating}
20153 type was available only on VAX systems, and is not available
20154 in either HP Ada or GNAT.
20155
20156 @item
20157 @code{IEEE_Float} specifies that floating-point
20158 types are represented by default with the IEEE single and
20159 double floating-point types.
20160 @end itemize
20161
20162 @noindent
20163 GNAT provides an identical implementation of the pragma
20164 @code{Float_Representation}, except that it functions as a
20165 configuration pragma. Note that the
20166 notion of configuration pragma corresponds closely to the
20167 HP Ada notion of a program library switch.
20168
20169 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20170 which is different
20171 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20172 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20173 advisable to change the format of numbers passed to standard library
20174 routines, and if necessary explicit type conversions may be needed.
20175
20176 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20177 efficient, and (given that it conforms to an international standard)
20178 potentially more portable.
20179 The situation in which @code{VAX_Float} may be useful is in interfacing
20180 to existing code and data that expect the use of @code{VAX_Float}.
20181 In such a situation use the predefined @code{VAX_Float}
20182 types in package @code{System}, as extended by
20183 @code{Extend_System}. For example, use @code{System.F_Float}
20184 to specify the 32-bit @code{F-Float} format.
20185
20186 @noindent
20187 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20188 to allow control over the internal representation chosen
20189 for the predefined type @code{Long_Float} and for floating-point
20190 type declarations with digits specified in the range 7 .. 15.
20191 The format of this pragma is as follows:
20192
20193 @smallexample @c ada
20194 @cartouche
20195 pragma Long_Float (D_FLOAT | G_FLOAT);
20196 @end cartouche
20197 @end smallexample
20198
20199 @node Fixed-Point Types and Representations
20200 @subsection Fixed-Point Types and Representations
20201
20202 @noindent
20203 On HP Ada for OpenVMS Alpha systems, rounding is
20204 away from zero for both positive and negative numbers.
20205 Therefore, @code{+0.5} rounds to @code{1},
20206 and @code{-0.5} rounds to @code{-1}.
20207
20208 On GNAT the results of operations
20209 on fixed-point types are in accordance with the Ada
20210 rules. In particular, results of operations on decimal
20211 fixed-point types are truncated.
20212
20213 @node Record and Array Component Alignment
20214 @subsection Record and Array Component Alignment
20215
20216 @noindent
20217 On HP Ada for OpenVMS Alpha, all non-composite components
20218 are aligned on natural boundaries. For example, 1-byte
20219 components are aligned on byte boundaries, 2-byte
20220 components on 2-byte boundaries, 4-byte components on 4-byte
20221 byte boundaries, and so on. The OpenVMS Alpha hardware
20222 runs more efficiently with naturally aligned data.
20223
20224 On GNAT, alignment rules are compatible
20225 with HP Ada for OpenVMS Alpha.
20226
20227 @node Address Clauses
20228 @subsection Address Clauses
20229
20230 @noindent
20231 In HP Ada and GNAT, address clauses are supported for
20232 objects and imported subprograms.
20233 The predefined type @code{System.Address} is a private type
20234 in both compilers on Alpha OpenVMS, with the same representation
20235 (it is simply a machine pointer). Addition, subtraction, and comparison
20236 operations are available in the standard Ada package
20237 @code{System.Storage_Elements}, or in package @code{System}
20238 if it is extended to include @code{System.Aux_DEC} using a
20239 pragma @code{Extend_System} as previously described.
20240
20241 Note that code that @code{with}'s both this extended package @code{System}
20242 and the package @code{System.Storage_Elements} should not @code{use}
20243 both packages, or ambiguities will result. In general it is better
20244 not to mix these two sets of facilities. The Ada package was
20245 designed specifically to provide the kind of features that HP Ada
20246 adds directly to package @code{System}.
20247
20248 The type @code{System.Address} is a 64-bit integer type in GNAT for
20249 I64 OpenVMS.  For more information,
20250 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20251
20252 GNAT is compatible with HP Ada in its handling of address
20253 clauses, except for some limitations in
20254 the form of address clauses for composite objects with
20255 initialization. Such address clauses are easily replaced
20256 by the use of an explicitly-defined constant as described
20257 in the Ada Reference Manual (13.1(22)). For example, the sequence
20258 of declarations:
20259
20260 @smallexample @c ada
20261 @cartouche
20262 X, Y : Integer := Init_Func;
20263 Q : String (X .. Y) := "abc";
20264 @dots{}
20265 for Q'Address use Compute_Address;
20266 @end cartouche
20267 @end smallexample
20268
20269 @noindent
20270 will be rejected by GNAT, since the address cannot be computed at the time
20271 that @code{Q} is declared. To achieve the intended effect, write instead:
20272
20273 @smallexample @c ada
20274 @group
20275 @cartouche
20276 X, Y : Integer := Init_Func;
20277 Q_Address : constant Address := Compute_Address;
20278 Q : String (X .. Y) := "abc";
20279 @dots{}
20280 for Q'Address use Q_Address;
20281 @end cartouche
20282 @end group
20283 @end smallexample
20284
20285 @noindent
20286 which will be accepted by GNAT (and other Ada compilers), and is also
20287 compatible with Ada 83. A fuller description of the restrictions
20288 on address specifications is found in @ref{Top, GNAT Reference Manual,
20289 About This Guide, gnat_rm, GNAT Reference Manual}.
20290
20291 @node Other Representation Clauses
20292 @subsection Other Representation Clauses
20293
20294 @noindent
20295 GNAT implements in a compatible manner all the representation
20296 clauses supported by HP Ada. In addition, GNAT
20297 implements the representation clause forms that were introduced in Ada 95,
20298 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20299
20300 @node The Package STANDARD
20301 @section The Package @code{STANDARD}
20302
20303 @noindent
20304 The package @code{STANDARD}, as implemented by HP Ada, is fully
20305 described in the @cite{Ada Reference Manual} and in the
20306 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20307 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20308
20309 In addition, HP Ada supports the Latin-1 character set in
20310 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20311 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20312 the type @code{WIDE_CHARACTER}.
20313
20314 The floating-point types supported by GNAT are those
20315 supported by HP Ada, but the defaults are different, and are controlled by
20316 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20317
20318 @node The Package SYSTEM
20319 @section The Package @code{SYSTEM}
20320
20321 @noindent
20322 HP Ada provides a specific version of the package
20323 @code{SYSTEM} for each platform on which the language is implemented.
20324 For the complete spec of the package @code{SYSTEM}, see
20325 Appendix F of the @cite{HP Ada Language Reference Manual}.
20326
20327 On HP Ada, the package @code{SYSTEM} includes the following conversion
20328 functions:
20329 @itemize @bullet
20330 @item @code{TO_ADDRESS(INTEGER)}
20331
20332 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20333
20334 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20335
20336 @item @code{TO_INTEGER(ADDRESS)}
20337
20338 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20339
20340 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20341 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20342 @end itemize
20343
20344 @noindent
20345 By default, GNAT supplies a version of @code{SYSTEM} that matches
20346 the definition given in the @cite{Ada Reference Manual}.
20347 This
20348 is a subset of the HP system definitions, which is as
20349 close as possible to the original definitions. The only difference
20350 is that the definition of @code{SYSTEM_NAME} is different:
20351
20352 @smallexample @c ada
20353 @cartouche
20354 type Name is (SYSTEM_NAME_GNAT);
20355 System_Name : constant Name := SYSTEM_NAME_GNAT;
20356 @end cartouche
20357 @end smallexample
20358
20359 @noindent
20360 Also, GNAT adds the Ada declarations for
20361 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20362
20363 However, the use of the following pragma causes GNAT
20364 to extend the definition of package @code{SYSTEM} so that it
20365 encompasses the full set of HP-specific extensions,
20366 including the functions listed above:
20367
20368 @smallexample @c ada
20369 @cartouche
20370 pragma Extend_System (Aux_DEC);
20371 @end cartouche
20372 @end smallexample
20373
20374 @noindent
20375 The pragma @code{Extend_System} is a configuration pragma that
20376 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20377 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20378
20379 HP Ada does not allow the recompilation of the package
20380 @code{SYSTEM}. Instead HP Ada provides several pragmas
20381 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20382 to modify values in the package @code{SYSTEM}.
20383 On OpenVMS Alpha systems, the pragma
20384 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20385 its single argument.
20386
20387 GNAT does permit the recompilation of package @code{SYSTEM} using
20388 the special switch @option{-gnatg}, and this switch can be used if
20389 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20390 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20391 or @code{MEMORY_SIZE} by any other means.
20392
20393 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20394 enumeration literal @code{SYSTEM_NAME_GNAT}.
20395
20396 The definitions provided by the use of
20397
20398 @smallexample @c ada
20399 pragma Extend_System (AUX_Dec);
20400 @end smallexample
20401
20402 @noindent
20403 are virtually identical to those provided by the HP Ada 83 package
20404 @code{SYSTEM}. One important difference is that the name of the
20405 @code{TO_ADDRESS}
20406 function for type @code{UNSIGNED_LONGWORD} is changed to
20407 @code{TO_ADDRESS_LONG}.
20408 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20409 discussion of why this change was necessary.
20410
20411 @noindent
20412 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20413 is in fact
20414 an extension to Ada 83 not strictly compatible with the reference manual.
20415 GNAT, in order to be exactly compatible with the standard,
20416 does not provide this capability. In HP Ada 83, the
20417 point of this definition is to deal with a call like:
20418
20419 @smallexample @c ada
20420 TO_ADDRESS (16#12777#);
20421 @end smallexample
20422
20423 @noindent
20424 Normally, according to Ada 83 semantics, one would expect this to be
20425 ambiguous, since it matches both the @code{INTEGER} and
20426 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20427 However, in HP Ada 83, there is no ambiguity, since the
20428 definition using @i{universal_integer} takes precedence.
20429
20430 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20431 it is
20432 not possible to be 100% compatible. Since there are many programs using
20433 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20434 GNAT was
20435 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20436 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20437
20438 @smallexample @c ada
20439 function To_Address (X : Integer) return Address;
20440 pragma Pure_Function (To_Address);
20441
20442 function To_Address_Long (X : Unsigned_Longword) return Address;
20443 pragma Pure_Function (To_Address_Long);
20444 @end smallexample
20445
20446 @noindent
20447 This means that programs using @code{TO_ADDRESS} for
20448 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20449
20450 @node Tasking and Task-Related Features
20451 @section Tasking and Task-Related Features
20452
20453 @noindent
20454 This section compares the treatment of tasking in GNAT
20455 and in HP Ada for OpenVMS Alpha.
20456 The GNAT description applies to both Alpha and I64 OpenVMS.
20457 For detailed information on tasking in
20458 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20459 relevant run-time reference manual.
20460
20461 @menu
20462 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20463 * Assigning Task IDs::
20464 * Task IDs and Delays::
20465 * Task-Related Pragmas::
20466 * Scheduling and Task Priority::
20467 * The Task Stack::
20468 * External Interrupts::
20469 @end menu
20470
20471 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20472 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20473
20474 @noindent
20475 On OpenVMS Alpha systems, each Ada task (except a passive
20476 task) is implemented as a single stream of execution
20477 that is created and managed by the kernel. On these
20478 systems, HP Ada tasking support is based on DECthreads,
20479 an implementation of the POSIX standard for threads.
20480
20481 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20482 code that calls DECthreads routines can be used together.
20483 The interaction between Ada tasks and DECthreads routines
20484 can have some benefits. For example when on OpenVMS Alpha,
20485 HP Ada can call C code that is already threaded.
20486
20487 GNAT uses the facilities of DECthreads,
20488 and Ada tasks are mapped to threads.
20489
20490 @node Assigning Task IDs
20491 @subsection Assigning Task IDs
20492
20493 @noindent
20494 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20495 the environment task that executes the main program. On
20496 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20497 that have been created but are not yet activated.
20498
20499 On OpenVMS Alpha systems, task IDs are assigned at
20500 activation. On GNAT systems, task IDs are also assigned at
20501 task creation but do not have the same form or values as
20502 task ID values in HP Ada. There is no null task, and the
20503 environment task does not have a specific task ID value.
20504
20505 @node Task IDs and Delays
20506 @subsection Task IDs and Delays
20507
20508 @noindent
20509 On OpenVMS Alpha systems, tasking delays are implemented
20510 using Timer System Services. The Task ID is used for the
20511 identification of the timer request (the @code{REQIDT} parameter).
20512 If Timers are used in the application take care not to use
20513 @code{0} for the identification, because cancelling such a timer
20514 will cancel all timers and may lead to unpredictable results.
20515
20516 @node Task-Related Pragmas
20517 @subsection Task-Related Pragmas
20518
20519 @noindent
20520 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20521 specification of the size of the guard area for a task
20522 stack. (The guard area forms an area of memory that has no
20523 read or write access and thus helps in the detection of
20524 stack overflow.) On OpenVMS Alpha systems, if the pragma
20525 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20526 area is created. In the absence of a pragma @code{TASK_STORAGE},
20527 a default guard area is created.
20528
20529 GNAT supplies the following task-related pragmas:
20530
20531 @itemize @bullet
20532 @item  @code{TASK_INFO}
20533
20534 This pragma appears within a task definition and
20535 applies to the task in which it appears. The argument
20536 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20537
20538 @item  @code{TASK_STORAGE}
20539
20540 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20541 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20542 @code{SUPPRESS}, and @code{VOLATILE}.
20543 @end itemize
20544 @node Scheduling and Task Priority
20545 @subsection Scheduling and Task Priority
20546
20547 @noindent
20548 HP Ada implements the Ada language requirement that
20549 when two tasks are eligible for execution and they have
20550 different priorities, the lower priority task does not
20551 execute while the higher priority task is waiting. The HP
20552 Ada Run-Time Library keeps a task running until either the
20553 task is suspended or a higher priority task becomes ready.
20554
20555 On OpenVMS Alpha systems, the default strategy is round-
20556 robin with preemption. Tasks of equal priority take turns
20557 at the processor. A task is run for a certain period of
20558 time and then placed at the tail of the ready queue for
20559 its priority level.
20560
20561 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20562 which can be used to enable or disable round-robin
20563 scheduling of tasks with the same priority.
20564 See the relevant HP Ada run-time reference manual for
20565 information on using the pragmas to control HP Ada task
20566 scheduling.
20567
20568 GNAT follows the scheduling rules of Annex D (Real-Time
20569 Annex) of the @cite{Ada Reference Manual}. In general, this
20570 scheduling strategy is fully compatible with HP Ada
20571 although it provides some additional constraints (as
20572 fully documented in Annex D).
20573 GNAT implements time slicing control in a manner compatible with
20574 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20575 are identical to the HP Ada 83 pragma of the same name.
20576 Note that it is not possible to mix GNAT tasking and
20577 HP Ada 83 tasking in the same program, since the two run-time
20578 libraries are not compatible.
20579
20580 @node The Task Stack
20581 @subsection The Task Stack
20582
20583 @noindent
20584 In HP Ada, a task stack is allocated each time a
20585 non-passive task is activated. As soon as the task is
20586 terminated, the storage for the task stack is deallocated.
20587 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20588 a default stack size is used. Also, regardless of the size
20589 specified, some additional space is allocated for task
20590 management purposes. On OpenVMS Alpha systems, at least
20591 one page is allocated.
20592
20593 GNAT handles task stacks in a similar manner. In accordance with
20594 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20595 an alternative method for controlling the task stack size.
20596 The specification of the attribute @code{T'STORAGE_SIZE} is also
20597 supported in a manner compatible with HP Ada.
20598
20599 @node External Interrupts
20600 @subsection External Interrupts
20601
20602 @noindent
20603 On HP Ada, external interrupts can be associated with task entries.
20604 GNAT is compatible with HP Ada in its handling of external interrupts.
20605
20606 @node Pragmas and Pragma-Related Features
20607 @section Pragmas and Pragma-Related Features
20608
20609 @noindent
20610 Both HP Ada and GNAT supply all language-defined pragmas
20611 as specified by the Ada 83 standard. GNAT also supplies all
20612 language-defined pragmas introduced by Ada 95 and Ada 2005.
20613 In addition, GNAT implements the implementation-defined pragmas
20614 from HP Ada 83.
20615
20616 @itemize @bullet
20617 @item  @code{AST_ENTRY}
20618
20619 @item  @code{COMMON_OBJECT}
20620
20621 @item  @code{COMPONENT_ALIGNMENT}
20622
20623 @item  @code{EXPORT_EXCEPTION}
20624
20625 @item  @code{EXPORT_FUNCTION}
20626
20627 @item  @code{EXPORT_OBJECT}
20628
20629 @item  @code{EXPORT_PROCEDURE}
20630
20631 @item  @code{EXPORT_VALUED_PROCEDURE}
20632
20633 @item  @code{FLOAT_REPRESENTATION}
20634
20635 @item  @code{IDENT}
20636
20637 @item  @code{IMPORT_EXCEPTION}
20638
20639 @item  @code{IMPORT_FUNCTION}
20640
20641 @item  @code{IMPORT_OBJECT}
20642
20643 @item  @code{IMPORT_PROCEDURE}
20644
20645 @item  @code{IMPORT_VALUED_PROCEDURE}
20646
20647 @item  @code{INLINE_GENERIC}
20648
20649 @item  @code{INTERFACE_NAME}
20650
20651 @item  @code{LONG_FLOAT}
20652
20653 @item  @code{MAIN_STORAGE}
20654
20655 @item  @code{PASSIVE}
20656
20657 @item  @code{PSECT_OBJECT}
20658
20659 @item  @code{SHARE_GENERIC}
20660
20661 @item  @code{SUPPRESS_ALL}
20662
20663 @item  @code{TASK_STORAGE}
20664
20665 @item  @code{TIME_SLICE}
20666
20667 @item  @code{TITLE}
20668 @end itemize
20669
20670 @noindent
20671 These pragmas are all fully implemented, with the exception of @code{TITLE},
20672 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20673 recognized, but which have no
20674 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20675 use of Ada protected objects. In GNAT, all generics are inlined.
20676
20677 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20678 a separate subprogram specification which must appear before the
20679 subprogram body.
20680
20681 GNAT also supplies a number of implementation-defined pragmas including the
20682 following:
20683
20684 @itemize @bullet
20685 @item  @code{ABORT_DEFER}
20686
20687 @item  @code{ADA_83}
20688
20689 @item  @code{ADA_95}
20690
20691 @item  @code{ADA_05}
20692
20693 @item  @code{Ada_2005}
20694
20695 @item  @code{Ada_12}
20696
20697 @item  @code{Ada_2012}
20698
20699 @item  @code{ANNOTATE}
20700
20701 @item  @code{ASSERT}
20702
20703 @item  @code{C_PASS_BY_COPY}
20704
20705 @item  @code{CPP_CLASS}
20706
20707 @item  @code{CPP_CONSTRUCTOR}
20708
20709 @item  @code{CPP_DESTRUCTOR}
20710
20711 @item  @code{DEBUG}
20712
20713 @item  @code{EXTEND_SYSTEM}
20714
20715 @item  @code{LINKER_ALIAS}
20716
20717 @item  @code{LINKER_SECTION}
20718
20719 @item  @code{MACHINE_ATTRIBUTE}
20720
20721 @item  @code{NO_RETURN}
20722
20723 @item  @code{PURE_FUNCTION}
20724
20725 @item  @code{SOURCE_FILE_NAME}
20726
20727 @item  @code{SOURCE_REFERENCE}
20728
20729 @item  @code{TASK_INFO}
20730
20731 @item  @code{UNCHECKED_UNION}
20732
20733 @item  @code{UNIMPLEMENTED_UNIT}
20734
20735 @item  @code{UNIVERSAL_DATA}
20736
20737 @item  @code{UNSUPPRESS}
20738
20739 @item  @code{WARNINGS}
20740
20741 @item  @code{WEAK_EXTERNAL}
20742 @end itemize
20743
20744 @noindent
20745 For full details on these and other GNAT implementation-defined pragmas,
20746 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20747 Manual}.
20748
20749 @menu
20750 * Restrictions on the Pragma INLINE::
20751 * Restrictions on the Pragma INTERFACE::
20752 * Restrictions on the Pragma SYSTEM_NAME::
20753 @end menu
20754
20755 @node Restrictions on the Pragma INLINE
20756 @subsection Restrictions on Pragma @code{INLINE}
20757
20758 @noindent
20759 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20760 @itemize @bullet
20761 @item  Parameters cannot have a task type.
20762
20763 @item  Function results cannot be task types, unconstrained
20764 array types, or unconstrained types with discriminants.
20765
20766 @item  Bodies cannot declare the following:
20767 @itemize @bullet
20768 @item  Subprogram body or stub (imported subprogram is allowed)
20769
20770 @item  Tasks
20771
20772 @item  Generic declarations
20773
20774 @item  Instantiations
20775
20776 @item  Exceptions
20777
20778 @item  Access types (types derived from access types allowed)
20779
20780 @item  Array or record types
20781
20782 @item  Dependent tasks
20783
20784 @item  Direct recursive calls of subprogram or containing
20785 subprogram, directly or via a renaming
20786
20787 @end itemize
20788 @end itemize
20789
20790 @noindent
20791 In GNAT, the only restriction on pragma @code{INLINE} is that the
20792 body must occur before the call if both are in the same
20793 unit, and the size must be appropriately small. There are
20794 no other specific restrictions which cause subprograms to
20795 be incapable of being inlined.
20796
20797 @node  Restrictions on the Pragma INTERFACE
20798 @subsection  Restrictions on Pragma @code{INTERFACE}
20799
20800 @noindent
20801 The following restrictions on pragma @code{INTERFACE}
20802 are enforced by both HP Ada and GNAT:
20803 @itemize @bullet
20804 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20805 Default is the default on OpenVMS Alpha systems.
20806
20807 @item  Parameter passing: Language specifies default
20808 mechanisms but can be overridden with an @code{EXPORT} pragma.
20809
20810 @itemize @bullet
20811 @item  Ada: Use internal Ada rules.
20812
20813 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20814 record or task type. Result cannot be a string, an
20815 array, or a record.
20816
20817 @item  Fortran: Parameters cannot have a task type. Result cannot
20818 be a string, an array, or a record.
20819 @end itemize
20820 @end itemize
20821
20822 @noindent
20823 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20824 record parameters for all languages.
20825
20826 @node  Restrictions on the Pragma SYSTEM_NAME
20827 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20828
20829 @noindent
20830 For HP Ada for OpenVMS Alpha, the enumeration literal
20831 for the type @code{NAME} is @code{OPENVMS_AXP}.
20832 In GNAT, the enumeration
20833 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20834
20835 @node  Library of Predefined Units
20836 @section  Library of Predefined Units
20837
20838 @noindent
20839 A library of predefined units is provided as part of the
20840 HP Ada and GNAT implementations. HP Ada does not provide
20841 the package @code{MACHINE_CODE} but instead recommends importing
20842 assembler code.
20843
20844 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20845 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20846 version.
20847 The HP Ada Predefined Library units are modified to remove post-Ada 83
20848 incompatibilities and to make them interoperable with GNAT
20849 (@pxref{Changes to DECLIB}, for details).
20850 The units are located in the @file{DECLIB} directory.
20851
20852 The GNAT RTL is contained in
20853 the @file{ADALIB} directory, and
20854 the default search path is set up to find @code{DECLIB} units in preference
20855 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20856 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20857
20858 @menu
20859 * Changes to DECLIB::
20860 @end menu
20861
20862 @node Changes to DECLIB
20863 @subsection Changes to @code{DECLIB}
20864
20865 @noindent
20866 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20867 compatibility are minor and include the following:
20868
20869 @itemize @bullet
20870 @item  Adjusting the location of pragmas and record representation
20871 clauses to obey Ada 95 (and thus Ada 2005) rules
20872
20873 @item  Adding the proper notation to generic formal parameters
20874 that take unconstrained types in instantiation
20875
20876 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20877 that have package bodies not otherwise allowed
20878
20879 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20880 ``@code{PROTECTD}''.
20881 Currently these are found only in the @code{STARLET} package spec.
20882
20883 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20884 where the address size is constrained to 32 bits.
20885 @end itemize
20886
20887 @noindent
20888 None of the above changes is visible to users.
20889
20890 @node Bindings
20891 @section Bindings
20892
20893 @noindent
20894 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20895 @itemize @bullet
20896
20897 @item  Command Language Interpreter (CLI interface)
20898
20899 @item  DECtalk Run-Time Library (DTK interface)
20900
20901 @item  Librarian utility routines (LBR interface)
20902
20903 @item  General Purpose Run-Time Library (LIB interface)
20904
20905 @item  Math Run-Time Library (MTH interface)
20906
20907 @item  National Character Set Run-Time Library (NCS interface)
20908
20909 @item  Compiled Code Support Run-Time Library (OTS interface)
20910
20911 @item  Parallel Processing Run-Time Library (PPL interface)
20912
20913 @item  Screen Management Run-Time Library (SMG interface)
20914
20915 @item  Sort Run-Time Library (SOR interface)
20916
20917 @item  String Run-Time Library (STR interface)
20918
20919 @item STARLET System Library
20920 @findex Starlet
20921
20922 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20923
20924 @item  X Windows Toolkit (XT interface)
20925
20926 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20927 @end itemize
20928
20929 @noindent
20930 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20931 directory, on both the Alpha and I64 OpenVMS platforms.
20932
20933 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20934 in the
20935 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20936 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20937 @code{Xt}, and @code{X_Lib}
20938 causing the default X/Motif sharable image libraries to be linked in. This
20939 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20940 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20941
20942 It may be necessary to edit these options files to update or correct the
20943 library names if, for example, the newer X/Motif bindings from
20944 @file{ADA$EXAMPLES}
20945 had been (previous to installing GNAT) copied and renamed to supersede the
20946 default @file{ADA$PREDEFINED} versions.
20947
20948 @menu
20949 * Shared Libraries and Options Files::
20950 * Interfaces to C::
20951 @end menu
20952
20953 @node Shared Libraries and Options Files
20954 @subsection Shared Libraries and Options Files
20955
20956 @noindent
20957 When using the HP Ada
20958 predefined X and Motif bindings, the linking with their sharable images is
20959 done automatically by @command{GNAT LINK}.
20960 When using other X and Motif bindings, you need
20961 to add the corresponding sharable images to the command line for
20962 @code{GNAT LINK}. When linking with shared libraries, or with
20963 @file{.OPT} files, you must
20964 also add them to the command line for @command{GNAT LINK}.
20965
20966 A shared library to be used with GNAT is built in the same way as other
20967 libraries under VMS. The VMS Link command can be used in standard fashion.
20968
20969 @node Interfaces to C
20970 @subsection Interfaces to C
20971
20972 @noindent
20973 HP Ada
20974 provides the following Ada types and operations:
20975
20976 @itemize @bullet
20977 @item C types package (@code{C_TYPES})
20978
20979 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20980
20981 @item Other_types (@code{SHORT_INT})
20982 @end itemize
20983
20984 @noindent
20985 Interfacing to C with GNAT, you can use the above approach
20986 described for HP Ada or the facilities of Annex B of
20987 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20988 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20989 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20990
20991 The @option{-gnatF} qualifier forces default and explicit
20992 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20993 to be uppercased for compatibility with the default behavior
20994 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20995
20996 @node Main Program Definition
20997 @section Main Program Definition
20998
20999 @noindent
21000 The following section discusses differences in the
21001 definition of main programs on HP Ada and GNAT.
21002 On HP Ada, main programs are defined to meet the
21003 following conditions:
21004 @itemize @bullet
21005 @item  Procedure with no formal parameters (returns @code{0} upon
21006 normal completion)
21007
21008 @item  Procedure with no formal parameters (returns @code{42} when
21009 an unhandled exception is raised)
21010
21011 @item  Function with no formal parameters whose returned value
21012 is of a discrete type
21013
21014 @item  Procedure with one @code{out} formal of a discrete type for
21015 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21016
21017 @end itemize
21018
21019 @noindent
21020 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21021 a main function or main procedure returns a discrete
21022 value whose size is less than 64 bits (32 on VAX systems),
21023 the value is zero- or sign-extended as appropriate.
21024 On GNAT, main programs are defined as follows:
21025 @itemize @bullet
21026 @item  Must be a non-generic, parameterless subprogram that
21027 is either a procedure or function returning an Ada
21028 @code{STANDARD.INTEGER} (the predefined type)
21029
21030 @item  Cannot be a generic subprogram or an instantiation of a
21031 generic subprogram
21032 @end itemize
21033
21034 @node Implementation-Defined Attributes
21035 @section Implementation-Defined Attributes
21036
21037 @noindent
21038 GNAT provides all HP Ada implementation-defined
21039 attributes.
21040
21041 @node Compiler and Run-Time Interfacing
21042 @section Compiler and Run-Time Interfacing
21043
21044 @noindent
21045 HP Ada provides the following qualifiers to pass options to the linker
21046 (ACS LINK):
21047 @itemize @bullet
21048 @item  @option{/WAIT} and @option{/SUBMIT}
21049
21050 @item  @option{/COMMAND}
21051
21052 @item  @option{/@r{[}NO@r{]}MAP}
21053
21054 @item  @option{/OUTPUT=@var{file-spec}}
21055
21056 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21057 @end itemize
21058
21059 @noindent
21060 To pass options to the linker, GNAT provides the following
21061 switches:
21062
21063 @itemize @bullet
21064 @item   @option{/EXECUTABLE=@var{exec-name}}
21065
21066 @item   @option{/VERBOSE}
21067
21068 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21069 @end itemize
21070
21071 @noindent
21072 For more information on these switches, see
21073 @ref{Switches for gnatlink}.
21074 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21075 to control optimization. HP Ada also supplies the
21076 following pragmas:
21077 @itemize @bullet
21078 @item  @code{OPTIMIZE}
21079
21080 @item  @code{INLINE}
21081
21082 @item  @code{INLINE_GENERIC}
21083
21084 @item  @code{SUPPRESS_ALL}
21085
21086 @item  @code{PASSIVE}
21087 @end itemize
21088
21089 @noindent
21090 In GNAT, optimization is controlled strictly by command
21091 line parameters, as described in the corresponding section of this guide.
21092 The HP pragmas for control of optimization are
21093 recognized but ignored.
21094
21095 Note that in GNAT, the default is optimization off, whereas in HP Ada
21096 the default is that optimization is turned on.
21097
21098 @node Program Compilation and Library Management
21099 @section Program Compilation and Library Management
21100
21101 @noindent
21102 HP Ada and GNAT provide a comparable set of commands to
21103 build programs. HP Ada also provides a program library,
21104 which is a concept that does not exist on GNAT. Instead,
21105 GNAT provides directories of sources that are compiled as
21106 needed.
21107
21108 The following table summarizes
21109 the HP Ada commands and provides
21110 equivalent GNAT commands. In this table, some GNAT
21111 equivalents reflect the fact that GNAT does not use the
21112 concept of a program library. Instead, it uses a model
21113 in which collections of source and object files are used
21114 in a manner consistent with other languages like C and
21115 Fortran. Therefore, standard system file commands are used
21116 to manipulate these elements. Those GNAT commands are marked with
21117 an asterisk.
21118 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21119
21120 @need 1500
21121 @multitable @columnfractions .35 .65
21122
21123 @item @emph{HP Ada Command}
21124 @tab @emph{GNAT Equivalent / Description}
21125
21126 @item @command{ADA}
21127 @tab @command{GNAT COMPILE}@*
21128 Invokes the compiler to compile one or more Ada source files.
21129
21130 @item @command{ACS ATTACH}@*
21131 @tab [No equivalent]@*
21132 Switches control of terminal from current process running the program
21133 library manager.
21134
21135 @item @command{ACS CHECK}
21136 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21137 Forms the execution closure of one
21138 or more compiled units and checks completeness and currency.
21139
21140 @item @command{ACS COMPILE}
21141 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21142 Forms the execution closure of one or
21143 more specified units, checks completeness and currency,
21144 identifies units that have revised source files, compiles same,
21145 and recompiles units that are or will become obsolete.
21146 Also completes incomplete generic instantiations.
21147
21148 @item @command{ACS COPY FOREIGN}
21149 @tab Copy (*)@*
21150 Copies a foreign object file into the program library as a
21151 library unit body.
21152
21153 @item @command{ACS COPY UNIT}
21154 @tab Copy (*)@*
21155 Copies a compiled unit from one program library to another.
21156
21157 @item @command{ACS CREATE LIBRARY}
21158 @tab Create /directory (*)@*
21159 Creates a program library.
21160
21161 @item @command{ACS CREATE SUBLIBRARY}
21162 @tab Create /directory (*)@*
21163 Creates a program sublibrary.
21164
21165 @item @command{ACS DELETE LIBRARY}
21166 @tab @*
21167 Deletes a program library and its contents.
21168
21169 @item @command{ACS DELETE SUBLIBRARY}
21170 @tab @*
21171 Deletes a program sublibrary and its contents.
21172
21173 @item @command{ACS DELETE UNIT}
21174 @tab Delete file (*)@*
21175 On OpenVMS systems, deletes one or more compiled units from
21176 the current program library.
21177
21178 @item @command{ACS DIRECTORY}
21179 @tab Directory (*)@*
21180 On OpenVMS systems, lists units contained in the current
21181 program library.
21182
21183 @item @command{ACS ENTER FOREIGN}
21184 @tab Copy (*)@*
21185 Allows the import of a foreign body as an Ada library
21186 spec and enters a reference to a pointer.
21187
21188 @item @command{ACS ENTER UNIT}
21189 @tab Copy (*)@*
21190 Enters a reference (pointer) from the current program library to
21191 a unit compiled into another program library.
21192
21193 @item @command{ACS EXIT}
21194 @tab [No equivalent]@*
21195 Exits from the program library manager.
21196
21197 @item @command{ACS EXPORT}
21198 @tab Copy (*)@*
21199 Creates an object file that contains system-specific object code
21200 for one or more units. With GNAT, object files can simply be copied
21201 into the desired directory.
21202
21203 @item @command{ACS EXTRACT SOURCE}
21204 @tab Copy (*)@*
21205 Allows access to the copied source file for each Ada compilation unit
21206
21207 @item @command{ACS HELP}
21208 @tab @command{HELP GNAT}@*
21209 Provides online help.
21210
21211 @item @command{ACS LINK}
21212 @tab @command{GNAT LINK}@*
21213 Links an object file containing Ada units into an executable file.
21214
21215 @item @command{ACS LOAD}
21216 @tab Copy (*)@*
21217 Loads (partially compiles) Ada units into the program library.
21218 Allows loading a program from a collection of files into a library
21219 without knowing the relationship among units.
21220
21221 @item @command{ACS MERGE}
21222 @tab Copy (*)@*
21223 Merges into the current program library, one or more units from
21224 another library where they were modified.
21225
21226 @item @command{ACS RECOMPILE}
21227 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21228 Recompiles from   external or copied source files any obsolete
21229 unit in the closure. Also, completes any incomplete generic
21230 instantiations.
21231
21232 @item @command{ACS REENTER}
21233 @tab @command{GNAT MAKE}@*
21234 Reenters current references to units compiled after last entered
21235 with the @command{ACS ENTER UNIT} command.
21236
21237 @item @command{ACS SET LIBRARY}
21238 @tab Set default (*)@*
21239 Defines a program library to be the compilation context as well
21240 as the target library for compiler output and commands in general.
21241
21242 @item @command{ACS SET PRAGMA}
21243 @tab Edit @file{gnat.adc} (*)@*
21244 Redefines specified  values of the library characteristics
21245 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21246 and @code{Float_Representation}.
21247
21248 @item @command{ACS SET SOURCE}
21249 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21250 Defines the source file search list for the @command{ACS COMPILE} command.
21251
21252 @item @command{ACS SHOW LIBRARY}
21253 @tab Directory (*)@*
21254 Lists information about one or more program libraries.
21255
21256 @item @command{ACS SHOW PROGRAM}
21257 @tab [No equivalent]@*
21258 Lists information about the execution closure of one or
21259 more units in the program library.
21260
21261 @item @command{ACS SHOW SOURCE}
21262 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21263 Shows the source file search used when compiling units.
21264
21265 @item @command{ACS SHOW VERSION}
21266 @tab Compile with @option{VERBOSE} option
21267 Displays the version number of the compiler and program library
21268 manager used.
21269
21270 @item @command{ACS SPAWN}
21271 @tab [No equivalent]@*
21272 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21273 command).
21274
21275 @item @command{ACS VERIFY}
21276 @tab [No equivalent]@*
21277 Performs a series of consistency checks on a program library to
21278 determine whether the library structure and library files are in
21279 valid form.
21280 @end multitable
21281
21282 @noindent
21283
21284 @node Input-Output
21285 @section Input-Output
21286
21287 @noindent
21288 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21289 Management Services (RMS) to perform operations on
21290 external files.
21291
21292 @noindent
21293 HP Ada and GNAT predefine an identical set of input-
21294 output packages. To make the use of the
21295 generic @code{TEXT_IO} operations more convenient, HP Ada
21296 provides predefined library packages that instantiate the
21297 integer and floating-point operations for the predefined
21298 integer and floating-point types as shown in the following table.
21299
21300 @multitable @columnfractions .45 .55
21301 @item @emph{Package Name} @tab Instantiation
21302
21303 @item @code{INTEGER_TEXT_IO}
21304 @tab @code{INTEGER_IO(INTEGER)}
21305
21306 @item @code{SHORT_INTEGER_TEXT_IO}
21307 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21308
21309 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21310 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21311
21312 @item @code{FLOAT_TEXT_IO}
21313 @tab @code{FLOAT_IO(FLOAT)}
21314
21315 @item @code{LONG_FLOAT_TEXT_IO}
21316 @tab @code{FLOAT_IO(LONG_FLOAT)}
21317 @end multitable
21318
21319 @noindent
21320 The HP Ada predefined packages and their operations
21321 are implemented using OpenVMS Alpha files and input-output
21322 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21323 Familiarity with the following is recommended:
21324 @itemize @bullet
21325 @item  RMS file organizations and access methods
21326
21327 @item  OpenVMS file specifications and directories
21328
21329 @item  OpenVMS File Definition Language (FDL)
21330 @end itemize
21331
21332 @noindent
21333 GNAT provides I/O facilities that are completely
21334 compatible with HP Ada. The distribution includes the
21335 standard HP Ada versions of all I/O packages, operating
21336 in a manner compatible with HP Ada. In particular, the
21337 following packages are by default the HP Ada (Ada 83)
21338 versions of these packages rather than the renamings
21339 suggested in Annex J of the Ada Reference Manual:
21340 @itemize @bullet
21341 @item  @code{TEXT_IO}
21342
21343 @item  @code{SEQUENTIAL_IO}
21344
21345 @item  @code{DIRECT_IO}
21346 @end itemize
21347
21348 @noindent
21349 The use of the standard child package syntax (for
21350 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21351 packages.
21352 GNAT provides HP-compatible predefined instantiations
21353 of the @code{TEXT_IO} packages, and also
21354 provides the standard predefined instantiations required
21355 by the @cite{Ada Reference Manual}.
21356
21357 For further information on how GNAT interfaces to the file
21358 system or how I/O is implemented in programs written in
21359 mixed languages, see @ref{Implementation of the Standard I/O,,,
21360 gnat_rm, GNAT Reference Manual}.
21361 This chapter covers the following:
21362 @itemize @bullet
21363 @item  Standard I/O packages
21364
21365 @item  @code{FORM} strings
21366
21367 @item  @code{ADA.DIRECT_IO}
21368
21369 @item  @code{ADA.SEQUENTIAL_IO}
21370
21371 @item  @code{ADA.TEXT_IO}
21372
21373 @item  Stream pointer positioning
21374
21375 @item  Reading and writing non-regular files
21376
21377 @item  @code{GET_IMMEDIATE}
21378
21379 @item  Treating @code{TEXT_IO} files as streams
21380
21381 @item  Shared files
21382
21383 @item  Open modes
21384 @end itemize
21385
21386 @node Implementation Limits
21387 @section Implementation Limits
21388
21389 @noindent
21390 The following table lists implementation limits for HP Ada
21391 and GNAT systems.
21392 @multitable @columnfractions .60 .20 .20
21393 @sp 1
21394 @item  @emph{Compilation Parameter}
21395 @tab   @emph{HP Ada}
21396 @tab   @emph{GNAT}
21397 @sp 1
21398
21399 @item  In a subprogram or entry  declaration, maximum number of
21400 formal parameters that are of an unconstrained record type
21401 @tab   32
21402 @tab   No set limit
21403 @sp 1
21404
21405 @item  Maximum identifier length (number of characters)
21406 @tab   255
21407 @tab   32766
21408 @sp 1
21409
21410 @item  Maximum number of characters in a source line
21411 @tab   255
21412 @tab   32766
21413 @sp 1
21414
21415 @item  Maximum collection size   (number of bytes)
21416 @tab   2**31-1
21417 @tab   2**31-1
21418 @sp 1
21419
21420 @item  Maximum number of discriminants for a record type
21421 @tab   245
21422 @tab   No set limit
21423 @sp 1
21424
21425 @item  Maximum number of formal parameters in an entry or
21426 subprogram declaration
21427 @tab   246
21428 @tab    No set limit
21429 @sp 1
21430
21431 @item  Maximum number of dimensions in an array type
21432 @tab   255
21433 @tab   No set limit
21434 @sp 1
21435
21436 @item  Maximum number of library  units and subunits in a compilation.
21437 @tab   4095
21438 @tab   No set limit
21439 @sp 1
21440
21441 @item  Maximum number of library units and subunits in an execution.
21442 @tab   16383
21443 @tab   No set limit
21444 @sp 1
21445
21446 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21447 or @code{PSECT_OBJECT}
21448 @tab   32757
21449 @tab   No set limit
21450 @sp 1
21451
21452 @item  Maximum number of enumeration literals in an enumeration type
21453 definition
21454 @tab   65535
21455 @tab   No set limit
21456 @sp 1
21457
21458 @item  Maximum number of lines in a source file
21459 @tab   65534
21460 @tab   No set limit
21461 @sp 1
21462
21463 @item  Maximum number of bits in any object
21464 @tab   2**31-1
21465 @tab   2**31-1
21466 @sp 1
21467
21468 @item  Maximum size of the static portion of a stack frame (approximate)
21469 @tab   2**31-1
21470 @tab   2**31-1
21471 @end multitable
21472
21473 @node Tools and Utilities
21474 @section Tools and Utilities
21475
21476 @noindent
21477 The following table lists some of the OpenVMS development tools
21478 available for HP Ada, and the corresponding tools for
21479 use with @value{EDITION} on Alpha and I64 platforms.
21480 Aside from the debugger, all the OpenVMS tools identified are part
21481 of the DECset package.
21482
21483 @iftex
21484 @c Specify table in TeX since Texinfo does a poor job
21485 @tex
21486 \smallskip
21487 \smallskip
21488 \settabs\+Language-Sensitive Editor\quad
21489    &Product with HP Ada\quad
21490    &\cr
21491 \+\it Tool
21492    &\it Product with HP Ada
21493    & \it Product with GNAT Pro\cr
21494 \smallskip
21495 \+Code Management System
21496    &HP CMS
21497    & HP CMS\cr
21498 \smallskip
21499 \+Language-Sensitive Editor
21500    &HP LSE
21501    & emacs or HP LSE (Alpha)\cr
21502 \+
21503    &
21504    & HP LSE (I64)\cr
21505 \smallskip
21506 \+Debugger
21507    &OpenVMS Debug
21508    & gdb (Alpha),\cr
21509 \+
21510    &
21511    & OpenVMS Debug (I64)\cr
21512 \smallskip
21513 \+Source Code Analyzer /
21514    &HP SCA
21515    & GNAT XREF\cr
21516 \+Cross Referencer
21517    &
21518    &\cr
21519 \smallskip
21520 \+Test Manager
21521    &HP Digital Test
21522    & HP DTM\cr
21523 \+
21524    &Manager (DTM)
21525    &\cr
21526 \smallskip
21527 \+Performance and
21528    & HP PCA
21529    & HP PCA\cr
21530 \+Coverage Analyzer
21531    &
21532    &\cr
21533 \smallskip
21534 \+Module Management
21535    & HP MMS
21536    & Not applicable\cr
21537 \+ System
21538    &
21539    &\cr
21540 \smallskip
21541 \smallskip
21542 @end tex
21543 @end iftex
21544
21545 @ifnottex
21546 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21547 @c the TeX version above for the printed version
21548 @flushleft
21549 @c @multitable @columnfractions .3 .4 .4
21550 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21551 @item @i{Tool}
21552 @tab @i{Tool with HP Ada}
21553 @tab @i{Tool with @value{EDITION}}
21554 @item Code Management@*System
21555 @tab HP CMS
21556 @tab HP CMS
21557 @item Language-Sensitive@*Editor
21558 @tab HP LSE
21559 @tab emacs or HP LSE (Alpha)
21560 @item
21561 @tab
21562 @tab HP LSE (I64)
21563 @item Debugger
21564 @tab OpenVMS Debug
21565 @tab gdb (Alpha),
21566 @item
21567 @tab
21568 @tab OpenVMS Debug (I64)
21569 @item Source Code Analyzer /@*Cross Referencer
21570 @tab HP SCA
21571 @tab GNAT XREF
21572 @item Test Manager
21573 @tab HP Digital Test@*Manager (DTM)
21574 @tab HP DTM
21575 @item Performance and@*Coverage Analyzer
21576 @tab HP PCA
21577 @tab HP PCA
21578 @item Module Management@*System
21579 @tab HP MMS
21580 @tab Not applicable
21581 @end multitable
21582 @end flushleft
21583 @end ifnottex
21584
21585 @end ifset
21586
21587 @c **************************************
21588 @node Platform-Specific Information for the Run-Time Libraries
21589 @appendix Platform-Specific Information for the Run-Time Libraries
21590 @cindex Tasking and threads libraries
21591 @cindex Threads libraries and tasking
21592 @cindex Run-time libraries (platform-specific information)
21593
21594 @noindent
21595 The GNAT run-time implementation may vary with respect to both the
21596 underlying threads library and the exception handling scheme.
21597 For threads support, one or more of the following are supplied:
21598 @itemize @bullet
21599 @item @b{native threads library}, a binding to the thread package from
21600 the underlying operating system
21601
21602 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21603 POSIX thread package
21604 @end itemize
21605
21606 @noindent
21607 For exception handling, either or both of two models are supplied:
21608 @itemize @bullet
21609 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21610 Most programs should experience a substantial speed improvement by
21611 being compiled with a ZCX run-time.
21612 This is especially true for
21613 tasking applications or applications with many exception handlers.}
21614 @cindex Zero-Cost Exceptions
21615 @cindex ZCX (Zero-Cost Exceptions)
21616 which uses binder-generated tables that
21617 are interrogated at run time to locate a handler
21618
21619 @item @b{setjmp / longjmp} (``SJLJ''),
21620 @cindex setjmp/longjmp Exception Model
21621 @cindex SJLJ (setjmp/longjmp Exception Model)
21622 which uses dynamically-set data to establish
21623 the set of handlers
21624 @end itemize
21625
21626 @noindent
21627 This appendix summarizes which combinations of threads and exception support
21628 are supplied on various GNAT platforms.
21629 It then shows how to select a particular library either
21630 permanently or temporarily,
21631 explains the properties of (and tradeoffs among) the various threads
21632 libraries, and provides some additional
21633 information about several specific platforms.
21634
21635 @menu
21636 * Summary of Run-Time Configurations::
21637 * Specifying a Run-Time Library::
21638 * Choosing the Scheduling Policy::
21639 * Solaris-Specific Considerations::
21640 * Linux-Specific Considerations::
21641 * AIX-Specific Considerations::
21642 * Irix-Specific Considerations::
21643 * RTX-Specific Considerations::
21644 * HP-UX-Specific Considerations::
21645 @end menu
21646
21647 @node Summary of Run-Time Configurations
21648 @section Summary of Run-Time Configurations
21649
21650 @multitable @columnfractions .30 .70
21651 @item @b{alpha-openvms}
21652 @item @code{@ @ }@i{rts-native (default)}
21653 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21654 @item @code{@ @ @ @ }Exceptions @tab ZCX
21655 @*
21656 @item @b{alpha-tru64}
21657 @item @code{@ @ }@i{rts-native (default)}
21658 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21659 @item @code{@ @ @ @ }Exceptions @tab ZCX
21660 @*
21661 @item @code{@ @ }@i{rts-sjlj}
21662 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21663 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21664 @*
21665 @item @b{ia64-hp_linux}
21666 @item @code{@ @ }@i{rts-native (default)}
21667 @item @code{@ @ @ @ }Tasking    @tab pthread library
21668 @item @code{@ @ @ @ }Exceptions @tab ZCX
21669 @*
21670 @item @b{ia64-hpux}
21671 @item @code{@ @ }@i{rts-native (default)}
21672 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21673 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21674 @*
21675 @item @b{ia64-openvms}
21676 @item @code{@ @ }@i{rts-native (default)}
21677 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21678 @item @code{@ @ @ @ }Exceptions @tab ZCX
21679 @*
21680 @item @b{ia64-sgi_linux}
21681 @item @code{@ @ }@i{rts-native (default)}
21682 @item @code{@ @ @ @ }Tasking    @tab pthread library
21683 @item @code{@ @ @ @ }Exceptions @tab ZCX
21684 @*
21685 @item @b{mips-irix}
21686 @item @code{@ @ }@i{rts-native (default)}
21687 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21688 @item @code{@ @ @ @ }Exceptions @tab ZCX
21689 @*
21690 @item @b{pa-hpux}
21691 @item @code{@ @ }@i{rts-native (default)}
21692 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21693 @item @code{@ @ @ @ }Exceptions @tab ZCX
21694 @*
21695 @item @code{@ @ }@i{rts-sjlj}
21696 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21697 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21698 @*
21699 @item @b{ppc-aix}
21700 @item @code{@ @ }@i{rts-native (default)}
21701 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21702 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21703 @*
21704 @item @b{ppc-darwin}
21705 @item @code{@ @ }@i{rts-native (default)}
21706 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21707 @item @code{@ @ @ @ }Exceptions @tab ZCX
21708 @*
21709 @item @b{sparc-solaris}  @tab
21710 @item @code{@ @ }@i{rts-native (default)}
21711 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21712 @item @code{@ @ @ @ }Exceptions @tab ZCX
21713 @*
21714 @item @code{@ @ }@i{rts-pthread}
21715 @item @code{@ @ @ @ }Tasking    @tab pthread library
21716 @item @code{@ @ @ @ }Exceptions @tab ZCX
21717 @*
21718 @item @code{@ @ }@i{rts-sjlj}
21719 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21721 @*
21722 @item @b{sparc64-solaris}  @tab
21723 @item @code{@ @ }@i{rts-native (default)}
21724 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21725 @item @code{@ @ @ @ }Exceptions @tab ZCX
21726 @*
21727 @item @b{x86-linux}
21728 @item @code{@ @ }@i{rts-native (default)}
21729 @item @code{@ @ @ @ }Tasking    @tab pthread library
21730 @item @code{@ @ @ @ }Exceptions @tab ZCX
21731 @*
21732 @item @code{@ @ }@i{rts-sjlj}
21733 @item @code{@ @ @ @ }Tasking    @tab pthread library
21734 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21735 @*
21736 @item @b{x86-lynx}
21737 @item @code{@ @ }@i{rts-native (default)}
21738 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21739 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21740 @*
21741 @item @b{x86-solaris}
21742 @item @code{@ @ }@i{rts-native (default)}
21743 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21744 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21745 @*
21746 @item @b{x86-windows}
21747 @item @code{@ @ }@i{rts-native (default)}
21748 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21749 @item @code{@ @ @ @ }Exceptions @tab ZCX
21750 @*
21751 @item @code{@ @ }@i{rts-sjlj (default)}
21752 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21753 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21754 @*
21755 @item @b{x86-windows-rtx}
21756 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21757 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21758 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21759 @*
21760 @item @code{@ @ }@i{rts-rtx-w32}
21761 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21762 @item @code{@ @ @ @ }Exceptions @tab ZCX
21763 @*
21764 @item @b{x86_64-linux}
21765 @item @code{@ @ }@i{rts-native (default)}
21766 @item @code{@ @ @ @ }Tasking    @tab pthread library
21767 @item @code{@ @ @ @ }Exceptions @tab ZCX
21768 @*
21769 @item @code{@ @ }@i{rts-sjlj}
21770 @item @code{@ @ @ @ }Tasking    @tab pthread library
21771 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21772 @*
21773 @end multitable
21774
21775 @node Specifying a Run-Time Library
21776 @section Specifying a Run-Time Library
21777
21778 @noindent
21779 The @file{adainclude} subdirectory containing the sources of the GNAT
21780 run-time library, and the @file{adalib} subdirectory containing the
21781 @file{ALI} files and the static and/or shared GNAT library, are located
21782 in the gcc target-dependent area:
21783
21784 @smallexample
21785 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21786 @end smallexample
21787
21788 @noindent
21789 As indicated above, on some platforms several run-time libraries are supplied.
21790 These libraries are installed in the target dependent area and
21791 contain a complete source and binary subdirectory. The detailed description
21792 below explains the differences between the different libraries in terms of
21793 their thread support.
21794
21795 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21796 This default run time is selected by the means of soft links.
21797 For example on x86-linux:
21798
21799 @smallexample
21800 @group
21801  $(target-dir)
21802      |
21803      +--- adainclude----------+
21804      |                        |
21805      +--- adalib-----------+  |
21806      |                     |  |
21807      +--- rts-native       |  |
21808      |    |                |  |
21809      |    +--- adainclude <---+
21810      |    |                |
21811      |    +--- adalib <----+
21812      |
21813      +--- rts-sjlj
21814           |
21815           +--- adainclude
21816           |
21817           +--- adalib
21818 @end group
21819 @end smallexample
21820
21821 @noindent
21822 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21823 these soft links can be modified with the following commands:
21824
21825 @smallexample
21826 $ cd $target
21827 $ rm -f adainclude adalib
21828 $ ln -s rts-sjlj/adainclude adainclude
21829 $ ln -s rts-sjlj/adalib adalib
21830 @end smallexample
21831
21832 @noindent
21833 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21834 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21835 @file{$target/ada_object_path}.
21836
21837 Selecting another run-time library temporarily can be
21838 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21839 @cindex @option{--RTS} option
21840
21841 @node Choosing the Scheduling Policy
21842 @section Choosing the Scheduling Policy
21843
21844 @noindent
21845 When using a POSIX threads implementation, you have a choice of several
21846 scheduling policies: @code{SCHED_FIFO},
21847 @cindex @code{SCHED_FIFO} scheduling policy
21848 @code{SCHED_RR}
21849 @cindex @code{SCHED_RR} scheduling policy
21850 and @code{SCHED_OTHER}.
21851 @cindex @code{SCHED_OTHER} scheduling policy
21852 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21853 or @code{SCHED_RR} requires special (e.g., root) privileges.
21854
21855 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21856 @code{SCHED_FIFO},
21857 @cindex @code{SCHED_FIFO} scheduling policy
21858 you can use one of the following:
21859
21860 @itemize @bullet
21861 @item
21862 @code{pragma Time_Slice (0.0)}
21863 @cindex pragma Time_Slice
21864 @item
21865 the corresponding binder option @option{-T0}
21866 @cindex @option{-T0} option
21867 @item
21868 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21869 @cindex pragma Task_Dispatching_Policy
21870 @end itemize
21871
21872 @noindent
21873 To specify @code{SCHED_RR},
21874 @cindex @code{SCHED_RR} scheduling policy
21875 you should use @code{pragma Time_Slice} with a
21876 value greater than @code{0.0}, or else use the corresponding @option{-T}
21877 binder option.
21878
21879 @node Solaris-Specific Considerations
21880 @section Solaris-Specific Considerations
21881 @cindex Solaris Sparc threads libraries
21882
21883 @noindent
21884 This section addresses some topics related to the various threads libraries
21885 on Sparc Solaris.
21886
21887 @menu
21888 * Solaris Threads Issues::
21889 @end menu
21890
21891 @node Solaris Threads Issues
21892 @subsection Solaris Threads Issues
21893
21894 @noindent
21895 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21896 library based on POSIX threads --- @emph{rts-pthread}.
21897 @cindex rts-pthread threads library
21898 This run-time library has the advantage of being mostly shared across all
21899 POSIX-compliant thread implementations, and it also provides under
21900 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21901 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21902 and @code{PTHREAD_PRIO_PROTECT}
21903 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21904 semantics that can be selected using the predefined pragma
21905 @code{Locking_Policy}
21906 @cindex pragma Locking_Policy (under rts-pthread)
21907 with respectively
21908 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21909 @cindex @code{Inheritance_Locking} (under rts-pthread)
21910 @cindex @code{Ceiling_Locking} (under rts-pthread)
21911
21912 As explained above, the native run-time library is based on the Solaris thread
21913 library (@code{libthread}) and is the default library.
21914
21915 When the Solaris threads library is used (this is the default), programs
21916 compiled with GNAT can automatically take advantage of
21917 and can thus execute on multiple processors.
21918 The user can alternatively specify a processor on which the program should run
21919 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21920 is made by
21921 setting the environment variable @env{GNAT_PROCESSOR}
21922 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21923 to one of the following:
21924
21925 @table @code
21926 @item -2
21927 Use the default configuration (run the program on all
21928 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21929 unset
21930
21931 @item -1
21932 Let the run-time implementation choose one processor and run the program on
21933 that processor
21934
21935 @item 0 .. Last_Proc
21936 Run the program on the specified processor.
21937 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21938 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21939 @end table
21940
21941 @node Linux-Specific Considerations
21942 @section Linux-Specific Considerations
21943 @cindex Linux threads libraries
21944
21945 @noindent
21946 On GNU/Linux without NPTL support (usually system with GNU C Library
21947 older than 2.3), the signal model is not POSIX compliant, which means
21948 that to send a signal to the process, you need to send the signal to all
21949 threads, e.g.@: by using @code{killpg()}.
21950
21951 @node AIX-Specific Considerations
21952 @section AIX-Specific Considerations
21953 @cindex AIX resolver library
21954
21955 @noindent
21956 On AIX, the resolver library initializes some internal structure on
21957 the first call to @code{get*by*} functions, which are used to implement
21958 @code{GNAT.Sockets.Get_Host_By_Name} and
21959 @code{GNAT.Sockets.Get_Host_By_Address}.
21960 If such initialization occurs within an Ada task, and the stack size for
21961 the task is the default size, a stack overflow may occur.
21962
21963 To avoid this overflow, the user should either ensure that the first call
21964 to @code{GNAT.Sockets.Get_Host_By_Name} or
21965 @code{GNAT.Sockets.Get_Host_By_Addrss}
21966 occurs in the environment task, or use @code{pragma Storage_Size} to
21967 specify a sufficiently large size for the stack of the task that contains
21968 this call.
21969
21970 @node Irix-Specific Considerations
21971 @section Irix-Specific Considerations
21972 @cindex Irix libraries
21973
21974 @noindent
21975 The GCC support libraries coming with the Irix compiler have moved to
21976 their canonical place with respect to the general Irix ABI related
21977 conventions. Running applications built with the default shared GNAT
21978 run-time now requires the LD_LIBRARY_PATH environment variable to
21979 include this location. A possible way to achieve this is to issue the
21980 following command line on a bash prompt:
21981
21982 @smallexample
21983 @group
21984 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21985 @end group
21986 @end smallexample
21987
21988 @node RTX-Specific Considerations
21989 @section RTX-Specific Considerations
21990 @cindex RTX libraries
21991
21992 @noindent
21993 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21994 API. Applications can be built to work in two different modes:
21995
21996 @itemize @bullet
21997 @item
21998 Windows executables that run in Ring 3 to utilize memory protection
21999 (@emph{rts-rtx-w32}).
22000
22001 @item
22002 Real-time subsystem (RTSS) executables that run in Ring 0, where
22003 performance can be optimized with RTSS applications taking precedent
22004 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22005 the Microsoft linker to handle RTSS libraries.
22006
22007 @end itemize
22008
22009 @node HP-UX-Specific Considerations
22010 @section HP-UX-Specific Considerations
22011 @cindex HP-UX Scheduling
22012
22013 @noindent
22014 On HP-UX, appropriate privileges are required to change the scheduling
22015 parameters of a task. The calling process must have appropriate
22016 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22017 successfully change the scheduling parameters.
22018
22019 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22020 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22021 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22022
22023 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22024 one of the following:
22025
22026 @itemize @bullet
22027 @item
22028 @code{pragma Time_Slice (0.0)}
22029 @cindex pragma Time_Slice
22030 @item
22031 the corresponding binder option @option{-T0}
22032 @cindex @option{-T0} option
22033 @item
22034 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22035 @cindex pragma Task_Dispatching_Policy
22036 @end itemize
22037
22038 @noindent
22039 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22040 you should use @code{pragma Time_Slice} with a
22041 value greater than @code{0.0}, or use the corresponding @option{-T}
22042 binder option, or set the @code{pragma Task_Dispatching_Policy
22043 (Round_Robin_Within_Priorities)}.
22044
22045 @c *******************************
22046 @node Example of Binder Output File
22047 @appendix Example of Binder Output File
22048
22049 @noindent
22050 This Appendix displays the source code for @command{gnatbind}'s output
22051 file generated for a simple ``Hello World'' program.
22052 Comments have been added for clarification purposes.
22053
22054 @smallexample @c adanocomment
22055 @iftex
22056 @leftskip=0cm
22057 @end iftex
22058 --  The package is called Ada_Main unless this name is actually used
22059 --  as a unit name in the partition, in which case some other unique
22060 --  name is used.
22061
22062 with System;
22063 package ada_main is
22064
22065    Elab_Final_Code : Integer;
22066    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22067
22068    --  The main program saves the parameters (argument count,
22069    --  argument values, environment pointer) in global variables
22070    --  for later access by other units including
22071    --  Ada.Command_Line.
22072
22073    gnat_argc : Integer;
22074    gnat_argv : System.Address;
22075    gnat_envp : System.Address;
22076
22077    --  The actual variables are stored in a library routine. This
22078    --  is useful for some shared library situations, where there
22079    --  are problems if variables are not in the library.
22080
22081    pragma Import (C, gnat_argc);
22082    pragma Import (C, gnat_argv);
22083    pragma Import (C, gnat_envp);
22084
22085    --  The exit status is similarly an external location
22086
22087    gnat_exit_status : Integer;
22088    pragma Import (C, gnat_exit_status);
22089
22090    GNAT_Version : constant String :=
22091                     "GNAT Version: 6.0.0w (20061115)";
22092    pragma Export (C, GNAT_Version, "__gnat_version");
22093
22094    --  This is the generated adafinal routine that performs
22095    --  finalization at the end of execution. In the case where
22096    --  Ada is the main program, this main program makes a call
22097    --  to adafinal at program termination.
22098
22099    procedure adafinal;
22100    pragma Export (C, adafinal, "adafinal");
22101
22102    --  This is the generated adainit routine that performs
22103    --  initialization at the start of execution. In the case
22104    --  where Ada is the main program, this main program makes
22105    --  a call to adainit at program startup.
22106
22107    procedure adainit;
22108    pragma Export (C, adainit, "adainit");
22109
22110    --  This routine is called at the start of execution. It is
22111    --  a dummy routine that is used by the debugger to breakpoint
22112    --  at the start of execution.
22113
22114    procedure Break_Start;
22115    pragma Import (C, Break_Start, "__gnat_break_start");
22116
22117    --  This is the actual generated main program (it would be
22118    --  suppressed if the no main program switch were used). As
22119    --  required by standard system conventions, this program has
22120    --  the external name main.
22121
22122    function main
22123      (argc : Integer;
22124       argv : System.Address;
22125       envp : System.Address)
22126       return Integer;
22127    pragma Export (C, main, "main");
22128
22129    --  The following set of constants give the version
22130    --  identification values for every unit in the bound
22131    --  partition. This identification is computed from all
22132    --  dependent semantic units, and corresponds to the
22133    --  string that would be returned by use of the
22134    --  Body_Version or Version attributes.
22135
22136    type Version_32 is mod 2 ** 32;
22137    u00001 : constant Version_32 := 16#7880BEB3#;
22138    u00002 : constant Version_32 := 16#0D24CBD0#;
22139    u00003 : constant Version_32 := 16#3283DBEB#;
22140    u00004 : constant Version_32 := 16#2359F9ED#;
22141    u00005 : constant Version_32 := 16#664FB847#;
22142    u00006 : constant Version_32 := 16#68E803DF#;
22143    u00007 : constant Version_32 := 16#5572E604#;
22144    u00008 : constant Version_32 := 16#46B173D8#;
22145    u00009 : constant Version_32 := 16#156A40CF#;
22146    u00010 : constant Version_32 := 16#033DABE0#;
22147    u00011 : constant Version_32 := 16#6AB38FEA#;
22148    u00012 : constant Version_32 := 16#22B6217D#;
22149    u00013 : constant Version_32 := 16#68A22947#;
22150    u00014 : constant Version_32 := 16#18CC4A56#;
22151    u00015 : constant Version_32 := 16#08258E1B#;
22152    u00016 : constant Version_32 := 16#367D5222#;
22153    u00017 : constant Version_32 := 16#20C9ECA4#;
22154    u00018 : constant Version_32 := 16#50D32CB6#;
22155    u00019 : constant Version_32 := 16#39A8BB77#;
22156    u00020 : constant Version_32 := 16#5CF8FA2B#;
22157    u00021 : constant Version_32 := 16#2F1EB794#;
22158    u00022 : constant Version_32 := 16#31AB6444#;
22159    u00023 : constant Version_32 := 16#1574B6E9#;
22160    u00024 : constant Version_32 := 16#5109C189#;
22161    u00025 : constant Version_32 := 16#56D770CD#;
22162    u00026 : constant Version_32 := 16#02F9DE3D#;
22163    u00027 : constant Version_32 := 16#08AB6B2C#;
22164    u00028 : constant Version_32 := 16#3FA37670#;
22165    u00029 : constant Version_32 := 16#476457A0#;
22166    u00030 : constant Version_32 := 16#731E1B6E#;
22167    u00031 : constant Version_32 := 16#23C2E789#;
22168    u00032 : constant Version_32 := 16#0F1BD6A1#;
22169    u00033 : constant Version_32 := 16#7C25DE96#;
22170    u00034 : constant Version_32 := 16#39ADFFA2#;
22171    u00035 : constant Version_32 := 16#571DE3E7#;
22172    u00036 : constant Version_32 := 16#5EB646AB#;
22173    u00037 : constant Version_32 := 16#4249379B#;
22174    u00038 : constant Version_32 := 16#0357E00A#;
22175    u00039 : constant Version_32 := 16#3784FB72#;
22176    u00040 : constant Version_32 := 16#2E723019#;
22177    u00041 : constant Version_32 := 16#623358EA#;
22178    u00042 : constant Version_32 := 16#107F9465#;
22179    u00043 : constant Version_32 := 16#6843F68A#;
22180    u00044 : constant Version_32 := 16#63305874#;
22181    u00045 : constant Version_32 := 16#31E56CE1#;
22182    u00046 : constant Version_32 := 16#02917970#;
22183    u00047 : constant Version_32 := 16#6CCBA70E#;
22184    u00048 : constant Version_32 := 16#41CD4204#;
22185    u00049 : constant Version_32 := 16#572E3F58#;
22186    u00050 : constant Version_32 := 16#20729FF5#;
22187    u00051 : constant Version_32 := 16#1D4F93E8#;
22188    u00052 : constant Version_32 := 16#30B2EC3D#;
22189    u00053 : constant Version_32 := 16#34054F96#;
22190    u00054 : constant Version_32 := 16#5A199860#;
22191    u00055 : constant Version_32 := 16#0E7F912B#;
22192    u00056 : constant Version_32 := 16#5760634A#;
22193    u00057 : constant Version_32 := 16#5D851835#;
22194
22195    --  The following Export pragmas export the version numbers
22196    --  with symbolic names ending in B (for body) or S
22197    --  (for spec) so that they can be located in a link. The
22198    --  information provided here is sufficient to track down
22199    --  the exact versions of units used in a given build.
22200
22201    pragma Export (C, u00001, "helloB");
22202    pragma Export (C, u00002, "system__standard_libraryB");
22203    pragma Export (C, u00003, "system__standard_libraryS");
22204    pragma Export (C, u00004, "adaS");
22205    pragma Export (C, u00005, "ada__text_ioB");
22206    pragma Export (C, u00006, "ada__text_ioS");
22207    pragma Export (C, u00007, "ada__exceptionsB");
22208    pragma Export (C, u00008, "ada__exceptionsS");
22209    pragma Export (C, u00009, "gnatS");
22210    pragma Export (C, u00010, "gnat__heap_sort_aB");
22211    pragma Export (C, u00011, "gnat__heap_sort_aS");
22212    pragma Export (C, u00012, "systemS");
22213    pragma Export (C, u00013, "system__exception_tableB");
22214    pragma Export (C, u00014, "system__exception_tableS");
22215    pragma Export (C, u00015, "gnat__htableB");
22216    pragma Export (C, u00016, "gnat__htableS");
22217    pragma Export (C, u00017, "system__exceptionsS");
22218    pragma Export (C, u00018, "system__machine_state_operationsB");
22219    pragma Export (C, u00019, "system__machine_state_operationsS");
22220    pragma Export (C, u00020, "system__machine_codeS");
22221    pragma Export (C, u00021, "system__storage_elementsB");
22222    pragma Export (C, u00022, "system__storage_elementsS");
22223    pragma Export (C, u00023, "system__secondary_stackB");
22224    pragma Export (C, u00024, "system__secondary_stackS");
22225    pragma Export (C, u00025, "system__parametersB");
22226    pragma Export (C, u00026, "system__parametersS");
22227    pragma Export (C, u00027, "system__soft_linksB");
22228    pragma Export (C, u00028, "system__soft_linksS");
22229    pragma Export (C, u00029, "system__stack_checkingB");
22230    pragma Export (C, u00030, "system__stack_checkingS");
22231    pragma Export (C, u00031, "system__tracebackB");
22232    pragma Export (C, u00032, "system__tracebackS");
22233    pragma Export (C, u00033, "ada__streamsS");
22234    pragma Export (C, u00034, "ada__tagsB");
22235    pragma Export (C, u00035, "ada__tagsS");
22236    pragma Export (C, u00036, "system__string_opsB");
22237    pragma Export (C, u00037, "system__string_opsS");
22238    pragma Export (C, u00038, "interfacesS");
22239    pragma Export (C, u00039, "interfaces__c_streamsB");
22240    pragma Export (C, u00040, "interfaces__c_streamsS");
22241    pragma Export (C, u00041, "system__file_ioB");
22242    pragma Export (C, u00042, "system__file_ioS");
22243    pragma Export (C, u00043, "ada__finalizationB");
22244    pragma Export (C, u00044, "ada__finalizationS");
22245    pragma Export (C, u00045, "system__finalization_rootB");
22246    pragma Export (C, u00046, "system__finalization_rootS");
22247    pragma Export (C, u00047, "system__finalization_implementationB");
22248    pragma Export (C, u00048, "system__finalization_implementationS");
22249    pragma Export (C, u00049, "system__string_ops_concat_3B");
22250    pragma Export (C, u00050, "system__string_ops_concat_3S");
22251    pragma Export (C, u00051, "system__stream_attributesB");
22252    pragma Export (C, u00052, "system__stream_attributesS");
22253    pragma Export (C, u00053, "ada__io_exceptionsS");
22254    pragma Export (C, u00054, "system__unsigned_typesS");
22255    pragma Export (C, u00055, "system__file_control_blockS");
22256    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22257    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22258
22259    -- BEGIN ELABORATION ORDER
22260    -- ada (spec)
22261    -- gnat (spec)
22262    -- gnat.heap_sort_a (spec)
22263    -- gnat.heap_sort_a (body)
22264    -- gnat.htable (spec)
22265    -- gnat.htable (body)
22266    -- interfaces (spec)
22267    -- system (spec)
22268    -- system.machine_code (spec)
22269    -- system.parameters (spec)
22270    -- system.parameters (body)
22271    -- interfaces.c_streams (spec)
22272    -- interfaces.c_streams (body)
22273    -- system.standard_library (spec)
22274    -- ada.exceptions (spec)
22275    -- system.exception_table (spec)
22276    -- system.exception_table (body)
22277    -- ada.io_exceptions (spec)
22278    -- system.exceptions (spec)
22279    -- system.storage_elements (spec)
22280    -- system.storage_elements (body)
22281    -- system.machine_state_operations (spec)
22282    -- system.machine_state_operations (body)
22283    -- system.secondary_stack (spec)
22284    -- system.stack_checking (spec)
22285    -- system.soft_links (spec)
22286    -- system.soft_links (body)
22287    -- system.stack_checking (body)
22288    -- system.secondary_stack (body)
22289    -- system.standard_library (body)
22290    -- system.string_ops (spec)
22291    -- system.string_ops (body)
22292    -- ada.tags (spec)
22293    -- ada.tags (body)
22294    -- ada.streams (spec)
22295    -- system.finalization_root (spec)
22296    -- system.finalization_root (body)
22297    -- system.string_ops_concat_3 (spec)
22298    -- system.string_ops_concat_3 (body)
22299    -- system.traceback (spec)
22300    -- system.traceback (body)
22301    -- ada.exceptions (body)
22302    -- system.unsigned_types (spec)
22303    -- system.stream_attributes (spec)
22304    -- system.stream_attributes (body)
22305    -- system.finalization_implementation (spec)
22306    -- system.finalization_implementation (body)
22307    -- ada.finalization (spec)
22308    -- ada.finalization (body)
22309    -- ada.finalization.list_controller (spec)
22310    -- ada.finalization.list_controller (body)
22311    -- system.file_control_block (spec)
22312    -- system.file_io (spec)
22313    -- system.file_io (body)
22314    -- ada.text_io (spec)
22315    -- ada.text_io (body)
22316    -- hello (body)
22317    -- END ELABORATION ORDER
22318
22319 end ada_main;
22320
22321 --  The following source file name pragmas allow the generated file
22322 --  names to be unique for different main programs. They are needed
22323 --  since the package name will always be Ada_Main.
22324
22325 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22326 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22327
22328 --  Generated package body for Ada_Main starts here
22329
22330 package body ada_main is
22331
22332    --  The actual finalization is performed by calling the
22333    --  library routine in System.Standard_Library.Adafinal
22334
22335    procedure Do_Finalize;
22336    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22337
22338    -------------
22339    -- adainit --
22340    -------------
22341
22342 @findex adainit
22343    procedure adainit is
22344
22345       --  These booleans are set to True once the associated unit has
22346       --  been elaborated. It is also used to avoid elaborating the
22347       --  same unit twice.
22348
22349       E040 : Boolean;
22350       pragma Import (Ada, E040, "interfaces__c_streams_E");
22351
22352       E008 : Boolean;
22353       pragma Import (Ada, E008, "ada__exceptions_E");
22354
22355       E014 : Boolean;
22356       pragma Import (Ada, E014, "system__exception_table_E");
22357
22358       E053 : Boolean;
22359       pragma Import (Ada, E053, "ada__io_exceptions_E");
22360
22361       E017 : Boolean;
22362       pragma Import (Ada, E017, "system__exceptions_E");
22363
22364       E024 : Boolean;
22365       pragma Import (Ada, E024, "system__secondary_stack_E");
22366
22367       E030 : Boolean;
22368       pragma Import (Ada, E030, "system__stack_checking_E");
22369
22370       E028 : Boolean;
22371       pragma Import (Ada, E028, "system__soft_links_E");
22372
22373       E035 : Boolean;
22374       pragma Import (Ada, E035, "ada__tags_E");
22375
22376       E033 : Boolean;
22377       pragma Import (Ada, E033, "ada__streams_E");
22378
22379       E046 : Boolean;
22380       pragma Import (Ada, E046, "system__finalization_root_E");
22381
22382       E048 : Boolean;
22383       pragma Import (Ada, E048, "system__finalization_implementation_E");
22384
22385       E044 : Boolean;
22386       pragma Import (Ada, E044, "ada__finalization_E");
22387
22388       E057 : Boolean;
22389       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22390
22391       E055 : Boolean;
22392       pragma Import (Ada, E055, "system__file_control_block_E");
22393
22394       E042 : Boolean;
22395       pragma Import (Ada, E042, "system__file_io_E");
22396
22397       E006 : Boolean;
22398       pragma Import (Ada, E006, "ada__text_io_E");
22399
22400       --  Set_Globals is a library routine that stores away the
22401       --  value of the indicated set of global values in global
22402       --  variables within the library.
22403
22404       procedure Set_Globals
22405         (Main_Priority            : Integer;
22406          Time_Slice_Value         : Integer;
22407          WC_Encoding              : Character;
22408          Locking_Policy           : Character;
22409          Queuing_Policy           : Character;
22410          Task_Dispatching_Policy  : Character;
22411          Adafinal                 : System.Address;
22412          Unreserve_All_Interrupts : Integer;
22413          Exception_Tracebacks     : Integer);
22414 @findex __gnat_set_globals
22415       pragma Import (C, Set_Globals, "__gnat_set_globals");
22416
22417       --  SDP_Table_Build is a library routine used to build the
22418       --  exception tables. See unit Ada.Exceptions in files
22419       --  a-except.ads/adb for full details of how zero cost
22420       --  exception handling works. This procedure, the call to
22421       --  it, and the two following tables are all omitted if the
22422       --  build is in longjmp/setjmp exception mode.
22423
22424 @findex SDP_Table_Build
22425 @findex Zero Cost Exceptions
22426       procedure SDP_Table_Build
22427         (SDP_Addresses   : System.Address;
22428          SDP_Count       : Natural;
22429          Elab_Addresses  : System.Address;
22430          Elab_Addr_Count : Natural);
22431       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22432
22433       --  Table of Unit_Exception_Table addresses. Used for zero
22434       --  cost exception handling to build the top level table.
22435
22436       ST : aliased constant array (1 .. 23) of System.Address := (
22437         Hello'UET_Address,
22438         Ada.Text_Io'UET_Address,
22439         Ada.Exceptions'UET_Address,
22440         Gnat.Heap_Sort_A'UET_Address,
22441         System.Exception_Table'UET_Address,
22442         System.Machine_State_Operations'UET_Address,
22443         System.Secondary_Stack'UET_Address,
22444         System.Parameters'UET_Address,
22445         System.Soft_Links'UET_Address,
22446         System.Stack_Checking'UET_Address,
22447         System.Traceback'UET_Address,
22448         Ada.Streams'UET_Address,
22449         Ada.Tags'UET_Address,
22450         System.String_Ops'UET_Address,
22451         Interfaces.C_Streams'UET_Address,
22452         System.File_Io'UET_Address,
22453         Ada.Finalization'UET_Address,
22454         System.Finalization_Root'UET_Address,
22455         System.Finalization_Implementation'UET_Address,
22456         System.String_Ops_Concat_3'UET_Address,
22457         System.Stream_Attributes'UET_Address,
22458         System.File_Control_Block'UET_Address,
22459         Ada.Finalization.List_Controller'UET_Address);
22460
22461       --  Table of addresses of elaboration routines. Used for
22462       --  zero cost exception handling to make sure these
22463       --  addresses are included in the top level procedure
22464       --  address table.
22465
22466       EA : aliased constant array (1 .. 23) of System.Address := (
22467         adainit'Code_Address,
22468         Do_Finalize'Code_Address,
22469         Ada.Exceptions'Elab_Spec'Address,
22470         System.Exceptions'Elab_Spec'Address,
22471         Interfaces.C_Streams'Elab_Spec'Address,
22472         System.Exception_Table'Elab_Body'Address,
22473         Ada.Io_Exceptions'Elab_Spec'Address,
22474         System.Stack_Checking'Elab_Spec'Address,
22475         System.Soft_Links'Elab_Body'Address,
22476         System.Secondary_Stack'Elab_Body'Address,
22477         Ada.Tags'Elab_Spec'Address,
22478         Ada.Tags'Elab_Body'Address,
22479         Ada.Streams'Elab_Spec'Address,
22480         System.Finalization_Root'Elab_Spec'Address,
22481         Ada.Exceptions'Elab_Body'Address,
22482         System.Finalization_Implementation'Elab_Spec'Address,
22483         System.Finalization_Implementation'Elab_Body'Address,
22484         Ada.Finalization'Elab_Spec'Address,
22485         Ada.Finalization.List_Controller'Elab_Spec'Address,
22486         System.File_Control_Block'Elab_Spec'Address,
22487         System.File_Io'Elab_Body'Address,
22488         Ada.Text_Io'Elab_Spec'Address,
22489         Ada.Text_Io'Elab_Body'Address);
22490
22491    --  Start of processing for adainit
22492
22493    begin
22494
22495       --  Call SDP_Table_Build to build the top level procedure
22496       --  table for zero cost exception handling (omitted in
22497       --  longjmp/setjmp mode).
22498
22499       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22500
22501       --  Call Set_Globals to record various information for
22502       --  this partition.  The values are derived by the binder
22503       --  from information stored in the ali files by the compiler.
22504
22505 @findex __gnat_set_globals
22506       Set_Globals
22507         (Main_Priority            => -1,
22508          --  Priority of main program, -1 if no pragma Priority used
22509
22510          Time_Slice_Value         => -1,
22511          --  Time slice from Time_Slice pragma, -1 if none used
22512
22513          WC_Encoding              => 'b',
22514          --  Wide_Character encoding used, default is brackets
22515
22516          Locking_Policy           => ' ',
22517          --  Locking_Policy used, default of space means not
22518          --  specified, otherwise it is the first character of
22519          --  the policy name.
22520
22521          Queuing_Policy           => ' ',
22522          --  Queuing_Policy used, default of space means not
22523          --  specified, otherwise it is the first character of
22524          --  the policy name.
22525
22526          Task_Dispatching_Policy  => ' ',
22527          --  Task_Dispatching_Policy used, default of space means
22528          --  not specified, otherwise first character of the
22529          --  policy name.
22530
22531          Adafinal                 => System.Null_Address,
22532          --  Address of Adafinal routine, not used anymore
22533
22534          Unreserve_All_Interrupts => 0,
22535          --  Set true if pragma Unreserve_All_Interrupts was used
22536
22537          Exception_Tracebacks     => 0);
22538          --  Indicates if exception tracebacks are enabled
22539
22540       Elab_Final_Code := 1;
22541
22542       --  Now we have the elaboration calls for all units in the partition.
22543       --  The Elab_Spec and Elab_Body attributes generate references to the
22544       --  implicit elaboration procedures generated by the compiler for
22545       --  each unit that requires elaboration.
22546
22547       if not E040 then
22548          Interfaces.C_Streams'Elab_Spec;
22549       end if;
22550       E040 := True;
22551       if not E008 then
22552          Ada.Exceptions'Elab_Spec;
22553       end if;
22554       if not E014 then
22555          System.Exception_Table'Elab_Body;
22556          E014 := True;
22557       end if;
22558       if not E053 then
22559          Ada.Io_Exceptions'Elab_Spec;
22560          E053 := True;
22561       end if;
22562       if not E017 then
22563          System.Exceptions'Elab_Spec;
22564          E017 := True;
22565       end if;
22566       if not E030 then
22567          System.Stack_Checking'Elab_Spec;
22568       end if;
22569       if not E028 then
22570          System.Soft_Links'Elab_Body;
22571          E028 := True;
22572       end if;
22573       E030 := True;
22574       if not E024 then
22575          System.Secondary_Stack'Elab_Body;
22576          E024 := True;
22577       end if;
22578       if not E035 then
22579          Ada.Tags'Elab_Spec;
22580       end if;
22581       if not E035 then
22582          Ada.Tags'Elab_Body;
22583          E035 := True;
22584       end if;
22585       if not E033 then
22586          Ada.Streams'Elab_Spec;
22587          E033 := True;
22588       end if;
22589       if not E046 then
22590          System.Finalization_Root'Elab_Spec;
22591       end if;
22592       E046 := True;
22593       if not E008 then
22594          Ada.Exceptions'Elab_Body;
22595          E008 := True;
22596       end if;
22597       if not E048 then
22598          System.Finalization_Implementation'Elab_Spec;
22599       end if;
22600       if not E048 then
22601          System.Finalization_Implementation'Elab_Body;
22602          E048 := True;
22603       end if;
22604       if not E044 then
22605          Ada.Finalization'Elab_Spec;
22606       end if;
22607       E044 := True;
22608       if not E057 then
22609          Ada.Finalization.List_Controller'Elab_Spec;
22610       end if;
22611       E057 := True;
22612       if not E055 then
22613          System.File_Control_Block'Elab_Spec;
22614          E055 := True;
22615       end if;
22616       if not E042 then
22617          System.File_Io'Elab_Body;
22618          E042 := True;
22619       end if;
22620       if not E006 then
22621          Ada.Text_Io'Elab_Spec;
22622       end if;
22623       if not E006 then
22624          Ada.Text_Io'Elab_Body;
22625          E006 := True;
22626       end if;
22627
22628       Elab_Final_Code := 0;
22629    end adainit;
22630
22631    --------------
22632    -- adafinal --
22633    --------------
22634
22635 @findex adafinal
22636    procedure adafinal is
22637    begin
22638       Do_Finalize;
22639    end adafinal;
22640
22641    ----------
22642    -- main --
22643    ----------
22644
22645    --  main is actually a function, as in the ANSI C standard,
22646    --  defined to return the exit status. The three parameters
22647    --  are the argument count, argument values and environment
22648    --  pointer.
22649
22650 @findex Main Program
22651    function main
22652      (argc : Integer;
22653       argv : System.Address;
22654       envp : System.Address)
22655       return Integer
22656    is
22657       --  The initialize routine performs low level system
22658       --  initialization using a standard library routine which
22659       --  sets up signal handling and performs any other
22660       --  required setup. The routine can be found in file
22661       --  a-init.c.
22662
22663 @findex __gnat_initialize
22664       procedure initialize;
22665       pragma Import (C, initialize, "__gnat_initialize");
22666
22667       --  The finalize routine performs low level system
22668       --  finalization using a standard library routine. The
22669       --  routine is found in file a-final.c and in the standard
22670       --  distribution is a dummy routine that does nothing, so
22671       --  really this is a hook for special user finalization.
22672
22673 @findex __gnat_finalize
22674       procedure finalize;
22675       pragma Import (C, finalize, "__gnat_finalize");
22676
22677       --  We get to the main program of the partition by using
22678       --  pragma Import because if we try to with the unit and
22679       --  call it Ada style, then not only do we waste time
22680       --  recompiling it, but also, we don't really know the right
22681       --  switches (e.g.@: identifier character set) to be used
22682       --  to compile it.
22683
22684       procedure Ada_Main_Program;
22685       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22686
22687    --  Start of processing for main
22688
22689    begin
22690       --  Save global variables
22691
22692       gnat_argc := argc;
22693       gnat_argv := argv;
22694       gnat_envp := envp;
22695
22696       --  Call low level system initialization
22697
22698       Initialize;
22699
22700       --  Call our generated Ada initialization routine
22701
22702       adainit;
22703
22704       --  This is the point at which we want the debugger to get
22705       --  control
22706
22707       Break_Start;
22708
22709       --  Now we call the main program of the partition
22710
22711       Ada_Main_Program;
22712
22713       --  Perform Ada finalization
22714
22715       adafinal;
22716
22717       --  Perform low level system finalization
22718
22719       Finalize;
22720
22721       --  Return the proper exit status
22722       return (gnat_exit_status);
22723    end;
22724
22725 --  This section is entirely comments, so it has no effect on the
22726 --  compilation of the Ada_Main package. It provides the list of
22727 --  object files and linker options, as well as some standard
22728 --  libraries needed for the link. The gnatlink utility parses
22729 --  this b~hello.adb file to read these comment lines to generate
22730 --  the appropriate command line arguments for the call to the
22731 --  system linker. The BEGIN/END lines are used for sentinels for
22732 --  this parsing operation.
22733
22734 --  The exact file names will of course depend on the environment,
22735 --  host/target and location of files on the host system.
22736
22737 @findex Object file list
22738 -- BEGIN Object file/option list
22739    --   ./hello.o
22740    --   -L./
22741    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22742    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22743 -- END Object file/option list
22744
22745 end ada_main;
22746 @end smallexample
22747
22748 @noindent
22749 The Ada code in the above example is exactly what is generated by the
22750 binder. We have added comments to more clearly indicate the function
22751 of each part of the generated @code{Ada_Main} package.
22752
22753 The code is standard Ada in all respects, and can be processed by any
22754 tools that handle Ada. In particular, it is possible to use the debugger
22755 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22756 suppose that for reasons that you do not understand, your program is crashing
22757 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22758 you can place a breakpoint on the call:
22759
22760 @smallexample @c ada
22761 Ada.Text_Io'Elab_Body;
22762 @end smallexample
22763
22764 @noindent
22765 and trace the elaboration routine for this package to find out where
22766 the problem might be (more usually of course you would be debugging
22767 elaboration code in your own application).
22768
22769 @node Elaboration Order Handling in GNAT
22770 @appendix Elaboration Order Handling in GNAT
22771 @cindex Order of elaboration
22772 @cindex Elaboration control
22773
22774 @menu
22775 * Elaboration Code::
22776 * Checking the Elaboration Order::
22777 * Controlling the Elaboration Order::
22778 * Controlling Elaboration in GNAT - Internal Calls::
22779 * Controlling Elaboration in GNAT - External Calls::
22780 * Default Behavior in GNAT - Ensuring Safety::
22781 * Treatment of Pragma Elaborate::
22782 * Elaboration Issues for Library Tasks::
22783 * Mixing Elaboration Models::
22784 * What to Do If the Default Elaboration Behavior Fails::
22785 * Elaboration for Access-to-Subprogram Values::
22786 * Summary of Procedures for Elaboration Control::
22787 * Other Elaboration Order Considerations::
22788 @end menu
22789
22790 @noindent
22791 This chapter describes the handling of elaboration code in Ada and
22792 in GNAT, and discusses how the order of elaboration of program units can
22793 be controlled in GNAT, either automatically or with explicit programming
22794 features.
22795
22796 @node Elaboration Code
22797 @section Elaboration Code
22798
22799 @noindent
22800 Ada provides rather general mechanisms for executing code at elaboration
22801 time, that is to say before the main program starts executing. Such code arises
22802 in three contexts:
22803
22804 @table @asis
22805 @item Initializers for variables.
22806 Variables declared at the library level, in package specs or bodies, can
22807 require initialization that is performed at elaboration time, as in:
22808 @smallexample @c ada
22809 @cartouche
22810 Sqrt_Half : Float := Sqrt (0.5);
22811 @end cartouche
22812 @end smallexample
22813
22814 @item Package initialization code
22815 Code in a @code{BEGIN-END} section at the outer level of a package body is
22816 executed as part of the package body elaboration code.
22817
22818 @item Library level task allocators
22819 Tasks that are declared using task allocators at the library level
22820 start executing immediately and hence can execute at elaboration time.
22821 @end table
22822
22823 @noindent
22824 Subprogram calls are possible in any of these contexts, which means that
22825 any arbitrary part of the program may be executed as part of the elaboration
22826 code. It is even possible to write a program which does all its work at
22827 elaboration time, with a null main program, although stylistically this
22828 would usually be considered an inappropriate way to structure
22829 a program.
22830
22831 An important concern arises in the context of elaboration code:
22832 we have to be sure that it is executed in an appropriate order. What we
22833 have is a series of elaboration code sections, potentially one section
22834 for each unit in the program. It is important that these execute
22835 in the correct order. Correctness here means that, taking the above
22836 example of the declaration of @code{Sqrt_Half},
22837 if some other piece of
22838 elaboration code references @code{Sqrt_Half},
22839 then it must run after the
22840 section of elaboration code that contains the declaration of
22841 @code{Sqrt_Half}.
22842
22843 There would never be any order of elaboration problem if we made a rule
22844 that whenever you @code{with} a unit, you must elaborate both the spec and body
22845 of that unit before elaborating the unit doing the @code{with}'ing:
22846
22847 @smallexample @c ada
22848 @group
22849 @cartouche
22850 with Unit_1;
22851 package Unit_2 is @dots{}
22852 @end cartouche
22853 @end group
22854 @end smallexample
22855
22856 @noindent
22857 would require that both the body and spec of @code{Unit_1} be elaborated
22858 before the spec of @code{Unit_2}. However, a rule like that would be far too
22859 restrictive. In particular, it would make it impossible to have routines
22860 in separate packages that were mutually recursive.
22861
22862 You might think that a clever enough compiler could look at the actual
22863 elaboration code and determine an appropriate correct order of elaboration,
22864 but in the general case, this is not possible. Consider the following
22865 example.
22866
22867 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22868 that references
22869 the variable @code{Sqrt_1}, which is declared in the elaboration code
22870 of the body of @code{Unit_1}:
22871
22872 @smallexample @c ada
22873 @cartouche
22874 Sqrt_1 : Float := Sqrt (0.1);
22875 @end cartouche
22876 @end smallexample
22877
22878 @noindent
22879 The elaboration code of the body of @code{Unit_1} also contains:
22880
22881 @smallexample @c ada
22882 @group
22883 @cartouche
22884 if expression_1 = 1 then
22885    Q := Unit_2.Func_2;
22886 end if;
22887 @end cartouche
22888 @end group
22889 @end smallexample
22890
22891 @noindent
22892 @code{Unit_2} is exactly parallel,
22893 it has a procedure @code{Func_2} that references
22894 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22895 the body @code{Unit_2}:
22896
22897 @smallexample @c ada
22898 @cartouche
22899 Sqrt_2 : Float := Sqrt (0.1);
22900 @end cartouche
22901 @end smallexample
22902
22903 @noindent
22904 The elaboration code of the body of @code{Unit_2} also contains:
22905
22906 @smallexample @c ada
22907 @group
22908 @cartouche
22909 if expression_2 = 2 then
22910    Q := Unit_1.Func_1;
22911 end if;
22912 @end cartouche
22913 @end group
22914 @end smallexample
22915
22916 @noindent
22917 Now the question is, which of the following orders of elaboration is
22918 acceptable:
22919
22920 @smallexample
22921 @group
22922 Spec of Unit_1
22923 Spec of Unit_2
22924 Body of Unit_1
22925 Body of Unit_2
22926 @end group
22927 @end smallexample
22928
22929 @noindent
22930 or
22931
22932 @smallexample
22933 @group
22934 Spec of Unit_2
22935 Spec of Unit_1
22936 Body of Unit_2
22937 Body of Unit_1
22938 @end group
22939 @end smallexample
22940
22941 @noindent
22942 If you carefully analyze the flow here, you will see that you cannot tell
22943 at compile time the answer to this question.
22944 If @code{expression_1} is not equal to 1,
22945 and @code{expression_2} is not equal to 2,
22946 then either order is acceptable, because neither of the function calls is
22947 executed. If both tests evaluate to true, then neither order is acceptable
22948 and in fact there is no correct order.
22949
22950 If one of the two expressions is true, and the other is false, then one
22951 of the above orders is correct, and the other is incorrect. For example,
22952 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22953 then the call to @code{Func_1}
22954 will occur, but not the call to @code{Func_2.}
22955 This means that it is essential
22956 to elaborate the body of @code{Unit_1} before
22957 the body of @code{Unit_2}, so the first
22958 order of elaboration is correct and the second is wrong.
22959
22960 By making @code{expression_1} and @code{expression_2}
22961 depend on input data, or perhaps
22962 the time of day, we can make it impossible for the compiler or binder
22963 to figure out which of these expressions will be true, and hence it
22964 is impossible to guarantee a safe order of elaboration at run time.
22965
22966 @node Checking the Elaboration Order
22967 @section Checking the Elaboration Order
22968
22969 @noindent
22970 In some languages that involve the same kind of elaboration problems,
22971 e.g.@: Java and C++, the programmer is expected to worry about these
22972 ordering problems himself, and it is common to
22973 write a program in which an incorrect elaboration order  gives
22974 surprising results, because it references variables before they
22975 are initialized.
22976 Ada is designed to be a safe language, and a programmer-beware approach is
22977 clearly not sufficient. Consequently, the language provides three lines
22978 of defense:
22979
22980 @table @asis
22981 @item Standard rules
22982 Some standard rules restrict the possible choice of elaboration
22983 order. In particular, if you @code{with} a unit, then its spec is always
22984 elaborated before the unit doing the @code{with}. Similarly, a parent
22985 spec is always elaborated before the child spec, and finally
22986 a spec is always elaborated before its corresponding body.
22987
22988 @item Dynamic elaboration checks
22989 @cindex Elaboration checks
22990 @cindex Checks, elaboration
22991 Dynamic checks are made at run time, so that if some entity is accessed
22992 before it is elaborated (typically  by means of a subprogram call)
22993 then the exception (@code{Program_Error}) is raised.
22994
22995 @item Elaboration control
22996 Facilities are provided for the programmer to specify the desired order
22997 of elaboration.
22998 @end table
22999
23000 Let's look at these facilities in more detail. First, the rules for
23001 dynamic checking. One possible rule would be simply to say that the
23002 exception is raised if you access a variable which has not yet been
23003 elaborated. The trouble with this approach is that it could require
23004 expensive checks on every variable reference. Instead Ada has two
23005 rules which are a little more restrictive, but easier to check, and
23006 easier to state:
23007
23008 @table @asis
23009 @item Restrictions on calls
23010 A subprogram can only be called at elaboration time if its body
23011 has been elaborated. The rules for elaboration given above guarantee
23012 that the spec of the subprogram has been elaborated before the
23013 call, but not the body. If this rule is violated, then the
23014 exception @code{Program_Error} is raised.
23015
23016 @item Restrictions on instantiations
23017 A generic unit can only be instantiated if the body of the generic
23018 unit has been elaborated. Again, the rules for elaboration given above
23019 guarantee that the spec of the generic unit has been elaborated
23020 before the instantiation, but not the body. If this rule is
23021 violated, then the exception @code{Program_Error} is raised.
23022 @end table
23023
23024 @noindent
23025 The idea is that if the body has been elaborated, then any variables
23026 it references must have been elaborated; by checking for the body being
23027 elaborated we guarantee that none of its references causes any
23028 trouble. As we noted above, this is a little too restrictive, because a
23029 subprogram that has no non-local references in its body may in fact be safe
23030 to call. However, it really would be unsafe to rely on this, because
23031 it would mean that the caller was aware of details of the implementation
23032 in the body. This goes against the basic tenets of Ada.
23033
23034 A plausible implementation can be described as follows.
23035 A Boolean variable is associated with each subprogram
23036 and each generic unit. This variable is initialized to False, and is set to
23037 True at the point body is elaborated. Every call or instantiation checks the
23038 variable, and raises @code{Program_Error} if the variable is False.
23039
23040 Note that one might think that it would be good enough to have one Boolean
23041 variable for each package, but that would not deal with cases of trying
23042 to call a body in the same package as the call
23043 that has not been elaborated yet.
23044 Of course a compiler may be able to do enough analysis to optimize away
23045 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23046 does such optimizations, but still the easiest conceptual model is to
23047 think of there being one variable per subprogram.
23048
23049 @node Controlling the Elaboration Order
23050 @section Controlling the Elaboration Order
23051
23052 @noindent
23053 In the previous section we discussed the rules in Ada which ensure
23054 that @code{Program_Error} is raised if an incorrect elaboration order is
23055 chosen. This prevents erroneous executions, but we need mechanisms to
23056 specify a correct execution and avoid the exception altogether.
23057 To achieve this, Ada provides a number of features for controlling
23058 the order of elaboration. We discuss these features in this section.
23059
23060 First, there are several ways of indicating to the compiler that a given
23061 unit has no elaboration problems:
23062
23063 @table @asis
23064 @item packages that do not require a body
23065 A library package that does not require a body does not permit
23066 a body (this rule was introduced in Ada 95).
23067 Thus if we have a such a package, as in:
23068
23069 @smallexample @c ada
23070 @group
23071 @cartouche
23072 package Definitions is
23073    generic
23074       type m is new integer;
23075    package Subp is
23076       type a is array (1 .. 10) of m;
23077       type b is array (1 .. 20) of m;
23078    end Subp;
23079 end Definitions;
23080 @end cartouche
23081 @end group
23082 @end smallexample
23083
23084 @noindent
23085 A package that @code{with}'s @code{Definitions} may safely instantiate
23086 @code{Definitions.Subp} because the compiler can determine that there
23087 definitely is no package body to worry about in this case
23088
23089 @item pragma Pure
23090 @cindex pragma Pure
23091 @findex Pure
23092 Places sufficient restrictions on a unit to guarantee that
23093 no call to any subprogram in the unit can result in an
23094 elaboration problem. This means that the compiler does not need
23095 to worry about the point of elaboration of such units, and in
23096 particular, does not need to check any calls to any subprograms
23097 in this unit.
23098
23099 @item pragma Preelaborate
23100 @findex Preelaborate
23101 @cindex pragma Preelaborate
23102 This pragma places slightly less stringent restrictions on a unit than
23103 does pragma Pure,
23104 but these restrictions are still sufficient to ensure that there
23105 are no elaboration problems with any calls to the unit.
23106
23107 @item pragma Elaborate_Body
23108 @findex Elaborate_Body
23109 @cindex pragma Elaborate_Body
23110 This pragma requires that the body of a unit be elaborated immediately
23111 after its spec. Suppose a unit @code{A} has such a pragma,
23112 and unit @code{B} does
23113 a @code{with} of unit @code{A}. Recall that the standard rules require
23114 the spec of unit @code{A}
23115 to be elaborated before the @code{with}'ing unit; given the pragma in
23116 @code{A}, we also know that the body of @code{A}
23117 will be elaborated before @code{B}, so
23118 that calls to @code{A} are safe and do not need a check.
23119 @end table
23120
23121 @noindent
23122 Note that,
23123 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23124 the use of
23125 @code{Elaborate_Body} does not guarantee that the program is
23126 free of elaboration problems, because it may not be possible
23127 to satisfy the requested elaboration order.
23128 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23129 If a programmer
23130 marks @code{Unit_1} as @code{Elaborate_Body},
23131 and not @code{Unit_2,} then the order of
23132 elaboration will be:
23133
23134 @smallexample
23135 @group
23136 Spec of Unit_2
23137 Spec of Unit_1
23138 Body of Unit_1
23139 Body of Unit_2
23140 @end group
23141 @end smallexample
23142
23143 @noindent
23144 Now that means that the call to @code{Func_1} in @code{Unit_2}
23145 need not be checked,
23146 it must be safe. But the call to @code{Func_2} in
23147 @code{Unit_1} may still fail if
23148 @code{Expression_1} is equal to 1,
23149 and the programmer must still take
23150 responsibility for this not being the case.
23151
23152 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23153 eliminated, except for calls entirely within a body, which are
23154 in any case fully under programmer control. However, using the pragma
23155 everywhere is not always possible.
23156 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23157 we marked both of them as having pragma @code{Elaborate_Body}, then
23158 clearly there would be no possible elaboration order.
23159
23160 The above pragmas allow a server to guarantee safe use by clients, and
23161 clearly this is the preferable approach. Consequently a good rule
23162 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23163 and if this is not possible,
23164 mark them as @code{Elaborate_Body} if possible.
23165 As we have seen, there are situations where neither of these
23166 three pragmas can be used.
23167 So we also provide methods for clients to control the
23168 order of elaboration of the servers on which they depend:
23169
23170 @table @asis
23171 @item pragma Elaborate (unit)
23172 @findex Elaborate
23173 @cindex pragma Elaborate
23174 This pragma is placed in the context clause, after a @code{with} clause,
23175 and it requires that the body of the named unit be elaborated before
23176 the unit in which the pragma occurs. The idea is to use this pragma
23177 if the current unit calls at elaboration time, directly or indirectly,
23178 some subprogram in the named unit.
23179
23180 @item pragma Elaborate_All (unit)
23181 @findex Elaborate_All
23182 @cindex pragma Elaborate_All
23183 This is a stronger version of the Elaborate pragma. Consider the
23184 following example:
23185
23186 @smallexample
23187 Unit A @code{with}'s unit B and calls B.Func in elab code
23188 Unit B @code{with}'s unit C, and B.Func calls C.Func
23189 @end smallexample
23190
23191 @noindent
23192 Now if we put a pragma @code{Elaborate (B)}
23193 in unit @code{A}, this ensures that the
23194 body of @code{B} is elaborated before the call, but not the
23195 body of @code{C}, so
23196 the call to @code{C.Func} could still cause @code{Program_Error} to
23197 be raised.
23198
23199 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23200 not only that the body of the named unit be elaborated before the
23201 unit doing the @code{with}, but also the bodies of all units that the
23202 named unit uses, following @code{with} links transitively. For example,
23203 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23204 then it requires
23205 not only that the body of @code{B} be elaborated before @code{A},
23206 but also the
23207 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23208 @end table
23209
23210 @noindent
23211 We are now in a position to give a usage rule in Ada for avoiding
23212 elaboration problems, at least if dynamic dispatching and access to
23213 subprogram values are not used. We will handle these cases separately
23214 later.
23215
23216 The rule is simple. If a unit has elaboration code that can directly or
23217 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23218 a generic package in a @code{with}'ed unit,
23219 then if the @code{with}'ed unit does not have
23220 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23221 a pragma @code{Elaborate_All}
23222 for the @code{with}'ed unit. By following this rule a client is
23223 assured that calls can be made without risk of an exception.
23224
23225 For generic subprogram instantiations, the rule can be relaxed to
23226 require only a pragma @code{Elaborate} since elaborating the body
23227 of a subprogram cannot cause any transitive elaboration (we are
23228 not calling the subprogram in this case, just elaborating its
23229 declaration).
23230
23231 If this rule is not followed, then a program may be in one of four
23232 states:
23233
23234 @table @asis
23235 @item No order exists
23236 No order of elaboration exists which follows the rules, taking into
23237 account any @code{Elaborate}, @code{Elaborate_All},
23238 or @code{Elaborate_Body} pragmas. In
23239 this case, an Ada compiler must diagnose the situation at bind
23240 time, and refuse to build an executable program.
23241
23242 @item One or more orders exist, all incorrect
23243 One or more acceptable elaboration orders exist, and all of them
23244 generate an elaboration order problem. In this case, the binder
23245 can build an executable program, but @code{Program_Error} will be raised
23246 when the program is run.
23247
23248 @item Several orders exist, some right, some incorrect
23249 One or more acceptable elaboration orders exists, and some of them
23250 work, and some do not. The programmer has not controlled
23251 the order of elaboration, so the binder may or may not pick one of
23252 the correct orders, and the program may or may not raise an
23253 exception when it is run. This is the worst case, because it means
23254 that the program may fail when moved to another compiler, or even
23255 another version of the same compiler.
23256
23257 @item One or more orders exists, all correct
23258 One ore more acceptable elaboration orders exist, and all of them
23259 work. In this case the program runs successfully. This state of
23260 affairs can be guaranteed by following the rule we gave above, but
23261 may be true even if the rule is not followed.
23262 @end table
23263
23264 @noindent
23265 Note that one additional advantage of following our rules on the use
23266 of @code{Elaborate} and @code{Elaborate_All}
23267 is that the program continues to stay in the ideal (all orders OK) state
23268 even if maintenance
23269 changes some bodies of some units. Conversely, if a program that does
23270 not follow this rule happens to be safe at some point, this state of affairs
23271 may deteriorate silently as a result of maintenance changes.
23272
23273 You may have noticed that the above discussion did not mention
23274 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23275 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23276 code in the body makes calls to some other unit, so it is still necessary
23277 to use @code{Elaborate_All} on such units.
23278
23279 @node Controlling Elaboration in GNAT - Internal Calls
23280 @section Controlling Elaboration in GNAT - Internal Calls
23281
23282 @noindent
23283 In the case of internal calls, i.e., calls within a single package, the
23284 programmer has full control over the order of elaboration, and it is up
23285 to the programmer to elaborate declarations in an appropriate order. For
23286 example writing:
23287
23288 @smallexample @c ada
23289 @group
23290 @cartouche
23291 function One return Float;
23292
23293 Q : Float := One;
23294
23295 function One return Float is
23296 begin
23297      return 1.0;
23298 end One;
23299 @end cartouche
23300 @end group
23301 @end smallexample
23302
23303 @noindent
23304 will obviously raise @code{Program_Error} at run time, because function
23305 One will be called before its body is elaborated. In this case GNAT will
23306 generate a warning that the call will raise @code{Program_Error}:
23307
23308 @smallexample
23309 @group
23310 @cartouche
23311  1. procedure y is
23312  2.    function One return Float;
23313  3.
23314  4.    Q : Float := One;
23315                     |
23316     >>> warning: cannot call "One" before body is elaborated
23317     >>> warning: Program_Error will be raised at run time
23318
23319  5.
23320  6.    function One return Float is
23321  7.    begin
23322  8.         return 1.0;
23323  9.    end One;
23324 10.
23325 11. begin
23326 12.    null;
23327 13. end;
23328 @end cartouche
23329 @end group
23330 @end smallexample
23331
23332 @noindent
23333 Note that in this particular case, it is likely that the call is safe, because
23334 the function @code{One} does not access any global variables.
23335 Nevertheless in Ada, we do not want the validity of the check to depend on
23336 the contents of the body (think about the separate compilation case), so this
23337 is still wrong, as we discussed in the previous sections.
23338
23339 The error is easily corrected by rearranging the declarations so that the
23340 body of @code{One} appears before the declaration containing the call
23341 (note that in Ada 95 and Ada 2005,
23342 declarations can appear in any order, so there is no restriction that
23343 would prevent this reordering, and if we write:
23344
23345 @smallexample @c ada
23346 @group
23347 @cartouche
23348 function One return Float;
23349
23350 function One return Float is
23351 begin
23352      return 1.0;
23353 end One;
23354
23355 Q : Float := One;
23356 @end cartouche
23357 @end group
23358 @end smallexample
23359
23360 @noindent
23361 then all is well, no warning is generated, and no
23362 @code{Program_Error} exception
23363 will be raised.
23364 Things are more complicated when a chain of subprograms is executed:
23365
23366 @smallexample @c ada
23367 @group
23368 @cartouche
23369 function A return Integer;
23370 function B return Integer;
23371 function C return Integer;
23372
23373 function B return Integer is begin return A; end;
23374 function C return Integer is begin return B; end;
23375
23376 X : Integer := C;
23377
23378 function A return Integer is begin return 1; end;
23379 @end cartouche
23380 @end group
23381 @end smallexample
23382
23383 @noindent
23384 Now the call to @code{C}
23385 at elaboration time in the declaration of @code{X} is correct, because
23386 the body of @code{C} is already elaborated,
23387 and the call to @code{B} within the body of
23388 @code{C} is correct, but the call
23389 to @code{A} within the body of @code{B} is incorrect, because the body
23390 of @code{A} has not been elaborated, so @code{Program_Error}
23391 will be raised on the call to @code{A}.
23392 In this case GNAT will generate a
23393 warning that @code{Program_Error} may be
23394 raised at the point of the call. Let's look at the warning:
23395
23396 @smallexample
23397 @group
23398 @cartouche
23399  1. procedure x is
23400  2.    function A return Integer;
23401  3.    function B return Integer;
23402  4.    function C return Integer;
23403  5.
23404  6.    function B return Integer is begin return A; end;
23405                                                     |
23406     >>> warning: call to "A" before body is elaborated may
23407                  raise Program_Error
23408     >>> warning: "B" called at line 7
23409     >>> warning: "C" called at line 9
23410
23411  7.    function C return Integer is begin return B; end;
23412  8.
23413  9.    X : Integer := C;
23414 10.
23415 11.    function A return Integer is begin return 1; end;
23416 12.
23417 13. begin
23418 14.    null;
23419 15. end;
23420 @end cartouche
23421 @end group
23422 @end smallexample
23423
23424 @noindent
23425 Note that the message here says ``may raise'', instead of the direct case,
23426 where the message says ``will be raised''. That's because whether
23427 @code{A} is
23428 actually called depends in general on run-time flow of control.
23429 For example, if the body of @code{B} said
23430
23431 @smallexample @c ada
23432 @group
23433 @cartouche
23434 function B return Integer is
23435 begin
23436    if some-condition-depending-on-input-data then
23437       return A;
23438    else
23439       return 1;
23440    end if;
23441 end B;
23442 @end cartouche
23443 @end group
23444 @end smallexample
23445
23446 @noindent
23447 then we could not know until run time whether the incorrect call to A would
23448 actually occur, so @code{Program_Error} might
23449 or might not be raised. It is possible for a compiler to
23450 do a better job of analyzing bodies, to
23451 determine whether or not @code{Program_Error}
23452 might be raised, but it certainly
23453 couldn't do a perfect job (that would require solving the halting problem
23454 and is provably impossible), and because this is a warning anyway, it does
23455 not seem worth the effort to do the analysis. Cases in which it
23456 would be relevant are rare.
23457
23458 In practice, warnings of either of the forms given
23459 above will usually correspond to
23460 real errors, and should be examined carefully and eliminated.
23461 In the rare case where a warning is bogus, it can be suppressed by any of
23462 the following methods:
23463
23464 @itemize @bullet
23465 @item
23466 Compile with the @option{-gnatws} switch set
23467
23468 @item
23469 Suppress @code{Elaboration_Check} for the called subprogram
23470
23471 @item
23472 Use pragma @code{Warnings_Off} to turn warnings off for the call
23473 @end itemize
23474
23475 @noindent
23476 For the internal elaboration check case,
23477 GNAT by default generates the
23478 necessary run-time checks to ensure
23479 that @code{Program_Error} is raised if any
23480 call fails an elaboration check. Of course this can only happen if a
23481 warning has been issued as described above. The use of pragma
23482 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23483 some of these checks, meaning that it may be possible (but is not
23484 guaranteed) for a program to be able to call a subprogram whose body
23485 is not yet elaborated, without raising a @code{Program_Error} exception.
23486
23487 @node Controlling Elaboration in GNAT - External Calls
23488 @section Controlling Elaboration in GNAT - External Calls
23489
23490 @noindent
23491 The previous section discussed the case in which the execution of a
23492 particular thread of elaboration code occurred entirely within a
23493 single unit. This is the easy case to handle, because a programmer
23494 has direct and total control over the order of elaboration, and
23495 furthermore, checks need only be generated in cases which are rare
23496 and which the compiler can easily detect.
23497 The situation is more complex when separate compilation is taken into account.
23498 Consider the following:
23499
23500 @smallexample @c ada
23501 @cartouche
23502 @group
23503 package Math is
23504    function Sqrt (Arg : Float) return Float;
23505 end Math;
23506
23507 package body Math is
23508    function Sqrt (Arg : Float) return Float is
23509    begin
23510          @dots{}
23511    end Sqrt;
23512 end Math;
23513 @end group
23514 @group
23515 with Math;
23516 package Stuff is
23517    X : Float := Math.Sqrt (0.5);
23518 end Stuff;
23519
23520 with Stuff;
23521 procedure Main is
23522 begin
23523    @dots{}
23524 end Main;
23525 @end group
23526 @end cartouche
23527 @end smallexample
23528
23529 @noindent
23530 where @code{Main} is the main program. When this program is executed, the
23531 elaboration code must first be executed, and one of the jobs of the
23532 binder is to determine the order in which the units of a program are
23533 to be elaborated. In this case we have four units: the spec and body
23534 of @code{Math},
23535 the spec of @code{Stuff} and the body of @code{Main}).
23536 In what order should the four separate sections of elaboration code
23537 be executed?
23538
23539 There are some restrictions in the order of elaboration that the binder
23540 can choose. In particular, if unit U has a @code{with}
23541 for a package @code{X}, then you
23542 are assured that the spec of @code{X}
23543 is elaborated before U , but you are
23544 not assured that the body of @code{X}
23545 is elaborated before U.
23546 This means that in the above case, the binder is allowed to choose the
23547 order:
23548
23549 @smallexample
23550 spec of Math
23551 spec of Stuff
23552 body of Math
23553 body of Main
23554 @end smallexample
23555
23556 @noindent
23557 but that's not good, because now the call to @code{Math.Sqrt}
23558 that happens during
23559 the elaboration of the @code{Stuff}
23560 spec happens before the body of @code{Math.Sqrt} is
23561 elaborated, and hence causes @code{Program_Error} exception to be raised.
23562 At first glance, one might say that the binder is misbehaving, because
23563 obviously you want to elaborate the body of something you @code{with}
23564 first, but
23565 that is not a general rule that can be followed in all cases. Consider
23566
23567 @smallexample @c ada
23568 @group
23569 @cartouche
23570 package X is @dots{}
23571
23572 package Y is @dots{}
23573
23574 with X;
23575 package body Y is @dots{}
23576
23577 with Y;
23578 package body X is @dots{}
23579 @end cartouche
23580 @end group
23581 @end smallexample
23582
23583 @noindent
23584 This is a common arrangement, and, apart from the order of elaboration
23585 problems that might arise in connection with elaboration code, this works fine.
23586 A rule that says that you must first elaborate the body of anything you
23587 @code{with} cannot work in this case:
23588 the body of @code{X} @code{with}'s @code{Y},
23589 which means you would have to
23590 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23591 which means
23592 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23593 loop that cannot be broken.
23594
23595 It is true that the binder can in many cases guess an order of elaboration
23596 that is unlikely to cause a @code{Program_Error}
23597 exception to be raised, and it tries to do so (in the
23598 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23599 by default
23600 elaborate the body of @code{Math} right after its spec, so all will be well).
23601
23602 However, a program that blindly relies on the binder to be helpful can
23603 get into trouble, as we discussed in the previous sections, so
23604 GNAT
23605 provides a number of facilities for assisting the programmer in
23606 developing programs that are robust with respect to elaboration order.
23607
23608 @node Default Behavior in GNAT - Ensuring Safety
23609 @section Default Behavior in GNAT - Ensuring Safety
23610
23611 @noindent
23612 The default behavior in GNAT ensures elaboration safety. In its
23613 default mode GNAT implements the
23614 rule we previously described as the right approach. Let's restate it:
23615
23616 @itemize
23617 @item
23618 @emph{If a unit has elaboration code that can directly or indirectly make a
23619 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23620 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23621 does not have pragma @code{Pure} or
23622 @code{Preelaborate}, then the client should have an
23623 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23624
23625 @emph{In the case of instantiating a generic subprogram, it is always
23626 sufficient to have only an @code{Elaborate} pragma for the
23627 @code{with}'ed unit.}
23628 @end itemize
23629
23630 @noindent
23631 By following this rule a client is assured that calls and instantiations
23632 can be made without risk of an exception.
23633
23634 In this mode GNAT traces all calls that are potentially made from
23635 elaboration code, and puts in any missing implicit @code{Elaborate}
23636 and @code{Elaborate_All} pragmas.
23637 The advantage of this approach is that no elaboration problems
23638 are possible if the binder can find an elaboration order that is
23639 consistent with these implicit @code{Elaborate} and
23640 @code{Elaborate_All} pragmas. The
23641 disadvantage of this approach is that no such order may exist.
23642
23643 If the binder does not generate any diagnostics, then it means that it has
23644 found an elaboration order that is guaranteed to be safe. However, the binder
23645 may still be relying on implicitly generated @code{Elaborate} and
23646 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23647 guaranteed.
23648
23649 If it is important to guarantee portability, then the compilations should
23650 use the
23651 @option{-gnatwl}
23652 (warn on elaboration problems) switch. This will cause warning messages
23653 to be generated indicating the missing @code{Elaborate} and
23654 @code{Elaborate_All} pragmas.
23655 Consider the following source program:
23656
23657 @smallexample @c ada
23658 @group
23659 @cartouche
23660 with k;
23661 package j is
23662   m : integer := k.r;
23663 end;
23664 @end cartouche
23665 @end group
23666 @end smallexample
23667
23668 @noindent
23669 where it is clear that there
23670 should be a pragma @code{Elaborate_All}
23671 for unit @code{k}. An implicit pragma will be generated, and it is
23672 likely that the binder will be able to honor it. However, if you want
23673 to port this program to some other Ada compiler than GNAT.
23674 it is safer to include the pragma explicitly in the source. If this
23675 unit is compiled with the
23676 @option{-gnatwl}
23677 switch, then the compiler outputs a warning:
23678
23679 @smallexample
23680 @group
23681 @cartouche
23682 1. with k;
23683 2. package j is
23684 3.   m : integer := k.r;
23685                      |
23686    >>> warning: call to "r" may raise Program_Error
23687    >>> warning: missing pragma Elaborate_All for "k"
23688
23689 4. end;
23690 @end cartouche
23691 @end group
23692 @end smallexample
23693
23694 @noindent
23695 and these warnings can be used as a guide for supplying manually
23696 the missing pragmas. It is usually a bad idea to use this warning
23697 option during development. That's because it will warn you when
23698 you need to put in a pragma, but cannot warn you when it is time
23699 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23700 unnecessary dependencies and even false circularities.
23701
23702 This default mode is more restrictive than the Ada Reference
23703 Manual, and it is possible to construct programs which will compile
23704 using the dynamic model described there, but will run into a
23705 circularity using the safer static model we have described.
23706
23707 Of course any Ada compiler must be able to operate in a mode
23708 consistent with the requirements of the Ada Reference Manual,
23709 and in particular must have the capability of implementing the
23710 standard dynamic model of elaboration with run-time checks.
23711
23712 In GNAT, this standard mode can be achieved either by the use of
23713 the @option{-gnatE} switch on the compiler (@command{gcc} or
23714 @command{gnatmake}) command, or by the use of the configuration pragma:
23715
23716 @smallexample @c ada
23717 pragma Elaboration_Checks (DYNAMIC);
23718 @end smallexample
23719
23720 @noindent
23721 Either approach will cause the unit affected to be compiled using the
23722 standard dynamic run-time elaboration checks described in the Ada
23723 Reference Manual. The static model is generally preferable, since it
23724 is clearly safer to rely on compile and link time checks rather than
23725 run-time checks. However, in the case of legacy code, it may be
23726 difficult to meet the requirements of the static model. This
23727 issue is further discussed in
23728 @ref{What to Do If the Default Elaboration Behavior Fails}.
23729
23730 Note that the static model provides a strict subset of the allowed
23731 behavior and programs of the Ada Reference Manual, so if you do
23732 adhere to the static model and no circularities exist,
23733 then you are assured that your program will
23734 work using the dynamic model, providing that you remove any
23735 pragma Elaborate statements from the source.
23736
23737 @node Treatment of Pragma Elaborate
23738 @section Treatment of Pragma Elaborate
23739 @cindex Pragma Elaborate
23740
23741 @noindent
23742 The use of @code{pragma Elaborate}
23743 should generally be avoided in Ada 95 and Ada 2005 programs,
23744 since there is no guarantee that transitive calls
23745 will be properly handled. Indeed at one point, this pragma was placed
23746 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23747
23748 Now that's a bit restrictive. In practice, the case in which
23749 @code{pragma Elaborate} is useful is when the caller knows that there
23750 are no transitive calls, or that the called unit contains all necessary
23751 transitive @code{pragma Elaborate} statements, and legacy code often
23752 contains such uses.
23753
23754 Strictly speaking the static mode in GNAT should ignore such pragmas,
23755 since there is no assurance at compile time that the necessary safety
23756 conditions are met. In practice, this would cause GNAT to be incompatible
23757 with correctly written Ada 83 code that had all necessary
23758 @code{pragma Elaborate} statements in place. Consequently, we made the
23759 decision that GNAT in its default mode will believe that if it encounters
23760 a @code{pragma Elaborate} then the programmer knows what they are doing,
23761 and it will trust that no elaboration errors can occur.
23762
23763 The result of this decision is two-fold. First to be safe using the
23764 static mode, you should remove all @code{pragma Elaborate} statements.
23765 Second, when fixing circularities in existing code, you can selectively
23766 use @code{pragma Elaborate} statements to convince the static mode of
23767 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23768 statement.
23769
23770 When using the static mode with @option{-gnatwl}, any use of
23771 @code{pragma Elaborate} will generate a warning about possible
23772 problems.
23773
23774 @node Elaboration Issues for Library Tasks
23775 @section Elaboration Issues for Library Tasks
23776 @cindex Library tasks, elaboration issues
23777 @cindex Elaboration of library tasks
23778
23779 @noindent
23780 In this section we examine special elaboration issues that arise for
23781 programs that declare library level tasks.
23782
23783 Generally the model of execution of an Ada program is that all units are
23784 elaborated, and then execution of the program starts. However, the
23785 declaration of library tasks definitely does not fit this model. The
23786 reason for this is that library tasks start as soon as they are declared
23787 (more precisely, as soon as the statement part of the enclosing package
23788 body is reached), that is to say before elaboration
23789 of the program is complete. This means that if such a task calls a
23790 subprogram, or an entry in another task, the callee may or may not be
23791 elaborated yet, and in the standard
23792 Reference Manual model of dynamic elaboration checks, you can even
23793 get timing dependent Program_Error exceptions, since there can be
23794 a race between the elaboration code and the task code.
23795
23796 The static model of elaboration in GNAT seeks to avoid all such
23797 dynamic behavior, by being conservative, and the conservative
23798 approach in this particular case is to assume that all the code
23799 in a task body is potentially executed at elaboration time if
23800 a task is declared at the library level.
23801
23802 This can definitely result in unexpected circularities. Consider
23803 the following example
23804
23805 @smallexample @c ada
23806 package Decls is
23807   task Lib_Task is
23808      entry Start;
23809   end Lib_Task;
23810
23811   type My_Int is new Integer;
23812
23813   function Ident (M : My_Int) return My_Int;
23814 end Decls;
23815
23816 with Utils;
23817 package body Decls is
23818   task body Lib_Task is
23819   begin
23820      accept Start;
23821      Utils.Put_Val (2);
23822   end Lib_Task;
23823
23824   function Ident (M : My_Int) return My_Int is
23825   begin
23826      return M;
23827   end Ident;
23828 end Decls;
23829
23830 with Decls;
23831 package Utils is
23832   procedure Put_Val (Arg : Decls.My_Int);
23833 end Utils;
23834
23835 with Text_IO;
23836 package body Utils is
23837   procedure Put_Val (Arg : Decls.My_Int) is
23838   begin
23839      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23840   end Put_Val;
23841 end Utils;
23842
23843 with Decls;
23844 procedure Main is
23845 begin
23846    Decls.Lib_Task.Start;
23847 end;
23848 @end smallexample
23849
23850 @noindent
23851 If the above example is compiled in the default static elaboration
23852 mode, then a circularity occurs. The circularity comes from the call
23853 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23854 this call occurs in elaboration code, we need an implicit pragma
23855 @code{Elaborate_All} for @code{Utils}. This means that not only must
23856 the spec and body of @code{Utils} be elaborated before the body
23857 of @code{Decls}, but also the spec and body of any unit that is
23858 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23859 the body of @code{Decls}. This is the transitive implication of
23860 pragma @code{Elaborate_All} and it makes sense, because in general
23861 the body of @code{Put_Val} might have a call to something in a
23862 @code{with'ed} unit.
23863
23864 In this case, the body of Utils (actually its spec) @code{with's}
23865 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23866 must be elaborated before itself, in case there is a call from the
23867 body of @code{Utils}.
23868
23869 Here is the exact chain of events we are worrying about:
23870
23871 @enumerate
23872 @item
23873 In the body of @code{Decls} a call is made from within the body of a library
23874 task to a subprogram in the package @code{Utils}. Since this call may
23875 occur at elaboration time (given that the task is activated at elaboration
23876 time), we have to assume the worst, i.e., that the
23877 call does happen at elaboration time.
23878
23879 @item
23880 This means that the body and spec of @code{Util} must be elaborated before
23881 the body of @code{Decls} so that this call does not cause an access before
23882 elaboration.
23883
23884 @item
23885 Within the body of @code{Util}, specifically within the body of
23886 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23887 by this package.
23888
23889 @item
23890 One such @code{with}'ed package is package @code{Decls}, so there
23891 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23892 In fact there is such a call in this example, but we would have to
23893 assume that there was such a call even if it were not there, since
23894 we are not supposed to write the body of @code{Decls} knowing what
23895 is in the body of @code{Utils}; certainly in the case of the
23896 static elaboration model, the compiler does not know what is in
23897 other bodies and must assume the worst.
23898
23899 @item
23900 This means that the spec and body of @code{Decls} must also be
23901 elaborated before we elaborate the unit containing the call, but
23902 that unit is @code{Decls}! This means that the body of @code{Decls}
23903 must be elaborated before itself, and that's a circularity.
23904 @end enumerate
23905
23906 @noindent
23907 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23908 the body of @code{Decls} you will get a true Ada Reference Manual
23909 circularity that makes the program illegal.
23910
23911 In practice, we have found that problems with the static model of
23912 elaboration in existing code often arise from library tasks, so
23913 we must address this particular situation.
23914
23915 Note that if we compile and run the program above, using the dynamic model of
23916 elaboration (that is to say use the @option{-gnatE} switch),
23917 then it compiles, binds,
23918 links, and runs, printing the expected result of 2. Therefore in some sense
23919 the circularity here is only apparent, and we need to capture
23920 the properties of this program that  distinguish it from other library-level
23921 tasks that have real elaboration problems.
23922
23923 We have four possible answers to this question:
23924
23925 @itemize @bullet
23926
23927 @item
23928 Use the dynamic model of elaboration.
23929
23930 If we use the @option{-gnatE} switch, then as noted above, the program works.
23931 Why is this? If we examine the task body, it is apparent that the task cannot
23932 proceed past the
23933 @code{accept} statement until after elaboration has been completed, because
23934 the corresponding entry call comes from the main program, not earlier.
23935 This is why the dynamic model works here. But that's really giving
23936 up on a precise analysis, and we prefer to take this approach only if we cannot
23937 solve the
23938 problem in any other manner. So let us examine two ways to reorganize
23939 the program to avoid the potential elaboration problem.
23940
23941 @item
23942 Split library tasks into separate packages.
23943
23944 Write separate packages, so that library tasks are isolated from
23945 other declarations as much as possible. Let us look at a variation on
23946 the above program.
23947
23948 @smallexample @c ada
23949 package Decls1 is
23950   task Lib_Task is
23951      entry Start;
23952   end Lib_Task;
23953 end Decls1;
23954
23955 with Utils;
23956 package body Decls1 is
23957   task body Lib_Task is
23958   begin
23959      accept Start;
23960      Utils.Put_Val (2);
23961   end Lib_Task;
23962 end Decls1;
23963
23964 package Decls2 is
23965   type My_Int is new Integer;
23966   function Ident (M : My_Int) return My_Int;
23967 end Decls2;
23968
23969 with Utils;
23970 package body Decls2 is
23971   function Ident (M : My_Int) return My_Int is
23972   begin
23973      return M;
23974   end Ident;
23975 end Decls2;
23976
23977 with Decls2;
23978 package Utils is
23979   procedure Put_Val (Arg : Decls2.My_Int);
23980 end Utils;
23981
23982 with Text_IO;
23983 package body Utils is
23984   procedure Put_Val (Arg : Decls2.My_Int) is
23985   begin
23986      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23987   end Put_Val;
23988 end Utils;
23989
23990 with Decls1;
23991 procedure Main is
23992 begin
23993    Decls1.Lib_Task.Start;
23994 end;
23995 @end smallexample
23996
23997 @noindent
23998 All we have done is to split @code{Decls} into two packages, one
23999 containing the library task, and one containing everything else. Now
24000 there is no cycle, and the program compiles, binds, links and executes
24001 using the default static model of elaboration.
24002
24003 @item
24004 Declare separate task types.
24005
24006 A significant part of the problem arises because of the use of the
24007 single task declaration form. This means that the elaboration of
24008 the task type, and the elaboration of the task itself (i.e.@: the
24009 creation of the task) happen at the same time. A good rule
24010 of style in Ada is to always create explicit task types. By
24011 following the additional step of placing task objects in separate
24012 packages from the task type declaration, many elaboration problems
24013 are avoided. Here is another modified example of the example program:
24014
24015 @smallexample @c ada
24016 package Decls is
24017   task type Lib_Task_Type is
24018      entry Start;
24019   end Lib_Task_Type;
24020
24021   type My_Int is new Integer;
24022
24023   function Ident (M : My_Int) return My_Int;
24024 end Decls;
24025
24026 with Utils;
24027 package body Decls is
24028   task body Lib_Task_Type is
24029   begin
24030      accept Start;
24031      Utils.Put_Val (2);
24032   end Lib_Task_Type;
24033
24034   function Ident (M : My_Int) return My_Int is
24035   begin
24036      return M;
24037   end Ident;
24038 end Decls;
24039
24040 with Decls;
24041 package Utils is
24042   procedure Put_Val (Arg : Decls.My_Int);
24043 end Utils;
24044
24045 with Text_IO;
24046 package body Utils is
24047   procedure Put_Val (Arg : Decls.My_Int) is
24048   begin
24049      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24050   end Put_Val;
24051 end Utils;
24052
24053 with Decls;
24054 package Declst is
24055    Lib_Task : Decls.Lib_Task_Type;
24056 end Declst;
24057
24058 with Declst;
24059 procedure Main is
24060 begin
24061    Declst.Lib_Task.Start;
24062 end;
24063 @end smallexample
24064
24065 @noindent
24066 What we have done here is to replace the @code{task} declaration in
24067 package @code{Decls} with a @code{task type} declaration. Then we
24068 introduce a separate package @code{Declst} to contain the actual
24069 task object. This separates the elaboration issues for
24070 the @code{task type}
24071 declaration, which causes no trouble, from the elaboration issues
24072 of the task object, which is also unproblematic, since it is now independent
24073 of the elaboration of  @code{Utils}.
24074 This separation of concerns also corresponds to
24075 a generally sound engineering principle of separating declarations
24076 from instances. This version of the program also compiles, binds, links,
24077 and executes, generating the expected output.
24078
24079 @item
24080 Use No_Entry_Calls_In_Elaboration_Code restriction.
24081 @cindex No_Entry_Calls_In_Elaboration_Code
24082
24083 The previous two approaches described how a program can be restructured
24084 to avoid the special problems caused by library task bodies. in practice,
24085 however, such restructuring may be difficult to apply to existing legacy code,
24086 so we must consider solutions that do not require massive rewriting.
24087
24088 Let us consider more carefully why our original sample program works
24089 under the dynamic model of elaboration. The reason is that the code
24090 in the task body blocks immediately on the @code{accept}
24091 statement. Now of course there is nothing to prohibit elaboration
24092 code from making entry calls (for example from another library level task),
24093 so we cannot tell in isolation that
24094 the task will not execute the accept statement  during elaboration.
24095
24096 However, in practice it is very unusual to see elaboration code
24097 make any entry calls, and the pattern of tasks starting
24098 at elaboration time and then immediately blocking on @code{accept} or
24099 @code{select} statements is very common. What this means is that
24100 the compiler is being too pessimistic when it analyzes the
24101 whole package body as though it might be executed at elaboration
24102 time.
24103
24104 If we know that the elaboration code contains no entry calls, (a very safe
24105 assumption most of the time, that could almost be made the default
24106 behavior), then we can compile all units of the program under control
24107 of the following configuration pragma:
24108
24109 @smallexample
24110 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24111 @end smallexample
24112
24113 @noindent
24114 This pragma can be placed in the @file{gnat.adc} file in the usual
24115 manner. If we take our original unmodified program and compile it
24116 in the presence of a @file{gnat.adc} containing the above pragma,
24117 then once again, we can compile, bind, link, and execute, obtaining
24118 the expected result. In the presence of this pragma, the compiler does
24119 not trace calls in a task body, that appear after the first @code{accept}
24120 or @code{select} statement, and therefore does not report a potential
24121 circularity in the original program.
24122
24123 The compiler will check to the extent it can that the above
24124 restriction is not violated, but it is not always possible to do a
24125 complete check at compile time, so it is important to use this
24126 pragma only if the stated restriction is in fact met, that is to say
24127 no task receives an entry call before elaboration of all units is completed.
24128
24129 @end itemize
24130
24131 @node Mixing Elaboration Models
24132 @section Mixing Elaboration Models
24133 @noindent
24134 So far, we have assumed that the entire program is either compiled
24135 using the dynamic model or static model, ensuring consistency. It
24136 is possible to mix the two models, but rules have to be followed
24137 if this mixing is done to ensure that elaboration checks are not
24138 omitted.
24139
24140 The basic rule is that @emph{a unit compiled with the static model cannot
24141 be @code{with'ed} by a unit compiled with the dynamic model}. The
24142 reason for this is that in the static model, a unit assumes that
24143 its clients guarantee to use (the equivalent of) pragma
24144 @code{Elaborate_All} so that no elaboration checks are required
24145 in inner subprograms, and this assumption is violated if the
24146 client is compiled with dynamic checks.
24147
24148 The precise rule is as follows. A unit that is compiled with dynamic
24149 checks can only @code{with} a unit that meets at least one of the
24150 following criteria:
24151
24152 @itemize @bullet
24153
24154 @item
24155 The @code{with'ed} unit is itself compiled with dynamic elaboration
24156 checks (that is with the @option{-gnatE} switch.
24157
24158 @item
24159 The @code{with'ed} unit is an internal GNAT implementation unit from
24160 the System, Interfaces, Ada, or GNAT hierarchies.
24161
24162 @item
24163 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24164
24165 @item
24166 The @code{with'ing} unit (that is the client) has an explicit pragma
24167 @code{Elaborate_All} for the @code{with'ed} unit.
24168
24169 @end itemize
24170
24171 @noindent
24172 If this rule is violated, that is if a unit with dynamic elaboration
24173 checks @code{with's} a unit that does not meet one of the above four
24174 criteria, then the binder (@code{gnatbind}) will issue a warning
24175 similar to that in the following example:
24176
24177 @smallexample
24178 warning: "x.ads" has dynamic elaboration checks and with's
24179 warning:   "y.ads" which has static elaboration checks
24180 @end smallexample
24181
24182 @noindent
24183 These warnings indicate that the rule has been violated, and that as a result
24184 elaboration checks may be missed in the resulting executable file.
24185 This warning may be suppressed using the @option{-ws} binder switch
24186 in the usual manner.
24187
24188 One useful application of this mixing rule is in the case of a subsystem
24189 which does not itself @code{with} units from the remainder of the
24190 application. In this case, the entire subsystem can be compiled with
24191 dynamic checks to resolve a circularity in the subsystem, while
24192 allowing the main application that uses this subsystem to be compiled
24193 using the more reliable default static model.
24194
24195 @node What to Do If the Default Elaboration Behavior Fails
24196 @section What to Do If the Default Elaboration Behavior Fails
24197
24198 @noindent
24199 If the binder cannot find an acceptable order, it outputs detailed
24200 diagnostics. For example:
24201 @smallexample
24202 @group
24203 @iftex
24204 @leftskip=0cm
24205 @end iftex
24206 error: elaboration circularity detected
24207 info:   "proc (body)" must be elaborated before "pack (body)"
24208 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24209 info:     recompile "pack (body)" with -gnatwl
24210 info:                             for full details
24211 info:       "proc (body)"
24212 info:         is needed by its spec:
24213 info:       "proc (spec)"
24214 info:         which is withed by:
24215 info:       "pack (body)"
24216 info:  "pack (body)" must be elaborated before "proc (body)"
24217 info:     reason: pragma Elaborate in unit "proc (body)"
24218 @end group
24219
24220 @end smallexample
24221
24222 @noindent
24223 In this case we have a cycle that the binder cannot break. On the one
24224 hand, there is an explicit pragma Elaborate in @code{proc} for
24225 @code{pack}. This means that the body of @code{pack} must be elaborated
24226 before the body of @code{proc}. On the other hand, there is elaboration
24227 code in @code{pack} that calls a subprogram in @code{proc}. This means
24228 that for maximum safety, there should really be a pragma
24229 Elaborate_All in @code{pack} for @code{proc} which would require that
24230 the body of @code{proc} be elaborated before the body of
24231 @code{pack}. Clearly both requirements cannot be satisfied.
24232 Faced with a circularity of this kind, you have three different options.
24233
24234 @table @asis
24235 @item Fix the program
24236 The most desirable option from the point of view of long-term maintenance
24237 is to rearrange the program so that the elaboration problems are avoided.
24238 One useful technique is to place the elaboration code into separate
24239 child packages. Another is to move some of the initialization code to
24240 explicitly called subprograms, where the program controls the order
24241 of initialization explicitly. Although this is the most desirable option,
24242 it may be impractical and involve too much modification, especially in
24243 the case of complex legacy code.
24244
24245 @item Perform dynamic checks
24246 If the compilations are done using the
24247 @option{-gnatE}
24248 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24249 manner. Dynamic checks are generated for all calls that could possibly result
24250 in raising an exception. With this switch, the compiler does not generate
24251 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24252 exactly as specified in the @cite{Ada Reference Manual}.
24253 The binder will generate
24254 an executable program that may or may not raise @code{Program_Error}, and then
24255 it is the programmer's job to ensure that it does not raise an exception. Note
24256 that it is important to compile all units with the switch, it cannot be used
24257 selectively.
24258
24259 @item Suppress checks
24260 The drawback of dynamic checks is that they generate a
24261 significant overhead at run time, both in space and time. If you
24262 are absolutely sure that your program cannot raise any elaboration
24263 exceptions, and you still want to use the dynamic elaboration model,
24264 then you can use the configuration pragma
24265 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24266 example this pragma could be placed in the @file{gnat.adc} file.
24267
24268 @item Suppress checks selectively
24269 When you know that certain calls or instantiations in elaboration code cannot
24270 possibly lead to an elaboration error, and the binder nevertheless complains
24271 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24272 elaboration circularities, it is possible to remove those warnings locally and
24273 obtain a program that will bind. Clearly this can be unsafe, and it is the
24274 responsibility of the programmer to make sure that the resulting program has no
24275 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24276 used with different granularity to suppress warnings and break elaboration
24277 circularities:
24278
24279 @itemize @bullet
24280 @item
24281 Place the pragma that names the called subprogram in the declarative part
24282 that contains the call.
24283
24284 @item
24285 Place the pragma in the declarative part, without naming an entity. This
24286 disables warnings on all calls in the corresponding  declarative region.
24287
24288 @item
24289 Place the pragma in the package spec that declares the called subprogram,
24290 and name the subprogram. This disables warnings on all elaboration calls to
24291 that subprogram.
24292
24293 @item
24294 Place the pragma in the package spec that declares the called subprogram,
24295 without naming any entity. This disables warnings on all elaboration calls to
24296 all subprograms declared in this spec.
24297
24298 @item Use Pragma Elaborate
24299 As previously described in section @xref{Treatment of Pragma Elaborate},
24300 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24301 that no elaboration checks are required on calls to the designated unit.
24302 There may be cases in which the caller knows that no transitive calls
24303 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24304 case where @code{pragma Elaborate_All} would cause a circularity.
24305 @end itemize
24306
24307 @noindent
24308 These five cases are listed in order of decreasing safety, and therefore
24309 require increasing programmer care in their application. Consider the
24310 following program:
24311
24312 @smallexample @c adanocomment
24313 package Pack1 is
24314   function F1 return Integer;
24315   X1 : Integer;
24316 end Pack1;
24317
24318 package Pack2 is
24319   function F2 return Integer;
24320   function Pure (x : integer) return integer;
24321   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24322   --  pragma Suppress (Elaboration_Check);              -- (4)
24323 end Pack2;
24324
24325 with Pack2;
24326 package body Pack1 is
24327   function F1 return Integer is
24328   begin
24329     return 100;
24330   end F1;
24331   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24332 begin
24333   declare
24334     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24335     --  pragma Suppress(Elaboration_Check);             -- (2)
24336   begin
24337     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24338   end;
24339 end Pack1;
24340
24341 with Pack1;
24342 package body Pack2 is
24343   function F2 return Integer is
24344   begin
24345      return Pack1.F1;
24346   end F2;
24347   function Pure (x : integer) return integer is
24348   begin
24349      return x ** 3 - 3 * x;
24350   end;
24351 end Pack2;
24352
24353 with Pack1, Ada.Text_IO;
24354 procedure Proc3 is
24355 begin
24356   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24357 end Proc3;
24358 @end smallexample
24359 In the absence of any pragmas, an attempt to bind this program produces
24360 the following diagnostics:
24361 @smallexample
24362 @group
24363 @iftex
24364 @leftskip=.5cm
24365 @end iftex
24366 error: elaboration circularity detected
24367 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24368 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24369 info:       recompile "pack1 (body)" with -gnatwl for full details
24370 info:          "pack1 (body)"
24371 info:             must be elaborated along with its spec:
24372 info:          "pack1 (spec)"
24373 info:             which is withed by:
24374 info:          "pack2 (body)"
24375 info:             which must be elaborated along with its spec:
24376 info:          "pack2 (spec)"
24377 info:             which is withed by:
24378 info:          "pack1 (body)"
24379 @end group
24380 @end smallexample
24381 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24382 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24383 F2 is safe, even though F2 calls F1, because the call appears after the
24384 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24385 remove the warning on the call. It is also possible to use pragma (2)
24386 because there are no other potentially unsafe calls in the block.
24387
24388 @noindent
24389 The call to @code{Pure} is safe because this function does not depend on the
24390 state of @code{Pack2}. Therefore any call to this function is safe, and it
24391 is correct to place pragma (3) in the corresponding package spec.
24392
24393 @noindent
24394 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24395 warnings on all calls to functions declared therein. Note that this is not
24396 necessarily safe, and requires more detailed examination of the subprogram
24397 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24398 be already elaborated.
24399 @end table
24400
24401 @noindent
24402 It is hard to generalize on which of these four approaches should be
24403 taken. Obviously if it is possible to fix the program so that the default
24404 treatment works, this is preferable, but this may not always be practical.
24405 It is certainly simple enough to use
24406 @option{-gnatE}
24407 but the danger in this case is that, even if the GNAT binder
24408 finds a correct elaboration order, it may not always do so,
24409 and certainly a binder from another Ada compiler might not. A
24410 combination of testing and analysis (for which the warnings generated
24411 with the
24412 @option{-gnatwl}
24413 switch can be useful) must be used to ensure that the program is free
24414 of errors. One switch that is useful in this testing is the
24415 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24416 switch for
24417 @code{gnatbind}.
24418 Normally the binder tries to find an order that has the best chance
24419 of avoiding elaboration problems. However, if this switch is used, the binder
24420 plays a devil's advocate role, and tries to choose the order that
24421 has the best chance of failing. If your program works even with this
24422 switch, then it has a better chance of being error free, but this is still
24423 not a guarantee.
24424
24425 For an example of this approach in action, consider the C-tests (executable
24426 tests) from the ACVC suite. If these are compiled and run with the default
24427 treatment, then all but one of them succeed without generating any error
24428 diagnostics from the binder. However, there is one test that fails, and
24429 this is not surprising, because the whole point of this test is to ensure
24430 that the compiler can handle cases where it is impossible to determine
24431 a correct order statically, and it checks that an exception is indeed
24432 raised at run time.
24433
24434 This one test must be compiled and run using the
24435 @option{-gnatE}
24436 switch, and then it passes. Alternatively, the entire suite can
24437 be run using this switch. It is never wrong to run with the dynamic
24438 elaboration switch if your code is correct, and we assume that the
24439 C-tests are indeed correct (it is less efficient, but efficiency is
24440 not a factor in running the ACVC tests.)
24441
24442 @node Elaboration for Access-to-Subprogram Values
24443 @section Elaboration for Access-to-Subprogram Values
24444 @cindex Access-to-subprogram
24445
24446 @noindent
24447 Access-to-subprogram types (introduced in Ada 95) complicate
24448 the handling of elaboration. The trouble is that it becomes
24449 impossible to tell at compile time which procedure
24450 is being called. This means that it is not possible for the binder
24451 to analyze the elaboration requirements in this case.
24452
24453 If at the point at which the access value is created
24454 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24455 the body of the subprogram is
24456 known to have been elaborated, then the access value is safe, and its use
24457 does not require a check. This may be achieved by appropriate arrangement
24458 of the order of declarations if the subprogram is in the current unit,
24459 or, if the subprogram is in another unit, by using pragma
24460 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24461 on the referenced unit.
24462
24463 If the referenced body is not known to have been elaborated at the point
24464 the access value is created, then any use of the access value must do a
24465 dynamic check, and this dynamic check will fail and raise a
24466 @code{Program_Error} exception if the body has not been elaborated yet.
24467 GNAT will generate the necessary checks, and in addition, if the
24468 @option{-gnatwl}
24469 switch is set, will generate warnings that such checks are required.
24470
24471 The use of dynamic dispatching for tagged types similarly generates
24472 a requirement for dynamic checks, and premature calls to any primitive
24473 operation of a tagged type before the body of the operation has been
24474 elaborated, will result in the raising of @code{Program_Error}.
24475
24476 @node Summary of Procedures for Elaboration Control
24477 @section Summary of Procedures for Elaboration Control
24478 @cindex Elaboration control
24479
24480 @noindent
24481 First, compile your program with the default options, using none of
24482 the special elaboration control switches. If the binder successfully
24483 binds your program, then you can be confident that, apart from issues
24484 raised by the use of access-to-subprogram types and dynamic dispatching,
24485 the program is free of elaboration errors. If it is important that the
24486 program be portable, then use the
24487 @option{-gnatwl}
24488 switch to generate warnings about missing @code{Elaborate} or
24489 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24490
24491 If the program fails to bind using the default static elaboration
24492 handling, then you can fix the program to eliminate the binder
24493 message, or recompile the entire program with the
24494 @option{-gnatE} switch to generate dynamic elaboration checks,
24495 and, if you are sure there really are no elaboration problems,
24496 use a global pragma @code{Suppress (Elaboration_Check)}.
24497
24498 @node Other Elaboration Order Considerations
24499 @section Other Elaboration Order Considerations
24500 @noindent
24501 This section has been entirely concerned with the issue of finding a valid
24502 elaboration order, as defined by the Ada Reference Manual. In a case
24503 where several elaboration orders are valid, the task is to find one
24504 of the possible valid elaboration orders (and the static model in GNAT
24505 will ensure that this is achieved).
24506
24507 The purpose of the elaboration rules in the Ada Reference Manual is to
24508 make sure that no entity is accessed before it has been elaborated. For
24509 a subprogram, this means that the spec and body must have been elaborated
24510 before the subprogram is called. For an object, this means that the object
24511 must have been elaborated before its value is read or written. A violation
24512 of either of these two requirements is an access before elaboration order,
24513 and this section has been all about avoiding such errors.
24514
24515 In the case where more than one order of elaboration is possible, in the
24516 sense that access before elaboration errors are avoided, then any one of
24517 the orders is ``correct'' in the sense that it meets the requirements of
24518 the Ada Reference Manual, and no such error occurs.
24519
24520 However, it may be the case for a given program, that there are
24521 constraints on the order of elaboration that come not from consideration
24522 of avoiding elaboration errors, but rather from extra-lingual logic
24523 requirements. Consider this example:
24524
24525 @smallexample @c ada
24526 with Init_Constants;
24527 package Constants is
24528    X : Integer := 0;
24529    Y : Integer := 0;
24530 end Constants;
24531
24532 package Init_Constants is
24533    procedure P; -- require a body
24534 end Init_Constants;
24535
24536 with Constants;
24537 package body Init_Constants is
24538    procedure P is begin null; end;
24539 begin
24540    Constants.X := 3;
24541    Constants.Y := 4;
24542 end Init_Constants;
24543
24544 with Constants;
24545 package Calc is
24546    Z : Integer := Constants.X + Constants.Y;
24547 end Calc;
24548
24549 with Calc;
24550 with Text_IO; use Text_IO;
24551 procedure Main is
24552 begin
24553    Put_Line (Calc.Z'Img);
24554 end Main;
24555 @end smallexample
24556
24557 @noindent
24558 In this example, there is more than one valid order of elaboration. For
24559 example both the following are correct orders:
24560
24561 @smallexample
24562 Init_Constants spec
24563 Constants spec
24564 Calc spec
24565 Init_Constants body
24566 Main body
24567
24568   and
24569
24570 Init_Constants spec
24571 Init_Constants body
24572 Constants spec
24573 Calc spec
24574 Main body
24575 @end smallexample
24576
24577 @noindent
24578 There is no language rule to prefer one or the other, both are correct
24579 from an order of elaboration point of view. But the programmatic effects
24580 of the two orders are very different. In the first, the elaboration routine
24581 of @code{Calc} initializes @code{Z} to zero, and then the main program
24582 runs with this value of zero. But in the second order, the elaboration
24583 routine of @code{Calc} runs after the body of Init_Constants has set
24584 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24585 runs.
24586
24587 One could perhaps by applying pretty clever non-artificial intelligence
24588 to the situation guess that it is more likely that the second order of
24589 elaboration is the one desired, but there is no formal linguistic reason
24590 to prefer one over the other. In fact in this particular case, GNAT will
24591 prefer the second order, because of the rule that bodies are elaborated
24592 as soon as possible, but it's just luck that this is what was wanted
24593 (if indeed the second order was preferred).
24594
24595 If the program cares about the order of elaboration routines in a case like
24596 this, it is important to specify the order required. In this particular
24597 case, that could have been achieved by adding to the spec of Calc:
24598
24599 @smallexample @c ada
24600 pragma Elaborate_All (Constants);
24601 @end smallexample
24602
24603 @noindent
24604 which requires that the body (if any) and spec of @code{Constants},
24605 as well as the body and spec of any unit @code{with}'ed by
24606 @code{Constants} be elaborated before @code{Calc} is elaborated.
24607
24608 Clearly no automatic method can always guess which alternative you require,
24609 and if you are working with legacy code that had constraints of this kind
24610 which were not properly specified by adding @code{Elaborate} or
24611 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24612 compilers can choose different orders.
24613
24614 However, GNAT does attempt to diagnose the common situation where there
24615 are uninitialized variables in the visible part of a package spec, and the
24616 corresponding package body has an elaboration block that directly or
24617 indirectly initialized one or more of these variables. This is the situation
24618 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24619 a warning that suggests this addition if it detects this situation.
24620
24621 The @code{gnatbind}
24622 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24623 out problems. This switch causes bodies to be elaborated as late as possible
24624 instead of as early as possible. In the example above, it would have forced
24625 the choice of the first elaboration order. If you get different results
24626 when using this switch, and particularly if one set of results is right,
24627 and one is wrong as far as you are concerned, it shows that you have some
24628 missing @code{Elaborate} pragmas. For the example above, we have the
24629 following output:
24630
24631 @smallexample
24632 gnatmake -f -q main
24633 main
24634  7
24635 gnatmake -f -q main -bargs -p
24636 main
24637  0
24638 @end smallexample
24639
24640 @noindent
24641 It is of course quite unlikely that both these results are correct, so
24642 it is up to you in a case like this to investigate the source of the
24643 difference, by looking at the two elaboration orders that are chosen,
24644 and figuring out which is correct, and then adding the necessary
24645 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24646
24647
24648
24649 @c *******************************
24650 @node Conditional Compilation
24651 @appendix Conditional Compilation
24652 @c *******************************
24653 @cindex Conditional compilation
24654
24655 @noindent
24656 It is often necessary to arrange for a single source program
24657 to serve multiple purposes, where it is compiled in different
24658 ways to achieve these different goals. Some examples of the
24659 need for this feature are
24660
24661 @itemize @bullet
24662 @item  Adapting a program to a different hardware environment
24663 @item  Adapting a program to a different target architecture
24664 @item  Turning debugging features on and off
24665 @item  Arranging for a program to compile with different compilers
24666 @end itemize
24667
24668 @noindent
24669 In C, or C++, the typical approach would be to use the preprocessor
24670 that is defined as part of the language. The Ada language does not
24671 contain such a feature. This is not an oversight, but rather a very
24672 deliberate design decision, based on the experience that overuse of
24673 the preprocessing features in C and C++ can result in programs that
24674 are extremely difficult to maintain. For example, if we have ten
24675 switches that can be on or off, this means that there are a thousand
24676 separate programs, any one of which might not even be syntactically
24677 correct, and even if syntactically correct, the resulting program
24678 might not work correctly. Testing all combinations can quickly become
24679 impossible.
24680
24681 Nevertheless, the need to tailor programs certainly exists, and in
24682 this Appendix we will discuss how this can
24683 be achieved using Ada in general, and GNAT in particular.
24684
24685 @menu
24686 * Use of Boolean Constants::
24687 * Debugging - A Special Case::
24688 * Conditionalizing Declarations::
24689 * Use of Alternative Implementations::
24690 * Preprocessing::
24691 @end menu
24692
24693 @node Use of Boolean Constants
24694 @section Use of Boolean Constants
24695
24696 @noindent
24697 In the case where the difference is simply which code
24698 sequence is executed, the cleanest solution is to use Boolean
24699 constants to control which code is executed.
24700
24701 @smallexample @c ada
24702 @group
24703 FP_Initialize_Required : constant Boolean := True;
24704 @dots{}
24705 if FP_Initialize_Required then
24706 @dots{}
24707 end if;
24708 @end group
24709 @end smallexample
24710
24711 @noindent
24712 Not only will the code inside the @code{if} statement not be executed if
24713 the constant Boolean is @code{False}, but it will also be completely
24714 deleted from the program.
24715 However, the code is only deleted after the @code{if} statement
24716 has been checked for syntactic and semantic correctness.
24717 (In contrast, with preprocessors the code is deleted before the
24718 compiler ever gets to see it, so it is not checked until the switch
24719 is turned on.)
24720 @cindex Preprocessors (contrasted with conditional compilation)
24721
24722 Typically the Boolean constants will be in a separate package,
24723 something like:
24724
24725 @smallexample @c ada
24726 @group
24727 package Config is
24728    FP_Initialize_Required : constant Boolean := True;
24729    Reset_Available        : constant Boolean := False;
24730    @dots{}
24731 end Config;
24732 @end group
24733 @end smallexample
24734
24735 @noindent
24736 The @code{Config} package exists in multiple forms for the various targets,
24737 with an appropriate script selecting the version of @code{Config} needed.
24738 Then any other unit requiring conditional compilation can do a @code{with}
24739 of @code{Config} to make the constants visible.
24740
24741
24742 @node Debugging - A Special Case
24743 @section Debugging - A Special Case
24744
24745 @noindent
24746 A common use of conditional code is to execute statements (for example
24747 dynamic checks, or output of intermediate results) under control of a
24748 debug switch, so that the debugging behavior can be turned on and off.
24749 This can be done using a Boolean constant to control whether the code
24750 is active:
24751
24752 @smallexample @c ada
24753 @group
24754 if Debugging then
24755    Put_Line ("got to the first stage!");
24756 end if;
24757 @end group
24758 @end smallexample
24759
24760 @noindent
24761 or
24762
24763 @smallexample @c ada
24764 @group
24765 if Debugging and then Temperature > 999.0 then
24766    raise Temperature_Crazy;
24767 end if;
24768 @end group
24769 @end smallexample
24770
24771 @noindent
24772 Since this is a common case, there are special features to deal with
24773 this in a convenient manner. For the case of tests, Ada 2005 has added
24774 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24775 @cindex pragma @code{Assert}
24776 on the @code{Assert} pragma that has always been available in GNAT, so this
24777 feature may be used with GNAT even if you are not using Ada 2005 features.
24778 The use of pragma @code{Assert} is described in
24779 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24780 example, the last test could be written:
24781
24782 @smallexample @c ada
24783 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24784 @end smallexample
24785
24786 @noindent
24787 or simply
24788
24789 @smallexample @c ada
24790 pragma Assert (Temperature <= 999.0);
24791 @end smallexample
24792
24793 @noindent
24794 In both cases, if assertions are active and the temperature is excessive,
24795 the exception @code{Assert_Failure} will be raised, with the given string in
24796 the first case or a string indicating the location of the pragma in the second
24797 case used as the exception message.
24798
24799 You can turn assertions on and off by using the @code{Assertion_Policy}
24800 pragma.
24801 @cindex pragma @code{Assertion_Policy}
24802 This is an Ada 2005 pragma which is implemented in all modes by
24803 GNAT, but only in the latest versions of GNAT which include Ada 2005
24804 capability. Alternatively, you can use the @option{-gnata} switch
24805 @cindex @option{-gnata} switch
24806 to enable assertions from the command line (this is recognized by all versions
24807 of GNAT).
24808
24809 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24810 @code{Debug} can be used:
24811 @cindex pragma @code{Debug}
24812
24813 @smallexample @c ada
24814 pragma Debug (Put_Line ("got to the first stage!"));
24815 @end smallexample
24816
24817 @noindent
24818 If debug pragmas are enabled, the argument, which must be of the form of
24819 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24820 Only one call can be present, but of course a special debugging procedure
24821 containing any code you like can be included in the program and then
24822 called in a pragma @code{Debug} argument as needed.
24823
24824 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24825 construct is that pragma @code{Debug} can appear in declarative contexts,
24826 such as at the very beginning of a procedure, before local declarations have
24827 been elaborated.
24828
24829 Debug pragmas are enabled using either the @option{-gnata} switch that also
24830 controls assertions, or with a separate Debug_Policy pragma.
24831 @cindex pragma @code{Debug_Policy}
24832 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24833 in Ada 95 and Ada 83 programs as well), and is analogous to
24834 pragma @code{Assertion_Policy} to control assertions.
24835
24836 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24837 and thus they can appear in @file{gnat.adc} if you are not using a
24838 project file, or in the file designated to contain configuration pragmas
24839 in a project file.
24840 They then apply to all subsequent compilations. In practice the use of
24841 the @option{-gnata} switch is often the most convenient method of controlling
24842 the status of these pragmas.
24843
24844 Note that a pragma is not a statement, so in contexts where a statement
24845 sequence is required, you can't just write a pragma on its own. You have
24846 to add a @code{null} statement.
24847
24848 @smallexample @c ada
24849 @group
24850 if @dots{} then
24851    @dots{} -- some statements
24852 else
24853    pragma Assert (Num_Cases < 10);
24854    null;
24855 end if;
24856 @end group
24857 @end smallexample
24858
24859
24860 @node Conditionalizing Declarations
24861 @section Conditionalizing Declarations
24862
24863 @noindent
24864 In some cases, it may be necessary to conditionalize declarations to meet
24865 different requirements. For example we might want a bit string whose length
24866 is set to meet some hardware message requirement.
24867
24868 In some cases, it may be possible to do this using declare blocks controlled
24869 by conditional constants:
24870
24871 @smallexample @c ada
24872 @group
24873 if Small_Machine then
24874    declare
24875       X : Bit_String (1 .. 10);
24876    begin
24877       @dots{}
24878    end;
24879 else
24880    declare
24881       X : Large_Bit_String (1 .. 1000);
24882    begin
24883       @dots{}
24884    end;
24885 end if;
24886 @end group
24887 @end smallexample
24888
24889 @noindent
24890 Note that in this approach, both declarations are analyzed by the
24891 compiler so this can only be used where both declarations are legal,
24892 even though one of them will not be used.
24893
24894 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24895 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24896 that are parameterized by these constants. For example
24897
24898 @smallexample @c ada
24899 @group
24900 for Rec use
24901   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24902 end record;
24903 @end group
24904 @end smallexample
24905
24906 @noindent
24907 If @code{Bits_Per_Word} is set to 32, this generates either
24908
24909 @smallexample @c ada
24910 @group
24911 for Rec use
24912   Field1 at 0 range 0 .. 32;
24913 end record;
24914 @end group
24915 @end smallexample
24916
24917 @noindent
24918 for the big endian case, or
24919
24920 @smallexample @c ada
24921 @group
24922 for Rec use record
24923   Field1 at 0 range 10 .. 32;
24924 end record;
24925 @end group
24926 @end smallexample
24927
24928 @noindent
24929 for the little endian case. Since a powerful subset of Ada expression
24930 notation is usable for creating static constants, clever use of this
24931 feature can often solve quite difficult problems in conditionalizing
24932 compilation (note incidentally that in Ada 95, the little endian
24933 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24934 need to define this one yourself).
24935
24936
24937 @node Use of Alternative Implementations
24938 @section Use of Alternative Implementations
24939
24940 @noindent
24941 In some cases, none of the approaches described above are adequate. This
24942 can occur for example if the set of declarations required is radically
24943 different for two different configurations.
24944
24945 In this situation, the official Ada way of dealing with conditionalizing
24946 such code is to write separate units for the different cases. As long as
24947 this does not result in excessive duplication of code, this can be done
24948 without creating maintenance problems. The approach is to share common
24949 code as far as possible, and then isolate the code and declarations
24950 that are different. Subunits are often a convenient method for breaking
24951 out a piece of a unit that is to be conditionalized, with separate files
24952 for different versions of the subunit for different targets, where the
24953 build script selects the right one to give to the compiler.
24954 @cindex Subunits (and conditional compilation)
24955
24956 As an example, consider a situation where a new feature in Ada 2005
24957 allows something to be done in a really nice way. But your code must be able
24958 to compile with an Ada 95 compiler. Conceptually you want to say:
24959
24960 @smallexample @c ada
24961 @group
24962 if Ada_2005 then
24963    @dots{} neat Ada 2005 code
24964 else
24965    @dots{} not quite as neat Ada 95 code
24966 end if;
24967 @end group
24968 @end smallexample
24969
24970 @noindent
24971 where @code{Ada_2005} is a Boolean constant.
24972
24973 But this won't work when @code{Ada_2005} is set to @code{False},
24974 since the @code{then} clause will be illegal for an Ada 95 compiler.
24975 (Recall that although such unreachable code would eventually be deleted
24976 by the compiler, it still needs to be legal.  If it uses features
24977 introduced in Ada 2005, it will be illegal in Ada 95.)
24978
24979 So instead we write
24980
24981 @smallexample @c ada
24982 procedure Insert is separate;
24983 @end smallexample
24984
24985 @noindent
24986 Then we have two files for the subunit @code{Insert}, with the two sets of
24987 code.
24988 If the package containing this is called @code{File_Queries}, then we might
24989 have two files
24990
24991 @itemize @bullet
24992 @item    @file{file_queries-insert-2005.adb}
24993 @item    @file{file_queries-insert-95.adb}
24994 @end itemize
24995
24996 @noindent
24997 and the build script renames the appropriate file to
24998
24999 @smallexample
25000 file_queries-insert.adb
25001 @end smallexample
25002
25003 @noindent
25004 and then carries out the compilation.
25005
25006 This can also be done with project files' naming schemes. For example:
25007
25008 @smallexample @c project
25009 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25010 @end smallexample
25011
25012 @noindent
25013 Note also that with project files it is desirable to use a different extension
25014 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25015 conflict may arise through another commonly used feature: to declare as part
25016 of the project a set of directories containing all the sources obeying the
25017 default naming scheme.
25018
25019 The use of alternative units is certainly feasible in all situations,
25020 and for example the Ada part of the GNAT run-time is conditionalized
25021 based on the target architecture using this approach. As a specific example,
25022 consider the implementation of the AST feature in VMS. There is one
25023 spec:
25024
25025 @smallexample
25026 s-asthan.ads
25027 @end smallexample
25028
25029 @noindent
25030 which is the same for all architectures, and three bodies:
25031
25032 @table @file
25033 @item    s-asthan.adb
25034 used for all non-VMS operating systems
25035 @item    s-asthan-vms-alpha.adb
25036 used for VMS on the Alpha
25037 @item    s-asthan-vms-ia64.adb
25038 used for VMS on the ia64
25039 @end table
25040
25041 @noindent
25042 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25043 this operating system feature is not available, and the two remaining
25044 versions interface with the corresponding versions of VMS to provide
25045 VMS-compatible AST handling. The GNAT build script knows the architecture
25046 and operating system, and automatically selects the right version,
25047 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25048
25049 Another style for arranging alternative implementations is through Ada's
25050 access-to-subprogram facility.
25051 In case some functionality is to be conditionally included,
25052 you can declare an access-to-procedure variable @code{Ref} that is initialized
25053 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25054 when appropriate.
25055 In some library package, set @code{Ref} to @code{Proc'Access} for some
25056 procedure @code{Proc} that performs the relevant processing.
25057 The initialization only occurs if the library package is included in the
25058 program.
25059 The same idea can also be implemented using tagged types and dispatching
25060 calls.
25061
25062
25063 @node Preprocessing
25064 @section Preprocessing
25065 @cindex Preprocessing
25066
25067 @noindent
25068 Although it is quite possible to conditionalize code without the use of
25069 C-style preprocessing, as described earlier in this section, it is
25070 nevertheless convenient in some cases to use the C approach. Moreover,
25071 older Ada compilers have often provided some preprocessing capability,
25072 so legacy code may depend on this approach, even though it is not
25073 standard.
25074
25075 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25076 extent on the various preprocessors that have been used
25077 with legacy code on other compilers, to enable easier transition).
25078
25079 The preprocessor may be used in two separate modes. It can be used quite
25080 separately from the compiler, to generate a separate output source file
25081 that is then fed to the compiler as a separate step. This is the
25082 @code{gnatprep} utility, whose use is fully described in
25083 @ref{Preprocessing Using gnatprep}.
25084 @cindex @code{gnatprep}
25085
25086 The preprocessing language allows such constructs as
25087
25088 @smallexample
25089 @group
25090 #if DEBUG or PRIORITY > 4 then
25091    bunch of declarations
25092 #else
25093    completely different bunch of declarations
25094 #end if;
25095 @end group
25096 @end smallexample
25097
25098 @noindent
25099 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25100 defined either on the command line or in a separate file.
25101
25102 The other way of running the preprocessor is even closer to the C style and
25103 often more convenient. In this approach the preprocessing is integrated into
25104 the compilation process. The compiler is fed the preprocessor input which
25105 includes @code{#if} lines etc, and then the compiler carries out the
25106 preprocessing internally and processes the resulting output.
25107 For more details on this approach, see @ref{Integrated Preprocessing}.
25108
25109
25110 @c *******************************
25111 @node Inline Assembler
25112 @appendix Inline Assembler
25113 @c *******************************
25114
25115 @noindent
25116 If you need to write low-level software that interacts directly
25117 with the hardware, Ada provides two ways to incorporate assembly
25118 language code into your program.  First, you can import and invoke
25119 external routines written in assembly language, an Ada feature fully
25120 supported by GNAT@.  However, for small sections of code it may be simpler
25121 or more efficient to include assembly language statements directly
25122 in your Ada source program, using the facilities of the implementation-defined
25123 package @code{System.Machine_Code}, which incorporates the gcc
25124 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25125 including the following:
25126
25127 @itemize @bullet
25128 @item No need to use non-Ada tools
25129 @item Consistent interface over different targets
25130 @item Automatic usage of the proper calling conventions
25131 @item Access to Ada constants and variables
25132 @item Definition of intrinsic routines
25133 @item Possibility of inlining a subprogram comprising assembler code
25134 @item Code optimizer can take Inline Assembler code into account
25135 @end itemize
25136
25137 This chapter presents a series of examples to show you how to use
25138 the Inline Assembler.  Although it focuses on the Intel x86,
25139 the general approach applies also to other processors.
25140 It is assumed that you are familiar with Ada
25141 and with assembly language programming.
25142
25143 @menu
25144 * Basic Assembler Syntax::
25145 * A Simple Example of Inline Assembler::
25146 * Output Variables in Inline Assembler::
25147 * Input Variables in Inline Assembler::
25148 * Inlining Inline Assembler Code::
25149 * Other Asm Functionality::
25150 @end menu
25151
25152 @c ---------------------------------------------------------------------------
25153 @node Basic Assembler Syntax
25154 @section Basic Assembler Syntax
25155
25156 @noindent
25157 The assembler used by GNAT and gcc is based not on the Intel assembly
25158 language, but rather on a language that descends from the AT&T Unix
25159 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25160 The following table summarizes the main features of @emph{as} syntax
25161 and points out the differences from the Intel conventions.
25162 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25163 pre-processor) documentation for further information.
25164
25165 @table @asis
25166 @item Register names
25167 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25168 @*
25169 Intel: No extra punctuation; for example @code{eax}
25170
25171 @item Immediate operand
25172 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25173 @*
25174 Intel: No extra punctuation; for example @code{4}
25175
25176 @item Address
25177 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25178 @*
25179 Intel: No extra punctuation; for example @code{loc}
25180
25181 @item Memory contents
25182 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25183 @*
25184 Intel: Square brackets; for example @code{[loc]}
25185
25186 @item Register contents
25187 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25188 @*
25189 Intel: Square brackets; for example @code{[eax]}
25190
25191 @item Hexadecimal numbers
25192 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25193 @*
25194 Intel: Trailing ``h''; for example @code{A0h}
25195
25196 @item Operand size
25197 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25198 a 16-bit word
25199 @*
25200 Intel: Implicit, deduced by assembler; for example @code{mov}
25201
25202 @item Instruction repetition
25203 gcc / @emph{as}: Split into two lines; for example
25204 @*
25205 @code{rep}
25206 @*
25207 @code{stosl}
25208 @*
25209 Intel: Keep on one line; for example @code{rep stosl}
25210
25211 @item Order of operands
25212 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25213 @*
25214 Intel: Destination first; for example @code{mov eax, 4}
25215 @end table
25216
25217 @c ---------------------------------------------------------------------------
25218 @node A Simple Example of Inline Assembler
25219 @section A Simple Example of Inline Assembler
25220
25221 @noindent
25222 The following example will generate a single assembly language statement,
25223 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25224 the example will be useful in illustrating the basics of
25225 the Inline Assembler facility.
25226
25227 @smallexample @c ada
25228 @group
25229 with System.Machine_Code; use System.Machine_Code;
25230 procedure Nothing is
25231 begin
25232    Asm ("nop");
25233 end Nothing;
25234 @end group
25235 @end smallexample
25236
25237 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25238 here it takes one parameter, a @emph{template string} that must be a static
25239 expression and that will form the generated instruction.
25240 @code{Asm} may be regarded as a compile-time procedure that parses
25241 the template string and additional parameters (none here),
25242 from which it generates a sequence of assembly language instructions.
25243
25244 The examples in this chapter will illustrate several of the forms
25245 for invoking @code{Asm}; a complete specification of the syntax
25246 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25247 Manual}.
25248
25249 Under the standard GNAT conventions, the @code{Nothing} procedure
25250 should be in a file named @file{nothing.adb}.
25251 You can build the executable in the usual way:
25252 @smallexample
25253 gnatmake nothing
25254 @end smallexample
25255 However, the interesting aspect of this example is not its run-time behavior
25256 but rather the generated assembly code.
25257 To see this output, invoke the compiler as follows:
25258 @smallexample
25259    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25260 @end smallexample
25261 where the options are:
25262
25263 @table @code
25264 @item -c
25265 compile only (no bind or link)
25266 @item -S
25267 generate assembler listing
25268 @item -fomit-frame-pointer
25269 do not set up separate stack frames
25270 @item -gnatp
25271 do not add runtime checks
25272 @end table
25273
25274 This gives a human-readable assembler version of the code. The resulting
25275 file will have the same name as the Ada source file, but with a @code{.s}
25276 extension. In our example, the file @file{nothing.s} has the following
25277 contents:
25278
25279 @smallexample
25280 @group
25281 .file "nothing.adb"
25282 gcc2_compiled.:
25283 ___gnu_compiled_ada:
25284 .text
25285    .align 4
25286 .globl __ada_nothing
25287 __ada_nothing:
25288 #APP
25289    nop
25290 #NO_APP
25291    jmp L1
25292    .align 2,0x90
25293 L1:
25294    ret
25295 @end group
25296 @end smallexample
25297
25298 The assembly code you included is clearly indicated by
25299 the compiler, between the @code{#APP} and @code{#NO_APP}
25300 delimiters. The character before the 'APP' and 'NOAPP'
25301 can differ on different targets. For example, GNU/Linux uses '#APP' while
25302 on NT you will see '/APP'.
25303
25304 If you make a mistake in your assembler code (such as using the
25305 wrong size modifier, or using a wrong operand for the instruction) GNAT
25306 will report this error in a temporary file, which will be deleted when
25307 the compilation is finished.  Generating an assembler file will help
25308 in such cases, since you can assemble this file separately using the
25309 @emph{as} assembler that comes with gcc.
25310
25311 Assembling the file using the command
25312
25313 @smallexample
25314 as @file{nothing.s}
25315 @end smallexample
25316 @noindent
25317 will give you error messages whose lines correspond to the assembler
25318 input file, so you can easily find and correct any mistakes you made.
25319 If there are no errors, @emph{as} will generate an object file
25320 @file{nothing.out}.
25321
25322 @c ---------------------------------------------------------------------------
25323 @node Output Variables in Inline Assembler
25324 @section Output Variables in Inline Assembler
25325
25326 @noindent
25327 The examples in this section, showing how to access the processor flags,
25328 illustrate how to specify the destination operands for assembly language
25329 statements.
25330
25331 @smallexample @c ada
25332 @group
25333 with Interfaces; use Interfaces;
25334 with Ada.Text_IO; use Ada.Text_IO;
25335 with System.Machine_Code; use System.Machine_Code;
25336 procedure Get_Flags is
25337    Flags : Unsigned_32;
25338    use ASCII;
25339 begin
25340    Asm ("pushfl"          & LF & HT & -- push flags on stack
25341         "popl %%eax"      & LF & HT & -- load eax with flags
25342         "movl %%eax, %0",             -- store flags in variable
25343         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25344    Put_Line ("Flags register:" & Flags'Img);
25345 end Get_Flags;
25346 @end group
25347 @end smallexample
25348
25349 In order to have a nicely aligned assembly listing, we have separated
25350 multiple assembler statements in the Asm template string with linefeed
25351 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25352 The resulting section of the assembly output file is:
25353
25354 @smallexample
25355 @group
25356 #APP
25357    pushfl
25358    popl %eax
25359    movl %eax, -40(%ebp)
25360 #NO_APP
25361 @end group
25362 @end smallexample
25363
25364 It would have been legal to write the Asm invocation as:
25365
25366 @smallexample
25367 Asm ("pushfl popl %%eax movl %%eax, %0")
25368 @end smallexample
25369
25370 but in the generated assembler file, this would come out as:
25371
25372 @smallexample
25373 #APP
25374    pushfl popl %eax movl %eax, -40(%ebp)
25375 #NO_APP
25376 @end smallexample
25377
25378 which is not so convenient for the human reader.
25379
25380 We use Ada comments
25381 at the end of each line to explain what the assembler instructions
25382 actually do.  This is a useful convention.
25383
25384 When writing Inline Assembler instructions, you need to precede each register
25385 and variable name with a percent sign.  Since the assembler already requires
25386 a percent sign at the beginning of a register name, you need two consecutive
25387 percent signs for such names in the Asm template string, thus @code{%%eax}.
25388 In the generated assembly code, one of the percent signs will be stripped off.
25389
25390 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25391 variables: operands you later define using @code{Input} or @code{Output}
25392 parameters to @code{Asm}.
25393 An output variable is illustrated in
25394 the third statement in the Asm template string:
25395 @smallexample
25396 movl %%eax, %0
25397 @end smallexample
25398 The intent is to store the contents of the eax register in a variable that can
25399 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25400 necessarily work, since the compiler might optimize by using a register
25401 to hold Flags, and the expansion of the @code{movl} instruction would not be
25402 aware of this optimization.  The solution is not to store the result directly
25403 but rather to advise the compiler to choose the correct operand form;
25404 that is the purpose of the @code{%0} output variable.
25405
25406 Information about the output variable is supplied in the @code{Outputs}
25407 parameter to @code{Asm}:
25408 @smallexample
25409 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25410 @end smallexample
25411
25412 The output is defined by the @code{Asm_Output} attribute of the target type;
25413 the general format is
25414 @smallexample
25415 Type'Asm_Output (constraint_string, variable_name)
25416 @end smallexample
25417
25418 The constraint string directs the compiler how
25419 to store/access the associated variable.  In the example
25420 @smallexample
25421 Unsigned_32'Asm_Output ("=m", Flags);
25422 @end smallexample
25423 the @code{"m"} (memory) constraint tells the compiler that the variable
25424 @code{Flags} should be stored in a memory variable, thus preventing
25425 the optimizer from keeping it in a register.  In contrast,
25426 @smallexample
25427 Unsigned_32'Asm_Output ("=r", Flags);
25428 @end smallexample
25429 uses the @code{"r"} (register) constraint, telling the compiler to
25430 store the variable in a register.
25431
25432 If the constraint is preceded by the equal character (@strong{=}), it tells
25433 the compiler that the variable will be used to store data into it.
25434
25435 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25436 allowing the optimizer to choose whatever it deems best.
25437
25438 There are a fairly large number of constraints, but the ones that are
25439 most useful (for the Intel x86 processor) are the following:
25440
25441 @table @code
25442 @item =
25443 output constraint
25444 @item g
25445 global (i.e.@: can be stored anywhere)
25446 @item m
25447 in memory
25448 @item I
25449 a constant
25450 @item a
25451 use eax
25452 @item b
25453 use ebx
25454 @item c
25455 use ecx
25456 @item d
25457 use edx
25458 @item S
25459 use esi
25460 @item D
25461 use edi
25462 @item r
25463 use one of eax, ebx, ecx or edx
25464 @item q
25465 use one of eax, ebx, ecx, edx, esi or edi
25466 @end table
25467
25468 The full set of constraints is described in the gcc and @emph{as}
25469 documentation; note that it is possible to combine certain constraints
25470 in one constraint string.
25471
25472 You specify the association of an output variable with an assembler operand
25473 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25474 integer.  Thus in
25475 @smallexample @c ada
25476 @group
25477 Asm ("pushfl"          & LF & HT & -- push flags on stack
25478      "popl %%eax"      & LF & HT & -- load eax with flags
25479      "movl %%eax, %0",             -- store flags in variable
25480      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25481 @end group
25482 @end smallexample
25483 @noindent
25484 @code{%0} will be replaced in the expanded code by the appropriate operand,
25485 whatever
25486 the compiler decided for the @code{Flags} variable.
25487
25488 In general, you may have any number of output variables:
25489 @itemize @bullet
25490 @item
25491 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25492 @item
25493 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25494 of @code{Asm_Output} attributes
25495 @end itemize
25496
25497 For example:
25498 @smallexample @c ada
25499 @group
25500 Asm ("movl %%eax, %0" & LF & HT &
25501      "movl %%ebx, %1" & LF & HT &
25502      "movl %%ecx, %2",
25503      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25504                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25505                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25506 @end group
25507 @end smallexample
25508 @noindent
25509 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25510 in the Ada program.
25511
25512 As a variation on the @code{Get_Flags} example, we can use the constraints
25513 string to direct the compiler to store the eax register into the @code{Flags}
25514 variable, instead of including the store instruction explicitly in the
25515 @code{Asm} template string:
25516
25517 @smallexample @c ada
25518 @group
25519 with Interfaces; use Interfaces;
25520 with Ada.Text_IO; use Ada.Text_IO;
25521 with System.Machine_Code; use System.Machine_Code;
25522 procedure Get_Flags_2 is
25523    Flags : Unsigned_32;
25524    use ASCII;
25525 begin
25526    Asm ("pushfl"      & LF & HT & -- push flags on stack
25527         "popl %%eax",             -- save flags in eax
25528         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25529    Put_Line ("Flags register:" & Flags'Img);
25530 end Get_Flags_2;
25531 @end group
25532 @end smallexample
25533
25534 @noindent
25535 The @code{"a"} constraint tells the compiler that the @code{Flags}
25536 variable will come from the eax register. Here is the resulting code:
25537
25538 @smallexample
25539 @group
25540 #APP
25541    pushfl
25542    popl %eax
25543 #NO_APP
25544    movl %eax,-40(%ebp)
25545 @end group
25546 @end smallexample
25547
25548 @noindent
25549 The compiler generated the store of eax into Flags after
25550 expanding the assembler code.
25551
25552 Actually, there was no need to pop the flags into the eax register;
25553 more simply, we could just pop the flags directly into the program variable:
25554
25555 @smallexample @c ada
25556 @group
25557 with Interfaces; use Interfaces;
25558 with Ada.Text_IO; use Ada.Text_IO;
25559 with System.Machine_Code; use System.Machine_Code;
25560 procedure Get_Flags_3 is
25561    Flags : Unsigned_32;
25562    use ASCII;
25563 begin
25564    Asm ("pushfl"  & LF & HT & -- push flags on stack
25565         "pop %0",             -- save flags in Flags
25566         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25567    Put_Line ("Flags register:" & Flags'Img);
25568 end Get_Flags_3;
25569 @end group
25570 @end smallexample
25571
25572 @c ---------------------------------------------------------------------------
25573 @node Input Variables in Inline Assembler
25574 @section Input Variables in Inline Assembler
25575
25576 @noindent
25577 The example in this section illustrates how to specify the source operands
25578 for assembly language statements.
25579 The program simply increments its input value by 1:
25580
25581 @smallexample @c ada
25582 @group
25583 with Interfaces; use Interfaces;
25584 with Ada.Text_IO; use Ada.Text_IO;
25585 with System.Machine_Code; use System.Machine_Code;
25586 procedure Increment is
25587
25588    function Incr (Value : Unsigned_32) return Unsigned_32 is
25589       Result : Unsigned_32;
25590    begin
25591       Asm ("incl %0",
25592            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25593            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25594       return Result;
25595    end Incr;
25596
25597    Value : Unsigned_32;
25598
25599 begin
25600    Value := 5;
25601    Put_Line ("Value before is" & Value'Img);
25602    Value := Incr (Value);
25603    Put_Line ("Value after is" & Value'Img);
25604 end Increment;
25605 @end group
25606 @end smallexample
25607
25608 The @code{Outputs} parameter to @code{Asm} specifies
25609 that the result will be in the eax register and that it is to be stored
25610 in the @code{Result} variable.
25611
25612 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25613 but with an @code{Asm_Input} attribute.
25614 The @code{"="} constraint, indicating an output value, is not present.
25615
25616 You can have multiple input variables, in the same way that you can have more
25617 than one output variable.
25618
25619 The parameter count (%0, %1) etc, now starts at the first input
25620 statement, and continues with the output statements.
25621 When both parameters use the same variable, the
25622 compiler will treat them as the same %n operand, which is the case here.
25623
25624 Just as the @code{Outputs} parameter causes the register to be stored into the
25625 target variable after execution of the assembler statements, so does the
25626 @code{Inputs} parameter cause its variable to be loaded into the register
25627 before execution of the assembler statements.
25628
25629 Thus the effect of the @code{Asm} invocation is:
25630 @enumerate
25631 @item load the 32-bit value of @code{Value} into eax
25632 @item execute the @code{incl %eax} instruction
25633 @item store the contents of eax into the @code{Result} variable
25634 @end enumerate
25635
25636 The resulting assembler file (with @option{-O2} optimization) contains:
25637 @smallexample
25638 @group
25639 _increment__incr.1:
25640    subl $4,%esp
25641    movl 8(%esp),%eax
25642 #APP
25643    incl %eax
25644 #NO_APP
25645    movl %eax,%edx
25646    movl %ecx,(%esp)
25647    addl $4,%esp
25648    ret
25649 @end group
25650 @end smallexample
25651
25652 @c ---------------------------------------------------------------------------
25653 @node Inlining Inline Assembler Code
25654 @section Inlining Inline Assembler Code
25655
25656 @noindent
25657 For a short subprogram such as the @code{Incr} function in the previous
25658 section, the overhead of the call and return (creating / deleting the stack
25659 frame) can be significant, compared to the amount of code in the subprogram
25660 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25661 which directs the compiler to expand invocations of the subprogram at the
25662 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25663 Here is the resulting program:
25664
25665 @smallexample @c ada
25666 @group
25667 with Interfaces; use Interfaces;
25668 with Ada.Text_IO; use Ada.Text_IO;
25669 with System.Machine_Code; use System.Machine_Code;
25670 procedure Increment_2 is
25671
25672    function Incr (Value : Unsigned_32) return Unsigned_32 is
25673       Result : Unsigned_32;
25674    begin
25675       Asm ("incl %0",
25676            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25677            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25678       return Result;
25679    end Incr;
25680    pragma Inline (Increment);
25681
25682    Value : Unsigned_32;
25683
25684 begin
25685    Value := 5;
25686    Put_Line ("Value before is" & Value'Img);
25687    Value := Increment (Value);
25688    Put_Line ("Value after is" & Value'Img);
25689 end Increment_2;
25690 @end group
25691 @end smallexample
25692
25693 Compile the program with both optimization (@option{-O2}) and inlining
25694 (@option{-gnatn}) enabled.
25695
25696 The @code{Incr} function is still compiled as usual, but at the
25697 point in @code{Increment} where our function used to be called:
25698
25699 @smallexample
25700 @group
25701 pushl %edi
25702 call _increment__incr.1
25703 @end group
25704 @end smallexample
25705
25706 @noindent
25707 the code for the function body directly appears:
25708
25709 @smallexample
25710 @group
25711 movl %esi,%eax
25712 #APP
25713    incl %eax
25714 #NO_APP
25715    movl %eax,%edx
25716 @end group
25717 @end smallexample
25718
25719 @noindent
25720 thus saving the overhead of stack frame setup and an out-of-line call.
25721
25722 @c ---------------------------------------------------------------------------
25723 @node Other Asm Functionality
25724 @section Other @code{Asm} Functionality
25725
25726 @noindent
25727 This section describes two important parameters to the @code{Asm}
25728 procedure: @code{Clobber}, which identifies register usage;
25729 and @code{Volatile}, which inhibits unwanted optimizations.
25730
25731 @menu
25732 * The Clobber Parameter::
25733 * The Volatile Parameter::
25734 @end menu
25735
25736 @c ---------------------------------------------------------------------------
25737 @node The Clobber Parameter
25738 @subsection The @code{Clobber} Parameter
25739
25740 @noindent
25741 One of the dangers of intermixing assembly language and a compiled language
25742 such as Ada is that the compiler needs to be aware of which registers are
25743 being used by the assembly code.  In some cases, such as the earlier examples,
25744 the constraint string is sufficient to indicate register usage (e.g.,
25745 @code{"a"} for
25746 the eax register).  But more generally, the compiler needs an explicit
25747 identification of the registers that are used by the Inline Assembly
25748 statements.
25749
25750 Using a register that the compiler doesn't know about
25751 could be a side effect of an instruction (like @code{mull}
25752 storing its result in both eax and edx).
25753 It can also arise from explicit register usage in your
25754 assembly code; for example:
25755 @smallexample
25756 @group
25757 Asm ("movl %0, %%ebx" & LF & HT &
25758      "movl %%ebx, %1",
25759      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25760      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25761 @end group
25762 @end smallexample
25763 @noindent
25764 where the compiler (since it does not analyze the @code{Asm} template string)
25765 does not know you are using the ebx register.
25766
25767 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25768 to identify the registers that will be used by your assembly code:
25769
25770 @smallexample
25771 @group
25772 Asm ("movl %0, %%ebx" & LF & HT &
25773      "movl %%ebx, %1",
25774      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25775      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25776      Clobber => "ebx");
25777 @end group
25778 @end smallexample
25779
25780 The Clobber parameter is a static string expression specifying the
25781 register(s) you are using.  Note that register names are @emph{not} prefixed
25782 by a percent sign. Also, if more than one register is used then their names
25783 are separated by commas; e.g., @code{"eax, ebx"}
25784
25785 The @code{Clobber} parameter has several additional uses:
25786 @enumerate
25787 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25788 @item Use ``register'' name @code{memory} if you changed a memory location
25789 @end enumerate
25790
25791 @c ---------------------------------------------------------------------------
25792 @node The Volatile Parameter
25793 @subsection The @code{Volatile} Parameter
25794 @cindex Volatile parameter
25795
25796 @noindent
25797 Compiler optimizations in the presence of Inline Assembler may sometimes have
25798 unwanted effects.  For example, when an @code{Asm} invocation with an input
25799 variable is inside a loop, the compiler might move the loading of the input
25800 variable outside the loop, regarding it as a one-time initialization.
25801
25802 If this effect is not desired, you can disable such optimizations by setting
25803 the @code{Volatile} parameter to @code{True}; for example:
25804
25805 @smallexample @c ada
25806 @group
25807 Asm ("movl %0, %%ebx" & LF & HT &
25808      "movl %%ebx, %1",
25809      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25810      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25811      Clobber  => "ebx",
25812      Volatile => True);
25813 @end group
25814 @end smallexample
25815
25816 By default, @code{Volatile} is set to @code{False} unless there is no
25817 @code{Outputs} parameter.
25818
25819 Although setting @code{Volatile} to @code{True} prevents unwanted
25820 optimizations, it will also disable other optimizations that might be
25821 important for efficiency. In general, you should set @code{Volatile}
25822 to @code{True} only if the compiler's optimizations have created
25823 problems.
25824 @c END OF INLINE ASSEMBLER CHAPTER
25825 @c ===============================
25826
25827 @c ***********************************
25828 @c * Compatibility and Porting Guide *
25829 @c ***********************************
25830 @node Compatibility and Porting Guide
25831 @appendix Compatibility and Porting Guide
25832
25833 @noindent
25834 This chapter describes the compatibility issues that may arise between
25835 GNAT and other Ada compilation systems (including those for Ada 83),
25836 and shows how GNAT can expedite porting
25837 applications developed in other Ada environments.
25838
25839 @menu
25840 * Compatibility with Ada 83::
25841 * Compatibility between Ada 95 and Ada 2005::
25842 * Implementation-dependent characteristics::
25843 * Compatibility with Other Ada Systems::
25844 * Representation Clauses::
25845 @ifclear vms
25846 @c Brief section is only in non-VMS version
25847 @c Full chapter is in VMS version
25848 * Compatibility with HP Ada 83::
25849 @end ifclear
25850 @ifset vms
25851 * Transitioning to 64-Bit GNAT for OpenVMS::
25852 @end ifset
25853 @end menu
25854
25855 @node Compatibility with Ada 83
25856 @section Compatibility with Ada 83
25857 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25858
25859 @noindent
25860 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25861 particular, the design intention was that the difficulties associated
25862 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25863 that occur when moving from one Ada 83 system to another.
25864
25865 However, there are a number of points at which there are minor
25866 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25867 full details of these issues,
25868 and should be consulted for a complete treatment.
25869 In practice the
25870 following subsections treat the most likely issues to be encountered.
25871
25872 @menu
25873 * Legal Ada 83 programs that are illegal in Ada 95::
25874 * More deterministic semantics::
25875 * Changed semantics::
25876 * Other language compatibility issues::
25877 @end menu
25878
25879 @node Legal Ada 83 programs that are illegal in Ada 95
25880 @subsection Legal Ada 83 programs that are illegal in Ada 95
25881
25882 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25883 Ada 95 and thus also in Ada 2005:
25884
25885 @table @emph
25886 @item Character literals
25887 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25888 @code{Wide_Character} as a new predefined character type, some uses of
25889 character literals that were legal in Ada 83 are illegal in Ada 95.
25890 For example:
25891 @smallexample @c ada
25892    for Char in 'A' .. 'Z' loop @dots{} end loop;
25893 @end smallexample
25894
25895 @noindent
25896 The problem is that @code{'A'} and @code{'Z'} could be from either
25897 @code{Character} or @code{Wide_Character}.  The simplest correction
25898 is to make the type explicit; e.g.:
25899 @smallexample @c ada
25900    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25901 @end smallexample
25902
25903 @item New reserved words
25904 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25905 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25906 Existing Ada 83 code using any of these identifiers must be edited to
25907 use some alternative name.
25908
25909 @item Freezing rules
25910 The rules in Ada 95 are slightly different with regard to the point at
25911 which entities are frozen, and representation pragmas and clauses are
25912 not permitted past the freeze point.  This shows up most typically in
25913 the form of an error message complaining that a representation item
25914 appears too late, and the appropriate corrective action is to move
25915 the item nearer to the declaration of the entity to which it refers.
25916
25917 A particular case is that representation pragmas
25918 @ifset vms
25919 (including the
25920 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25921 @end ifset
25922 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25923 declaration must be introduced to which the pragma can be applied.
25924
25925 @item Optional bodies for library packages
25926 In Ada 83, a package that did not require a package body was nevertheless
25927 allowed to have one.  This lead to certain surprises in compiling large
25928 systems (situations in which the body could be unexpectedly ignored by the
25929 binder).  In Ada 95, if a package does not require a body then it is not
25930 permitted to have a body.  To fix this problem, simply remove a redundant
25931 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25932 into the spec that makes the body required.  One approach is to add a private
25933 part to the package declaration (if necessary), and define a parameterless
25934 procedure called @code{Requires_Body}, which must then be given a dummy
25935 procedure body in the package body, which then becomes required.
25936 Another approach (assuming that this does not introduce elaboration
25937 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25938 since one effect of this pragma is to require the presence of a package body.
25939
25940 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25941 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25942 @code{Constraint_Error}.
25943 This means that it is illegal to have separate exception handlers for
25944 the two exceptions.  The fix is simply to remove the handler for the
25945 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25946 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25947
25948 @item Indefinite subtypes in generics
25949 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25950 as the actual for a generic formal private type, but then the instantiation
25951 would be illegal if there were any instances of declarations of variables
25952 of this type in the generic body.  In Ada 95, to avoid this clear violation
25953 of the methodological principle known as the ``contract model'',
25954 the generic declaration explicitly indicates whether
25955 or not such instantiations are permitted.  If a generic formal parameter
25956 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25957 type name, then it can be instantiated with indefinite types, but no
25958 stand-alone variables can be declared of this type.  Any attempt to declare
25959 such a variable will result in an illegality at the time the generic is
25960 declared.  If the @code{(<>)} notation is not used, then it is illegal
25961 to instantiate the generic with an indefinite type.
25962 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25963 It will show up as a compile time error, and
25964 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25965 @end table
25966
25967 @node More deterministic semantics
25968 @subsection More deterministic semantics
25969
25970 @table @emph
25971 @item Conversions
25972 Conversions from real types to integer types round away from 0.  In Ada 83
25973 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25974 implementation freedom was intended to support unbiased rounding in
25975 statistical applications, but in practice it interfered with portability.
25976 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25977 is required.  Numeric code may be affected by this change in semantics.
25978 Note, though, that this issue is no worse than already existed in Ada 83
25979 when porting code from one vendor to another.
25980
25981 @item Tasking
25982 The Real-Time Annex introduces a set of policies that define the behavior of
25983 features that were implementation dependent in Ada 83, such as the order in
25984 which open select branches are executed.
25985 @end table
25986
25987 @node Changed semantics
25988 @subsection Changed semantics
25989
25990 @noindent
25991 The worst kind of incompatibility is one where a program that is legal in
25992 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25993 possible in Ada 83.  Fortunately this is extremely rare, but the one
25994 situation that you should be alert to is the change in the predefined type
25995 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25996
25997 @table @emph
25998 @item Range of type @code{Character}
25999 The range of @code{Standard.Character} is now the full 256 characters
26000 of Latin-1, whereas in most Ada 83 implementations it was restricted
26001 to 128 characters. Although some of the effects of
26002 this change will be manifest in compile-time rejection of legal
26003 Ada 83 programs it is possible for a working Ada 83 program to have
26004 a different effect in Ada 95, one that was not permitted in Ada 83.
26005 As an example, the expression
26006 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26007 delivers @code{255} as its value.
26008 In general, you should look at the logic of any
26009 character-processing Ada 83 program and see whether it needs to be adapted
26010 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26011 character handling package that may be relevant if code needs to be adapted
26012 to account for the additional Latin-1 elements.
26013 The desirable fix is to
26014 modify the program to accommodate the full character set, but in some cases
26015 it may be convenient to define a subtype or derived type of Character that
26016 covers only the restricted range.
26017 @cindex Latin-1
26018 @end table
26019
26020 @node Other language compatibility issues
26021 @subsection Other language compatibility issues
26022
26023 @table @emph
26024 @item @option{-gnat83} switch
26025 All implementations of GNAT provide a switch that causes GNAT to operate
26026 in Ada 83 mode.  In this mode, some but not all compatibility problems
26027 of the type described above are handled automatically.  For example, the
26028 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26029 as identifiers as in Ada 83.
26030 However,
26031 in practice, it is usually advisable to make the necessary modifications
26032 to the program to remove the need for using this switch.
26033 See @ref{Compiling Different Versions of Ada}.
26034
26035 @item Support for removed Ada 83 pragmas and attributes
26036 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26037 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26038 compilers are allowed, but not required, to implement these missing
26039 elements.  In contrast with some other compilers, GNAT implements all
26040 such pragmas and attributes, eliminating this compatibility concern.  These
26041 include @code{pragma Interface} and the floating point type attributes
26042 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26043 @end table
26044
26045
26046 @node Compatibility between Ada 95 and Ada 2005
26047 @section Compatibility between Ada 95 and Ada 2005
26048 @cindex Compatibility between Ada 95 and Ada 2005
26049
26050 @noindent
26051 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26052 a number of incompatibilities. Several are enumerated below;
26053 for a complete description please see the
26054 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26055 @cite{Rationale for Ada 2005}.
26056
26057 @table @emph
26058 @item New reserved words.
26059 The words @code{interface}, @code{overriding} and @code{synchronized} are
26060 reserved in Ada 2005.
26061 A pre-Ada 2005 program that uses any of these as an identifier will be
26062 illegal.
26063
26064 @item New declarations in predefined packages.
26065 A number of packages in the predefined environment contain new declarations:
26066 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26067 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26068 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26069 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26070 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26071 If an Ada 95 program does a @code{with} and @code{use} of any of these
26072 packages, the new declarations may cause name clashes.
26073
26074 @item Access parameters.
26075 A nondispatching subprogram with an access parameter cannot be renamed
26076 as a dispatching operation.  This was permitted in Ada 95.
26077
26078 @item Access types, discriminants, and constraints.
26079 Rule changes in this area have led to some incompatibilities; for example,
26080 constrained subtypes of some access types are not permitted in Ada 2005.
26081
26082 @item Aggregates for limited types.
26083 The allowance of aggregates for limited types in Ada 2005 raises the
26084 possibility of ambiguities in legal Ada 95 programs, since additional types
26085 now need to be considered in expression resolution.
26086
26087 @item Fixed-point multiplication and division.
26088 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26089 were legal in Ada 95 and invoked the predefined versions of these operations,
26090 are now ambiguous.
26091 The ambiguity may be resolved either by applying a type conversion to the
26092 expression, or by explicitly invoking the operation from package
26093 @code{Standard}.
26094
26095 @item Return-by-reference types.
26096 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26097 can declare a function returning a value from an anonymous access type.
26098 @end table
26099
26100
26101 @node Implementation-dependent characteristics
26102 @section Implementation-dependent characteristics
26103 @noindent
26104 Although the Ada language defines the semantics of each construct as
26105 precisely as practical, in some situations (for example for reasons of
26106 efficiency, or where the effect is heavily dependent on the host or target
26107 platform) the implementation is allowed some freedom.  In porting Ada 83
26108 code to GNAT, you need to be aware of whether / how the existing code
26109 exercised such implementation dependencies.  Such characteristics fall into
26110 several categories, and GNAT offers specific support in assisting the
26111 transition from certain Ada 83 compilers.
26112
26113 @menu
26114 * Implementation-defined pragmas::
26115 * Implementation-defined attributes::
26116 * Libraries::
26117 * Elaboration order::
26118 * Target-specific aspects::
26119 @end menu
26120
26121 @node Implementation-defined pragmas
26122 @subsection Implementation-defined pragmas
26123
26124 @noindent
26125 Ada compilers are allowed to supplement the language-defined pragmas, and
26126 these are a potential source of non-portability.  All GNAT-defined pragmas
26127 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26128 Reference Manual}, and these include several that are specifically
26129 intended to correspond to other vendors' Ada 83 pragmas.
26130 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26131 For compatibility with HP Ada 83, GNAT supplies the pragmas
26132 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26133 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26134 and @code{Volatile}.
26135 Other relevant pragmas include @code{External} and @code{Link_With}.
26136 Some vendor-specific
26137 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26138 recognized, thus
26139 avoiding compiler rejection of units that contain such pragmas; they are not
26140 relevant in a GNAT context and hence are not otherwise implemented.
26141
26142 @node Implementation-defined attributes
26143 @subsection Implementation-defined attributes
26144
26145 Analogous to pragmas, the set of attributes may be extended by an
26146 implementation.  All GNAT-defined attributes are described in
26147 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26148 Manual}, and these include several that are specifically intended
26149 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26150 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26151 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26152 @code{Type_Class}.
26153
26154 @node Libraries
26155 @subsection Libraries
26156 @noindent
26157 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26158 code uses vendor-specific libraries then there are several ways to manage
26159 this in Ada 95 or Ada 2005:
26160 @enumerate
26161 @item
26162 If the source code for the libraries (specs and bodies) are
26163 available, then the libraries can be migrated in the same way as the
26164 application.
26165 @item
26166 If the source code for the specs but not the bodies are
26167 available, then you can reimplement the bodies.
26168 @item
26169 Some features introduced by Ada 95 obviate the need for library support.  For
26170 example most Ada 83 vendors supplied a package for unsigned integers.  The
26171 Ada 95 modular type feature is the preferred way to handle this need, so
26172 instead of migrating or reimplementing the unsigned integer package it may
26173 be preferable to retrofit the application using modular types.
26174 @end enumerate
26175
26176 @node Elaboration order
26177 @subsection Elaboration order
26178 @noindent
26179 The implementation can choose any elaboration order consistent with the unit
26180 dependency relationship.  This freedom means that some orders can result in
26181 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26182 to invoke a subprogram its body has been elaborated, or to instantiate a
26183 generic before the generic body has been elaborated.  By default GNAT
26184 attempts to choose a safe order (one that will not encounter access before
26185 elaboration problems) by implicitly inserting @code{Elaborate} or
26186 @code{Elaborate_All} pragmas where
26187 needed.  However, this can lead to the creation of elaboration circularities
26188 and a resulting rejection of the program by gnatbind.  This issue is
26189 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26190 In brief, there are several
26191 ways to deal with this situation:
26192
26193 @itemize @bullet
26194 @item
26195 Modify the program to eliminate the circularities, e.g.@: by moving
26196 elaboration-time code into explicitly-invoked procedures
26197 @item
26198 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26199 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26200 @code{Elaborate_All}
26201 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26202 (by selectively suppressing elaboration checks via pragma
26203 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26204 @end itemize
26205
26206 @node Target-specific aspects
26207 @subsection Target-specific aspects
26208 @noindent
26209 Low-level applications need to deal with machine addresses, data
26210 representations, interfacing with assembler code, and similar issues.  If
26211 such an Ada 83 application is being ported to different target hardware (for
26212 example where the byte endianness has changed) then you will need to
26213 carefully examine the program logic; the porting effort will heavily depend
26214 on the robustness of the original design.  Moreover, Ada 95 (and thus
26215 Ada 2005) are sometimes
26216 incompatible with typical Ada 83 compiler practices regarding implicit
26217 packing, the meaning of the Size attribute, and the size of access values.
26218 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26219
26220 @node Compatibility with Other Ada Systems
26221 @section Compatibility with Other Ada Systems
26222
26223 @noindent
26224 If programs avoid the use of implementation dependent and
26225 implementation defined features, as documented in the @cite{Ada
26226 Reference Manual}, there should be a high degree of portability between
26227 GNAT and other Ada systems.  The following are specific items which
26228 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26229 compilers, but do not affect porting code to GNAT@.
26230 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26231 the following issues may or may not arise for Ada 2005 programs
26232 when other compilers appear.)
26233
26234 @table @emph
26235 @item Ada 83 Pragmas and Attributes
26236 Ada 95 compilers are allowed, but not required, to implement the missing
26237 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26238 GNAT implements all such pragmas and attributes, eliminating this as
26239 a compatibility concern, but some other Ada 95 compilers reject these
26240 pragmas and attributes.
26241
26242 @item Specialized Needs Annexes
26243 GNAT implements the full set of special needs annexes.  At the
26244 current time, it is the only Ada 95 compiler to do so.  This means that
26245 programs making use of these features may not be portable to other Ada
26246 95 compilation systems.
26247
26248 @item Representation Clauses
26249 Some other Ada 95 compilers implement only the minimal set of
26250 representation clauses required by the Ada 95 reference manual.  GNAT goes
26251 far beyond this minimal set, as described in the next section.
26252 @end table
26253
26254 @node Representation Clauses
26255 @section Representation Clauses
26256
26257 @noindent
26258 The Ada 83 reference manual was quite vague in describing both the minimal
26259 required implementation of representation clauses, and also their precise
26260 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26261 minimal set of capabilities required is still quite limited.
26262
26263 GNAT implements the full required set of capabilities in
26264 Ada 95 and Ada 2005, but also goes much further, and in particular
26265 an effort has been made to be compatible with existing Ada 83 usage to the
26266 greatest extent possible.
26267
26268 A few cases exist in which Ada 83 compiler behavior is incompatible with
26269 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26270 intentional or accidental dependence on specific implementation dependent
26271 characteristics of these Ada 83 compilers.  The following is a list of
26272 the cases most likely to arise in existing Ada 83 code.
26273
26274 @table @emph
26275 @item Implicit Packing
26276 Some Ada 83 compilers allowed a Size specification to cause implicit
26277 packing of an array or record.  This could cause expensive implicit
26278 conversions for change of representation in the presence of derived
26279 types, and the Ada design intends to avoid this possibility.
26280 Subsequent AI's were issued to make it clear that such implicit
26281 change of representation in response to a Size clause is inadvisable,
26282 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26283 Reference Manuals as implementation advice that is followed by GNAT@.
26284 The problem will show up as an error
26285 message rejecting the size clause.  The fix is simply to provide
26286 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26287 a Component_Size clause.
26288
26289 @item Meaning of Size Attribute
26290 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26291 the minimal number of bits required to hold values of the type.  For example,
26292 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26293 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26294 some 32 in this situation.  This problem will usually show up as a compile
26295 time error, but not always.  It is a good idea to check all uses of the
26296 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26297 Object_Size can provide a useful way of duplicating the behavior of
26298 some Ada 83 compiler systems.
26299
26300 @item Size of Access Types
26301 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26302 and that therefore it will be the same size as a System.Address value.  This
26303 assumption is true for GNAT in most cases with one exception.  For the case of
26304 a pointer to an unconstrained array type (where the bounds may vary from one
26305 value of the access type to another), the default is to use a ``fat pointer'',
26306 which is represented as two separate pointers, one to the bounds, and one to
26307 the array.  This representation has a number of advantages, including improved
26308 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26309 code which makes the assumption that, for example, pointers fit in 32 bits on
26310 a machine with 32-bit addressing.
26311
26312 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26313 access types in this case (where the designated type is an unconstrained array
26314 type).  These thin pointers are indeed the same size as a System.Address value.
26315 To specify a thin pointer, use a size clause for the type, for example:
26316
26317 @smallexample @c ada
26318 type X is access all String;
26319 for X'Size use Standard'Address_Size;
26320 @end smallexample
26321
26322 @noindent
26323 which will cause the type X to be represented using a single pointer.
26324 When using this representation, the bounds are right behind the array.
26325 This representation is slightly less efficient, and does not allow quite
26326 such flexibility in the use of foreign pointers or in using the
26327 Unrestricted_Access attribute to create pointers to non-aliased objects.
26328 But for any standard portable use of the access type it will work in
26329 a functionally correct manner and allow porting of existing code.
26330 Note that another way of forcing a thin pointer representation
26331 is to use a component size clause for the element size in an array,
26332 or a record representation clause for an access field in a record.
26333 @end table
26334
26335 @ifclear vms
26336 @c This brief section is only in the non-VMS version
26337 @c The complete chapter on HP Ada is in the VMS version
26338 @node Compatibility with HP Ada 83
26339 @section Compatibility with HP Ada 83
26340
26341 @noindent
26342 The VMS version of GNAT fully implements all the pragmas and attributes
26343 provided by HP Ada 83, as well as providing the standard HP Ada 83
26344 libraries, including Starlet.  In addition, data layouts and parameter
26345 passing conventions are highly compatible.  This means that porting
26346 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26347 most other porting efforts.  The following are some of the most
26348 significant differences between GNAT and HP Ada 83.
26349
26350 @table @emph
26351 @item Default floating-point representation
26352 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26353 it is VMS format.  GNAT does implement the necessary pragmas
26354 (Long_Float, Float_Representation) for changing this default.
26355
26356 @item System
26357 The package System in GNAT exactly corresponds to the definition in the
26358 Ada 95 reference manual, which means that it excludes many of the
26359 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26360 that contains the additional definitions, and a special pragma,
26361 Extend_System allows this package to be treated transparently as an
26362 extension of package System.
26363
26364 @item To_Address
26365 The definitions provided by Aux_DEC are exactly compatible with those
26366 in the HP Ada 83 version of System, with one exception.
26367 HP Ada provides the following declarations:
26368
26369 @smallexample @c ada
26370 TO_ADDRESS (INTEGER)
26371 TO_ADDRESS (UNSIGNED_LONGWORD)
26372 TO_ADDRESS (@i{universal_integer})
26373 @end smallexample
26374
26375 @noindent
26376 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26377 an extension to Ada 83 not strictly compatible with the reference manual.
26378 In GNAT, we are constrained to be exactly compatible with the standard,
26379 and this means we cannot provide this capability.  In HP Ada 83, the
26380 point of this definition is to deal with a call like:
26381
26382 @smallexample @c ada
26383 TO_ADDRESS (16#12777#);
26384 @end smallexample
26385
26386 @noindent
26387 Normally, according to the Ada 83 standard, one would expect this to be
26388 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26389 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26390 definition using @i{universal_integer} takes precedence.
26391
26392 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26393 is not possible to be 100% compatible.  Since there are many programs using
26394 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26395 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26396 declarations provided in the GNAT version of AUX_Dec are:
26397
26398 @smallexample @c ada
26399 function To_Address (X : Integer) return Address;
26400 pragma Pure_Function (To_Address);
26401
26402 function To_Address_Long (X : Unsigned_Longword)
26403  return Address;
26404 pragma Pure_Function (To_Address_Long);
26405 @end smallexample
26406
26407 @noindent
26408 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26409 change the name to TO_ADDRESS_LONG@.
26410
26411 @item Task_Id values
26412 The Task_Id values assigned will be different in the two systems, and GNAT
26413 does not provide a specified value for the Task_Id of the environment task,
26414 which in GNAT is treated like any other declared task.
26415 @end table
26416
26417 @noindent
26418 For full details on these and other less significant compatibility issues,
26419 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26420 Overview and Comparison on HP Platforms}.
26421
26422 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26423 attributes are recognized, although only a subset of them can sensibly
26424 be implemented.  The description of pragmas in @ref{Implementation
26425 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26426 indicates whether or not they are applicable to non-VMS systems.
26427 @end ifclear
26428
26429 @ifset vms
26430 @node Transitioning to 64-Bit GNAT for OpenVMS
26431 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26432
26433 @noindent
26434 This section is meant to assist users of pre-2006 @value{EDITION}
26435 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26436 the version of the GNAT technology supplied in 2006 and later for
26437 OpenVMS on both Alpha and I64.
26438
26439 @menu
26440 * Introduction to transitioning::
26441 * Migration of 32 bit code::
26442 * Taking advantage of 64 bit addressing::
26443 * Technical details::
26444 @end menu
26445
26446 @node Introduction to transitioning
26447 @subsection Introduction
26448
26449 @noindent
26450 64-bit @value{EDITION} for Open VMS has been designed to meet
26451 three main goals:
26452
26453 @enumerate
26454 @item
26455 Providing a full conforming implementation of Ada 95 and Ada 2005
26456
26457 @item
26458 Allowing maximum backward compatibility, thus easing migration of existing
26459 Ada source code
26460
26461 @item
26462 Supplying a path for exploiting the full 64-bit address range
26463 @end enumerate
26464
26465 @noindent
26466 Ada's strong typing semantics has made it
26467 impractical to have different 32-bit and 64-bit modes. As soon as
26468 one object could possibly be outside the 32-bit address space, this
26469 would make it necessary for the @code{System.Address} type to be 64 bits.
26470 In particular, this would cause inconsistencies if 32-bit code is
26471 called from 64-bit code that raises an exception.
26472
26473 This issue has been resolved by always using 64-bit addressing
26474 at the system level, but allowing for automatic conversions between
26475 32-bit and 64-bit addresses where required. Thus users who
26476 do not currently require 64-bit addressing capabilities, can
26477 recompile their code with only minimal changes (and indeed
26478 if the code is written in portable Ada, with no assumptions about
26479 the size of the @code{Address} type, then no changes at all are necessary).
26480 At the same time,
26481 this approach provides a simple, gradual upgrade path to future
26482 use of larger memories than available for 32-bit systems.
26483 Also, newly written applications or libraries will by default
26484 be fully compatible with future systems exploiting 64-bit
26485 addressing capabilities.
26486
26487 @ref{Migration of 32 bit code}, will focus on porting applications
26488 that do not require more than 2 GB of
26489 addressable memory. This code will be referred to as
26490 @emph{32-bit code}.
26491 For applications intending to exploit the full 64-bit address space,
26492 @ref{Taking advantage of 64 bit addressing},
26493 will consider further changes that may be required.
26494 Such code will be referred to below as @emph{64-bit code}.
26495
26496 @node Migration of 32 bit code
26497 @subsection Migration of 32-bit code
26498
26499 @menu
26500 * Address types::
26501 * Access types::
26502 * Unchecked conversions::
26503 * Predefined constants::
26504 * Interfacing with C::
26505 * Experience with source compatibility::
26506 @end menu
26507
26508 @node Address types
26509 @subsubsection Address types
26510
26511 @noindent
26512 To solve the problem of mixing 64-bit and 32-bit addressing,
26513 while maintaining maximum backward compatibility, the following
26514 approach has been taken:
26515
26516 @itemize @bullet
26517 @item
26518 @code{System.Address} always has a size of 64 bits
26519
26520 @item
26521 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26522 @end itemize
26523
26524 @noindent
26525 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26526 a @code{Short_Address}
26527 may be used where an @code{Address} is required, and vice versa, without
26528 needing explicit type conversions.
26529 By virtue of the Open VMS parameter passing conventions,
26530 even imported
26531 and exported subprograms that have 32-bit address parameters are
26532 compatible with those that have 64-bit address parameters.
26533 (See @ref{Making code 64 bit clean} for details.)
26534
26535 The areas that may need attention are those where record types have
26536 been defined that contain components of the type @code{System.Address}, and
26537 where objects of this type are passed to code expecting a record layout with
26538 32-bit addresses.
26539
26540 Different compilers on different platforms cannot be
26541 expected to represent the same type in the same way,
26542 since alignment constraints
26543 and other system-dependent properties affect the compiler's decision.
26544 For that reason, Ada code
26545 generally uses representation clauses to specify the expected
26546 layout where required.
26547
26548 If such a representation clause uses 32 bits for a component having
26549 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26550 will detect that error and produce a specific diagnostic message.
26551 The developer should then determine whether the representation
26552 should be 64 bits or not and make either of two changes:
26553 change the size to 64 bits and leave the type as @code{System.Address}, or
26554 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26555 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26556 required in any code setting or accessing the field; the compiler will
26557 automatically perform any needed conversions between address
26558 formats.
26559
26560 @node Access types
26561 @subsubsection Access types
26562
26563 @noindent
26564 By default, objects designated by access values are always
26565 allocated in the 32-bit
26566 address space. Thus legacy code will never contain
26567 any objects that are not addressable with 32-bit addresses, and
26568 the compiler will never raise exceptions as result of mixing
26569 32-bit and 64-bit addresses.
26570
26571 However, the access values themselves are represented in 64 bits, for optimum
26572 performance and future compatibility with 64-bit code. As was
26573 the case with @code{System.Address}, the compiler will give an error message
26574 if an object or record component has a representation clause that
26575 requires the access value to fit in 32 bits. In such a situation,
26576 an explicit size clause for the access type, specifying 32 bits,
26577 will have the desired effect.
26578
26579 General access types (declared with @code{access all}) can never be
26580 32 bits, as values of such types must be able to refer to any object
26581 of the  designated type,
26582 including objects residing outside the 32-bit address range.
26583 Existing Ada 83 code will not contain such type definitions,
26584 however, since general access types were introduced in Ada 95.
26585
26586 @node Unchecked conversions
26587 @subsubsection Unchecked conversions
26588
26589 @noindent
26590 In the case of an @code{Unchecked_Conversion} where the source type is a
26591 64-bit access type or the type @code{System.Address}, and the target
26592 type is a 32-bit type, the compiler will generate a warning.
26593 Even though the generated code will still perform the required
26594 conversions, it is highly recommended in these cases to use
26595 respectively a 32-bit access type or @code{System.Short_Address}
26596 as the source type.
26597
26598 @node Predefined constants
26599 @subsubsection Predefined constants
26600
26601 @noindent
26602 The following table shows the correspondence between pre-2006 versions of
26603 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26604 (``New''):
26605
26606 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26607 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26608 @item   @code{System.Word_Size}          @tab 32      @tab 64
26609 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26610 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26611 @item   @code{System.Address_Size}       @tab 32      @tab 64
26612 @end multitable
26613
26614 @noindent
26615 If you need to refer to the specific
26616 memory size of a 32-bit implementation, instead of the
26617 actual memory size, use @code{System.Short_Memory_Size}
26618 rather than @code{System.Memory_Size}.
26619 Similarly, references to @code{System.Address_Size} may need
26620 to be replaced by @code{System.Short_Address'Size}.
26621 The program @command{gnatfind} may be useful for locating
26622 references to the above constants, so that you can verify that they
26623 are still correct.
26624
26625 @node Interfacing with C
26626 @subsubsection Interfacing with C
26627
26628 @noindent
26629 In order to minimize the impact of the transition to 64-bit addresses on
26630 legacy programs, some fundamental types in the @code{Interfaces.C}
26631 package hierarchy continue to be represented in 32 bits.
26632 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26633 This eases integration with the default HP C layout choices, for example
26634 as found in the system routines in @code{DECC$SHR.EXE}.
26635 Because of this implementation choice, the type fully compatible with
26636 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26637 Depending on the context the compiler will issue a
26638 warning or an error when type @code{Address} is used, alerting the user to a
26639 potential problem. Otherwise 32-bit programs that use
26640 @code{Interfaces.C} should normally not require code modifications
26641
26642 The other issue arising with C interfacing concerns pragma @code{Convention}.
26643 For VMS 64-bit systems, there is an issue of the appropriate default size
26644 of C convention pointers in the absence of an explicit size clause. The HP
26645 C compiler can choose either 32 or 64 bits depending on compiler options.
26646 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26647 clause is given. This proves a better choice for porting 32-bit legacy
26648 applications. In order to have a 64-bit representation, it is necessary to
26649 specify a size representation clause. For example:
26650
26651 @smallexample @c ada
26652 type int_star is access Interfaces.C.int;
26653 pragma Convention(C, int_star);
26654 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26655 @end smallexample
26656
26657 @node Experience with source compatibility
26658 @subsubsection Experience with source compatibility
26659
26660 @noindent
26661 The Security Server and STARLET on I64 provide an interesting ``test case''
26662 for source compatibility issues, since it is in such system code
26663 where assumptions about @code{Address} size might be expected to occur.
26664 Indeed, there were a small number of occasions in the Security Server
26665 file @file{jibdef.ads}
26666 where a representation clause for a record type specified
26667 32 bits for a component of type @code{Address}.
26668 All of these errors were detected by the compiler.
26669 The repair was obvious and immediate; to simply replace @code{Address} by
26670 @code{Short_Address}.
26671
26672 In the case of STARLET, there were several record types that should
26673 have had representation clauses but did not.  In these record types
26674 there was an implicit assumption that an @code{Address} value occupied
26675 32 bits.
26676 These compiled without error, but their usage resulted in run-time error
26677 returns from STARLET system calls.
26678 Future GNAT technology enhancements may include a tool that detects and flags
26679 these sorts of potential source code porting problems.
26680
26681 @c ****************************************
26682 @node Taking advantage of 64 bit addressing
26683 @subsection Taking advantage of 64-bit addressing
26684
26685 @menu
26686 * Making code 64 bit clean::
26687 * Allocating memory from the 64 bit storage pool::
26688 * Restrictions on use of 64 bit objects::
26689 * Using 64 bit storage pools by default::
26690 * General access types::
26691 * STARLET and other predefined libraries::
26692 @end menu
26693
26694 @node Making code 64 bit clean
26695 @subsubsection Making code 64-bit clean
26696
26697 @noindent
26698 In order to prevent problems that may occur when (parts of) a
26699 system start using memory outside the 32-bit address range,
26700 we recommend some additional guidelines:
26701
26702 @itemize @bullet
26703 @item
26704 For imported subprograms that take parameters of the
26705 type @code{System.Address}, ensure that these subprograms can
26706 indeed handle 64-bit addresses. If not, or when in doubt,
26707 change the subprogram declaration to specify
26708 @code{System.Short_Address} instead.
26709
26710 @item
26711 Resolve all warnings related to size mismatches in
26712 unchecked conversions. Failing to do so causes
26713 erroneous execution if the source object is outside
26714 the 32-bit address space.
26715
26716 @item
26717 (optional) Explicitly use the 32-bit storage pool
26718 for access types used in a 32-bit context, or use
26719 generic access types where possible
26720 (@pxref{Restrictions on use of 64 bit objects}).
26721 @end itemize
26722
26723 @noindent
26724 If these rules are followed, the compiler will automatically insert
26725 any necessary checks to ensure that no addresses or access values
26726 passed to 32-bit code ever refer to objects outside the 32-bit
26727 address range.
26728 Any attempt to do this will raise @code{Constraint_Error}.
26729
26730 @node Allocating memory from the 64 bit storage pool
26731 @subsubsection Allocating memory from the 64-bit storage pool
26732
26733 @noindent
26734 For any access type @code{T} that potentially requires memory allocations
26735 beyond the 32-bit address space,
26736 use the following representation clause:
26737
26738 @smallexample @c ada
26739    for T'Storage_Pool use System.Pool_64;
26740 @end smallexample
26741
26742 @node Restrictions on use of 64 bit objects
26743 @subsubsection Restrictions on use of 64-bit objects
26744
26745 @noindent
26746 Taking the address of an object allocated from a 64-bit storage pool,
26747 and then passing this address to a subprogram expecting
26748 @code{System.Short_Address},
26749 or assigning it to a variable of type @code{Short_Address}, will cause
26750 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26751 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26752 no exception is raised and execution
26753 will become erroneous.
26754
26755 @node Using 64 bit storage pools by default
26756 @subsubsection Using 64-bit storage pools by default
26757
26758 @noindent
26759 In some cases it may be desirable to have the compiler allocate
26760 from 64-bit storage pools by default. This may be the case for
26761 libraries that are 64-bit clean, but may be used in both 32-bit
26762 and 64-bit contexts. For these cases the following configuration
26763 pragma may be specified:
26764
26765 @smallexample @c ada
26766   pragma Pool_64_Default;
26767 @end smallexample
26768
26769 @noindent
26770 Any code compiled in the context of this pragma will by default
26771 use the @code{System.Pool_64} storage pool. This default may be overridden
26772 for a specific access type @code{T} by the representation clause:
26773
26774 @smallexample @c ada
26775    for T'Storage_Pool use System.Pool_32;
26776 @end smallexample
26777
26778 @noindent
26779 Any object whose address may be passed to a subprogram with a
26780 @code{Short_Address} argument, or assigned to a variable of type
26781 @code{Short_Address}, needs to be allocated from this pool.
26782
26783 @node General access types
26784 @subsubsection General access types
26785
26786 @noindent
26787 Objects designated by access values from a
26788 general access type (declared with @code{access all}) are never allocated
26789 from a 64-bit storage pool. Code that uses general access types will
26790 accept objects allocated in either 32-bit or 64-bit address spaces,
26791 but never allocate objects outside the 32-bit address space.
26792 Using general access types ensures maximum compatibility with both
26793 32-bit and 64-bit code.
26794
26795 @node STARLET and other predefined libraries
26796 @subsubsection STARLET and other predefined libraries
26797
26798 @noindent
26799 All code that comes as part of GNAT is 64-bit clean, but the
26800 restrictions given in @ref{Restrictions on use of 64 bit objects},
26801 still apply. Look at the package
26802 specs to see in which contexts objects allocated
26803 in 64-bit address space are acceptable.
26804
26805 @node Technical details
26806 @subsection Technical details
26807
26808 @noindent
26809 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26810 Ada standard with respect to the type of @code{System.Address}. Previous
26811 versions of GNAT Pro have defined this type as private and implemented it as a
26812 modular type.
26813
26814 In order to allow defining @code{System.Short_Address} as a proper subtype,
26815 and to match the implicit sign extension in parameter passing,
26816 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26817 visible (i.e., non-private) integer type.
26818 Standard operations on the type, such as the binary operators ``+'', ``-'',
26819 etc., that take @code{Address} operands and return an @code{Address} result,
26820 have been hidden by declaring these
26821 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26822 ambiguities that would otherwise result from overloading.
26823 (Note that, although @code{Address} is a visible integer type,
26824 good programming practice dictates against exploiting the type's
26825 integer properties such as literals, since this will compromise
26826 code portability.)
26827
26828 Defining @code{Address} as a visible integer type helps achieve
26829 maximum compatibility for existing Ada code,
26830 without sacrificing the capabilities of the 64-bit architecture.
26831 @end ifset
26832
26833 @c ************************************************
26834 @ifset unw
26835 @node Microsoft Windows Topics
26836 @appendix Microsoft Windows Topics
26837 @cindex Windows NT
26838 @cindex Windows 95
26839 @cindex Windows 98
26840
26841 @noindent
26842 This chapter describes topics that are specific to the Microsoft Windows
26843 platforms (NT, 2000, and XP Professional).
26844
26845 @menu
26846 * Using GNAT on Windows::
26847 * Using a network installation of GNAT::
26848 * CONSOLE and WINDOWS subsystems::
26849 * Temporary Files::
26850 * Mixed-Language Programming on Windows::
26851 * Windows Calling Conventions::
26852 * Introduction to Dynamic Link Libraries (DLLs)::
26853 * Using DLLs with GNAT::
26854 * Building DLLs with GNAT Project files::
26855 * Building DLLs with GNAT::
26856 * Building DLLs with gnatdll::
26857 * GNAT and Windows Resources::
26858 * Debugging a DLL::
26859 * Setting Stack Size from gnatlink::
26860 * Setting Heap Size from gnatlink::
26861 @end menu
26862
26863 @node Using GNAT on Windows
26864 @section Using GNAT on Windows
26865
26866 @noindent
26867 One of the strengths of the GNAT technology is that its tool set
26868 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26869 @code{gdb} debugger, etc.) is used in the same way regardless of the
26870 platform.
26871
26872 On Windows this tool set is complemented by a number of Microsoft-specific
26873 tools that have been provided to facilitate interoperability with Windows
26874 when this is required. With these tools:
26875
26876 @itemize @bullet
26877
26878 @item
26879 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26880 subsystems.
26881
26882 @item
26883 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26884 relocatable and non-relocatable DLLs are supported).
26885
26886 @item
26887 You can build Ada DLLs for use in other applications. These applications
26888 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26889 relocatable and non-relocatable Ada DLLs are supported.
26890
26891 @item
26892 You can include Windows resources in your Ada application.
26893
26894 @item
26895 You can use or create COM/DCOM objects.
26896 @end itemize
26897
26898 @noindent
26899 Immediately below are listed all known general GNAT-for-Windows restrictions.
26900 Other restrictions about specific features like Windows Resources and DLLs
26901 are listed in separate sections below.
26902
26903 @itemize @bullet
26904
26905 @item
26906 It is not possible to use @code{GetLastError} and @code{SetLastError}
26907 when tasking, protected records, or exceptions are used. In these
26908 cases, in order to implement Ada semantics, the GNAT run-time system
26909 calls certain Win32 routines that set the last error variable to 0 upon
26910 success. It should be possible to use @code{GetLastError} and
26911 @code{SetLastError} when tasking, protected record, and exception
26912 features are not used, but it is not guaranteed to work.
26913
26914 @item
26915 It is not possible to link against Microsoft libraries except for
26916 import libraries. Interfacing must be done by the mean of DLLs.
26917
26918 @item
26919 When the compilation environment is located on FAT32 drives, users may
26920 experience recompilations of the source files that have not changed if
26921 Daylight Saving Time (DST) state has changed since the last time files
26922 were compiled. NTFS drives do not have this problem.
26923
26924 @item
26925 No components of the GNAT toolset use any entries in the Windows
26926 registry. The only entries that can be created are file associations and
26927 PATH settings, provided the user has chosen to create them at installation
26928 time, as well as some minimal book-keeping information needed to correctly
26929 uninstall or integrate different GNAT products.
26930 @end itemize
26931
26932 @node Using a network installation of GNAT
26933 @section Using a network installation of GNAT
26934
26935 @noindent
26936 Make sure the system on which GNAT is installed is accessible from the
26937 current machine, i.e., the install location is shared over the network.
26938 Shared resources are accessed on Windows by means of UNC paths, which
26939 have the format @code{\\server\sharename\path}
26940
26941 In order to use such a network installation, simply add the UNC path of the
26942 @file{bin} directory of your GNAT installation in front of your PATH. For
26943 example, if GNAT is installed in @file{\GNAT} directory of a share location
26944 called @file{c-drive} on a machine @file{LOKI}, the following command will
26945 make it available:
26946
26947 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26948
26949 Be aware that every compilation using the network installation results in the
26950 transfer of large amounts of data across the network and will likely cause
26951 serious performance penalty.
26952
26953 @node CONSOLE and WINDOWS subsystems
26954 @section CONSOLE and WINDOWS subsystems
26955 @cindex CONSOLE Subsystem
26956 @cindex WINDOWS Subsystem
26957 @cindex -mwindows
26958
26959 @noindent
26960 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26961 (which is the default subsystem) will always create a console when
26962 launching the application. This is not something desirable when the
26963 application has a Windows GUI. To get rid of this console the
26964 application must be using the @code{WINDOWS} subsystem. To do so
26965 the @option{-mwindows} linker option must be specified.
26966
26967 @smallexample
26968 $ gnatmake winprog -largs -mwindows
26969 @end smallexample
26970
26971 @node Temporary Files
26972 @section Temporary Files
26973 @cindex Temporary files
26974
26975 @noindent
26976 It is possible to control where temporary files gets created by setting
26977 the @env{TMP} environment variable. The file will be created:
26978
26979 @itemize
26980 @item Under the directory pointed to by the @env{TMP} environment variable if
26981 this directory exists.
26982
26983 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26984 set (or not pointing to a directory) and if this directory exists.
26985
26986 @item Under the current working directory otherwise.
26987 @end itemize
26988
26989 @noindent
26990 This allows you to determine exactly where the temporary
26991 file will be created. This is particularly useful in networked
26992 environments where you may not have write access to some
26993 directories.
26994
26995 @node Mixed-Language Programming on Windows
26996 @section Mixed-Language Programming on Windows
26997
26998 @noindent
26999 Developing pure Ada applications on Windows is no different than on
27000 other GNAT-supported platforms. However, when developing or porting an
27001 application that contains a mix of Ada and C/C++, the choice of your
27002 Windows C/C++ development environment conditions your overall
27003 interoperability strategy.
27004
27005 If you use @command{gcc} to compile the non-Ada part of your application,
27006 there are no Windows-specific restrictions that affect the overall
27007 interoperability with your Ada code. If you do want to use the
27008 Microsoft tools for your non-Ada code, you have two choices:
27009
27010 @enumerate
27011 @item
27012 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27013 application. In this case, use the Microsoft or whatever environment to
27014 build the DLL and use GNAT to build your executable
27015 (@pxref{Using DLLs with GNAT}).
27016
27017 @item
27018 Or you can encapsulate your Ada code in a DLL to be linked with the
27019 other part of your application. In this case, use GNAT to build the DLL
27020 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27021 or whatever environment to build your executable.
27022 @end enumerate
27023
27024 @node Windows Calling Conventions
27025 @section Windows Calling Conventions
27026 @findex Stdcall
27027 @findex APIENTRY
27028
27029 This section pertain only to Win32. On Win64 there is a single native
27030 calling convention. All convention specifiers are ignored on this
27031 platform.
27032
27033 @menu
27034 * C Calling Convention::
27035 * Stdcall Calling Convention::
27036 * Win32 Calling Convention::
27037 * DLL Calling Convention::
27038 @end menu
27039
27040 @noindent
27041 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27042 (callee), there are several ways to push @code{G}'s parameters on the
27043 stack and there are several possible scenarios to clean up the stack
27044 upon @code{G}'s return. A calling convention is an agreed upon software
27045 protocol whereby the responsibilities between the caller (@code{F}) and
27046 the callee (@code{G}) are clearly defined. Several calling conventions
27047 are available for Windows:
27048
27049 @itemize @bullet
27050 @item
27051 @code{C} (Microsoft defined)
27052
27053 @item
27054 @code{Stdcall} (Microsoft defined)
27055
27056 @item
27057 @code{Win32} (GNAT specific)
27058
27059 @item
27060 @code{DLL} (GNAT specific)
27061 @end itemize
27062
27063 @node C Calling Convention
27064 @subsection @code{C} Calling Convention
27065
27066 @noindent
27067 This is the default calling convention used when interfacing to C/C++
27068 routines compiled with either @command{gcc} or Microsoft Visual C++.
27069
27070 In the @code{C} calling convention subprogram parameters are pushed on the
27071 stack by the caller from right to left. The caller itself is in charge of
27072 cleaning up the stack after the call. In addition, the name of a routine
27073 with @code{C} calling convention is mangled by adding a leading underscore.
27074
27075 The name to use on the Ada side when importing (or exporting) a routine
27076 with @code{C} calling convention is the name of the routine. For
27077 instance the C function:
27078
27079 @smallexample
27080 int get_val (long);
27081 @end smallexample
27082
27083 @noindent
27084 should be imported from Ada as follows:
27085
27086 @smallexample @c ada
27087 @group
27088 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27089 pragma Import (C, Get_Val, External_Name => "get_val");
27090 @end group
27091 @end smallexample
27092
27093 @noindent
27094 Note that in this particular case the @code{External_Name} parameter could
27095 have been omitted since, when missing, this parameter is taken to be the
27096 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27097 is missing, as in the above example, this parameter is set to be the
27098 @code{External_Name} with a leading underscore.
27099
27100 When importing a variable defined in C, you should always use the @code{C}
27101 calling convention unless the object containing the variable is part of a
27102 DLL (in which case you should use the @code{Stdcall} calling
27103 convention, @pxref{Stdcall Calling Convention}).
27104
27105 @node Stdcall Calling Convention
27106 @subsection @code{Stdcall} Calling Convention
27107
27108 @noindent
27109 This convention, which was the calling convention used for Pascal
27110 programs, is used by Microsoft for all the routines in the Win32 API for
27111 efficiency reasons. It must be used to import any routine for which this
27112 convention was specified.
27113
27114 In the @code{Stdcall} calling convention subprogram parameters are pushed
27115 on the stack by the caller from right to left. The callee (and not the
27116 caller) is in charge of cleaning the stack on routine exit. In addition,
27117 the name of a routine with @code{Stdcall} calling convention is mangled by
27118 adding a leading underscore (as for the @code{C} calling convention) and a
27119 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27120 bytes) of the parameters passed to the routine.
27121
27122 The name to use on the Ada side when importing a C routine with a
27123 @code{Stdcall} calling convention is the name of the C routine. The leading
27124 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27125 the compiler. For instance the Win32 function:
27126
27127 @smallexample
27128 @b{APIENTRY} int get_val (long);
27129 @end smallexample
27130
27131 @noindent
27132 should be imported from Ada as follows:
27133
27134 @smallexample @c ada
27135 @group
27136 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27137 pragma Import (Stdcall, Get_Val);
27138 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27139 @end group
27140 @end smallexample
27141
27142 @noindent
27143 As for the @code{C} calling convention, when the @code{External_Name}
27144 parameter is missing, it is taken to be the name of the Ada entity in lower
27145 case. If instead of writing the above import pragma you write:
27146
27147 @smallexample @c ada
27148 @group
27149 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27150 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27151 @end group
27152 @end smallexample
27153
27154 @noindent
27155 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27156 of specifying the @code{External_Name} parameter you specify the
27157 @code{Link_Name} as in the following example:
27158
27159 @smallexample @c ada
27160 @group
27161 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27162 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27163 @end group
27164 @end smallexample
27165
27166 @noindent
27167 then the imported routine is @code{retrieve_val}, that is, there is no
27168 decoration at all. No leading underscore and no Stdcall suffix
27169 @code{@@}@code{@var{nn}}.
27170
27171 @noindent
27172 This is especially important as in some special cases a DLL's entry
27173 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27174 name generated for a call has it.
27175
27176 @noindent
27177 It is also possible to import variables defined in a DLL by using an
27178 import pragma for a variable. As an example, if a DLL contains a
27179 variable defined as:
27180
27181 @smallexample
27182 int my_var;
27183 @end smallexample
27184
27185 @noindent
27186 then, to access this variable from Ada you should write:
27187
27188 @smallexample @c ada
27189 @group
27190 My_Var : Interfaces.C.int;
27191 pragma Import (Stdcall, My_Var);
27192 @end group
27193 @end smallexample
27194
27195 @noindent
27196 Note that to ease building cross-platform bindings this convention
27197 will be handled as a @code{C} calling convention on non-Windows platforms.
27198
27199 @node Win32 Calling Convention
27200 @subsection @code{Win32} Calling Convention
27201
27202 @noindent
27203 This convention, which is GNAT-specific is fully equivalent to the
27204 @code{Stdcall} calling convention described above.
27205
27206 @node DLL Calling Convention
27207 @subsection @code{DLL} Calling Convention
27208
27209 @noindent
27210 This convention, which is GNAT-specific is fully equivalent to the
27211 @code{Stdcall} calling convention described above.
27212
27213 @node Introduction to Dynamic Link Libraries (DLLs)
27214 @section Introduction to Dynamic Link Libraries (DLLs)
27215 @findex DLL
27216
27217 @noindent
27218 A Dynamically Linked Library (DLL) is a library that can be shared by
27219 several applications running under Windows. A DLL can contain any number of
27220 routines and variables.
27221
27222 One advantage of DLLs is that you can change and enhance them without
27223 forcing all the applications that depend on them to be relinked or
27224 recompiled. However, you should be aware than all calls to DLL routines are
27225 slower since, as you will understand below, such calls are indirect.
27226
27227 To illustrate the remainder of this section, suppose that an application
27228 wants to use the services of a DLL @file{API.dll}. To use the services
27229 provided by @file{API.dll} you must statically link against the DLL or
27230 an import library which contains a jump table with an entry for each
27231 routine and variable exported by the DLL. In the Microsoft world this
27232 import library is called @file{API.lib}. When using GNAT this import
27233 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27234 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27235
27236 After you have linked your application with the DLL or the import library
27237 and you run your application, here is what happens:
27238
27239 @enumerate
27240 @item
27241 Your application is loaded into memory.
27242
27243 @item
27244 The DLL @file{API.dll} is mapped into the address space of your
27245 application. This means that:
27246
27247 @itemize @bullet
27248 @item
27249 The DLL will use the stack of the calling thread.
27250
27251 @item
27252 The DLL will use the virtual address space of the calling process.
27253
27254 @item
27255 The DLL will allocate memory from the virtual address space of the calling
27256 process.
27257
27258 @item
27259 Handles (pointers) can be safely exchanged between routines in the DLL
27260 routines and routines in the application using the DLL.
27261 @end itemize
27262
27263 @item
27264 The entries in the jump table (from the import library @file{libAPI.dll.a}
27265 or @file{API.lib} or automatically created when linking against a DLL)
27266 which is part of your application are initialized with the addresses
27267 of the routines and variables in @file{API.dll}.
27268
27269 @item
27270 If present in @file{API.dll}, routines @code{DllMain} or
27271 @code{DllMainCRTStartup} are invoked. These routines typically contain
27272 the initialization code needed for the well-being of the routines and
27273 variables exported by the DLL.
27274 @end enumerate
27275
27276 @noindent
27277 There is an additional point which is worth mentioning. In the Windows
27278 world there are two kind of DLLs: relocatable and non-relocatable
27279 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27280 in the target application address space. If the addresses of two
27281 non-relocatable DLLs overlap and these happen to be used by the same
27282 application, a conflict will occur and the application will run
27283 incorrectly. Hence, when possible, it is always preferable to use and
27284 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27285 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27286 User's Guide) removes the debugging symbols from the DLL but the DLL can
27287 still be relocated.
27288
27289 As a side note, an interesting difference between Microsoft DLLs and
27290 Unix shared libraries, is the fact that on most Unix systems all public
27291 routines are exported by default in a Unix shared library, while under
27292 Windows it is possible (but not required) to list exported routines in
27293 a definition file (@pxref{The Definition File}).
27294
27295 @node Using DLLs with GNAT
27296 @section Using DLLs with GNAT
27297
27298 @menu
27299 * Creating an Ada Spec for the DLL Services::
27300 * Creating an Import Library::
27301 @end menu
27302
27303 @noindent
27304 To use the services of a DLL, say @file{API.dll}, in your Ada application
27305 you must have:
27306
27307 @enumerate
27308 @item
27309 The Ada spec for the routines and/or variables you want to access in
27310 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27311 header files provided with the DLL.
27312
27313 @item
27314 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27315 mentioned an import library is a statically linked library containing the
27316 import table which will be filled at load time to point to the actual
27317 @file{API.dll} routines. Sometimes you don't have an import library for the
27318 DLL you want to use. The following sections will explain how to build
27319 one. Note that this is optional.
27320
27321 @item
27322 The actual DLL, @file{API.dll}.
27323 @end enumerate
27324
27325 @noindent
27326 Once you have all the above, to compile an Ada application that uses the
27327 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27328 you simply issue the command
27329
27330 @smallexample
27331 $ gnatmake my_ada_app -largs -lAPI
27332 @end smallexample
27333
27334 @noindent
27335 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27336 tells the GNAT linker to look for an import library. The linker will
27337 look for a library name in this specific order:
27338
27339 @enumerate
27340 @item @file{libAPI.dll.a}
27341 @item @file{API.dll.a}
27342 @item @file{libAPI.a}
27343 @item @file{API.lib}
27344 @item @file{libAPI.dll}
27345 @item @file{API.dll}
27346 @end enumerate
27347
27348 The first three are the GNU style import libraries. The third is the
27349 Microsoft style import libraries. The last two are the DLL themself.
27350
27351 Note that if the Ada package spec for @file{API.dll} contains the
27352 following pragma
27353
27354 @smallexample @c ada
27355 pragma Linker_Options ("-lAPI");
27356 @end smallexample
27357
27358 @noindent
27359 you do not have to add @option{-largs -lAPI} at the end of the
27360 @command{gnatmake} command.
27361
27362 If any one of the items above is missing you will have to create it
27363 yourself. The following sections explain how to do so using as an
27364 example a fictitious DLL called @file{API.dll}.
27365
27366 @node Creating an Ada Spec for the DLL Services
27367 @subsection Creating an Ada Spec for the DLL Services
27368
27369 @noindent
27370 A DLL typically comes with a C/C++ header file which provides the
27371 definitions of the routines and variables exported by the DLL. The Ada
27372 equivalent of this header file is a package spec that contains definitions
27373 for the imported entities. If the DLL you intend to use does not come with
27374 an Ada spec you have to generate one such spec yourself. For example if
27375 the header file of @file{API.dll} is a file @file{api.h} containing the
27376 following two definitions:
27377
27378 @smallexample
27379 @group
27380 @cartouche
27381 int some_var;
27382 int get (char *);
27383 @end cartouche
27384 @end group
27385 @end smallexample
27386
27387 @noindent
27388 then the equivalent Ada spec could be:
27389
27390 @smallexample @c ada
27391 @group
27392 @cartouche
27393 with Interfaces.C.Strings;
27394 package API is
27395    use Interfaces;
27396
27397    Some_Var : C.int;
27398    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27399
27400 private
27401    pragma Import (C, Get);
27402    pragma Import (DLL, Some_Var);
27403 end API;
27404 @end cartouche
27405 @end group
27406 @end smallexample
27407
27408 @noindent
27409 Note that a variable is
27410 @strong{always imported with a DLL convention}. A function
27411 can have @code{C} or @code{Stdcall} convention.
27412 (@pxref{Windows Calling Conventions}).
27413
27414 @node Creating an Import Library
27415 @subsection Creating an Import Library
27416 @cindex Import library
27417
27418 @menu
27419 * The Definition File::
27420 * GNAT-Style Import Library::
27421 * Microsoft-Style Import Library::
27422 @end menu
27423
27424 @noindent
27425 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27426 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27427 with @file{API.dll} you can skip this section. You can also skip this
27428 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27429 as in this case it is possible to link directly against the
27430 DLL. Otherwise read on.
27431
27432 @node The Definition File
27433 @subsubsection The Definition File
27434 @cindex Definition file
27435 @findex .def
27436
27437 @noindent
27438 As previously mentioned, and unlike Unix systems, the list of symbols
27439 that are exported from a DLL must be provided explicitly in Windows.
27440 The main goal of a definition file is precisely that: list the symbols
27441 exported by a DLL. A definition file (usually a file with a @code{.def}
27442 suffix) has the following structure:
27443
27444 @smallexample
27445 @group
27446 @cartouche
27447 @r{[}LIBRARY @var{name}@r{]}
27448 @r{[}DESCRIPTION @var{string}@r{]}
27449 EXPORTS
27450    @var{symbol1}
27451    @var{symbol2}
27452    @dots{}
27453 @end cartouche
27454 @end group
27455 @end smallexample
27456
27457 @table @code
27458 @item LIBRARY @var{name}
27459 This section, which is optional, gives the name of the DLL.
27460
27461 @item DESCRIPTION @var{string}
27462 This section, which is optional, gives a description string that will be
27463 embedded in the import library.
27464
27465 @item EXPORTS
27466 This section gives the list of exported symbols (procedures, functions or
27467 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27468 section of @file{API.def} looks like:
27469
27470 @smallexample
27471 @group
27472 @cartouche
27473 EXPORTS
27474    some_var
27475    get
27476 @end cartouche
27477 @end group
27478 @end smallexample
27479 @end table
27480
27481 @noindent
27482 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27483 (@pxref{Windows Calling Conventions}) for a Stdcall
27484 calling convention function in the exported symbols list.
27485
27486 @noindent
27487 There can actually be other sections in a definition file, but these
27488 sections are not relevant to the discussion at hand.
27489
27490 @node GNAT-Style Import Library
27491 @subsubsection GNAT-Style Import Library
27492
27493 @noindent
27494 To create a static import library from @file{API.dll} with the GNAT tools
27495 you should proceed as follows:
27496
27497 @enumerate
27498 @item
27499 Create the definition file @file{API.def} (@pxref{The Definition File}).
27500 For that use the @code{dll2def} tool as follows:
27501
27502 @smallexample
27503 $ dll2def API.dll > API.def
27504 @end smallexample
27505
27506 @noindent
27507 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27508 to standard output the list of entry points in the DLL. Note that if
27509 some routines in the DLL have the @code{Stdcall} convention
27510 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27511 suffix then you'll have to edit @file{api.def} to add it, and specify
27512 @option{-k} to @command{gnatdll} when creating the import library.
27513
27514 @noindent
27515 Here are some hints to find the right @code{@@}@var{nn} suffix.
27516
27517 @enumerate
27518 @item
27519 If you have the Microsoft import library (.lib), it is possible to get
27520 the right symbols by using Microsoft @code{dumpbin} tool (see the
27521 corresponding Microsoft documentation for further details).
27522
27523 @smallexample
27524 $ dumpbin /exports api.lib
27525 @end smallexample
27526
27527 @item
27528 If you have a message about a missing symbol at link time the compiler
27529 tells you what symbol is expected. You just have to go back to the
27530 definition file and add the right suffix.
27531 @end enumerate
27532
27533 @item
27534 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27535 (@pxref{Using gnatdll}) as follows:
27536
27537 @smallexample
27538 $ gnatdll -e API.def -d API.dll
27539 @end smallexample
27540
27541 @noindent
27542 @code{gnatdll} takes as input a definition file @file{API.def} and the
27543 name of the DLL containing the services listed in the definition file
27544 @file{API.dll}. The name of the static import library generated is
27545 computed from the name of the definition file as follows: if the
27546 definition file name is @var{xyz}@code{.def}, the import library name will
27547 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27548 @option{-e} could have been removed because the name of the definition
27549 file (before the ``@code{.def}'' suffix) is the same as the name of the
27550 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27551 @end enumerate
27552
27553 @node Microsoft-Style Import Library
27554 @subsubsection Microsoft-Style Import Library
27555
27556 @noindent
27557 With GNAT you can either use a GNAT-style or Microsoft-style import
27558 library. A Microsoft import library is needed only if you plan to make an
27559 Ada DLL available to applications developed with Microsoft
27560 tools (@pxref{Mixed-Language Programming on Windows}).
27561
27562 To create a Microsoft-style import library for @file{API.dll} you
27563 should proceed as follows:
27564
27565 @enumerate
27566 @item
27567 Create the definition file @file{API.def} from the DLL. For this use either
27568 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27569 tool (see the corresponding Microsoft documentation for further details).
27570
27571 @item
27572 Build the actual import library using Microsoft's @code{lib} utility:
27573
27574 @smallexample
27575 $ lib -machine:IX86 -def:API.def -out:API.lib
27576 @end smallexample
27577
27578 @noindent
27579 If you use the above command the definition file @file{API.def} must
27580 contain a line giving the name of the DLL:
27581
27582 @smallexample
27583 LIBRARY      "API"
27584 @end smallexample
27585
27586 @noindent
27587 See the Microsoft documentation for further details about the usage of
27588 @code{lib}.
27589 @end enumerate
27590
27591 @node Building DLLs with GNAT Project files
27592 @section Building DLLs with GNAT Project files
27593 @cindex DLLs, building
27594
27595 @noindent
27596 There is nothing specific to Windows in the build process.
27597 @pxref{Library Projects}.
27598
27599 @noindent
27600 Due to a system limitation, it is not possible under Windows to create threads
27601 when inside the @code{DllMain} routine which is used for auto-initialization
27602 of shared libraries, so it is not possible to have library level tasks in SALs.
27603
27604 @node Building DLLs with GNAT
27605 @section Building DLLs with GNAT
27606 @cindex DLLs, building
27607
27608 @noindent
27609 This section explain how to build DLLs using the GNAT built-in DLL
27610 support. With the following procedure it is straight forward to build
27611 and use DLLs with GNAT.
27612
27613 @enumerate
27614
27615 @item building object files
27616
27617 The first step is to build all objects files that are to be included
27618 into the DLL. This is done by using the standard @command{gnatmake} tool.
27619
27620 @item building the DLL
27621
27622 To build the DLL you must use @command{gcc}'s @option{-shared}
27623 option. It is quite simple to use this method:
27624
27625 @smallexample
27626 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27627 @end smallexample
27628
27629 It is important to note that in this case all symbols found in the
27630 object files are automatically exported. It is possible to restrict
27631 the set of symbols to export by passing to @command{gcc} a definition
27632 file, @pxref{The Definition File}. For example:
27633
27634 @smallexample
27635 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27636 @end smallexample
27637
27638 If you use a definition file you must export the elaboration procedures
27639 for every package that required one. Elaboration procedures are named
27640 using the package name followed by "_E".
27641
27642 @item preparing DLL to be used
27643
27644 For the DLL to be used by client programs the bodies must be hidden
27645 from it and the .ali set with read-only attribute. This is very important
27646 otherwise GNAT will recompile all packages and will not actually use
27647 the code in the DLL. For example:
27648
27649 @smallexample
27650 $ mkdir apilib
27651 $ copy *.ads *.ali api.dll apilib
27652 $ attrib +R apilib\*.ali
27653 @end smallexample
27654
27655 @end enumerate
27656
27657 At this point it is possible to use the DLL by directly linking
27658 against it. Note that you must use the GNAT shared runtime when using
27659 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27660 option.
27661
27662 @smallexample
27663 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27664 @end smallexample
27665
27666 @node Building DLLs with gnatdll
27667 @section Building DLLs with gnatdll
27668 @cindex DLLs, building
27669
27670 @menu
27671 * Limitations When Using Ada DLLs from Ada::
27672 * Exporting Ada Entities::
27673 * Ada DLLs and Elaboration::
27674 * Ada DLLs and Finalization::
27675 * Creating a Spec for Ada DLLs::
27676 * Creating the Definition File::
27677 * Using gnatdll::
27678 @end menu
27679
27680 @noindent
27681 Note that it is preferred to use GNAT Project files
27682 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27683 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27684
27685 This section explains how to build DLLs containing Ada code using
27686 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27687 remainder of this section.
27688
27689 The steps required to build an Ada DLL that is to be used by Ada as well as
27690 non-Ada applications are as follows:
27691
27692 @enumerate
27693 @item
27694 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27695 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27696 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27697 skip this step if you plan to use the Ada DLL only from Ada applications.
27698
27699 @item
27700 Your Ada code must export an initialization routine which calls the routine
27701 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27702 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27703 routine exported by the Ada DLL must be invoked by the clients of the DLL
27704 to initialize the DLL.
27705
27706 @item
27707 When useful, the DLL should also export a finalization routine which calls
27708 routine @code{adafinal} generated by @command{gnatbind} to perform the
27709 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27710 The finalization routine exported by the Ada DLL must be invoked by the
27711 clients of the DLL when the DLL services are no further needed.
27712
27713 @item
27714 You must provide a spec for the services exported by the Ada DLL in each
27715 of the programming languages to which you plan to make the DLL available.
27716
27717 @item
27718 You must provide a definition file listing the exported entities
27719 (@pxref{The Definition File}).
27720
27721 @item
27722 Finally you must use @code{gnatdll} to produce the DLL and the import
27723 library (@pxref{Using gnatdll}).
27724 @end enumerate
27725
27726 @noindent
27727 Note that a relocatable DLL stripped using the @code{strip}
27728 binutils tool will not be relocatable anymore. To build a DLL without
27729 debug information pass @code{-largs -s} to @code{gnatdll}. This
27730 restriction does not apply to a DLL built using a Library Project.
27731 @pxref{Library Projects}.
27732
27733 @node Limitations When Using Ada DLLs from Ada
27734 @subsection Limitations When Using Ada DLLs from Ada
27735
27736 @noindent
27737 When using Ada DLLs from Ada applications there is a limitation users
27738 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27739 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27740 each Ada DLL includes the services of the GNAT run time that are necessary
27741 to the Ada code inside the DLL. As a result, when an Ada program uses an
27742 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27743 one in the main program.
27744
27745 It is therefore not possible to exchange GNAT run-time objects between the
27746 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27747 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27748 types, etc.
27749
27750 It is completely safe to exchange plain elementary, array or record types,
27751 Windows object handles, etc.
27752
27753 @node Exporting Ada Entities
27754 @subsection Exporting Ada Entities
27755 @cindex Export table
27756
27757 @noindent
27758 Building a DLL is a way to encapsulate a set of services usable from any
27759 application. As a result, the Ada entities exported by a DLL should be
27760 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27761 any Ada name mangling. As an example here is an Ada package
27762 @code{API}, spec and body, exporting two procedures, a function, and a
27763 variable:
27764
27765 @smallexample @c ada
27766 @group
27767 @cartouche
27768 with Interfaces.C; use Interfaces;
27769 package API is
27770    Count : C.int := 0;
27771    function Factorial (Val : C.int) return C.int;
27772
27773    procedure Initialize_API;
27774    procedure Finalize_API;
27775    --  Initialization & Finalization routines. More in the next section.
27776 private
27777    pragma Export (C, Initialize_API);
27778    pragma Export (C, Finalize_API);
27779    pragma Export (C, Count);
27780    pragma Export (C, Factorial);
27781 end API;
27782 @end cartouche
27783 @end group
27784 @end smallexample
27785
27786 @smallexample @c ada
27787 @group
27788 @cartouche
27789 package body API is
27790    function Factorial (Val : C.int) return C.int is
27791       Fact : C.int := 1;
27792    begin
27793       Count := Count + 1;
27794       for K in 1 .. Val loop
27795          Fact := Fact * K;
27796       end loop;
27797       return Fact;
27798    end Factorial;
27799
27800    procedure Initialize_API is
27801       procedure Adainit;
27802       pragma Import (C, Adainit);
27803    begin
27804       Adainit;
27805    end Initialize_API;
27806
27807    procedure Finalize_API is
27808       procedure Adafinal;
27809       pragma Import (C, Adafinal);
27810    begin
27811       Adafinal;
27812    end Finalize_API;
27813 end API;
27814 @end cartouche
27815 @end group
27816 @end smallexample
27817
27818 @noindent
27819 If the Ada DLL you are building will only be used by Ada applications
27820 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27821 convention. As an example, the previous package could be written as
27822 follows:
27823
27824 @smallexample @c ada
27825 @group
27826 @cartouche
27827 package API is
27828    Count : Integer := 0;
27829    function Factorial (Val : Integer) return Integer;
27830
27831    procedure Initialize_API;
27832    procedure Finalize_API;
27833    --  Initialization and Finalization routines.
27834 end API;
27835 @end cartouche
27836 @end group
27837 @end smallexample
27838
27839 @smallexample @c ada
27840 @group
27841 @cartouche
27842 package body API is
27843    function Factorial (Val : Integer) return Integer is
27844       Fact : Integer := 1;
27845    begin
27846       Count := Count + 1;
27847       for K in 1 .. Val loop
27848          Fact := Fact * K;
27849       end loop;
27850       return Fact;
27851    end Factorial;
27852
27853    @dots{}
27854    --  The remainder of this package body is unchanged.
27855 end API;
27856 @end cartouche
27857 @end group
27858 @end smallexample
27859
27860 @noindent
27861 Note that if you do not export the Ada entities with a @code{C} or
27862 @code{Stdcall} convention you will have to provide the mangled Ada names
27863 in the definition file of the Ada DLL
27864 (@pxref{Creating the Definition File}).
27865
27866 @node Ada DLLs and Elaboration
27867 @subsection Ada DLLs and Elaboration
27868 @cindex DLLs and elaboration
27869
27870 @noindent
27871 The DLL that you are building contains your Ada code as well as all the
27872 routines in the Ada library that are needed by it. The first thing a
27873 user of your DLL must do is elaborate the Ada code
27874 (@pxref{Elaboration Order Handling in GNAT}).
27875
27876 To achieve this you must export an initialization routine
27877 (@code{Initialize_API} in the previous example), which must be invoked
27878 before using any of the DLL services. This elaboration routine must call
27879 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27880 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27881 @code{Initialize_Api} for an example. Note that the GNAT binder is
27882 automatically invoked during the DLL build process by the @code{gnatdll}
27883 tool (@pxref{Using gnatdll}).
27884
27885 When a DLL is loaded, Windows systematically invokes a routine called
27886 @code{DllMain}. It would therefore be possible to call @code{adainit}
27887 directly from @code{DllMain} without having to provide an explicit
27888 initialization routine. Unfortunately, it is not possible to call
27889 @code{adainit} from the @code{DllMain} if your program has library level
27890 tasks because access to the @code{DllMain} entry point is serialized by
27891 the system (that is, only a single thread can execute ``through'' it at a
27892 time), which means that the GNAT run time will deadlock waiting for the
27893 newly created task to complete its initialization.
27894
27895 @node Ada DLLs and Finalization
27896 @subsection Ada DLLs and Finalization
27897 @cindex DLLs and finalization
27898
27899 @noindent
27900 When the services of an Ada DLL are no longer needed, the client code should
27901 invoke the DLL finalization routine, if available. The DLL finalization
27902 routine is in charge of releasing all resources acquired by the DLL. In the
27903 case of the Ada code contained in the DLL, this is achieved by calling
27904 routine @code{adafinal} generated by the GNAT binder
27905 (@pxref{Binding with Non-Ada Main Programs}).
27906 See the body of @code{Finalize_Api} for an
27907 example. As already pointed out the GNAT binder is automatically invoked
27908 during the DLL build process by the @code{gnatdll} tool
27909 (@pxref{Using gnatdll}).
27910
27911 @node Creating a Spec for Ada DLLs
27912 @subsection Creating a Spec for Ada DLLs
27913
27914 @noindent
27915 To use the services exported by the Ada DLL from another programming
27916 language (e.g.@: C), you have to translate the specs of the exported Ada
27917 entities in that language. For instance in the case of @code{API.dll},
27918 the corresponding C header file could look like:
27919
27920 @smallexample
27921 @group
27922 @cartouche
27923 extern int *_imp__count;
27924 #define count (*_imp__count)
27925 int factorial (int);
27926 @end cartouche
27927 @end group
27928 @end smallexample
27929
27930 @noindent
27931 It is important to understand that when building an Ada DLL to be used by
27932 other Ada applications, you need two different specs for the packages
27933 contained in the DLL: one for building the DLL and the other for using
27934 the DLL. This is because the @code{DLL} calling convention is needed to
27935 use a variable defined in a DLL, but when building the DLL, the variable
27936 must have either the @code{Ada} or @code{C} calling convention. As an
27937 example consider a DLL comprising the following package @code{API}:
27938
27939 @smallexample @c ada
27940 @group
27941 @cartouche
27942 package API is
27943    Count : Integer := 0;
27944    @dots{}
27945    --  Remainder of the package omitted.
27946 end API;
27947 @end cartouche
27948 @end group
27949 @end smallexample
27950
27951 @noindent
27952 After producing a DLL containing package @code{API}, the spec that
27953 must be used to import @code{API.Count} from Ada code outside of the
27954 DLL is:
27955
27956 @smallexample @c ada
27957 @group
27958 @cartouche
27959 package API is
27960    Count : Integer;
27961    pragma Import (DLL, Count);
27962 end API;
27963 @end cartouche
27964 @end group
27965 @end smallexample
27966
27967 @node Creating the Definition File
27968 @subsection Creating the Definition File
27969
27970 @noindent
27971 The definition file is the last file needed to build the DLL. It lists
27972 the exported symbols. As an example, the definition file for a DLL
27973 containing only package @code{API} (where all the entities are exported
27974 with a @code{C} calling convention) is:
27975
27976 @smallexample
27977 @group
27978 @cartouche
27979 EXPORTS
27980     count
27981     factorial
27982     finalize_api
27983     initialize_api
27984 @end cartouche
27985 @end group
27986 @end smallexample
27987
27988 @noindent
27989 If the @code{C} calling convention is missing from package @code{API},
27990 then the definition file contains the mangled Ada names of the above
27991 entities, which in this case are:
27992
27993 @smallexample
27994 @group
27995 @cartouche
27996 EXPORTS
27997     api__count
27998     api__factorial
27999     api__finalize_api
28000     api__initialize_api
28001 @end cartouche
28002 @end group
28003 @end smallexample
28004
28005 @node Using gnatdll
28006 @subsection Using @code{gnatdll}
28007 @findex gnatdll
28008
28009 @menu
28010 * gnatdll Example::
28011 * gnatdll behind the Scenes::
28012 * Using dlltool::
28013 @end menu
28014
28015 @noindent
28016 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28017 and non-Ada sources that make up your DLL have been compiled.
28018 @code{gnatdll} is actually in charge of two distinct tasks: build the
28019 static import library for the DLL and the actual DLL. The form of the
28020 @code{gnatdll} command is
28021
28022 @smallexample
28023 @cartouche
28024 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28025 @c Expanding @ovar macro inline (explanation in macro def comments)
28026 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28027 @end cartouche
28028 @end smallexample
28029
28030 @noindent
28031 where @var{list-of-files} is a list of ALI and object files. The object
28032 file list must be the exact list of objects corresponding to the non-Ada
28033 sources whose services are to be included in the DLL. The ALI file list
28034 must be the exact list of ALI files for the corresponding Ada sources
28035 whose services are to be included in the DLL. If @var{list-of-files} is
28036 missing, only the static import library is generated.
28037
28038 @noindent
28039 You may specify any of the following switches to @code{gnatdll}:
28040
28041 @table @code
28042 @c @item -a@ovar{address}
28043 @c Expanding @ovar macro inline (explanation in macro def comments)
28044 @item -a@r{[}@var{address}@r{]}
28045 @cindex @option{-a} (@code{gnatdll})
28046 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28047 specified the default address @var{0x11000000} will be used. By default,
28048 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28049 advise the reader to build relocatable DLL.
28050
28051 @item -b @var{address}
28052 @cindex @option{-b} (@code{gnatdll})
28053 Set the relocatable DLL base address. By default the address is
28054 @code{0x11000000}.
28055
28056 @item -bargs @var{opts}
28057 @cindex @option{-bargs} (@code{gnatdll})
28058 Binder options. Pass @var{opts} to the binder.
28059
28060 @item -d @var{dllfile}
28061 @cindex @option{-d} (@code{gnatdll})
28062 @var{dllfile} is the name of the DLL. This switch must be present for
28063 @code{gnatdll} to do anything. The name of the generated import library is
28064 obtained algorithmically from @var{dllfile} as shown in the following
28065 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28066 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28067 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28068 as shown in the following example:
28069 if @var{dllfile} is @code{xyz.dll}, the definition
28070 file used is @code{xyz.def}.
28071
28072 @item -e @var{deffile}
28073 @cindex @option{-e} (@code{gnatdll})
28074 @var{deffile} is the name of the definition file.
28075
28076 @item -g
28077 @cindex @option{-g} (@code{gnatdll})
28078 Generate debugging information. This information is stored in the object
28079 file and copied from there to the final DLL file by the linker,
28080 where it can be read by the debugger. You must use the
28081 @option{-g} switch if you plan on using the debugger or the symbolic
28082 stack traceback.
28083
28084 @item -h
28085 @cindex @option{-h} (@code{gnatdll})
28086 Help mode. Displays @code{gnatdll} switch usage information.
28087
28088 @item -Idir
28089 @cindex @option{-I} (@code{gnatdll})
28090 Direct @code{gnatdll} to search the @var{dir} directory for source and
28091 object files needed to build the DLL.
28092 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28093
28094 @item -k
28095 @cindex @option{-k} (@code{gnatdll})
28096 Removes the @code{@@}@var{nn} suffix from the import library's exported
28097 names, but keeps them for the link names. You must specify this
28098 option if you want to use a @code{Stdcall} function in a DLL for which
28099 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28100 of the Windows NT DLL for example. This option has no effect when
28101 @option{-n} option is specified.
28102
28103 @item -l @var{file}
28104 @cindex @option{-l} (@code{gnatdll})
28105 The list of ALI and object files used to build the DLL are listed in
28106 @var{file}, instead of being given in the command line. Each line in
28107 @var{file} contains the name of an ALI or object file.
28108
28109 @item -n
28110 @cindex @option{-n} (@code{gnatdll})
28111 No Import. Do not create the import library.
28112
28113 @item -q
28114 @cindex @option{-q} (@code{gnatdll})
28115 Quiet mode. Do not display unnecessary messages.
28116
28117 @item -v
28118 @cindex @option{-v} (@code{gnatdll})
28119 Verbose mode. Display extra information.
28120
28121 @item -largs @var{opts}
28122 @cindex @option{-largs} (@code{gnatdll})
28123 Linker options. Pass @var{opts} to the linker.
28124 @end table
28125
28126 @node gnatdll Example
28127 @subsubsection @code{gnatdll} Example
28128
28129 @noindent
28130 As an example the command to build a relocatable DLL from @file{api.adb}
28131 once @file{api.adb} has been compiled and @file{api.def} created is
28132
28133 @smallexample
28134 $ gnatdll -d api.dll api.ali
28135 @end smallexample
28136
28137 @noindent
28138 The above command creates two files: @file{libapi.dll.a} (the import
28139 library) and @file{api.dll} (the actual DLL). If you want to create
28140 only the DLL, just type:
28141
28142 @smallexample
28143 $ gnatdll -d api.dll -n api.ali
28144 @end smallexample
28145
28146 @noindent
28147 Alternatively if you want to create just the import library, type:
28148
28149 @smallexample
28150 $ gnatdll -d api.dll
28151 @end smallexample
28152
28153 @node gnatdll behind the Scenes
28154 @subsubsection @code{gnatdll} behind the Scenes
28155
28156 @noindent
28157 This section details the steps involved in creating a DLL. @code{gnatdll}
28158 does these steps for you. Unless you are interested in understanding what
28159 goes on behind the scenes, you should skip this section.
28160
28161 We use the previous example of a DLL containing the Ada package @code{API},
28162 to illustrate the steps necessary to build a DLL. The starting point is a
28163 set of objects that will make up the DLL and the corresponding ALI
28164 files. In the case of this example this means that @file{api.o} and
28165 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28166 the following:
28167
28168 @enumerate
28169 @item
28170 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28171 the information necessary to generate relocation information for the
28172 DLL.
28173
28174 @smallexample
28175 @group
28176 $ gnatbind -n api
28177 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28178 @end group
28179 @end smallexample
28180
28181 @noindent
28182 In addition to the base file, the @command{gnatlink} command generates an
28183 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28184 asks @command{gnatlink} to generate the routines @code{DllMain} and
28185 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28186 is loaded into memory.
28187
28188 @item
28189 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28190 export table (@file{api.exp}). The export table contains the relocation
28191 information in a form which can be used during the final link to ensure
28192 that the Windows loader is able to place the DLL anywhere in memory.
28193
28194 @smallexample
28195 @group
28196 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28197           --output-exp api.exp
28198 @end group
28199 @end smallexample
28200
28201 @item
28202 @code{gnatdll} builds the base file using the new export table. Note that
28203 @command{gnatbind} must be called once again since the binder generated file
28204 has been deleted during the previous call to @command{gnatlink}.
28205
28206 @smallexample
28207 @group
28208 $ gnatbind -n api
28209 $ gnatlink api -o api.jnk api.exp -mdll
28210       -Wl,--base-file,api.base
28211 @end group
28212 @end smallexample
28213
28214 @item
28215 @code{gnatdll} builds the new export table using the new base file and
28216 generates the DLL import library @file{libAPI.dll.a}.
28217
28218 @smallexample
28219 @group
28220 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28221           --output-exp api.exp --output-lib libAPI.a
28222 @end group
28223 @end smallexample
28224
28225 @item
28226 Finally @code{gnatdll} builds the relocatable DLL using the final export
28227 table.
28228
28229 @smallexample
28230 @group
28231 $ gnatbind -n api
28232 $ gnatlink api api.exp -o api.dll -mdll
28233 @end group
28234 @end smallexample
28235 @end enumerate
28236
28237 @node Using dlltool
28238 @subsubsection Using @code{dlltool}
28239
28240 @noindent
28241 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28242 DLLs and static import libraries. This section summarizes the most
28243 common @code{dlltool} switches. The form of the @code{dlltool} command
28244 is
28245
28246 @smallexample
28247 @c $ dlltool @ovar{switches}
28248 @c Expanding @ovar macro inline (explanation in macro def comments)
28249 $ dlltool @r{[}@var{switches}@r{]}
28250 @end smallexample
28251
28252 @noindent
28253 @code{dlltool} switches include:
28254
28255 @table @option
28256 @item --base-file @var{basefile}
28257 @cindex @option{--base-file} (@command{dlltool})
28258 Read the base file @var{basefile} generated by the linker. This switch
28259 is used to create a relocatable DLL.
28260
28261 @item --def @var{deffile}
28262 @cindex @option{--def} (@command{dlltool})
28263 Read the definition file.
28264
28265 @item --dllname @var{name}
28266 @cindex @option{--dllname} (@command{dlltool})
28267 Gives the name of the DLL. This switch is used to embed the name of the
28268 DLL in the static import library generated by @code{dlltool} with switch
28269 @option{--output-lib}.
28270
28271 @item -k
28272 @cindex @option{-k} (@command{dlltool})
28273 Kill @code{@@}@var{nn} from exported names
28274 (@pxref{Windows Calling Conventions}
28275 for a discussion about @code{Stdcall}-style symbols.
28276
28277 @item --help
28278 @cindex @option{--help} (@command{dlltool})
28279 Prints the @code{dlltool} switches with a concise description.
28280
28281 @item --output-exp @var{exportfile}
28282 @cindex @option{--output-exp} (@command{dlltool})
28283 Generate an export file @var{exportfile}. The export file contains the
28284 export table (list of symbols in the DLL) and is used to create the DLL.
28285
28286 @item --output-lib @var{libfile}
28287 @cindex @option{--output-lib} (@command{dlltool})
28288 Generate a static import library @var{libfile}.
28289
28290 @item -v
28291 @cindex @option{-v} (@command{dlltool})
28292 Verbose mode.
28293
28294 @item --as @var{assembler-name}
28295 @cindex @option{--as} (@command{dlltool})
28296 Use @var{assembler-name} as the assembler. The default is @code{as}.
28297 @end table
28298
28299 @node GNAT and Windows Resources
28300 @section GNAT and Windows Resources
28301 @cindex Resources, windows
28302
28303 @menu
28304 * Building Resources::
28305 * Compiling Resources::
28306 * Using Resources::
28307 @end menu
28308
28309 @noindent
28310 Resources are an easy way to add Windows specific objects to your
28311 application. The objects that can be added as resources include:
28312
28313 @itemize @bullet
28314 @item
28315 menus
28316
28317 @item
28318 accelerators
28319
28320 @item
28321 dialog boxes
28322
28323 @item
28324 string tables
28325
28326 @item
28327 bitmaps
28328
28329 @item
28330 cursors
28331
28332 @item
28333 icons
28334
28335 @item
28336 fonts
28337 @end itemize
28338
28339 @noindent
28340 This section explains how to build, compile and use resources.
28341
28342 @node Building Resources
28343 @subsection Building Resources
28344 @cindex Resources, building
28345
28346 @noindent
28347 A resource file is an ASCII file. By convention resource files have an
28348 @file{.rc} extension.
28349 The easiest way to build a resource file is to use Microsoft tools
28350 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28351 @code{dlgedit.exe} to build dialogs.
28352 It is always possible to build an @file{.rc} file yourself by writing a
28353 resource script.
28354
28355 It is not our objective to explain how to write a resource file. A
28356 complete description of the resource script language can be found in the
28357 Microsoft documentation.
28358
28359 @node Compiling Resources
28360 @subsection Compiling Resources
28361 @findex rc
28362 @findex windres
28363 @cindex Resources, compiling
28364
28365 @noindent
28366 This section describes how to build a GNAT-compatible (COFF) object file
28367 containing the resources. This is done using the Resource Compiler
28368 @code{windres} as follows:
28369
28370 @smallexample
28371 $ windres -i myres.rc -o myres.o
28372 @end smallexample
28373
28374 @noindent
28375 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28376 file. You can specify an alternate preprocessor (usually named
28377 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28378 parameter. A list of all possible options may be obtained by entering
28379 the command @code{windres} @option{--help}.
28380
28381 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28382 to produce a @file{.res} file (binary resource file). See the
28383 corresponding Microsoft documentation for further details. In this case
28384 you need to use @code{windres} to translate the @file{.res} file to a
28385 GNAT-compatible object file as follows:
28386
28387 @smallexample
28388 $ windres -i myres.res -o myres.o
28389 @end smallexample
28390
28391 @node Using Resources
28392 @subsection Using Resources
28393 @cindex Resources, using
28394
28395 @noindent
28396 To include the resource file in your program just add the
28397 GNAT-compatible object file for the resource(s) to the linker
28398 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28399 option:
28400
28401 @smallexample
28402 $ gnatmake myprog -largs myres.o
28403 @end smallexample
28404
28405 @node Debugging a DLL
28406 @section Debugging a DLL
28407 @cindex DLL debugging
28408
28409 @menu
28410 * Program and DLL Both Built with GCC/GNAT::
28411 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28412 @end menu
28413
28414 @noindent
28415 Debugging a DLL is similar to debugging a standard program. But
28416 we have to deal with two different executable parts: the DLL and the
28417 program that uses it. We have the following four possibilities:
28418
28419 @enumerate 1
28420 @item
28421 The program and the DLL are built with @code{GCC/GNAT}.
28422 @item
28423 The program is built with foreign tools and the DLL is built with
28424 @code{GCC/GNAT}.
28425 @item
28426 The program is built with @code{GCC/GNAT} and the DLL is built with
28427 foreign tools.
28428 @end enumerate
28429
28430 @noindent
28431 In this section we address only cases one and two above.
28432 There is no point in trying to debug
28433 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28434 information in it. To do so you must use a debugger compatible with the
28435 tools suite used to build the DLL.
28436
28437 @node Program and DLL Both Built with GCC/GNAT
28438 @subsection Program and DLL Both Built with GCC/GNAT
28439
28440 @noindent
28441 This is the simplest case. Both the DLL and the program have @code{GDB}
28442 compatible debugging information. It is then possible to break anywhere in
28443 the process. Let's suppose here that the main procedure is named
28444 @code{ada_main} and that in the DLL there is an entry point named
28445 @code{ada_dll}.
28446
28447 @noindent
28448 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28449 program must have been built with the debugging information (see GNAT -g
28450 switch). Here are the step-by-step instructions for debugging it:
28451
28452 @enumerate 1
28453 @item Launch @code{GDB} on the main program.
28454
28455 @smallexample
28456 $ gdb -nw ada_main
28457 @end smallexample
28458
28459 @item Start the program and stop at the beginning of the main procedure
28460
28461 @smallexample
28462 (gdb) start
28463 @end smallexample
28464
28465 @noindent
28466 This step is required to be able to set a breakpoint inside the DLL. As long
28467 as the program is not run, the DLL is not loaded. This has the
28468 consequence that the DLL debugging information is also not loaded, so it is not
28469 possible to set a breakpoint in the DLL.
28470
28471 @item Set a breakpoint inside the DLL
28472
28473 @smallexample
28474 (gdb) break ada_dll
28475 (gdb) cont
28476 @end smallexample
28477
28478 @end enumerate
28479
28480 @noindent
28481 At this stage a breakpoint is set inside the DLL. From there on
28482 you can use the standard approach to debug the whole program
28483 (@pxref{Running and Debugging Ada Programs}).
28484
28485 @ignore
28486 @c This used to work, probably because the DLLs were non-relocatable
28487 @c keep this section around until the problem is sorted out.
28488
28489 To break on the @code{DllMain} routine it is not possible to follow
28490 the procedure above. At the time the program stop on @code{ada_main}
28491 the @code{DllMain} routine as already been called. Either you can use
28492 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28493
28494 @enumerate 1
28495 @item Launch @code{GDB} on the main program.
28496
28497 @smallexample
28498 $ gdb ada_main
28499 @end smallexample
28500
28501 @item Load DLL symbols
28502
28503 @smallexample
28504 (gdb) add-sym api.dll
28505 @end smallexample
28506
28507 @item Set a breakpoint inside the DLL
28508
28509 @smallexample
28510 (gdb) break ada_dll.adb:45
28511 @end smallexample
28512
28513 Note that at this point it is not possible to break using the routine symbol
28514 directly as the program is not yet running. The solution is to break
28515 on the proper line (break in @file{ada_dll.adb} line 45).
28516
28517 @item Start the program
28518
28519 @smallexample
28520 (gdb) run
28521 @end smallexample
28522
28523 @end enumerate
28524 @end ignore
28525
28526 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28527 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28528
28529 @menu
28530 * Debugging the DLL Directly::
28531 * Attaching to a Running Process::
28532 @end menu
28533
28534 @noindent
28535 In this case things are slightly more complex because it is not possible to
28536 start the main program and then break at the beginning to load the DLL and the
28537 associated DLL debugging information. It is not possible to break at the
28538 beginning of the program because there is no @code{GDB} debugging information,
28539 and therefore there is no direct way of getting initial control. This
28540 section addresses this issue by describing some methods that can be used
28541 to break somewhere in the DLL to debug it.
28542
28543 @noindent
28544 First suppose that the main procedure is named @code{main} (this is for
28545 example some C code built with Microsoft Visual C) and that there is a
28546 DLL named @code{test.dll} containing an Ada entry point named
28547 @code{ada_dll}.
28548
28549 @noindent
28550 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28551 been built with debugging information (see GNAT -g option).
28552
28553 @node Debugging the DLL Directly
28554 @subsubsection Debugging the DLL Directly
28555
28556 @enumerate 1
28557 @item
28558 Find out the executable starting address
28559
28560 @smallexample
28561 $ objdump --file-header main.exe
28562 @end smallexample
28563
28564 The starting address is reported on the last line. For example:
28565
28566 @smallexample
28567 main.exe:     file format pei-i386
28568 architecture: i386, flags 0x0000010a:
28569 EXEC_P, HAS_DEBUG, D_PAGED
28570 start address 0x00401010
28571 @end smallexample
28572
28573 @item
28574 Launch the debugger on the executable.
28575
28576 @smallexample
28577 $ gdb main.exe
28578 @end smallexample
28579
28580 @item
28581 Set a breakpoint at the starting address, and launch the program.
28582
28583 @smallexample
28584 $ (gdb) break *0x00401010
28585 $ (gdb) run
28586 @end smallexample
28587
28588 The program will stop at the given address.
28589
28590 @item
28591 Set a breakpoint on a DLL subroutine.
28592
28593 @smallexample
28594 (gdb) break ada_dll.adb:45
28595 @end smallexample
28596
28597 Or if you want to break using a symbol on the DLL, you need first to
28598 select the Ada language (language used by the DLL).
28599
28600 @smallexample
28601 (gdb) set language ada
28602 (gdb) break ada_dll
28603 @end smallexample
28604
28605 @item
28606 Continue the program.
28607
28608 @smallexample
28609 (gdb) cont
28610 @end smallexample
28611
28612 @noindent
28613 This will run the program until it reaches the breakpoint that has been
28614 set. From that point you can use the standard way to debug a program
28615 as described in (@pxref{Running and Debugging Ada Programs}).
28616
28617 @end enumerate
28618
28619 @noindent
28620 It is also possible to debug the DLL by attaching to a running process.
28621
28622 @node Attaching to a Running Process
28623 @subsubsection Attaching to a Running Process
28624 @cindex DLL debugging, attach to process
28625
28626 @noindent
28627 With @code{GDB} it is always possible to debug a running process by
28628 attaching to it. It is possible to debug a DLL this way. The limitation
28629 of this approach is that the DLL must run long enough to perform the
28630 attach operation. It may be useful for instance to insert a time wasting
28631 loop in the code of the DLL to meet this criterion.
28632
28633 @enumerate 1
28634
28635 @item Launch the main program @file{main.exe}.
28636
28637 @smallexample
28638 $ main
28639 @end smallexample
28640
28641 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28642 that the process PID for @file{main.exe} is 208.
28643
28644 @item Launch gdb.
28645
28646 @smallexample
28647 $ gdb
28648 @end smallexample
28649
28650 @item Attach to the running process to be debugged.
28651
28652 @smallexample
28653 (gdb) attach 208
28654 @end smallexample
28655
28656 @item Load the process debugging information.
28657
28658 @smallexample
28659 (gdb) symbol-file main.exe
28660 @end smallexample
28661
28662 @item Break somewhere in the DLL.
28663
28664 @smallexample
28665 (gdb) break ada_dll
28666 @end smallexample
28667
28668 @item Continue process execution.
28669
28670 @smallexample
28671 (gdb) cont
28672 @end smallexample
28673
28674 @end enumerate
28675
28676 @noindent
28677 This last step will resume the process execution, and stop at
28678 the breakpoint we have set. From there you can use the standard
28679 approach to debug a program as described in
28680 (@pxref{Running and Debugging Ada Programs}).
28681
28682 @node Setting Stack Size from gnatlink
28683 @section Setting Stack Size from @command{gnatlink}
28684
28685 @noindent
28686 It is possible to specify the program stack size at link time. On modern
28687 versions of Windows, starting with XP, this is mostly useful to set the size of
28688 the main stack (environment task). The other task stacks are set with pragma
28689 Storage_Size or with the @command{gnatbind -d} command.
28690
28691 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28692 reserve size of individual tasks, the link-time stack size applies to all
28693 tasks, and pragma Storage_Size has no effect.
28694 In particular, Stack Overflow checks are made against this
28695 link-time specified size.
28696
28697 This setting can be done with
28698 @command{gnatlink} using either:
28699
28700 @itemize @bullet
28701
28702 @item using @option{-Xlinker} linker option
28703
28704 @smallexample
28705 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28706 @end smallexample
28707
28708 This sets the stack reserve size to 0x10000 bytes and the stack commit
28709 size to 0x1000 bytes.
28710
28711 @item using @option{-Wl} linker option
28712
28713 @smallexample
28714 $ gnatlink hello -Wl,--stack=0x1000000
28715 @end smallexample
28716
28717 This sets the stack reserve size to 0x1000000 bytes. Note that with
28718 @option{-Wl} option it is not possible to set the stack commit size
28719 because the coma is a separator for this option.
28720
28721 @end itemize
28722
28723 @node Setting Heap Size from gnatlink
28724 @section Setting Heap Size from @command{gnatlink}
28725
28726 @noindent
28727 Under Windows systems, it is possible to specify the program heap size from
28728 @command{gnatlink} using either:
28729
28730 @itemize @bullet
28731
28732 @item using @option{-Xlinker} linker option
28733
28734 @smallexample
28735 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28736 @end smallexample
28737
28738 This sets the heap reserve size to 0x10000 bytes and the heap commit
28739 size to 0x1000 bytes.
28740
28741 @item using @option{-Wl} linker option
28742
28743 @smallexample
28744 $ gnatlink hello -Wl,--heap=0x1000000
28745 @end smallexample
28746
28747 This sets the heap reserve size to 0x1000000 bytes. Note that with
28748 @option{-Wl} option it is not possible to set the heap commit size
28749 because the coma is a separator for this option.
28750
28751 @end itemize
28752
28753 @end ifset
28754
28755 @c **********************************
28756 @c * GNU Free Documentation License *
28757 @c **********************************
28758 @include fdl.texi
28759 @c GNU Free Documentation License
28760
28761 @node Index,,GNU Free Documentation License, Top
28762 @unnumbered Index
28763
28764 @printindex cp
28765
28766 @contents
28767 @c Put table of contents at end, otherwise it precedes the "title page" in
28768 @c the .txt version
28769 @c Edit the pdf file to move the contents to the beginning, after the title
28770 @c page
28771
28772 @bye