OSDN Git Service

2010-09-10 Jose Ruiz <ruiz@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 Note that this is by no means intended to be a general facility for
6148 checking arbitrary coding standards. It is simply an embedding of the
6149 style rules we have chosen for the GNAT sources. If you are starting
6150 a project which does not have established style standards, you may
6151 find it useful to adopt the entire set of GNAT coding standards, or
6152 some subset of them. If you already have an established set of coding
6153 standards, then it may be that selected style checking options do
6154 indeed correspond to choices you have made, but for general checking
6155 of an existing set of coding rules, you should look to the gnatcheck
6156 tool, which is designed for that purpose.
6157
6158 @ifset vms
6159 @code{(option,option,@dots{})} is a sequence of keywords
6160 @end ifset
6161 @ifclear vms
6162 The string @var{x} is a sequence of letters or digits
6163 @end ifclear
6164 indicating the particular style
6165 checks to be performed. The following checks are defined:
6166
6167 @table @option
6168 @c !sort!
6169 @item 0-9
6170 @emph{Specify indentation level.}
6171 If a digit from 1-9 appears
6172 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6173 then proper indentation is checked, with the digit indicating the
6174 indentation level required. A value of zero turns off this style check.
6175 The general style of required indentation is as specified by
6176 the examples in the Ada Reference Manual. Full line comments must be
6177 aligned with the @code{--} starting on a column that is a multiple of
6178 the alignment level, or they may be aligned the same way as the following
6179 non-blank line (this is useful when full line comments appear in the middle
6180 of a statement.
6181
6182 @item ^a^ATTRIBUTE^
6183 @emph{Check attribute casing.}
6184 Attribute names, including the case of keywords such as @code{digits}
6185 used as attributes names, must be written in mixed case, that is, the
6186 initial letter and any letter following an underscore must be uppercase.
6187 All other letters must be lowercase.
6188
6189 @item ^A^ARRAY_INDEXES^
6190 @emph{Use of array index numbers in array attributes.}
6191 When using the array attributes First, Last, Range,
6192 or Length, the index number must be omitted for one-dimensional arrays
6193 and is required for multi-dimensional arrays.
6194
6195 @item ^b^BLANKS^
6196 @emph{Blanks not allowed at statement end.}
6197 Trailing blanks are not allowed at the end of statements. The purpose of this
6198 rule, together with h (no horizontal tabs), is to enforce a canonical format
6199 for the use of blanks to separate source tokens.
6200
6201 @item ^B^BOOLEAN_OPERATORS^
6202 @emph{Check Boolean operators.}
6203 The use of AND/OR operators is not permitted except in the cases of modular
6204 operands, array operands, and simple stand-alone boolean variables or
6205 boolean constants. In all other cases AND THEN/OR ELSE are required.
6206
6207 @item ^c^COMMENTS^
6208 @emph{Check comments.}
6209 Comments must meet the following set of rules:
6210
6211 @itemize @bullet
6212
6213 @item
6214 The ``@code{--}'' that starts the column must either start in column one,
6215 or else at least one blank must precede this sequence.
6216
6217 @item
6218 Comments that follow other tokens on a line must have at least one blank
6219 following the ``@code{--}'' at the start of the comment.
6220
6221 @item
6222 Full line comments must have at least two blanks following the
6223 ``@code{--}'' that starts the comment, with the following exceptions.
6224
6225 @item
6226 A line consisting only of the ``@code{--}'' characters, possibly preceded
6227 by blanks is permitted.
6228
6229 @item
6230 A comment starting with ``@code{--x}'' where @code{x} is a special character
6231 is permitted.
6232 This allows proper processing of the output generated by specialized tools
6233 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6234 annotation
6235 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6236 special character is defined as being in one of the ASCII ranges
6237 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6238 Note that this usage is not permitted
6239 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6240
6241 @item
6242 A line consisting entirely of minus signs, possibly preceded by blanks, is
6243 permitted. This allows the construction of box comments where lines of minus
6244 signs are used to form the top and bottom of the box.
6245
6246 @item
6247 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6248 least one blank follows the initial ``@code{--}''. Together with the preceding
6249 rule, this allows the construction of box comments, as shown in the following
6250 example:
6251 @smallexample
6252 ---------------------------
6253 -- This is a box comment --
6254 -- with two text lines.  --
6255 ---------------------------
6256 @end smallexample
6257 @end itemize
6258
6259 @item ^d^DOS_LINE_ENDINGS^
6260 @emph{Check no DOS line terminators present.}
6261 All lines must be terminated by a single ASCII.LF
6262 character (in particular the DOS line terminator sequence CR/LF is not
6263 allowed).
6264
6265 @item ^e^END^
6266 @emph{Check end/exit labels.}
6267 Optional labels on @code{end} statements ending subprograms and on
6268 @code{exit} statements exiting named loops, are required to be present.
6269
6270 @item ^f^VTABS^
6271 @emph{No form feeds or vertical tabs.}
6272 Neither form feeds nor vertical tab characters are permitted
6273 in the source text.
6274
6275 @item ^g^GNAT^
6276 @emph{GNAT style mode}
6277 The set of style check switches is set to match that used by the GNAT sources.
6278 This may be useful when developing code that is eventually intended to be
6279 incorporated into GNAT. For further details, see GNAT sources.
6280
6281 @item ^h^HTABS^
6282 @emph{No horizontal tabs.}
6283 Horizontal tab characters are not permitted in the source text.
6284 Together with the b (no blanks at end of line) check, this
6285 enforces a canonical form for the use of blanks to separate
6286 source tokens.
6287
6288 @item ^i^IF_THEN^
6289 @emph{Check if-then layout.}
6290 The keyword @code{then} must appear either on the same
6291 line as corresponding @code{if}, or on a line on its own, lined
6292 up under the @code{if} with at least one non-blank line in between
6293 containing all or part of the condition to be tested.
6294
6295 @item ^I^IN_MODE^
6296 @emph{check mode IN keywords}
6297 Mode @code{in} (the default mode) is not
6298 allowed to be given explicitly. @code{in out} is fine,
6299 but not @code{in} on its own.
6300
6301 @item ^k^KEYWORD^
6302 @emph{Check keyword casing.}
6303 All keywords must be in lower case (with the exception of keywords
6304 such as @code{digits} used as attribute names to which this check
6305 does not apply).
6306
6307 @item ^l^LAYOUT^
6308 @emph{Check layout.}
6309 Layout of statement and declaration constructs must follow the
6310 recommendations in the Ada Reference Manual, as indicated by the
6311 form of the syntax rules. For example an @code{else} keyword must
6312 be lined up with the corresponding @code{if} keyword.
6313
6314 There are two respects in which the style rule enforced by this check
6315 option are more liberal than those in the Ada Reference Manual. First
6316 in the case of record declarations, it is permissible to put the
6317 @code{record} keyword on the same line as the @code{type} keyword, and
6318 then the @code{end} in @code{end record} must line up under @code{type}.
6319 This is also permitted when the type declaration is split on two lines.
6320 For example, any of the following three layouts is acceptable:
6321
6322 @smallexample @c ada
6323 @cartouche
6324 type q is record
6325    a : integer;
6326    b : integer;
6327 end record;
6328
6329 type q is
6330    record
6331       a : integer;
6332       b : integer;
6333    end record;
6334
6335 type q is
6336    record
6337       a : integer;
6338       b : integer;
6339 end record;
6340
6341 @end cartouche
6342 @end smallexample
6343
6344 @noindent
6345 Second, in the case of a block statement, a permitted alternative
6346 is to put the block label on the same line as the @code{declare} or
6347 @code{begin} keyword, and then line the @code{end} keyword up under
6348 the block label. For example both the following are permitted:
6349
6350 @smallexample @c ada
6351 @cartouche
6352 Block : declare
6353    A : Integer := 3;
6354 begin
6355    Proc (A, A);
6356 end Block;
6357
6358 Block :
6359    declare
6360       A : Integer := 3;
6361    begin
6362       Proc (A, A);
6363    end Block;
6364 @end cartouche
6365 @end smallexample
6366
6367 @noindent
6368 The same alternative format is allowed for loops. For example, both of
6369 the following are permitted:
6370
6371 @smallexample @c ada
6372 @cartouche
6373 Clear : while J < 10 loop
6374    A (J) := 0;
6375 end loop Clear;
6376
6377 Clear :
6378    while J < 10 loop
6379       A (J) := 0;
6380    end loop Clear;
6381 @end cartouche
6382 @end smallexample
6383
6384 @item ^Lnnn^MAX_NESTING=nnn^
6385 @emph{Set maximum nesting level}
6386 The maximum level of nesting of constructs (including subprograms, loops,
6387 blocks, packages, and conditionals) may not exceed the given value
6388 @option{nnn}. A value of zero disconnects this style check.
6389
6390 @item ^m^LINE_LENGTH^
6391 @emph{Check maximum line length.}
6392 The length of source lines must not exceed 79 characters, including
6393 any trailing blanks. The value of 79 allows convenient display on an
6394 80 character wide device or window, allowing for possible special
6395 treatment of 80 character lines. Note that this count is of
6396 characters in the source text. This means that a tab character counts
6397 as one character in this count but a wide character sequence counts as
6398 a single character (however many bytes are needed in the encoding).
6399
6400 @item ^Mnnn^MAX_LENGTH=nnn^
6401 @emph{Set maximum line length.}
6402 The length of lines must not exceed the
6403 given value @option{nnn}. The maximum value that can be specified is 32767.
6404
6405 @item ^n^STANDARD_CASING^
6406 @emph{Check casing of entities in Standard.}
6407 Any identifier from Standard must be cased
6408 to match the presentation in the Ada Reference Manual (for example,
6409 @code{Integer} and @code{ASCII.NUL}).
6410
6411 @item ^N^NONE^
6412 @emph{Turn off all style checks}
6413 All style check options are turned off.
6414
6415 @item ^o^ORDERED_SUBPROGRAMS^
6416 @emph{Check order of subprogram bodies.}
6417 All subprogram bodies in a given scope
6418 (e.g.@: a package body) must be in alphabetical order. The ordering
6419 rule uses normal Ada rules for comparing strings, ignoring casing
6420 of letters, except that if there is a trailing numeric suffix, then
6421 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6422 before Junk10).
6423
6424 @item ^O^OVERRIDING_INDICATORS^
6425 @emph{Check that overriding subprograms are explicitly marked as such.}
6426 The declaration of a primitive operation of a type extension that overrides
6427 an inherited operation must carry an overriding indicator.
6428
6429 @item ^p^PRAGMA^
6430 @emph{Check pragma casing.}
6431 Pragma names must be written in mixed case, that is, the
6432 initial letter and any letter following an underscore must be uppercase.
6433 All other letters must be lowercase.
6434
6435 @item ^r^REFERENCES^
6436 @emph{Check references.}
6437 All identifier references must be cased in the same way as the
6438 corresponding declaration. No specific casing style is imposed on
6439 identifiers. The only requirement is for consistency of references
6440 with declarations.
6441
6442 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6443 @emph{Check no statements after THEN/ELSE.}
6444 No statements are allowed
6445 on the same line as a THEN or ELSE keyword following the
6446 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6447 and a special exception allows a pragma to appear after ELSE.
6448
6449 @item ^s^SPECS^
6450 @emph{Check separate specs.}
6451 Separate declarations (``specs'') are required for subprograms (a
6452 body is not allowed to serve as its own declaration). The only
6453 exception is that parameterless library level procedures are
6454 not required to have a separate declaration. This exception covers
6455 the most frequent form of main program procedures.
6456
6457 @item ^t^TOKEN^
6458 @emph{Check token spacing.}
6459 The following token spacing rules are enforced:
6460
6461 @itemize @bullet
6462
6463 @item
6464 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6465
6466 @item
6467 The token @code{=>} must be surrounded by spaces.
6468
6469 @item
6470 The token @code{<>} must be preceded by a space or a left parenthesis.
6471
6472 @item
6473 Binary operators other than @code{**} must be surrounded by spaces.
6474 There is no restriction on the layout of the @code{**} binary operator.
6475
6476 @item
6477 Colon must be surrounded by spaces.
6478
6479 @item
6480 Colon-equal (assignment, initialization) must be surrounded by spaces.
6481
6482 @item
6483 Comma must be the first non-blank character on the line, or be
6484 immediately preceded by a non-blank character, and must be followed
6485 by a space.
6486
6487 @item
6488 If the token preceding a left parenthesis ends with a letter or digit, then
6489 a space must separate the two tokens.
6490
6491 @item
6492 if the token following a right parenthesis starts with a letter or digit, then
6493 a space must separate the two tokens.
6494
6495 @item
6496 A right parenthesis must either be the first non-blank character on
6497 a line, or it must be preceded by a non-blank character.
6498
6499 @item
6500 A semicolon must not be preceded by a space, and must not be followed by
6501 a non-blank character.
6502
6503 @item
6504 A unary plus or minus may not be followed by a space.
6505
6506 @item
6507 A vertical bar must be surrounded by spaces.
6508 @end itemize
6509
6510 @item ^u^UNNECESSARY_BLANK_LINES^
6511 @emph{Check unnecessary blank lines.}
6512 Unnecessary blank lines are not allowed. A blank line is considered
6513 unnecessary if it appears at the end of the file, or if more than
6514 one blank line occurs in sequence.
6515
6516 @item ^x^XTRA_PARENS^
6517 @emph{Check extra parentheses.}
6518 Unnecessary extra level of parentheses (C-style) are not allowed
6519 around conditions in @code{if} statements, @code{while} statements and
6520 @code{exit} statements.
6521
6522 @item ^y^ALL_BUILTIN^
6523 @emph{Set all standard style check options}
6524 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6525 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6526 @option{-gnatyS}, @option{-gnatyLnnn},
6527 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6528
6529 @ifclear vms
6530 @item -
6531 @emph{Remove style check options}
6532 This causes any subsequent options in the string to act as canceling the
6533 corresponding style check option. To cancel maximum nesting level control,
6534 use @option{L} parameter witout any integer value after that, because any
6535 digit following @option{-} in the parameter string of the @option{-gnaty}
6536 option will be threated as canceling indentation check. The same is true
6537 for @option{M} parameter. @option{y} and @option{N} parameters are not
6538 allowed after @option{-}.
6539
6540 @item +
6541 This causes any subsequent options in the string to enable the corresponding
6542 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6543 if any.
6544 @end ifclear
6545
6546 @ifset vms
6547 @item NOxxx
6548 @emph{Removing style check options}
6549 If the name of a style check is preceded by @option{NO} then the corresponding
6550 style check is turned off. For example @option{NOCOMMENTS} turns off style
6551 checking for comments.
6552 @end ifset
6553 @end table
6554
6555 @noindent
6556 In the above rules, appearing in column one is always permitted, that is,
6557 counts as meeting either a requirement for a required preceding space,
6558 or as meeting a requirement for no preceding space.
6559
6560 Appearing at the end of a line is also always permitted, that is, counts
6561 as meeting either a requirement for a following space, or as meeting
6562 a requirement for no following space.
6563
6564 @noindent
6565 If any of these style rules is violated, a message is generated giving
6566 details on the violation. The initial characters of such messages are
6567 always ``@code{(style)}''. Note that these messages are treated as warning
6568 messages, so they normally do not prevent the generation of an object
6569 file. The @option{-gnatwe} switch can be used to treat warning messages,
6570 including style messages, as fatal errors.
6571
6572 The switch
6573 @ifclear vms
6574 @option{-gnaty} on its own (that is not
6575 followed by any letters or digits), then the effect is equivalent
6576 to the use of @option{-gnatyy}, as described above, that is all
6577 built-in standard style check options are enabled.
6578
6579 @end ifclear
6580 @ifset vms
6581 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6582 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6583 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6584 @end ifset
6585
6586 The switch
6587 @ifclear vms
6588 @option{-gnatyN}
6589 @end ifclear
6590 @ifset vms
6591 /STYLE_CHECKS=NONE
6592 @end ifset
6593 clears any previously set style checks.
6594
6595 @node Run-Time Checks
6596 @subsection Run-Time Checks
6597 @cindex Division by zero
6598 @cindex Access before elaboration
6599 @cindex Checks, division by zero
6600 @cindex Checks, access before elaboration
6601 @cindex Checks, stack overflow checking
6602
6603 @noindent
6604 By default, the following checks are suppressed: integer overflow
6605 checks, stack overflow checks, and checks for access before
6606 elaboration on subprogram calls. All other checks, including range
6607 checks and array bounds checks, are turned on by default. The
6608 following @command{gcc} switches refine this default behavior.
6609
6610 @table @option
6611 @c !sort!
6612 @item -gnatp
6613 @cindex @option{-gnatp} (@command{gcc})
6614 @cindex Suppressing checks
6615 @cindex Checks, suppressing
6616 @findex Suppress
6617 This switch causes the unit to be compiled
6618 as though @code{pragma Suppress (All_checks)}
6619 had been present in the source. Validity checks are also eliminated (in
6620 other words @option{-gnatp} also implies @option{-gnatVn}.
6621 Use this switch to improve the performance
6622 of the code at the expense of safety in the presence of invalid data or
6623 program bugs.
6624
6625 Note that when checks are suppressed, the compiler is allowed, but not
6626 required, to omit the checking code. If the run-time cost of the
6627 checking code is zero or near-zero, the compiler will generate it even
6628 if checks are suppressed. In particular, if the compiler can prove
6629 that a certain check will necessarily fail, it will generate code to
6630 do an unconditional ``raise'', even if checks are suppressed. The
6631 compiler warns in this case. Another case in which checks may not be
6632 eliminated is when they are embedded in certain run time routines such
6633 as math library routines.
6634
6635 Of course, run-time checks are omitted whenever the compiler can prove
6636 that they will not fail, whether or not checks are suppressed.
6637
6638 Note that if you suppress a check that would have failed, program
6639 execution is erroneous, which means the behavior is totally
6640 unpredictable. The program might crash, or print wrong answers, or
6641 do anything else. It might even do exactly what you wanted it to do
6642 (and then it might start failing mysteriously next week or next
6643 year). The compiler will generate code based on the assumption that
6644 the condition being checked is true, which can result in disaster if
6645 that assumption is wrong.
6646
6647 The @option{-gnatp} switch has no effect if a subsequent
6648 @option{-gnat-p} switch appears.
6649
6650 @item -gnat-p
6651 @cindex @option{-gnat-p} (@command{gcc})
6652 @cindex Suppressing checks
6653 @cindex Checks, suppressing
6654 @findex Suppress
6655 This switch cancels the effect of a previous @option{gnatp} switch.
6656
6657 @item -gnato
6658 @cindex @option{-gnato} (@command{gcc})
6659 @cindex Overflow checks
6660 @cindex Check, overflow
6661 Enables overflow checking for integer operations.
6662 This causes GNAT to generate slower and larger executable
6663 programs by adding code to check for overflow (resulting in raising
6664 @code{Constraint_Error} as required by standard Ada
6665 semantics). These overflow checks correspond to situations in which
6666 the true value of the result of an operation may be outside the base
6667 range of the result type. The following example shows the distinction:
6668
6669 @smallexample @c ada
6670 X1 : Integer := "Integer'Last";
6671 X2 : Integer range 1 .. 5 := "5";
6672 X3 : Integer := "Integer'Last";
6673 X4 : Integer range 1 .. 5 := "5";
6674 F  : Float := "2.0E+20";
6675 @dots{}
6676 X1 := X1 + 1;
6677 X2 := X2 + 1;
6678 X3 := Integer (F);
6679 X4 := Integer (F);
6680 @end smallexample
6681
6682 @noindent
6683 Note that if explicit values are assigned at compile time, the
6684 compiler may be able to detect overflow at compile time, in which case
6685 no actual run-time checking code is required, and Constraint_Error
6686 will be raised unconditionally, with or without
6687 @option{-gnato}. That's why the assigned values in the above fragment
6688 are in quotes, the meaning is "assign a value not known to the
6689 compiler that happens to be equal to ...". The remaining discussion
6690 assumes that the compiler cannot detect the values at compile time.
6691
6692 Here the first addition results in a value that is outside the base range
6693 of Integer, and hence requires an overflow check for detection of the
6694 constraint error. Thus the first assignment to @code{X1} raises a
6695 @code{Constraint_Error} exception only if @option{-gnato} is set.
6696
6697 The second increment operation results in a violation of the explicit
6698 range constraint; such range checks are performed by default, and are
6699 unaffected by @option{-gnato}.
6700
6701 The two conversions of @code{F} both result in values that are outside
6702 the base range of type @code{Integer} and thus will raise
6703 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6704 The fact that the result of the second conversion is assigned to
6705 variable @code{X4} with a restricted range is irrelevant, since the problem
6706 is in the conversion, not the assignment.
6707
6708 Basically the rule is that in the default mode (@option{-gnato} not
6709 used), the generated code assures that all integer variables stay
6710 within their declared ranges, or within the base range if there is
6711 no declared range. This prevents any serious problems like indexes
6712 out of range for array operations.
6713
6714 What is not checked in default mode is an overflow that results in
6715 an in-range, but incorrect value. In the above example, the assignments
6716 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6717 range of the target variable, but the result is wrong in the sense that
6718 it is too large to be represented correctly. Typically the assignment
6719 to @code{X1} will result in wrap around to the largest negative number.
6720 The conversions of @code{F} will result in some @code{Integer} value
6721 and if that integer value is out of the @code{X4} range then the
6722 subsequent assignment would generate an exception.
6723
6724 @findex Machine_Overflows
6725 Note that the @option{-gnato} switch does not affect the code generated
6726 for any floating-point operations; it applies only to integer
6727 semantics).
6728 For floating-point, GNAT has the @code{Machine_Overflows}
6729 attribute set to @code{False} and the normal mode of operation is to
6730 generate IEEE NaN and infinite values on overflow or invalid operations
6731 (such as dividing 0.0 by 0.0).
6732
6733 The reason that we distinguish overflow checking from other kinds of
6734 range constraint checking is that a failure of an overflow check, unlike
6735 for example the failure of a range check, can result in an incorrect
6736 value, but cannot cause random memory destruction (like an out of range
6737 subscript), or a wild jump (from an out of range case value). Overflow
6738 checking is also quite expensive in time and space, since in general it
6739 requires the use of double length arithmetic.
6740
6741 Note again that @option{-gnato} is off by default, so overflow checking is
6742 not performed in default mode. This means that out of the box, with the
6743 default settings, GNAT does not do all the checks expected from the
6744 language description in the Ada Reference Manual. If you want all constraint
6745 checks to be performed, as described in this Manual, then you must
6746 explicitly use the -gnato switch either on the @command{gnatmake} or
6747 @command{gcc} command.
6748
6749 @item -gnatE
6750 @cindex @option{-gnatE} (@command{gcc})
6751 @cindex Elaboration checks
6752 @cindex Check, elaboration
6753 Enables dynamic checks for access-before-elaboration
6754 on subprogram calls and generic instantiations.
6755 Note that @option{-gnatE} is not necessary for safety, because in the
6756 default mode, GNAT ensures statically that the checks would not fail.
6757 For full details of the effect and use of this switch,
6758 @xref{Compiling Using gcc}.
6759
6760 @item -fstack-check
6761 @cindex @option{-fstack-check} (@command{gcc})
6762 @cindex Stack Overflow Checking
6763 @cindex Checks, stack overflow checking
6764 Activates stack overflow checking. For full details of the effect and use of
6765 this switch see @ref{Stack Overflow Checking}.
6766 @end table
6767
6768 @findex Unsuppress
6769 @noindent
6770 The setting of these switches only controls the default setting of the
6771 checks. You may modify them using either @code{Suppress} (to remove
6772 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6773 the program source.
6774
6775 @node Using gcc for Syntax Checking
6776 @subsection Using @command{gcc} for Syntax Checking
6777 @table @option
6778 @item -gnats
6779 @cindex @option{-gnats} (@command{gcc})
6780 @ifclear vms
6781
6782 @noindent
6783 The @code{s} stands for ``syntax''.
6784 @end ifclear
6785
6786 Run GNAT in syntax checking only mode. For
6787 example, the command
6788
6789 @smallexample
6790 $ gcc -c -gnats x.adb
6791 @end smallexample
6792
6793 @noindent
6794 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6795 series of files in a single command
6796 @ifclear vms
6797 , and can use wild cards to specify such a group of files.
6798 Note that you must specify the @option{-c} (compile
6799 only) flag in addition to the @option{-gnats} flag.
6800 @end ifclear
6801 .
6802 You may use other switches in conjunction with @option{-gnats}. In
6803 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6804 format of any generated error messages.
6805
6806 When the source file is empty or contains only empty lines and/or comments,
6807 the output is a warning:
6808
6809 @smallexample
6810 $ gcc -c -gnats -x ada toto.txt
6811 toto.txt:1:01: warning: empty file, contains no compilation units
6812 $
6813 @end smallexample
6814
6815 Otherwise, the output is simply the error messages, if any. No object file or
6816 ALI file is generated by a syntax-only compilation. Also, no units other
6817 than the one specified are accessed. For example, if a unit @code{X}
6818 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6819 check only mode does not access the source file containing unit
6820 @code{Y}.
6821
6822 @cindex Multiple units, syntax checking
6823 Normally, GNAT allows only a single unit in a source file. However, this
6824 restriction does not apply in syntax-check-only mode, and it is possible
6825 to check a file containing multiple compilation units concatenated
6826 together. This is primarily used by the @code{gnatchop} utility
6827 (@pxref{Renaming Files Using gnatchop}).
6828 @end table
6829
6830 @node Using gcc for Semantic Checking
6831 @subsection Using @command{gcc} for Semantic Checking
6832 @table @option
6833 @item -gnatc
6834 @cindex @option{-gnatc} (@command{gcc})
6835
6836 @ifclear vms
6837 @noindent
6838 The @code{c} stands for ``check''.
6839 @end ifclear
6840 Causes the compiler to operate in semantic check mode,
6841 with full checking for all illegalities specified in the
6842 Ada Reference Manual, but without generation of any object code
6843 (no object file is generated).
6844
6845 Because dependent files must be accessed, you must follow the GNAT
6846 semantic restrictions on file structuring to operate in this mode:
6847
6848 @itemize @bullet
6849 @item
6850 The needed source files must be accessible
6851 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6852
6853 @item
6854 Each file must contain only one compilation unit.
6855
6856 @item
6857 The file name and unit name must match (@pxref{File Naming Rules}).
6858 @end itemize
6859
6860 The output consists of error messages as appropriate. No object file is
6861 generated. An @file{ALI} file is generated for use in the context of
6862 cross-reference tools, but this file is marked as not being suitable
6863 for binding (since no object file is generated).
6864 The checking corresponds exactly to the notion of
6865 legality in the Ada Reference Manual.
6866
6867 Any unit can be compiled in semantics-checking-only mode, including
6868 units that would not normally be compiled (subunits,
6869 and specifications where a separate body is present).
6870 @end table
6871
6872 @node Compiling Different Versions of Ada
6873 @subsection Compiling Different Versions of Ada
6874
6875 @noindent
6876 The switches described in this section allow you to explicitly specify
6877 the version of the Ada language that your programs are written in.
6878 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6879 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6880 indicate Ada 83 compatibility mode.
6881
6882 @table @option
6883 @cindex Compatibility with Ada 83
6884
6885 @item -gnat83 (Ada 83 Compatibility Mode)
6886 @cindex @option{-gnat83} (@command{gcc})
6887 @cindex ACVC, Ada 83 tests
6888 @cindex Ada 83 mode
6889
6890 @noindent
6891 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6892 specifies that the program is to be compiled in Ada 83 mode. With
6893 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6894 semantics where this can be done easily.
6895 It is not possible to guarantee this switch does a perfect
6896 job; some subtle tests, such as are
6897 found in earlier ACVC tests (and that have been removed from the ACATS suite
6898 for Ada 95), might not compile correctly.
6899 Nevertheless, this switch may be useful in some circumstances, for example
6900 where, due to contractual reasons, existing code needs to be maintained
6901 using only Ada 83 features.
6902
6903 With few exceptions (most notably the need to use @code{<>} on
6904 @cindex Generic formal parameters
6905 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6906 reserved words, and the use of packages
6907 with optional bodies), it is not necessary to specify the
6908 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6909 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6910 a correct Ada 83 program is usually also a correct program
6911 in these later versions of the language standard.
6912 For further information, please refer to @ref{Compatibility and Porting Guide}.
6913
6914 @item -gnat95 (Ada 95 mode)
6915 @cindex @option{-gnat95} (@command{gcc})
6916 @cindex Ada 95 mode
6917
6918 @noindent
6919 This switch directs the compiler to implement the Ada 95 version of the
6920 language.
6921 Since Ada 95 is almost completely upwards
6922 compatible with Ada 83, Ada 83 programs may generally be compiled using
6923 this switch (see the description of the @option{-gnat83} switch for further
6924 information about Ada 83 mode).
6925 If an Ada 2005 program is compiled in Ada 95 mode,
6926 uses of the new Ada 2005 features will cause error
6927 messages or warnings.
6928
6929 This switch also can be used to cancel the effect of a previous
6930 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6931 switch earlier in the command line.
6932
6933 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6934 @cindex @option{-gnat05} (@command{gcc})
6935 @cindex @option{-gnat2005} (@command{gcc})
6936 @cindex Ada 2005 mode
6937
6938 @noindent
6939 This switch directs the compiler to implement the Ada 2005 version of the
6940 language, as documented in the official Ada standards document.
6941 Since Ada 2005 is almost completely upwards
6942 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6943 may generally be compiled using this switch (see the description of the
6944 @option{-gnat83} and @option{-gnat95} switches for further
6945 information).
6946
6947 Note that even though Ada 2005 is the current official version of the
6948 language, GNAT still compiles in Ada 95 mode by default, so if you are
6949 using Ada 2005 features in your program, you must use this switch (or
6950 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6951
6952 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6953 @cindex @option{-gnat12} (@command{gcc})
6954 @cindex @option{-gnat2012} (@command{gcc})
6955 @cindex Ada 2012 mode
6956
6957 @noindent
6958 This switch directs the compiler to implement the Ada 2012 version of the
6959 language.
6960 Since Ada 2012 is almost completely upwards
6961 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6962 Ada 83 and Ada 95 programs
6963 may generally be compiled using this switch (see the description of the
6964 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6965 for further information).
6966
6967 For information about the approved ``Ada Issues'' that have been incorporated
6968 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6969 Included with GNAT releases is a file @file{features-ada12} that describes
6970 the set of implemented Ada 2012 features.
6971
6972 @item -gnatX (Enable GNAT Extensions)
6973 @cindex @option{-gnatX} (@command{gcc})
6974 @cindex Ada language extensions
6975 @cindex GNAT extensions
6976
6977 @noindent
6978 This switch directs the compiler to implement the latest version of the
6979 language (currently Ada 2012) and also to enable certain GNAT implementation
6980 extensions that are not part of any Ada standard. For a full list of these
6981 extensions, see the GNAT reference manual.
6982
6983 @end table
6984
6985 @node Character Set Control
6986 @subsection Character Set Control
6987 @table @option
6988 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6989 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6990
6991 @noindent
6992 Normally GNAT recognizes the Latin-1 character set in source program
6993 identifiers, as described in the Ada Reference Manual.
6994 This switch causes
6995 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6996 single character ^^or word^ indicating the character set, as follows:
6997
6998 @table @code
6999 @item 1
7000 ISO 8859-1 (Latin-1) identifiers
7001
7002 @item 2
7003 ISO 8859-2 (Latin-2) letters allowed in identifiers
7004
7005 @item 3
7006 ISO 8859-3 (Latin-3) letters allowed in identifiers
7007
7008 @item 4
7009 ISO 8859-4 (Latin-4) letters allowed in identifiers
7010
7011 @item 5
7012 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7013
7014 @item 9
7015 ISO 8859-15 (Latin-9) letters allowed in identifiers
7016
7017 @item ^p^PC^
7018 IBM PC letters (code page 437) allowed in identifiers
7019
7020 @item ^8^PC850^
7021 IBM PC letters (code page 850) allowed in identifiers
7022
7023 @item ^f^FULL_UPPER^
7024 Full upper-half codes allowed in identifiers
7025
7026 @item ^n^NO_UPPER^
7027 No upper-half codes allowed in identifiers
7028
7029 @item ^w^WIDE^
7030 Wide-character codes (that is, codes greater than 255)
7031 allowed in identifiers
7032 @end table
7033
7034 @xref{Foreign Language Representation}, for full details on the
7035 implementation of these character sets.
7036
7037 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7038 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7039 Specify the method of encoding for wide characters.
7040 @var{e} is one of the following:
7041
7042 @table @code
7043
7044 @item ^h^HEX^
7045 Hex encoding (brackets coding also recognized)
7046
7047 @item ^u^UPPER^
7048 Upper half encoding (brackets encoding also recognized)
7049
7050 @item ^s^SHIFT_JIS^
7051 Shift/JIS encoding (brackets encoding also recognized)
7052
7053 @item ^e^EUC^
7054 EUC encoding (brackets encoding also recognized)
7055
7056 @item ^8^UTF8^
7057 UTF-8 encoding (brackets encoding also recognized)
7058
7059 @item ^b^BRACKETS^
7060 Brackets encoding only (default value)
7061 @end table
7062 For full details on these encoding
7063 methods see @ref{Wide Character Encodings}.
7064 Note that brackets coding is always accepted, even if one of the other
7065 options is specified, so for example @option{-gnatW8} specifies that both
7066 brackets and UTF-8 encodings will be recognized. The units that are
7067 with'ed directly or indirectly will be scanned using the specified
7068 representation scheme, and so if one of the non-brackets scheme is
7069 used, it must be used consistently throughout the program. However,
7070 since brackets encoding is always recognized, it may be conveniently
7071 used in standard libraries, allowing these libraries to be used with
7072 any of the available coding schemes.
7073 scheme.
7074
7075 If no @option{-gnatW?} parameter is present, then the default
7076 representation is normally Brackets encoding only. However, if the
7077 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7078 byte order mark or BOM for UTF-8), then these three characters are
7079 skipped and the default representation for the file is set to UTF-8.
7080
7081 Note that the wide character representation that is specified (explicitly
7082 or by default) for the main program also acts as the default encoding used
7083 for Wide_Text_IO files if not specifically overridden by a WCEM form
7084 parameter.
7085
7086 @end table
7087 @node File Naming Control
7088 @subsection File Naming Control
7089
7090 @table @option
7091 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7092 @cindex @option{-gnatk} (@command{gcc})
7093 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7094 1-999, indicates the maximum allowable length of a file name (not
7095 including the @file{.ads} or @file{.adb} extension). The default is not
7096 to enable file name krunching.
7097
7098 For the source file naming rules, @xref{File Naming Rules}.
7099 @end table
7100
7101 @node Subprogram Inlining Control
7102 @subsection Subprogram Inlining Control
7103
7104 @table @option
7105 @c !sort!
7106 @item -gnatn
7107 @cindex @option{-gnatn} (@command{gcc})
7108 @ifclear vms
7109 The @code{n} here is intended to suggest the first syllable of the
7110 word ``inline''.
7111 @end ifclear
7112 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7113 inlining to actually occur, optimization must be enabled. To enable
7114 inlining of subprograms specified by pragma @code{Inline},
7115 you must also specify this switch.
7116 In the absence of this switch, GNAT does not attempt
7117 inlining and does not need to access the bodies of
7118 subprograms for which @code{pragma Inline} is specified if they are not
7119 in the current unit.
7120
7121 If you specify this switch the compiler will access these bodies,
7122 creating an extra source dependency for the resulting object file, and
7123 where possible, the call will be inlined.
7124 For further details on when inlining is possible
7125 see @ref{Inlining of Subprograms}.
7126
7127 @item -gnatN
7128 @cindex @option{-gnatN} (@command{gcc})
7129 This switch activates front-end inlining which also
7130 generates additional dependencies.
7131
7132 When using a gcc-based back end (in practice this means using any version
7133 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7134 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7135 Historically front end inlining was more extensive than the gcc back end
7136 inlining, but that is no longer the case.
7137 @end table
7138
7139 @node Auxiliary Output Control
7140 @subsection Auxiliary Output Control
7141
7142 @table @option
7143 @item -gnatt
7144 @cindex @option{-gnatt} (@command{gcc})
7145 @cindex Writing internal trees
7146 @cindex Internal trees, writing to file
7147 Causes GNAT to write the internal tree for a unit to a file (with the
7148 extension @file{.adt}.
7149 This not normally required, but is used by separate analysis tools.
7150 Typically
7151 these tools do the necessary compilations automatically, so you should
7152 not have to specify this switch in normal operation.
7153 Note that the combination of switches @option{-gnatct}
7154 generates a tree in the form required by ASIS applications.
7155
7156 @item -gnatu
7157 @cindex @option{-gnatu} (@command{gcc})
7158 Print a list of units required by this compilation on @file{stdout}.
7159 The listing includes all units on which the unit being compiled depends
7160 either directly or indirectly.
7161
7162 @ifclear vms
7163 @item -pass-exit-codes
7164 @cindex @option{-pass-exit-codes} (@command{gcc})
7165 If this switch is not used, the exit code returned by @command{gcc} when
7166 compiling multiple files indicates whether all source files have
7167 been successfully used to generate object files or not.
7168
7169 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7170 exit status and allows an integrated development environment to better
7171 react to a compilation failure. Those exit status are:
7172
7173 @table @asis
7174 @item 5
7175 There was an error in at least one source file.
7176 @item 3
7177 At least one source file did not generate an object file.
7178 @item 2
7179 The compiler died unexpectedly (internal error for example).
7180 @item 0
7181 An object file has been generated for every source file.
7182 @end table
7183 @end ifclear
7184 @end table
7185
7186 @node Debugging Control
7187 @subsection Debugging Control
7188
7189 @table @option
7190 @c !sort!
7191 @cindex Debugging options
7192 @ifclear vms
7193 @item -gnatd@var{x}
7194 @cindex @option{-gnatd} (@command{gcc})
7195 Activate internal debugging switches. @var{x} is a letter or digit, or
7196 string of letters or digits, which specifies the type of debugging
7197 outputs desired. Normally these are used only for internal development
7198 or system debugging purposes. You can find full documentation for these
7199 switches in the body of the @code{Debug} unit in the compiler source
7200 file @file{debug.adb}.
7201 @end ifclear
7202
7203 @item -gnatG[=nn]
7204 @cindex @option{-gnatG} (@command{gcc})
7205 This switch causes the compiler to generate auxiliary output containing
7206 a pseudo-source listing of the generated expanded code. Like most Ada
7207 compilers, GNAT works by first transforming the high level Ada code into
7208 lower level constructs. For example, tasking operations are transformed
7209 into calls to the tasking run-time routines. A unique capability of GNAT
7210 is to list this expanded code in a form very close to normal Ada source.
7211 This is very useful in understanding the implications of various Ada
7212 usage on the efficiency of the generated code. There are many cases in
7213 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7214 generate a lot of run-time code. By using @option{-gnatG} you can identify
7215 these cases, and consider whether it may be desirable to modify the coding
7216 approach to improve efficiency.
7217
7218 The optional parameter @code{nn} if present after -gnatG specifies an
7219 alternative maximum line length that overrides the normal default of 72.
7220 This value is in the range 40-999999, values less than 40 being silently
7221 reset to 40. The equal sign is optional.
7222
7223 The format of the output is very similar to standard Ada source, and is
7224 easily understood by an Ada programmer. The following special syntactic
7225 additions correspond to low level features used in the generated code that
7226 do not have any exact analogies in pure Ada source form. The following
7227 is a partial list of these special constructions. See the spec
7228 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7229
7230 If the switch @option{-gnatL} is used in conjunction with
7231 @cindex @option{-gnatL} (@command{gcc})
7232 @option{-gnatG}, then the original source lines are interspersed
7233 in the expanded source (as comment lines with the original line number).
7234
7235 @table @code
7236 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7237 Shows the storage pool being used for an allocator.
7238
7239 @item at end @var{procedure-name};
7240 Shows the finalization (cleanup) procedure for a scope.
7241
7242 @item (if @var{expr} then @var{expr} else @var{expr})
7243 Conditional expression equivalent to the @code{x?y:z} construction in C.
7244
7245 @item @var{target}^^^(@var{source})
7246 A conversion with floating-point truncation instead of rounding.
7247
7248 @item @var{target}?(@var{source})
7249 A conversion that bypasses normal Ada semantic checking. In particular
7250 enumeration types and fixed-point types are treated simply as integers.
7251
7252 @item @var{target}?^^^(@var{source})
7253 Combines the above two cases.
7254
7255 @item @var{x} #/ @var{y}
7256 @itemx @var{x} #mod @var{y}
7257 @itemx @var{x} #* @var{y}
7258 @itemx @var{x} #rem @var{y}
7259 A division or multiplication of fixed-point values which are treated as
7260 integers without any kind of scaling.
7261
7262 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7263 Shows the storage pool associated with a @code{free} statement.
7264
7265 @item [subtype or type declaration]
7266 Used to list an equivalent declaration for an internally generated
7267 type that is referenced elsewhere in the listing.
7268
7269 @c @item freeze @var{type-name} @ovar{actions}
7270 @c Expanding @ovar macro inline (explanation in macro def comments)
7271 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7272 Shows the point at which @var{type-name} is frozen, with possible
7273 associated actions to be performed at the freeze point.
7274
7275 @item reference @var{itype}
7276 Reference (and hence definition) to internal type @var{itype}.
7277
7278 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7279 Intrinsic function call.
7280
7281 @item @var{label-name} : label
7282 Declaration of label @var{labelname}.
7283
7284 @item #$ @var{subprogram-name}
7285 An implicit call to a run-time support routine
7286 (to meet the requirement of H.3.1(9) in a
7287 convenient manner).
7288
7289 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7290 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7291 @var{expr}, but handled more efficiently).
7292
7293 @item [constraint_error]
7294 Raise the @code{Constraint_Error} exception.
7295
7296 @item @var{expression}'reference
7297 A pointer to the result of evaluating @var{expression}.
7298
7299 @item @var{target-type}!(@var{source-expression})
7300 An unchecked conversion of @var{source-expression} to @var{target-type}.
7301
7302 @item [@var{numerator}/@var{denominator}]
7303 Used to represent internal real literals (that) have no exact
7304 representation in base 2-16 (for example, the result of compile time
7305 evaluation of the expression 1.0/27.0).
7306 @end table
7307
7308 @item -gnatD[=nn]
7309 @cindex @option{-gnatD} (@command{gcc})
7310 When used in conjunction with @option{-gnatG}, this switch causes
7311 the expanded source, as described above for
7312 @option{-gnatG} to be written to files with names
7313 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7314 instead of to the standard output file. For
7315 example, if the source file name is @file{hello.adb}, then a file
7316 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7317 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7318 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7319 you to do source level debugging using the generated code which is
7320 sometimes useful for complex code, for example to find out exactly
7321 which part of a complex construction raised an exception. This switch
7322 also suppress generation of cross-reference information (see
7323 @option{-gnatx}) since otherwise the cross-reference information
7324 would refer to the @file{^.dg^.DG^} file, which would cause
7325 confusion since this is not the original source file.
7326
7327 Note that @option{-gnatD} actually implies @option{-gnatG}
7328 automatically, so it is not necessary to give both options.
7329 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7330
7331 If the switch @option{-gnatL} is used in conjunction with
7332 @cindex @option{-gnatL} (@command{gcc})
7333 @option{-gnatDG}, then the original source lines are interspersed
7334 in the expanded source (as comment lines with the original line number).
7335
7336 The optional parameter @code{nn} if present after -gnatD specifies an
7337 alternative maximum line length that overrides the normal default of 72.
7338 This value is in the range 40-999999, values less than 40 being silently
7339 reset to 40. The equal sign is optional.
7340
7341 @item -gnatr
7342 @cindex @option{-gnatr} (@command{gcc})
7343 @cindex pragma Restrictions
7344 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7345 so that violation of restrictions causes warnings rather than illegalities.
7346 This is useful during the development process when new restrictions are added
7347 or investigated. The switch also causes pragma Profile to be treated as
7348 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7349 restriction warnings rather than restrictions.
7350
7351 @ifclear vms
7352 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7353 @cindex @option{-gnatR} (@command{gcc})
7354 This switch controls output from the compiler of a listing showing
7355 representation information for declared types and objects. For
7356 @option{-gnatR0}, no information is output (equivalent to omitting
7357 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7358 so @option{-gnatR} with no parameter has the same effect), size and alignment
7359 information is listed for declared array and record types. For
7360 @option{-gnatR2}, size and alignment information is listed for all
7361 declared types and objects. Finally @option{-gnatR3} includes symbolic
7362 expressions for values that are computed at run time for
7363 variant records. These symbolic expressions have a mostly obvious
7364 format with #n being used to represent the value of the n'th
7365 discriminant. See source files @file{repinfo.ads/adb} in the
7366 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7367 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7368 the output is to a file with the name @file{^file.rep^file_REP^} where
7369 file is the name of the corresponding source file.
7370 @end ifclear
7371 @ifset vms
7372 @item /REPRESENTATION_INFO
7373 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7374 This qualifier controls output from the compiler of a listing showing
7375 representation information for declared types and objects. For
7376 @option{/REPRESENTATION_INFO=NONE}, no information is output
7377 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7378 @option{/REPRESENTATION_INFO} without option is equivalent to
7379 @option{/REPRESENTATION_INFO=ARRAYS}.
7380 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7381 information is listed for declared array and record types. For
7382 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7383 is listed for all expression information for values that are computed
7384 at run time for variant records. These symbolic expressions have a mostly
7385 obvious format with #n being used to represent the value of the n'th
7386 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7387 @code{GNAT} sources for full details on the format of
7388 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7389 If _FILE is added at the end of an option
7390 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7391 then the output is to a file with the name @file{file_REP} where
7392 file is the name of the corresponding source file.
7393 @end ifset
7394 Note that it is possible for record components to have zero size. In
7395 this case, the component clause uses an obvious extension of permitted
7396 Ada syntax, for example @code{at 0 range 0 .. -1}.
7397
7398 Representation information requires that code be generated (since it is the
7399 code generator that lays out complex data structures). If an attempt is made
7400 to output representation information when no code is generated, for example
7401 when a subunit is compiled on its own, then no information can be generated
7402 and the compiler outputs a message to this effect.
7403
7404 @item -gnatS
7405 @cindex @option{-gnatS} (@command{gcc})
7406 The use of the switch @option{-gnatS} for an
7407 Ada compilation will cause the compiler to output a
7408 representation of package Standard in a form very
7409 close to standard Ada. It is not quite possible to
7410 do this entirely in standard Ada (since new
7411 numeric base types cannot be created in standard
7412 Ada), but the output is easily
7413 readable to any Ada programmer, and is useful to
7414 determine the characteristics of target dependent
7415 types in package Standard.
7416
7417 @item -gnatx
7418 @cindex @option{-gnatx} (@command{gcc})
7419 Normally the compiler generates full cross-referencing information in
7420 the @file{ALI} file. This information is used by a number of tools,
7421 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7422 suppresses this information. This saves some space and may slightly
7423 speed up compilation, but means that these tools cannot be used.
7424 @end table
7425
7426 @node Exception Handling Control
7427 @subsection Exception Handling Control
7428
7429 @noindent
7430 GNAT uses two methods for handling exceptions at run-time. The
7431 @code{setjmp/longjmp} method saves the context when entering
7432 a frame with an exception handler. Then when an exception is
7433 raised, the context can be restored immediately, without the
7434 need for tracing stack frames. This method provides very fast
7435 exception propagation, but introduces significant overhead for
7436 the use of exception handlers, even if no exception is raised.
7437
7438 The other approach is called ``zero cost'' exception handling.
7439 With this method, the compiler builds static tables to describe
7440 the exception ranges. No dynamic code is required when entering
7441 a frame containing an exception handler. When an exception is
7442 raised, the tables are used to control a back trace of the
7443 subprogram invocation stack to locate the required exception
7444 handler. This method has considerably poorer performance for
7445 the propagation of exceptions, but there is no overhead for
7446 exception handlers if no exception is raised. Note that in this
7447 mode and in the context of mixed Ada and C/C++ programming,
7448 to propagate an exception through a C/C++ code, the C/C++ code
7449 must be compiled with the @option{-funwind-tables} GCC's
7450 option.
7451
7452 The following switches may be used to control which of the
7453 two exception handling methods is used.
7454
7455 @table @option
7456 @c !sort!
7457
7458 @item --RTS=sjlj
7459 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7460 This switch causes the setjmp/longjmp run-time (when available) to be used
7461 for exception handling. If the default
7462 mechanism for the target is zero cost exceptions, then
7463 this switch can be used to modify this default, and must be
7464 used for all units in the partition.
7465 This option is rarely used. One case in which it may be
7466 advantageous is if you have an application where exception
7467 raising is common and the overall performance of the
7468 application is improved by favoring exception propagation.
7469
7470 @item --RTS=zcx
7471 @cindex @option{--RTS=zcx} (@command{gnatmake})
7472 @cindex Zero Cost Exceptions
7473 This switch causes the zero cost approach to be used
7474 for exception handling. If this is the default mechanism for the
7475 target (see below), then this switch is unneeded. If the default
7476 mechanism for the target is setjmp/longjmp exceptions, then
7477 this switch can be used to modify this default, and must be
7478 used for all units in the partition.
7479 This option can only be used if the zero cost approach
7480 is available for the target in use, otherwise it will generate an error.
7481 @end table
7482
7483 @noindent
7484 The same option @option{--RTS} must be used both for @command{gcc}
7485 and @command{gnatbind}. Passing this option to @command{gnatmake}
7486 (@pxref{Switches for gnatmake}) will ensure the required consistency
7487 through the compilation and binding steps.
7488
7489 @node Units to Sources Mapping Files
7490 @subsection Units to Sources Mapping Files
7491
7492 @table @option
7493
7494 @item -gnatem=@var{path}
7495 @cindex @option{-gnatem} (@command{gcc})
7496 A mapping file is a way to communicate to the compiler two mappings:
7497 from unit names to file names (without any directory information) and from
7498 file names to path names (with full directory information). These mappings
7499 are used by the compiler to short-circuit the path search.
7500
7501 The use of mapping files is not required for correct operation of the
7502 compiler, but mapping files can improve efficiency, particularly when
7503 sources are read over a slow network connection. In normal operation,
7504 you need not be concerned with the format or use of mapping files,
7505 and the @option{-gnatem} switch is not a switch that you would use
7506 explicitly. It is intended primarily for use by automatic tools such as
7507 @command{gnatmake} running under the project file facility. The
7508 description here of the format of mapping files is provided
7509 for completeness and for possible use by other tools.
7510
7511 A mapping file is a sequence of sets of three lines. In each set, the
7512 first line is the unit name, in lower case, with @code{%s} appended
7513 for specs and @code{%b} appended for bodies; the second line is the
7514 file name; and the third line is the path name.
7515
7516 Example:
7517 @smallexample
7518    main%b
7519    main.2.ada
7520    /gnat/project1/sources/main.2.ada
7521 @end smallexample
7522
7523 When the switch @option{-gnatem} is specified, the compiler will
7524 create in memory the two mappings from the specified file. If there is
7525 any problem (nonexistent file, truncated file or duplicate entries),
7526 no mapping will be created.
7527
7528 Several @option{-gnatem} switches may be specified; however, only the
7529 last one on the command line will be taken into account.
7530
7531 When using a project file, @command{gnatmake} creates a temporary
7532 mapping file and communicates it to the compiler using this switch.
7533
7534 @end table
7535
7536 @node Integrated Preprocessing
7537 @subsection Integrated Preprocessing
7538
7539 @noindent
7540 GNAT sources may be preprocessed immediately before compilation.
7541 In this case, the actual
7542 text of the source is not the text of the source file, but is derived from it
7543 through a process called preprocessing. Integrated preprocessing is specified
7544 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7545 indicates, through a text file, the preprocessing data to be used.
7546 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7547
7548 @noindent
7549 Note that when integrated preprocessing is used, the output from the
7550 preprocessor is not written to any external file. Instead it is passed
7551 internally to the compiler. If you need to preserve the result of
7552 preprocessing in a file, then you should use @command{gnatprep}
7553 to perform the desired preprocessing in stand-alone mode.
7554
7555 @noindent
7556 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7557 used when Integrated Preprocessing is used. The reason is that preprocessing
7558 with another Preprocessing Data file without changing the sources will
7559 not trigger recompilation without this switch.
7560
7561 @noindent
7562 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7563 always trigger recompilation for sources that are preprocessed,
7564 because @command{gnatmake} cannot compute the checksum of the source after
7565 preprocessing.
7566
7567 @noindent
7568 The actual preprocessing function is described in details in section
7569 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7570 preprocessing is triggered and parameterized.
7571
7572 @table @code
7573
7574 @item -gnatep=@var{file}
7575 @cindex @option{-gnatep} (@command{gcc})
7576 This switch indicates to the compiler the file name (without directory
7577 information) of the preprocessor data file to use. The preprocessor data file
7578 should be found in the source directories.
7579
7580 @noindent
7581 A preprocessing data file is a text file with significant lines indicating
7582 how should be preprocessed either a specific source or all sources not
7583 mentioned in other lines. A significant line is a nonempty, non-comment line.
7584 Comments are similar to Ada comments.
7585
7586 @noindent
7587 Each significant line starts with either a literal string or the character '*'.
7588 A literal string is the file name (without directory information) of the source
7589 to preprocess. A character '*' indicates the preprocessing for all the sources
7590 that are not specified explicitly on other lines (order of the lines is not
7591 significant). It is an error to have two lines with the same file name or two
7592 lines starting with the character '*'.
7593
7594 @noindent
7595 After the file name or the character '*', another optional literal string
7596 indicating the file name of the definition file to be used for preprocessing
7597 (@pxref{Form of Definitions File}). The definition files are found by the
7598 compiler in one of the source directories. In some cases, when compiling
7599 a source in a directory other than the current directory, if the definition
7600 file is in the current directory, it may be necessary to add the current
7601 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7602 the compiler would not find the definition file.
7603
7604 @noindent
7605 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7606 be found. Those ^switches^switches^ are:
7607
7608 @table @code
7609
7610 @item -b
7611 Causes both preprocessor lines and the lines deleted by
7612 preprocessing to be replaced by blank lines, preserving the line number.
7613 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7614 it cancels the effect of @option{-c}.
7615
7616 @item -c
7617 Causes both preprocessor lines and the lines deleted
7618 by preprocessing to be retained as comments marked
7619 with the special string ``@code{--! }''.
7620
7621 @item -Dsymbol=value
7622 Define or redefine a symbol, associated with value. A symbol is an Ada
7623 identifier, or an Ada reserved word, with the exception of @code{if},
7624 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7625 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7626 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7627 same name defined in a definition file.
7628
7629 @item -s
7630 Causes a sorted list of symbol names and values to be
7631 listed on the standard output file.
7632
7633 @item -u
7634 Causes undefined symbols to be treated as having the value @code{FALSE}
7635 in the context
7636 of a preprocessor test. In the absence of this option, an undefined symbol in
7637 a @code{#if} or @code{#elsif} test will be treated as an error.
7638
7639 @end table
7640
7641 @noindent
7642 Examples of valid lines in a preprocessor data file:
7643
7644 @smallexample
7645   "toto.adb"  "prep.def" -u
7646   --  preprocess "toto.adb", using definition file "prep.def",
7647   --  undefined symbol are False.
7648
7649   * -c -DVERSION=V101
7650   --  preprocess all other sources without a definition file;
7651   --  suppressed lined are commented; symbol VERSION has the value V101.
7652
7653   "titi.adb" "prep2.def" -s
7654   --  preprocess "titi.adb", using definition file "prep2.def";
7655   --  list all symbols with their values.
7656 @end smallexample
7657
7658 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7659 @cindex @option{-gnateD} (@command{gcc})
7660 Define or redefine a preprocessing symbol, associated with value. If no value
7661 is given on the command line, then the value of the symbol is @code{True}.
7662 A symbol is an identifier, following normal Ada (case-insensitive)
7663 rules for its syntax, and value is any sequence (including an empty sequence)
7664 of characters from the set (letters, digits, period, underline).
7665 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7666 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7667
7668 @noindent
7669 A symbol declared with this ^switch^switch^ on the command line replaces a
7670 symbol with the same name either in a definition file or specified with a
7671 ^switch^switch^ -D in the preprocessor data file.
7672
7673 @noindent
7674 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7675
7676 @item -gnateG
7677 When integrated preprocessing is performed and the preprocessor modifies
7678 the source text, write the result of this preprocessing into a file
7679 <source>^.prep^_prep^.
7680
7681 @end table
7682
7683 @node Code Generation Control
7684 @subsection Code Generation Control
7685
7686 @noindent
7687
7688 The GCC technology provides a wide range of target dependent
7689 @option{-m} switches for controlling
7690 details of code generation with respect to different versions of
7691 architectures. This includes variations in instruction sets (e.g.@:
7692 different members of the power pc family), and different requirements
7693 for optimal arrangement of instructions (e.g.@: different members of
7694 the x86 family). The list of available @option{-m} switches may be
7695 found in the GCC documentation.
7696
7697 Use of these @option{-m} switches may in some cases result in improved
7698 code performance.
7699
7700 The GNAT Pro technology is tested and qualified without any
7701 @option{-m} switches,
7702 so generally the most reliable approach is to avoid the use of these
7703 switches. However, we generally expect most of these switches to work
7704 successfully with GNAT Pro, and many customers have reported successful
7705 use of these options.
7706
7707 Our general advice is to avoid the use of @option{-m} switches unless
7708 special needs lead to requirements in this area. In particular,
7709 there is no point in using @option{-m} switches to improve performance
7710 unless you actually see a performance improvement.
7711
7712 @ifset vms
7713 @node Return Codes
7714 @subsection Return Codes
7715 @cindex Return Codes
7716 @cindex @option{/RETURN_CODES=VMS}
7717
7718 @noindent
7719 On VMS, GNAT compiled programs return POSIX-style codes by default,
7720 e.g.@: @option{/RETURN_CODES=POSIX}.
7721
7722 To enable VMS style return codes, use GNAT BIND and LINK with the option
7723 @option{/RETURN_CODES=VMS}. For example:
7724
7725 @smallexample
7726 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7727 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7728 @end smallexample
7729
7730 @noindent
7731 Programs built with /RETURN_CODES=VMS are suitable to be called in
7732 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7733 are suitable for spawning with appropriate GNAT RTL routines.
7734
7735 @end ifset
7736
7737 @node Search Paths and the Run-Time Library (RTL)
7738 @section Search Paths and the Run-Time Library (RTL)
7739
7740 @noindent
7741 With the GNAT source-based library system, the compiler must be able to
7742 find source files for units that are needed by the unit being compiled.
7743 Search paths are used to guide this process.
7744
7745 The compiler compiles one source file whose name must be given
7746 explicitly on the command line. In other words, no searching is done
7747 for this file. To find all other source files that are needed (the most
7748 common being the specs of units), the compiler examines the following
7749 directories, in the following order:
7750
7751 @enumerate
7752 @item
7753 The directory containing the source file of the main unit being compiled
7754 (the file name on the command line).
7755
7756 @item
7757 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7758 @command{gcc} command line, in the order given.
7759
7760 @item
7761 @findex ADA_PRJ_INCLUDE_FILE
7762 Each of the directories listed in the text file whose name is given
7763 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7764
7765 @noindent
7766 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7767 driver when project files are used. It should not normally be set
7768 by other means.
7769
7770 @item
7771 @findex ADA_INCLUDE_PATH
7772 Each of the directories listed in the value of the
7773 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7774 @ifclear vms
7775 Construct this value
7776 exactly as the @env{PATH} environment variable: a list of directory
7777 names separated by colons (semicolons when working with the NT version).
7778 @end ifclear
7779 @ifset vms
7780 Normally, define this value as a logical name containing a comma separated
7781 list of directory names.
7782
7783 This variable can also be defined by means of an environment string
7784 (an argument to the HP C exec* set of functions).
7785
7786 Logical Name:
7787 @smallexample
7788 DEFINE ANOTHER_PATH FOO:[BAG]
7789 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7790 @end smallexample
7791
7792 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7793 first, followed by the standard Ada
7794 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7795 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7796 (Text_IO, Sequential_IO, etc)
7797 instead of the standard Ada packages. Thus, in order to get the standard Ada
7798 packages by default, ADA_INCLUDE_PATH must be redefined.
7799 @end ifset
7800
7801 @item
7802 The content of the @file{ada_source_path} file which is part of the GNAT
7803 installation tree and is used to store standard libraries such as the
7804 GNAT Run Time Library (RTL) source files.
7805 @ifclear vms
7806 @ref{Installing a library}
7807 @end ifclear
7808 @end enumerate
7809
7810 @noindent
7811 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7812 inhibits the use of the directory
7813 containing the source file named in the command line. You can still
7814 have this directory on your search path, but in this case it must be
7815 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7816
7817 Specifying the switch @option{-nostdinc}
7818 inhibits the search of the default location for the GNAT Run Time
7819 Library (RTL) source files.
7820
7821 The compiler outputs its object files and ALI files in the current
7822 working directory.
7823 @ifclear vms
7824 Caution: The object file can be redirected with the @option{-o} switch;
7825 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7826 so the @file{ALI} file will not go to the right place. Therefore, you should
7827 avoid using the @option{-o} switch.
7828 @end ifclear
7829
7830 @findex System.IO
7831 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7832 children make up the GNAT RTL, together with the simple @code{System.IO}
7833 package used in the @code{"Hello World"} example. The sources for these units
7834 are needed by the compiler and are kept together in one directory. Not
7835 all of the bodies are needed, but all of the sources are kept together
7836 anyway. In a normal installation, you need not specify these directory
7837 names when compiling or binding. Either the environment variables or
7838 the built-in defaults cause these files to be found.
7839
7840 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7841 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7842 consisting of child units of @code{GNAT}. This is a collection of generally
7843 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7844 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7845
7846 Besides simplifying access to the RTL, a major use of search paths is
7847 in compiling sources from multiple directories. This can make
7848 development environments much more flexible.
7849
7850 @node Order of Compilation Issues
7851 @section Order of Compilation Issues
7852
7853 @noindent
7854 If, in our earlier example, there was a spec for the @code{hello}
7855 procedure, it would be contained in the file @file{hello.ads}; yet this
7856 file would not have to be explicitly compiled. This is the result of the
7857 model we chose to implement library management. Some of the consequences
7858 of this model are as follows:
7859
7860 @itemize @bullet
7861 @item
7862 There is no point in compiling specs (except for package
7863 specs with no bodies) because these are compiled as needed by clients. If
7864 you attempt a useless compilation, you will receive an error message.
7865 It is also useless to compile subunits because they are compiled as needed
7866 by the parent.
7867
7868 @item
7869 There are no order of compilation requirements: performing a
7870 compilation never obsoletes anything. The only way you can obsolete
7871 something and require recompilations is to modify one of the
7872 source files on which it depends.
7873
7874 @item
7875 There is no library as such, apart from the ALI files
7876 (@pxref{The Ada Library Information Files}, for information on the format
7877 of these files). For now we find it convenient to create separate ALI files,
7878 but eventually the information therein may be incorporated into the object
7879 file directly.
7880
7881 @item
7882 When you compile a unit, the source files for the specs of all units
7883 that it @code{with}'s, all its subunits, and the bodies of any generics it
7884 instantiates must be available (reachable by the search-paths mechanism
7885 described above), or you will receive a fatal error message.
7886 @end itemize
7887
7888 @node Examples
7889 @section Examples
7890
7891 @noindent
7892 The following are some typical Ada compilation command line examples:
7893
7894 @table @code
7895 @item $ gcc -c xyz.adb
7896 Compile body in file @file{xyz.adb} with all default options.
7897
7898 @ifclear vms
7899 @item $ gcc -c -O2 -gnata xyz-def.adb
7900 @end ifclear
7901 @ifset vms
7902 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7903 @end ifset
7904
7905 Compile the child unit package in file @file{xyz-def.adb} with extensive
7906 optimizations, and pragma @code{Assert}/@code{Debug} statements
7907 enabled.
7908
7909 @item $ gcc -c -gnatc abc-def.adb
7910 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7911 mode.
7912 @end table
7913
7914 @node Binding Using gnatbind
7915 @chapter Binding Using @code{gnatbind}
7916 @findex gnatbind
7917
7918 @menu
7919 * Running gnatbind::
7920 * Switches for gnatbind::
7921 * Command-Line Access::
7922 * Search Paths for gnatbind::
7923 * Examples of gnatbind Usage::
7924 @end menu
7925
7926 @noindent
7927 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7928 to bind compiled GNAT objects.
7929
7930 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7931 driver (see @ref{The GNAT Driver and Project Files}).
7932
7933 The @code{gnatbind} program performs four separate functions:
7934
7935 @enumerate
7936 @item
7937 Checks that a program is consistent, in accordance with the rules in
7938 Chapter 10 of the Ada Reference Manual. In particular, error
7939 messages are generated if a program uses inconsistent versions of a
7940 given unit.
7941
7942 @item
7943 Checks that an acceptable order of elaboration exists for the program
7944 and issues an error message if it cannot find an order of elaboration
7945 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7946
7947 @item
7948 Generates a main program incorporating the given elaboration order.
7949 This program is a small Ada package (body and spec) that
7950 must be subsequently compiled
7951 using the GNAT compiler. The necessary compilation step is usually
7952 performed automatically by @command{gnatlink}. The two most important
7953 functions of this program
7954 are to call the elaboration routines of units in an appropriate order
7955 and to call the main program.
7956
7957 @item
7958 Determines the set of object files required by the given main program.
7959 This information is output in the forms of comments in the generated program,
7960 to be read by the @command{gnatlink} utility used to link the Ada application.
7961 @end enumerate
7962
7963 @node Running gnatbind
7964 @section Running @code{gnatbind}
7965
7966 @noindent
7967 The form of the @code{gnatbind} command is
7968
7969 @smallexample
7970 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7971 @c Expanding @ovar macro inline (explanation in macro def comments)
7972 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7973 @end smallexample
7974
7975 @noindent
7976 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7977 unit body. @code{gnatbind} constructs an Ada
7978 package in two files whose names are
7979 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7980 For example, if given the
7981 parameter @file{hello.ali}, for a main program contained in file
7982 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7983 and @file{b~hello.adb}.
7984
7985 When doing consistency checking, the binder takes into consideration
7986 any source files it can locate. For example, if the binder determines
7987 that the given main program requires the package @code{Pack}, whose
7988 @file{.ALI}
7989 file is @file{pack.ali} and whose corresponding source spec file is
7990 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7991 (using the same search path conventions as previously described for the
7992 @command{gcc} command). If it can locate this source file, it checks that
7993 the time stamps
7994 or source checksums of the source and its references to in @file{ALI} files
7995 match. In other words, any @file{ALI} files that mentions this spec must have
7996 resulted from compiling this version of the source file (or in the case
7997 where the source checksums match, a version close enough that the
7998 difference does not matter).
7999
8000 @cindex Source files, use by binder
8001 The effect of this consistency checking, which includes source files, is
8002 that the binder ensures that the program is consistent with the latest
8003 version of the source files that can be located at bind time. Editing a
8004 source file without compiling files that depend on the source file cause
8005 error messages to be generated by the binder.
8006
8007 For example, suppose you have a main program @file{hello.adb} and a
8008 package @code{P}, from file @file{p.ads} and you perform the following
8009 steps:
8010
8011 @enumerate
8012 @item
8013 Enter @code{gcc -c hello.adb} to compile the main program.
8014
8015 @item
8016 Enter @code{gcc -c p.ads} to compile package @code{P}.
8017
8018 @item
8019 Edit file @file{p.ads}.
8020
8021 @item
8022 Enter @code{gnatbind hello}.
8023 @end enumerate
8024
8025 @noindent
8026 At this point, the file @file{p.ali} contains an out-of-date time stamp
8027 because the file @file{p.ads} has been edited. The attempt at binding
8028 fails, and the binder generates the following error messages:
8029
8030 @smallexample
8031 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8032 error: "p.ads" has been modified and must be recompiled
8033 @end smallexample
8034
8035 @noindent
8036 Now both files must be recompiled as indicated, and then the bind can
8037 succeed, generating a main program. You need not normally be concerned
8038 with the contents of this file, but for reference purposes a sample
8039 binder output file is given in @ref{Example of Binder Output File}.
8040
8041 In most normal usage, the default mode of @command{gnatbind} which is to
8042 generate the main package in Ada, as described in the previous section.
8043 In particular, this means that any Ada programmer can read and understand
8044 the generated main program. It can also be debugged just like any other
8045 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8046 @command{gnatbind} and @command{gnatlink}.
8047
8048 @node Switches for gnatbind
8049 @section Switches for @command{gnatbind}
8050
8051 @noindent
8052 The following switches are available with @code{gnatbind}; details will
8053 be presented in subsequent sections.
8054
8055 @menu
8056 * Consistency-Checking Modes::
8057 * Binder Error Message Control::
8058 * Elaboration Control::
8059 * Output Control::
8060 * Dynamic Allocation Control::
8061 * Binding with Non-Ada Main Programs::
8062 * Binding Programs with No Main Subprogram::
8063 @end menu
8064
8065 @table @option
8066 @c !sort!
8067
8068 @item --version
8069 @cindex @option{--version} @command{gnatbind}
8070 Display Copyright and version, then exit disregarding all other options.
8071
8072 @item --help
8073 @cindex @option{--help} @command{gnatbind}
8074 If @option{--version} was not used, display usage, then exit disregarding
8075 all other options.
8076
8077 @item -a
8078 @cindex @option{-a} @command{gnatbind}
8079 Indicates that, if supported by the platform, the adainit procedure should
8080 be treated as an initialisation routine by the linker (a constructor). This
8081 is intended to be used by the Project Manager to automatically initialize
8082 shared Stand-Alone Libraries.
8083
8084 @item ^-aO^/OBJECT_SEARCH^
8085 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8086 Specify directory to be searched for ALI files.
8087
8088 @item ^-aI^/SOURCE_SEARCH^
8089 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8090 Specify directory to be searched for source file.
8091
8092 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8093 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8094 Output ALI list (to standard output or to the named file).
8095
8096 @item ^-b^/REPORT_ERRORS=BRIEF^
8097 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8098 Generate brief messages to @file{stderr} even if verbose mode set.
8099
8100 @item ^-c^/NOOUTPUT^
8101 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8102 Check only, no generation of binder output file.
8103
8104 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8105 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8106 This switch can be used to change the default task stack size value
8107 to a specified size @var{nn}, which is expressed in bytes by default, or
8108 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8109 with @var{m}.
8110 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8111 in effect, to completing all task specs with
8112 @smallexample @c ada
8113    pragma Storage_Size (nn);
8114 @end smallexample
8115 When they do not already have such a pragma.
8116
8117 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8118 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8119 This switch can be used to change the default secondary stack size value
8120 to a specified size @var{nn}, which is expressed in bytes by default, or
8121 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8122 with @var{m}.
8123
8124 The secondary stack is used to deal with functions that return a variable
8125 sized result, for example a function returning an unconstrained
8126 String. There are two ways in which this secondary stack is allocated.
8127
8128 For most targets, the secondary stack is growing on demand and is allocated
8129 as a chain of blocks in the heap. The -D option is not very
8130 relevant. It only give some control over the size of the allocated
8131 blocks (whose size is the minimum of the default secondary stack size value,
8132 and the actual size needed for the current allocation request).
8133
8134 For certain targets, notably VxWorks 653,
8135 the secondary stack is allocated by carving off a fixed ratio chunk of the
8136 primary task stack. The -D option is used to define the
8137 size of the environment task's secondary stack.
8138
8139 @item ^-e^/ELABORATION_DEPENDENCIES^
8140 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8141 Output complete list of elaboration-order dependencies.
8142
8143 @item ^-E^/STORE_TRACEBACKS^
8144 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8145 Store tracebacks in exception occurrences when the target supports it.
8146 @ignore
8147 @c The following may get moved to an appendix
8148 This option is currently supported on the following targets:
8149 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8150 @end ignore
8151 See also the packages @code{GNAT.Traceback} and
8152 @code{GNAT.Traceback.Symbolic} for more information.
8153 @ifclear vms
8154 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8155 @command{gcc} option.
8156 @end ifclear
8157
8158 @item ^-F^/FORCE_ELABS_FLAGS^
8159 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8160 Force the checks of elaboration flags. @command{gnatbind} does not normally
8161 generate checks of elaboration flags for the main executable, except when
8162 a Stand-Alone Library is used. However, there are cases when this cannot be
8163 detected by gnatbind. An example is importing an interface of a Stand-Alone
8164 Library through a pragma Import and only specifying through a linker switch
8165 this Stand-Alone Library. This switch is used to guarantee that elaboration
8166 flag checks are generated.
8167
8168 @item ^-h^/HELP^
8169 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8170 Output usage (help) information
8171
8172 @item ^-H32^/32_MALLOC^
8173 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8174 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8175 For further details see @ref{Dynamic Allocation Control}.
8176
8177 @item ^-H64^/64_MALLOC^
8178 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8179 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8180 @cindex @code{__gnat_malloc}
8181 For further details see @ref{Dynamic Allocation Control}.
8182
8183 @item ^-I^/SEARCH^
8184 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8185 Specify directory to be searched for source and ALI files.
8186
8187 @item ^-I-^/NOCURRENT_DIRECTORY^
8188 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8189 Do not look for sources in the current directory where @code{gnatbind} was
8190 invoked, and do not look for ALI files in the directory containing the
8191 ALI file named in the @code{gnatbind} command line.
8192
8193 @item ^-l^/ORDER_OF_ELABORATION^
8194 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8195 Output chosen elaboration order.
8196
8197 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8198 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8199 Bind the units for library building. In this case the adainit and
8200 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8201 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8202 ^@var{xxx}final^@var{XXX}FINAL^.
8203 Implies ^-n^/NOCOMPILE^.
8204 @ifclear vms
8205 (@xref{GNAT and Libraries}, for more details.)
8206 @end ifclear
8207 @ifset vms
8208 On OpenVMS, these init and final procedures are exported in uppercase
8209 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8210 the init procedure will be "TOTOINIT" and the exported name of the final
8211 procedure will be "TOTOFINAL".
8212 @end ifset
8213
8214 @item ^-Mxyz^/RENAME_MAIN=xyz^
8215 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8216 Rename generated main program from main to xyz. This option is
8217 supported on cross environments only.
8218
8219 @item ^-m^/ERROR_LIMIT=^@var{n}
8220 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8221 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8222 in the range 1..999999. The default value if no switch is
8223 given is 9999. If the number of warnings reaches this limit, then a
8224 message is output and further warnings are suppressed, the bind
8225 continues in this case. If the number of errors reaches this
8226 limit, then a message is output and the bind is abandoned.
8227 A value of zero means that no limit is enforced. The equal
8228 sign is optional.
8229
8230 @ifset unw
8231 Furthermore, under Windows, the sources pointed to by the libraries path
8232 set in the registry are not searched for.
8233 @end ifset
8234
8235 @item ^-n^/NOMAIN^
8236 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8237 No main program.
8238
8239 @item -nostdinc
8240 @cindex @option{-nostdinc} (@command{gnatbind})
8241 Do not look for sources in the system default directory.
8242
8243 @item -nostdlib
8244 @cindex @option{-nostdlib} (@command{gnatbind})
8245 Do not look for library files in the system default directory.
8246
8247 @item --RTS=@var{rts-path}
8248 @cindex @option{--RTS} (@code{gnatbind})
8249 Specifies the default location of the runtime library. Same meaning as the
8250 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8251
8252 @item ^-o ^/OUTPUT=^@var{file}
8253 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8254 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8255 Note that if this option is used, then linking must be done manually,
8256 gnatlink cannot be used.
8257
8258 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8259 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8260 Output object list (to standard output or to the named file).
8261
8262 @item ^-p^/PESSIMISTIC_ELABORATION^
8263 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8264 Pessimistic (worst-case) elaboration order
8265
8266 @item ^-R^-R^
8267 @cindex @option{^-R^-R^} (@command{gnatbind})
8268 Output closure source list.
8269
8270 @item ^-s^/READ_SOURCES=ALL^
8271 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8272 Require all source files to be present.
8273
8274 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8275 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8276 Specifies the value to be used when detecting uninitialized scalar
8277 objects with pragma Initialize_Scalars.
8278 The @var{xxx} ^string specified with the switch^option^ may be either
8279 @itemize @bullet
8280 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8281 @item ``@option{^lo^LOW^}'' for the lowest possible value
8282 @item ``@option{^hi^HIGH^}'' for the highest possible value
8283 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8284 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8285 @end itemize
8286
8287 In addition, you can specify @option{-Sev} to indicate that the value is
8288 to be set at run time. In this case, the program will look for an environment
8289 @cindex GNAT_INIT_SCALARS
8290 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8291 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8292 If no environment variable is found, or if it does not have a valid value,
8293 then the default is @option{in} (invalid values).
8294
8295 @ifclear vms
8296 @item -static
8297 @cindex @option{-static} (@code{gnatbind})
8298 Link against a static GNAT run time.
8299
8300 @item -shared
8301 @cindex @option{-shared} (@code{gnatbind})
8302 Link against a shared GNAT run time when available.
8303 @end ifclear
8304
8305 @item ^-t^/NOTIME_STAMP_CHECK^
8306 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8307 Tolerate time stamp and other consistency errors
8308
8309 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8310 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8311 Set the time slice value to @var{n} milliseconds. If the system supports
8312 the specification of a specific time slice value, then the indicated value
8313 is used. If the system does not support specific time slice values, but
8314 does support some general notion of round-robin scheduling, then any
8315 nonzero value will activate round-robin scheduling.
8316
8317 A value of zero is treated specially. It turns off time
8318 slicing, and in addition, indicates to the tasking run time that the
8319 semantics should match as closely as possible the Annex D
8320 requirements of the Ada RM, and in particular sets the default
8321 scheduling policy to @code{FIFO_Within_Priorities}.
8322
8323 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8324 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8325 Enable dynamic stack usage, with @var{n} results stored and displayed
8326 at program termination. A result is generated when a task
8327 terminates. Results that can't be stored are displayed on the fly, at
8328 task termination. This option is currently not supported on Itanium
8329 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8330
8331 @item ^-v^/REPORT_ERRORS=VERBOSE^
8332 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8333 Verbose mode. Write error messages, header, summary output to
8334 @file{stdout}.
8335
8336 @ifclear vms
8337 @item -w@var{x}
8338 @cindex @option{-w} (@code{gnatbind})
8339 Warning mode (@var{x}=s/e for suppress/treat as error)
8340 @end ifclear
8341
8342 @ifset vms
8343 @item /WARNINGS=NORMAL
8344 @cindex @option{/WARNINGS} (@code{gnatbind})
8345 Normal warnings mode. Warnings are issued but ignored
8346
8347 @item /WARNINGS=SUPPRESS
8348 @cindex @option{/WARNINGS} (@code{gnatbind})
8349 All warning messages are suppressed
8350
8351 @item /WARNINGS=ERROR
8352 @cindex @option{/WARNINGS} (@code{gnatbind})
8353 Warning messages are treated as fatal errors
8354 @end ifset
8355
8356 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8357 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8358 Override default wide character encoding for standard Text_IO files.
8359
8360 @item ^-x^/READ_SOURCES=NONE^
8361 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8362 Exclude source files (check object consistency only).
8363
8364 @ifset vms
8365 @item /READ_SOURCES=AVAILABLE
8366 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8367 Default mode, in which sources are checked for consistency only if
8368 they are available.
8369 @end ifset
8370
8371 @item ^-y^/ENABLE_LEAP_SECONDS^
8372 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8373 Enable leap seconds support in @code{Ada.Calendar} and its children.
8374
8375 @item ^-z^/ZERO_MAIN^
8376 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8377 No main subprogram.
8378 @end table
8379
8380 @ifclear vms
8381 @noindent
8382 You may obtain this listing of switches by running @code{gnatbind} with
8383 no arguments.
8384 @end ifclear
8385
8386 @node Consistency-Checking Modes
8387 @subsection Consistency-Checking Modes
8388
8389 @noindent
8390 As described earlier, by default @code{gnatbind} checks
8391 that object files are consistent with one another and are consistent
8392 with any source files it can locate. The following switches control binder
8393 access to sources.
8394
8395 @table @option
8396 @c !sort!
8397 @item ^-s^/READ_SOURCES=ALL^
8398 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8399 Require source files to be present. In this mode, the binder must be
8400 able to locate all source files that are referenced, in order to check
8401 their consistency. In normal mode, if a source file cannot be located it
8402 is simply ignored. If you specify this switch, a missing source
8403 file is an error.
8404
8405 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8406 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8407 Override default wide character encoding for standard Text_IO files.
8408 Normally the default wide character encoding method used for standard
8409 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8410 the main source input (see description of switch
8411 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8412 use of this switch for the binder (which has the same set of
8413 possible arguments) overrides this default as specified.
8414
8415 @item ^-x^/READ_SOURCES=NONE^
8416 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8417 Exclude source files. In this mode, the binder only checks that ALI
8418 files are consistent with one another. Source files are not accessed.
8419 The binder runs faster in this mode, and there is still a guarantee that
8420 the resulting program is self-consistent.
8421 If a source file has been edited since it was last compiled, and you
8422 specify this switch, the binder will not detect that the object
8423 file is out of date with respect to the source file. Note that this is the
8424 mode that is automatically used by @command{gnatmake} because in this
8425 case the checking against sources has already been performed by
8426 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8427
8428 @ifset vms
8429 @item /READ_SOURCES=AVAILABLE
8430 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8431 This is the default mode in which source files are checked if they are
8432 available, and ignored if they are not available.
8433 @end ifset
8434 @end table
8435
8436 @node Binder Error Message Control
8437 @subsection Binder Error Message Control
8438
8439 @noindent
8440 The following switches provide control over the generation of error
8441 messages from the binder:
8442
8443 @table @option
8444 @c !sort!
8445 @item ^-v^/REPORT_ERRORS=VERBOSE^
8446 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8447 Verbose mode. In the normal mode, brief error messages are generated to
8448 @file{stderr}. If this switch is present, a header is written
8449 to @file{stdout} and any error messages are directed to @file{stdout}.
8450 All that is written to @file{stderr} is a brief summary message.
8451
8452 @item ^-b^/REPORT_ERRORS=BRIEF^
8453 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8454 Generate brief error messages to @file{stderr} even if verbose mode is
8455 specified. This is relevant only when used with the
8456 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8457
8458 @ifclear vms
8459 @item -m@var{n}
8460 @cindex @option{-m} (@code{gnatbind})
8461 Limits the number of error messages to @var{n}, a decimal integer in the
8462 range 1-999. The binder terminates immediately if this limit is reached.
8463
8464 @item -M@var{xxx}
8465 @cindex @option{-M} (@code{gnatbind})
8466 Renames the generated main program from @code{main} to @code{xxx}.
8467 This is useful in the case of some cross-building environments, where
8468 the actual main program is separate from the one generated
8469 by @code{gnatbind}.
8470 @end ifclear
8471
8472 @item ^-ws^/WARNINGS=SUPPRESS^
8473 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8474 @cindex Warnings
8475 Suppress all warning messages.
8476
8477 @item ^-we^/WARNINGS=ERROR^
8478 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8479 Treat any warning messages as fatal errors.
8480
8481 @ifset vms
8482 @item /WARNINGS=NORMAL
8483 Standard mode with warnings generated, but warnings do not get treated
8484 as errors.
8485 @end ifset
8486
8487 @item ^-t^/NOTIME_STAMP_CHECK^
8488 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8489 @cindex Time stamp checks, in binder
8490 @cindex Binder consistency checks
8491 @cindex Consistency checks, in binder
8492 The binder performs a number of consistency checks including:
8493
8494 @itemize @bullet
8495 @item
8496 Check that time stamps of a given source unit are consistent
8497 @item
8498 Check that checksums of a given source unit are consistent
8499 @item
8500 Check that consistent versions of @code{GNAT} were used for compilation
8501 @item
8502 Check consistency of configuration pragmas as required
8503 @end itemize
8504
8505 @noindent
8506 Normally failure of such checks, in accordance with the consistency
8507 requirements of the Ada Reference Manual, causes error messages to be
8508 generated which abort the binder and prevent the output of a binder
8509 file and subsequent link to obtain an executable.
8510
8511 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8512 into warnings, so that
8513 binding and linking can continue to completion even in the presence of such
8514 errors. The result may be a failed link (due to missing symbols), or a
8515 non-functional executable which has undefined semantics.
8516 @emph{This means that
8517 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8518 with extreme care.}
8519 @end table
8520
8521 @node Elaboration Control
8522 @subsection Elaboration Control
8523
8524 @noindent
8525 The following switches provide additional control over the elaboration
8526 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8527
8528 @table @option
8529 @item ^-p^/PESSIMISTIC_ELABORATION^
8530 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8531 Normally the binder attempts to choose an elaboration order that is
8532 likely to minimize the likelihood of an elaboration order error resulting
8533 in raising a @code{Program_Error} exception. This switch reverses the
8534 action of the binder, and requests that it deliberately choose an order
8535 that is likely to maximize the likelihood of an elaboration error.
8536 This is useful in ensuring portability and avoiding dependence on
8537 accidental fortuitous elaboration ordering.
8538
8539 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8540 switch if dynamic
8541 elaboration checking is used (@option{-gnatE} switch used for compilation).
8542 This is because in the default static elaboration mode, all necessary
8543 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8544 These implicit pragmas are still respected by the binder in
8545 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8546 safe elaboration order is assured.
8547 @end table
8548
8549 @node Output Control
8550 @subsection Output Control
8551
8552 @noindent
8553 The following switches allow additional control over the output
8554 generated by the binder.
8555
8556 @table @option
8557 @c !sort!
8558
8559 @item ^-c^/NOOUTPUT^
8560 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8561 Check only. Do not generate the binder output file. In this mode the
8562 binder performs all error checks but does not generate an output file.
8563
8564 @item ^-e^/ELABORATION_DEPENDENCIES^
8565 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8566 Output complete list of elaboration-order dependencies, showing the
8567 reason for each dependency. This output can be rather extensive but may
8568 be useful in diagnosing problems with elaboration order. The output is
8569 written to @file{stdout}.
8570
8571 @item ^-h^/HELP^
8572 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8573 Output usage information. The output is written to @file{stdout}.
8574
8575 @item ^-K^/LINKER_OPTION_LIST^
8576 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8577 Output linker options to @file{stdout}. Includes library search paths,
8578 contents of pragmas Ident and Linker_Options, and libraries added
8579 by @code{gnatbind}.
8580
8581 @item ^-l^/ORDER_OF_ELABORATION^
8582 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8583 Output chosen elaboration order. The output is written to @file{stdout}.
8584
8585 @item ^-O^/OBJECT_LIST^
8586 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8587 Output full names of all the object files that must be linked to provide
8588 the Ada component of the program. The output is written to @file{stdout}.
8589 This list includes the files explicitly supplied and referenced by the user
8590 as well as implicitly referenced run-time unit files. The latter are
8591 omitted if the corresponding units reside in shared libraries. The
8592 directory names for the run-time units depend on the system configuration.
8593
8594 @item ^-o ^/OUTPUT=^@var{file}
8595 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8596 Set name of output file to @var{file} instead of the normal
8597 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8598 binder generated body filename.
8599 Note that if this option is used, then linking must be done manually.
8600 It is not possible to use gnatlink in this case, since it cannot locate
8601 the binder file.
8602
8603 @item ^-r^/RESTRICTION_LIST^
8604 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8605 Generate list of @code{pragma Restrictions} that could be applied to
8606 the current unit. This is useful for code audit purposes, and also may
8607 be used to improve code generation in some cases.
8608
8609 @end table
8610
8611 @node Dynamic Allocation Control
8612 @subsection Dynamic Allocation Control
8613
8614 @noindent
8615 The heap control switches -- @option{-H32} and @option{-H64} --
8616 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8617 They only affect compiler-generated allocations via @code{__gnat_malloc};
8618 explicit calls to @code{malloc} and related functions from the C
8619 run-time library are unaffected.
8620
8621 @table @option
8622 @item -H32
8623 Allocate memory on 32-bit heap
8624
8625 @item -H64
8626 Allocate memory on 64-bit heap.  This is the default
8627 unless explicitly overridden by a @code{'Size} clause on the access type.
8628 @end table
8629
8630 @ifset vms
8631 @noindent
8632 See also @ref{Access types and 32/64-bit allocation}.
8633 @end ifset
8634 @ifclear vms
8635 @noindent
8636 These switches are only effective on VMS platforms.
8637 @end ifclear
8638
8639
8640 @node Binding with Non-Ada Main Programs
8641 @subsection Binding with Non-Ada Main Programs
8642
8643 @noindent
8644 In our description so far we have assumed that the main
8645 program is in Ada, and that the task of the binder is to generate a
8646 corresponding function @code{main} that invokes this Ada main
8647 program. GNAT also supports the building of executable programs where
8648 the main program is not in Ada, but some of the called routines are
8649 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8650 The following switch is used in this situation:
8651
8652 @table @option
8653 @item ^-n^/NOMAIN^
8654 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8655 No main program. The main program is not in Ada.
8656 @end table
8657
8658 @noindent
8659 In this case, most of the functions of the binder are still required,
8660 but instead of generating a main program, the binder generates a file
8661 containing the following callable routines:
8662
8663 @table @code
8664 @item adainit
8665 @findex adainit
8666 You must call this routine to initialize the Ada part of the program by
8667 calling the necessary elaboration routines. A call to @code{adainit} is
8668 required before the first call to an Ada subprogram.
8669
8670 Note that it is assumed that the basic execution environment must be setup
8671 to be appropriate for Ada execution at the point where the first Ada
8672 subprogram is called. In particular, if the Ada code will do any
8673 floating-point operations, then the FPU must be setup in an appropriate
8674 manner. For the case of the x86, for example, full precision mode is
8675 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8676 that the FPU is in the right state.
8677
8678 @item adafinal
8679 @findex adafinal
8680 You must call this routine to perform any library-level finalization
8681 required by the Ada subprograms. A call to @code{adafinal} is required
8682 after the last call to an Ada subprogram, and before the program
8683 terminates.
8684 @end table
8685
8686 @noindent
8687 If the @option{^-n^/NOMAIN^} switch
8688 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8689 @cindex Binder, multiple input files
8690 is given, more than one ALI file may appear on
8691 the command line for @code{gnatbind}. The normal @dfn{closure}
8692 calculation is performed for each of the specified units. Calculating
8693 the closure means finding out the set of units involved by tracing
8694 @code{with} references. The reason it is necessary to be able to
8695 specify more than one ALI file is that a given program may invoke two or
8696 more quite separate groups of Ada units.
8697
8698 The binder takes the name of its output file from the last specified ALI
8699 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8700 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8701 The output is an Ada unit in source form that can be compiled with GNAT.
8702 This compilation occurs automatically as part of the @command{gnatlink}
8703 processing.
8704
8705 Currently the GNAT run time requires a FPU using 80 bits mode
8706 precision. Under targets where this is not the default it is required to
8707 call GNAT.Float_Control.Reset before using floating point numbers (this
8708 include float computation, float input and output) in the Ada code. A
8709 side effect is that this could be the wrong mode for the foreign code
8710 where floating point computation could be broken after this call.
8711
8712 @node Binding Programs with No Main Subprogram
8713 @subsection Binding Programs with No Main Subprogram
8714
8715 @noindent
8716 It is possible to have an Ada program which does not have a main
8717 subprogram. This program will call the elaboration routines of all the
8718 packages, then the finalization routines.
8719
8720 The following switch is used to bind programs organized in this manner:
8721
8722 @table @option
8723 @item ^-z^/ZERO_MAIN^
8724 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8725 Normally the binder checks that the unit name given on the command line
8726 corresponds to a suitable main subprogram. When this switch is used,
8727 a list of ALI files can be given, and the execution of the program
8728 consists of elaboration of these units in an appropriate order. Note
8729 that the default wide character encoding method for standard Text_IO
8730 files is always set to Brackets if this switch is set (you can use
8731 the binder switch
8732 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8733 @end table
8734
8735 @node Command-Line Access
8736 @section Command-Line Access
8737
8738 @noindent
8739 The package @code{Ada.Command_Line} provides access to the command-line
8740 arguments and program name. In order for this interface to operate
8741 correctly, the two variables
8742
8743 @smallexample
8744 @group
8745 int gnat_argc;
8746 char **gnat_argv;
8747 @end group
8748 @end smallexample
8749
8750 @noindent
8751 @findex gnat_argv
8752 @findex gnat_argc
8753 are declared in one of the GNAT library routines. These variables must
8754 be set from the actual @code{argc} and @code{argv} values passed to the
8755 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8756 generates the C main program to automatically set these variables.
8757 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8758 set these variables. If they are not set, the procedures in
8759 @code{Ada.Command_Line} will not be available, and any attempt to use
8760 them will raise @code{Constraint_Error}. If command line access is
8761 required, your main program must set @code{gnat_argc} and
8762 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8763 it.
8764
8765 @node Search Paths for gnatbind
8766 @section Search Paths for @code{gnatbind}
8767
8768 @noindent
8769 The binder takes the name of an ALI file as its argument and needs to
8770 locate source files as well as other ALI files to verify object consistency.
8771
8772 For source files, it follows exactly the same search rules as @command{gcc}
8773 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8774 directories searched are:
8775
8776 @enumerate
8777 @item
8778 The directory containing the ALI file named in the command line, unless
8779 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8780
8781 @item
8782 All directories specified by @option{^-I^/SEARCH^}
8783 switches on the @code{gnatbind}
8784 command line, in the order given.
8785
8786 @item
8787 @findex ADA_PRJ_OBJECTS_FILE
8788 Each of the directories listed in the text file whose name is given
8789 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8790
8791 @noindent
8792 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8793 driver when project files are used. It should not normally be set
8794 by other means.
8795
8796 @item
8797 @findex ADA_OBJECTS_PATH
8798 Each of the directories listed in the value of the
8799 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8800 @ifset unw
8801 Construct this value
8802 exactly as the @env{PATH} environment variable: a list of directory
8803 names separated by colons (semicolons when working with the NT version
8804 of GNAT).
8805 @end ifset
8806 @ifset vms
8807 Normally, define this value as a logical name containing a comma separated
8808 list of directory names.
8809
8810 This variable can also be defined by means of an environment string
8811 (an argument to the HP C exec* set of functions).
8812
8813 Logical Name:
8814 @smallexample
8815 DEFINE ANOTHER_PATH FOO:[BAG]
8816 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8817 @end smallexample
8818
8819 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8820 first, followed by the standard Ada
8821 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8822 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8823 (Text_IO, Sequential_IO, etc)
8824 instead of the standard Ada packages. Thus, in order to get the standard Ada
8825 packages by default, ADA_OBJECTS_PATH must be redefined.
8826 @end ifset
8827
8828 @item
8829 The content of the @file{ada_object_path} file which is part of the GNAT
8830 installation tree and is used to store standard libraries such as the
8831 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8832 specified.
8833 @ifclear vms
8834 @ref{Installing a library}
8835 @end ifclear
8836 @end enumerate
8837
8838 @noindent
8839 In the binder the switch @option{^-I^/SEARCH^}
8840 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8841 is used to specify both source and
8842 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8843 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8844 instead if you want to specify
8845 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8846 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8847 if you want to specify library paths
8848 only. This means that for the binder
8849 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8850 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8851 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8852 The binder generates the bind file (a C language source file) in the
8853 current working directory.
8854
8855 @findex Ada
8856 @findex System
8857 @findex Interfaces
8858 @findex GNAT
8859 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8860 children make up the GNAT Run-Time Library, together with the package
8861 GNAT and its children, which contain a set of useful additional
8862 library functions provided by GNAT. The sources for these units are
8863 needed by the compiler and are kept together in one directory. The ALI
8864 files and object files generated by compiling the RTL are needed by the
8865 binder and the linker and are kept together in one directory, typically
8866 different from the directory containing the sources. In a normal
8867 installation, you need not specify these directory names when compiling
8868 or binding. Either the environment variables or the built-in defaults
8869 cause these files to be found.
8870
8871 Besides simplifying access to the RTL, a major use of search paths is
8872 in compiling sources from multiple directories. This can make
8873 development environments much more flexible.
8874
8875 @node Examples of gnatbind Usage
8876 @section Examples of @code{gnatbind} Usage
8877
8878 @noindent
8879 This section contains a number of examples of using the GNAT binding
8880 utility @code{gnatbind}.
8881
8882 @table @code
8883 @item gnatbind hello
8884 The main program @code{Hello} (source program in @file{hello.adb}) is
8885 bound using the standard switch settings. The generated main program is
8886 @file{b~hello.adb}. This is the normal, default use of the binder.
8887
8888 @ifclear vms
8889 @item gnatbind hello -o mainprog.adb
8890 @end ifclear
8891 @ifset vms
8892 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8893 @end ifset
8894 The main program @code{Hello} (source program in @file{hello.adb}) is
8895 bound using the standard switch settings. The generated main program is
8896 @file{mainprog.adb} with the associated spec in
8897 @file{mainprog.ads}. Note that you must specify the body here not the
8898 spec. Note that if this option is used, then linking must be done manually,
8899 since gnatlink will not be able to find the generated file.
8900 @end table
8901
8902 @c ------------------------------------
8903 @node Linking Using gnatlink
8904 @chapter Linking Using @command{gnatlink}
8905 @c ------------------------------------
8906 @findex gnatlink
8907
8908 @noindent
8909 This chapter discusses @command{gnatlink}, a tool that links
8910 an Ada program and builds an executable file. This utility
8911 invokes the system linker ^(via the @command{gcc} command)^^
8912 with a correct list of object files and library references.
8913 @command{gnatlink} automatically determines the list of files and
8914 references for the Ada part of a program. It uses the binder file
8915 generated by the @command{gnatbind} to determine this list.
8916
8917 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8918 driver (see @ref{The GNAT Driver and Project Files}).
8919
8920 @menu
8921 * Running gnatlink::
8922 * Switches for gnatlink::
8923 @end menu
8924
8925 @node Running gnatlink
8926 @section Running @command{gnatlink}
8927
8928 @noindent
8929 The form of the @command{gnatlink} command is
8930
8931 @smallexample
8932 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8933 @c            @ovar{non-Ada objects} @ovar{linker options}
8934 @c Expanding @ovar macro inline (explanation in macro def comments)
8935 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8936            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8937
8938 @end smallexample
8939
8940 @noindent
8941 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8942 non-Ada objects
8943 or linker options) may be in any order, provided that no non-Ada object may
8944 be mistaken for a main @file{ALI} file.
8945 Any file name @file{F} without the @file{.ali}
8946 extension will be taken as the main @file{ALI} file if a file exists
8947 whose name is the concatenation of @file{F} and @file{.ali}.
8948
8949 @noindent
8950 @file{@var{mainprog}.ali} references the ALI file of the main program.
8951 The @file{.ali} extension of this file can be omitted. From this
8952 reference, @command{gnatlink} locates the corresponding binder file
8953 @file{b~@var{mainprog}.adb} and, using the information in this file along
8954 with the list of non-Ada objects and linker options, constructs a
8955 linker command file to create the executable.
8956
8957 The arguments other than the @command{gnatlink} switches and the main
8958 @file{ALI} file are passed to the linker uninterpreted.
8959 They typically include the names of
8960 object files for units written in other languages than Ada and any library
8961 references required to resolve references in any of these foreign language
8962 units, or in @code{Import} pragmas in any Ada units.
8963
8964 @var{linker options} is an optional list of linker specific
8965 switches.
8966 The default linker called by gnatlink is @command{gcc} which in
8967 turn calls the appropriate system linker.
8968 Standard options for the linker such as @option{-lmy_lib} or
8969 @option{-Ldir} can be added as is.
8970 For options that are not recognized by
8971 @command{gcc} as linker options, use the @command{gcc} switches
8972 @option{-Xlinker} or @option{-Wl,}.
8973 Refer to the GCC documentation for
8974 details. Here is an example showing how to generate a linker map:
8975
8976 @smallexample
8977 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8978 @end smallexample
8979
8980 Using @var{linker options} it is possible to set the program stack and
8981 heap size.
8982 @ifset unw
8983 See @ref{Setting Stack Size from gnatlink} and
8984 @ref{Setting Heap Size from gnatlink}.
8985 @end ifset
8986
8987 @command{gnatlink} determines the list of objects required by the Ada
8988 program and prepends them to the list of objects passed to the linker.
8989 @command{gnatlink} also gathers any arguments set by the use of
8990 @code{pragma Linker_Options} and adds them to the list of arguments
8991 presented to the linker.
8992
8993 @ifset vms
8994 @command{gnatlink} accepts the following types of extra files on the command
8995 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8996 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8997 handled according to their extension.
8998 @end ifset
8999
9000 @node Switches for gnatlink
9001 @section Switches for @command{gnatlink}
9002
9003 @noindent
9004 The following switches are available with the @command{gnatlink} utility:
9005
9006 @table @option
9007 @c !sort!
9008
9009 @item --version
9010 @cindex @option{--version} @command{gnatlink}
9011 Display Copyright and version, then exit disregarding all other options.
9012
9013 @item --help
9014 @cindex @option{--help} @command{gnatlink}
9015 If @option{--version} was not used, display usage, then exit disregarding
9016 all other options.
9017
9018 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9019 @cindex Command line length
9020 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9021 On some targets, the command line length is limited, and @command{gnatlink}
9022 will generate a separate file for the linker if the list of object files
9023 is too long.
9024 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9025 to be generated even if
9026 the limit is not exceeded. This is useful in some cases to deal with
9027 special situations where the command line length is exceeded.
9028
9029 @item ^-g^/DEBUG^
9030 @cindex Debugging information, including
9031 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9032 The option to include debugging information causes the Ada bind file (in
9033 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9034 @option{^-g^/DEBUG^}.
9035 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9036 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9037 Without @option{^-g^/DEBUG^}, the binder removes these files by
9038 default. The same procedure apply if a C bind file was generated using
9039 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9040 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9041
9042 @item ^-n^/NOCOMPILE^
9043 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9044 Do not compile the file generated by the binder. This may be used when
9045 a link is rerun with different options, but there is no need to recompile
9046 the binder file.
9047
9048 @item ^-v^/VERBOSE^
9049 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9050 Causes additional information to be output, including a full list of the
9051 included object files. This switch option is most useful when you want
9052 to see what set of object files are being used in the link step.
9053
9054 @item ^-v -v^/VERBOSE/VERBOSE^
9055 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9056 Very verbose mode. Requests that the compiler operate in verbose mode when
9057 it compiles the binder file, and that the system linker run in verbose mode.
9058
9059 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9060 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9061 @var{exec-name} specifies an alternate name for the generated
9062 executable program. If this switch is omitted, the executable has the same
9063 name as the main unit. For example, @code{gnatlink try.ali} creates
9064 an executable called @file{^try^TRY.EXE^}.
9065
9066 @ifclear vms
9067 @item -b @var{target}
9068 @cindex @option{-b} (@command{gnatlink})
9069 Compile your program to run on @var{target}, which is the name of a
9070 system configuration. You must have a GNAT cross-compiler built if
9071 @var{target} is not the same as your host system.
9072
9073 @item -B@var{dir}
9074 @cindex @option{-B} (@command{gnatlink})
9075 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9076 from @var{dir} instead of the default location. Only use this switch
9077 when multiple versions of the GNAT compiler are available.
9078 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9079 for further details. You would normally use the @option{-b} or
9080 @option{-V} switch instead.
9081
9082 @item --GCC=@var{compiler_name}
9083 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9084 Program used for compiling the binder file. The default is
9085 @command{gcc}. You need to use quotes around @var{compiler_name} if
9086 @code{compiler_name} contains spaces or other separator characters.
9087 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9088 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9089 inserted after your command name. Thus in the above example the compiler
9090 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9091 A limitation of this syntax is that the name and path name of the executable
9092 itself must not include any embedded spaces. If the compiler executable is
9093 different from the default one (gcc or <prefix>-gcc), then the back-end
9094 switches in the ALI file are not used to compile the binder generated source.
9095 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9096 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9097 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9098 is taken into account. However, all the additional switches are also taken
9099 into account. Thus,
9100 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9101 @option{--GCC="bar -x -y -z -t"}.
9102
9103 @item --LINK=@var{name}
9104 @cindex @option{--LINK=} (@command{gnatlink})
9105 @var{name} is the name of the linker to be invoked. This is especially
9106 useful in mixed language programs since languages such as C++ require
9107 their own linker to be used. When this switch is omitted, the default
9108 name for the linker is @command{gcc}. When this switch is used, the
9109 specified linker is called instead of @command{gcc} with exactly the same
9110 parameters that would have been passed to @command{gcc} so if the desired
9111 linker requires different parameters it is necessary to use a wrapper
9112 script that massages the parameters before invoking the real linker. It
9113 may be useful to control the exact invocation by using the verbose
9114 switch.
9115
9116 @end ifclear
9117
9118 @ifset vms
9119 @item /DEBUG=TRACEBACK
9120 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9121 This qualifier causes sufficient information to be included in the
9122 executable file to allow a traceback, but does not include the full
9123 symbol information needed by the debugger.
9124
9125 @item /IDENTIFICATION="<string>"
9126 @code{"<string>"} specifies the string to be stored in the image file
9127 identification field in the image header.
9128 It overrides any pragma @code{Ident} specified string.
9129
9130 @item /NOINHIBIT-EXEC
9131 Generate the executable file even if there are linker warnings.
9132
9133 @item /NOSTART_FILES
9134 Don't link in the object file containing the ``main'' transfer address.
9135 Used when linking with a foreign language main program compiled with an
9136 HP compiler.
9137
9138 @item /STATIC
9139 Prefer linking with object libraries over sharable images, even without
9140 /DEBUG.
9141 @end ifset
9142
9143 @end table
9144
9145 @node The GNAT Make Program gnatmake
9146 @chapter The GNAT Make Program @command{gnatmake}
9147 @findex gnatmake
9148
9149 @menu
9150 * Running gnatmake::
9151 * Switches for gnatmake::
9152 * Mode Switches for gnatmake::
9153 * Notes on the Command Line::
9154 * How gnatmake Works::
9155 * Examples of gnatmake Usage::
9156 @end menu
9157 @noindent
9158 A typical development cycle when working on an Ada program consists of
9159 the following steps:
9160
9161 @enumerate
9162 @item
9163 Edit some sources to fix bugs.
9164
9165 @item
9166 Add enhancements.
9167
9168 @item
9169 Compile all sources affected.
9170
9171 @item
9172 Rebind and relink.
9173
9174 @item
9175 Test.
9176 @end enumerate
9177
9178 @noindent
9179 The third step can be tricky, because not only do the modified files
9180 @cindex Dependency rules
9181 have to be compiled, but any files depending on these files must also be
9182 recompiled. The dependency rules in Ada can be quite complex, especially
9183 in the presence of overloading, @code{use} clauses, generics and inlined
9184 subprograms.
9185
9186 @command{gnatmake} automatically takes care of the third and fourth steps
9187 of this process. It determines which sources need to be compiled,
9188 compiles them, and binds and links the resulting object files.
9189
9190 Unlike some other Ada make programs, the dependencies are always
9191 accurately recomputed from the new sources. The source based approach of
9192 the GNAT compilation model makes this possible. This means that if
9193 changes to the source program cause corresponding changes in
9194 dependencies, they will always be tracked exactly correctly by
9195 @command{gnatmake}.
9196
9197 @node Running gnatmake
9198 @section Running @command{gnatmake}
9199
9200 @noindent
9201 The usual form of the @command{gnatmake} command is
9202
9203 @smallexample
9204 @c $ gnatmake @ovar{switches} @var{file_name}
9205 @c       @ovar{file_names} @ovar{mode_switches}
9206 @c Expanding @ovar macro inline (explanation in macro def comments)
9207 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9208       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9209 @end smallexample
9210
9211 @noindent
9212 The only required argument is one @var{file_name}, which specifies
9213 a compilation unit that is a main program. Several @var{file_names} can be
9214 specified: this will result in several executables being built.
9215 If @code{switches} are present, they can be placed before the first
9216 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9217 If @var{mode_switches} are present, they must always be placed after
9218 the last @var{file_name} and all @code{switches}.
9219
9220 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9221 extension may be omitted from the @var{file_name} arguments. However, if
9222 you are using non-standard extensions, then it is required that the
9223 extension be given. A relative or absolute directory path can be
9224 specified in a @var{file_name}, in which case, the input source file will
9225 be searched for in the specified directory only. Otherwise, the input
9226 source file will first be searched in the directory where
9227 @command{gnatmake} was invoked and if it is not found, it will be search on
9228 the source path of the compiler as described in
9229 @ref{Search Paths and the Run-Time Library (RTL)}.
9230
9231 All @command{gnatmake} output (except when you specify
9232 @option{^-M^/DEPENDENCIES_LIST^}) is to
9233 @file{stderr}. The output produced by the
9234 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9235 @file{stdout}.
9236
9237 @node Switches for gnatmake
9238 @section Switches for @command{gnatmake}
9239
9240 @noindent
9241 You may specify any of the following switches to @command{gnatmake}:
9242
9243 @table @option
9244 @c !sort!
9245
9246 @item --version
9247 @cindex @option{--version} @command{gnatmake}
9248 Display Copyright and version, then exit disregarding all other options.
9249
9250 @item --help
9251 @cindex @option{--help} @command{gnatmake}
9252 If @option{--version} was not used, display usage, then exit disregarding
9253 all other options.
9254
9255 @ifclear vms
9256 @item --GCC=@var{compiler_name}
9257 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9258 Program used for compiling. The default is `@command{gcc}'. You need to use
9259 quotes around @var{compiler_name} if @code{compiler_name} contains
9260 spaces or other separator characters. As an example @option{--GCC="foo -x
9261 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9262 compiler. A limitation of this syntax is that the name and path name of
9263 the executable itself must not include any embedded spaces. Note that
9264 switch @option{-c} is always inserted after your command name. Thus in the
9265 above example the compiler command that will be used by @command{gnatmake}
9266 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9267 used, only the last @var{compiler_name} is taken into account. However,
9268 all the additional switches are also taken into account. Thus,
9269 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9270 @option{--GCC="bar -x -y -z -t"}.
9271
9272 @item --GNATBIND=@var{binder_name}
9273 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9274 Program used for binding. The default is `@code{gnatbind}'. You need to
9275 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9276 or other separator characters. As an example @option{--GNATBIND="bar -x
9277 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9278 binder. Binder switches that are normally appended by @command{gnatmake}
9279 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9280 A limitation of this syntax is that the name and path name of the executable
9281 itself must not include any embedded spaces.
9282
9283 @item --GNATLINK=@var{linker_name}
9284 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9285 Program used for linking. The default is `@command{gnatlink}'. You need to
9286 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9287 or other separator characters. As an example @option{--GNATLINK="lan -x
9288 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9289 linker. Linker switches that are normally appended by @command{gnatmake} to
9290 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9291 A limitation of this syntax is that the name and path name of the executable
9292 itself must not include any embedded spaces.
9293
9294 @end ifclear
9295
9296 @item ^--subdirs^/SUBDIRS^=subdir
9297 Actual object directory of each project file is the subdirectory subdir of the
9298 object directory specified or defaulted in the project file.
9299
9300 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9301 Disallow simultaneous compilations in the same object directory when
9302 project files are used.
9303
9304 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9305 By default, shared library projects are not allowed to import static library
9306 projects. When this switch is used on the command line, this restriction is
9307 relaxed.
9308
9309 @ifclear vms
9310 @item --create-map-file
9311 When linking an executable, create a map file. The name of the map file
9312 has the same name as the executable with extension ".map".
9313
9314 @item --create-map-file=mapfile
9315 When linking an executable, create a map file. The name of the map file is
9316 "mapfile".
9317
9318 @end ifclear
9319
9320 @item ^-a^/ALL_FILES^
9321 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9322 Consider all files in the make process, even the GNAT internal system
9323 files (for example, the predefined Ada library files), as well as any
9324 locked files. Locked files are files whose ALI file is write-protected.
9325 By default,
9326 @command{gnatmake} does not check these files,
9327 because the assumption is that the GNAT internal files are properly up
9328 to date, and also that any write protected ALI files have been properly
9329 installed. Note that if there is an installation problem, such that one
9330 of these files is not up to date, it will be properly caught by the
9331 binder.
9332 You may have to specify this switch if you are working on GNAT
9333 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9334 in conjunction with @option{^-f^/FORCE_COMPILE^}
9335 if you need to recompile an entire application,
9336 including run-time files, using special configuration pragmas,
9337 such as a @code{Normalize_Scalars} pragma.
9338
9339 By default
9340 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9341 internal files with
9342 @ifclear vms
9343 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9344 @end ifclear
9345 @ifset vms
9346 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9347 @end ifset
9348
9349 @item ^-b^/ACTIONS=BIND^
9350 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9351 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9352 compilation and binding, but no link.
9353 Can be combined with @option{^-l^/ACTIONS=LINK^}
9354 to do binding and linking. When not combined with
9355 @option{^-c^/ACTIONS=COMPILE^}
9356 all the units in the closure of the main program must have been previously
9357 compiled and must be up to date. The root unit specified by @var{file_name}
9358 may be given without extension, with the source extension or, if no GNAT
9359 Project File is specified, with the ALI file extension.
9360
9361 @item ^-c^/ACTIONS=COMPILE^
9362 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9363 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9364 is also specified. Do not perform linking, except if both
9365 @option{^-b^/ACTIONS=BIND^} and
9366 @option{^-l^/ACTIONS=LINK^} are also specified.
9367 If the root unit specified by @var{file_name} is not a main unit, this is the
9368 default. Otherwise @command{gnatmake} will attempt binding and linking
9369 unless all objects are up to date and the executable is more recent than
9370 the objects.
9371
9372 @item ^-C^/MAPPING^
9373 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9374 Use a temporary mapping file. A mapping file is a way to communicate
9375 to the compiler two mappings: from unit names to file names (without
9376 any directory information) and from file names to path names (with
9377 full directory information). A mapping file can make the compiler's
9378 file searches faster, especially if there are many source directories,
9379 or the sources are read over a slow network connection. If
9380 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9381 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9382 is initially populated based on the project file. If
9383 @option{^-C^/MAPPING^} is used without
9384 @option{^-P^/PROJECT_FILE^},
9385 the mapping file is initially empty. Each invocation of the compiler
9386 will add any newly accessed sources to the mapping file.
9387
9388 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9389 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9390 Use a specific mapping file. The file, specified as a path name (absolute or
9391 relative) by this switch, should already exist, otherwise the switch is
9392 ineffective. The specified mapping file will be communicated to the compiler.
9393 This switch is not compatible with a project file
9394 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9395 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9396
9397 @item ^-d^/DISPLAY_PROGRESS^
9398 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9399 Display progress for each source, up to date or not, as a single line
9400
9401 @smallexample
9402 completed x out of y (zz%)
9403 @end smallexample
9404
9405 If the file needs to be compiled this is displayed after the invocation of
9406 the compiler. These lines are displayed even in quiet output mode.
9407
9408 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9409 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9410 Put all object files and ALI file in directory @var{dir}.
9411 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9412 and ALI files go in the current working directory.
9413
9414 This switch cannot be used when using a project file.
9415
9416 @ifclear vms
9417 @item -eL
9418 @cindex @option{-eL} (@command{gnatmake})
9419 @cindex symbolic links
9420 Follow all symbolic links when processing project files.
9421 This should be used if your project uses symbolic links for files or
9422 directories, but is not needed in other cases.
9423
9424 @cindex naming scheme
9425 This also assumes that no directory matches the naming scheme for files (for
9426 instance that you do not have a directory called "sources.ads" when using the
9427 default GNAT naming scheme).
9428
9429 When you do not have to use this switch (ie by default), gnatmake is able to
9430 save a lot of system calls (several per source file and object file), which
9431 can result in a significant speed up to load and manipulate a project file,
9432 especially when using source files from a remote system.
9433
9434 @end ifclear
9435
9436 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9437 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9438 Output the commands for the compiler, the binder and the linker
9439 on ^standard output^SYS$OUTPUT^,
9440 instead of ^standard error^SYS$ERROR^.
9441
9442 @item ^-f^/FORCE_COMPILE^
9443 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9444 Force recompilations. Recompile all sources, even though some object
9445 files may be up to date, but don't recompile predefined or GNAT internal
9446 files or locked files (files with a write-protected ALI file),
9447 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9448
9449 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9450 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9451 When using project files, if some errors or warnings are detected during
9452 parsing and verbose mode is not in effect (no use of switch
9453 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9454 file, rather than its simple file name.
9455
9456 @item ^-g^/DEBUG^
9457 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9458 Enable debugging. This switch is simply passed to the compiler and to the
9459 linker.
9460
9461 @item ^-i^/IN_PLACE^
9462 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9463 In normal mode, @command{gnatmake} compiles all object files and ALI files
9464 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9465 then instead object files and ALI files that already exist are overwritten
9466 in place. This means that once a large project is organized into separate
9467 directories in the desired manner, then @command{gnatmake} will automatically
9468 maintain and update this organization. If no ALI files are found on the
9469 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9470 the new object and ALI files are created in the
9471 directory containing the source being compiled. If another organization
9472 is desired, where objects and sources are kept in different directories,
9473 a useful technique is to create dummy ALI files in the desired directories.
9474 When detecting such a dummy file, @command{gnatmake} will be forced to
9475 recompile the corresponding source file, and it will be put the resulting
9476 object and ALI files in the directory where it found the dummy file.
9477
9478 @item ^-j^/PROCESSES=^@var{n}
9479 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9480 @cindex Parallel make
9481 Use @var{n} processes to carry out the (re)compilations. On a
9482 multiprocessor machine compilations will occur in parallel. In the
9483 event of compilation errors, messages from various compilations might
9484 get interspersed (but @command{gnatmake} will give you the full ordered
9485 list of failing compiles at the end). If this is problematic, rerun
9486 the make process with n set to 1 to get a clean list of messages.
9487
9488 @item ^-k^/CONTINUE_ON_ERROR^
9489 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9490 Keep going. Continue as much as possible after a compilation error. To
9491 ease the programmer's task in case of compilation errors, the list of
9492 sources for which the compile fails is given when @command{gnatmake}
9493 terminates.
9494
9495 If @command{gnatmake} is invoked with several @file{file_names} and with this
9496 switch, if there are compilation errors when building an executable,
9497 @command{gnatmake} will not attempt to build the following executables.
9498
9499 @item ^-l^/ACTIONS=LINK^
9500 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9501 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9502 and linking. Linking will not be performed if combined with
9503 @option{^-c^/ACTIONS=COMPILE^}
9504 but not with @option{^-b^/ACTIONS=BIND^}.
9505 When not combined with @option{^-b^/ACTIONS=BIND^}
9506 all the units in the closure of the main program must have been previously
9507 compiled and must be up to date, and the main program needs to have been bound.
9508 The root unit specified by @var{file_name}
9509 may be given without extension, with the source extension or, if no GNAT
9510 Project File is specified, with the ALI file extension.
9511
9512 @item ^-m^/MINIMAL_RECOMPILATION^
9513 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9514 Specify that the minimum necessary amount of recompilations
9515 be performed. In this mode @command{gnatmake} ignores time
9516 stamp differences when the only
9517 modifications to a source file consist in adding/removing comments,
9518 empty lines, spaces or tabs. This means that if you have changed the
9519 comments in a source file or have simply reformatted it, using this
9520 switch will tell @command{gnatmake} not to recompile files that depend on it
9521 (provided other sources on which these files depend have undergone no
9522 semantic modifications). Note that the debugging information may be
9523 out of date with respect to the sources if the @option{-m} switch causes
9524 a compilation to be switched, so the use of this switch represents a
9525 trade-off between compilation time and accurate debugging information.
9526
9527 @item ^-M^/DEPENDENCIES_LIST^
9528 @cindex Dependencies, producing list
9529 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9530 Check if all objects are up to date. If they are, output the object
9531 dependences to @file{stdout} in a form that can be directly exploited in
9532 a @file{Makefile}. By default, each source file is prefixed with its
9533 (relative or absolute) directory name. This name is whatever you
9534 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9535 and @option{^-I^/SEARCH^} switches. If you use
9536 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9537 @option{^-q^/QUIET^}
9538 (see below), only the source file names,
9539 without relative paths, are output. If you just specify the
9540 @option{^-M^/DEPENDENCIES_LIST^}
9541 switch, dependencies of the GNAT internal system files are omitted. This
9542 is typically what you want. If you also specify
9543 the @option{^-a^/ALL_FILES^} switch,
9544 dependencies of the GNAT internal files are also listed. Note that
9545 dependencies of the objects in external Ada libraries (see switch
9546 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9547 are never reported.
9548
9549 @item ^-n^/DO_OBJECT_CHECK^
9550 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9551 Don't compile, bind, or link. Checks if all objects are up to date.
9552 If they are not, the full name of the first file that needs to be
9553 recompiled is printed.
9554 Repeated use of this option, followed by compiling the indicated source
9555 file, will eventually result in recompiling all required units.
9556
9557 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9558 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9559 Output executable name. The name of the final executable program will be
9560 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9561 name for the executable will be the name of the input file in appropriate form
9562 for an executable file on the host system.
9563
9564 This switch cannot be used when invoking @command{gnatmake} with several
9565 @file{file_names}.
9566
9567 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9568 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9569 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9570 automatically missing object directories, library directories and exec
9571 directories.
9572
9573 @item ^-P^/PROJECT_FILE=^@var{project}
9574 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9575 Use project file @var{project}. Only one such switch can be used.
9576 @xref{gnatmake and Project Files}.
9577
9578 @item ^-q^/QUIET^
9579 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9580 Quiet. When this flag is not set, the commands carried out by
9581 @command{gnatmake} are displayed.
9582
9583 @item ^-s^/SWITCH_CHECK/^
9584 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9585 Recompile if compiler switches have changed since last compilation.
9586 All compiler switches but -I and -o are taken into account in the
9587 following way:
9588 orders between different ``first letter'' switches are ignored, but
9589 orders between same switches are taken into account. For example,
9590 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9591 is equivalent to @option{-O -g}.
9592
9593 This switch is recommended when Integrated Preprocessing is used.
9594
9595 @item ^-u^/UNIQUE^
9596 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9597 Unique. Recompile at most the main files. It implies -c. Combined with
9598 -f, it is equivalent to calling the compiler directly. Note that using
9599 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9600 (@pxref{Project Files and Main Subprograms}).
9601
9602 @item ^-U^/ALL_PROJECTS^
9603 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9604 When used without a project file or with one or several mains on the command
9605 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9606 on the command line, all sources of all project files are checked and compiled
9607 if not up to date, and libraries are rebuilt, if necessary.
9608
9609 @item ^-v^/REASONS^
9610 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9611 Verbose. Display the reason for all recompilations @command{gnatmake}
9612 decides are necessary, with the highest verbosity level.
9613
9614 @item ^-vl^/LOW_VERBOSITY^
9615 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9616 Verbosity level Low. Display fewer lines than in verbosity Medium.
9617
9618 @item ^-vm^/MEDIUM_VERBOSITY^
9619 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9620 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9621
9622 @item ^-vh^/HIGH_VERBOSITY^
9623 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9624 Verbosity level High. Equivalent to ^-v^/REASONS^.
9625
9626 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9627 Indicate the verbosity of the parsing of GNAT project files.
9628 @xref{Switches Related to Project Files}.
9629
9630 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9631 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9632 Indicate that sources that are not part of any Project File may be compiled.
9633 Normally, when using Project Files, only sources that are part of a Project
9634 File may be compile. When this switch is used, a source outside of all Project
9635 Files may be compiled. The ALI file and the object file will be put in the
9636 object directory of the main Project. The compilation switches used will only
9637 be those specified on the command line. Even when
9638 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9639 command line need to be sources of a project file.
9640
9641 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9642 Indicate that external variable @var{name} has the value @var{value}.
9643 The Project Manager will use this value for occurrences of
9644 @code{external(name)} when parsing the project file.
9645 @xref{Switches Related to Project Files}.
9646
9647 @item ^-z^/NOMAIN^
9648 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9649 No main subprogram. Bind and link the program even if the unit name
9650 given on the command line is a package name. The resulting executable
9651 will execute the elaboration routines of the package and its closure,
9652 then the finalization routines.
9653
9654 @end table
9655
9656 @table @asis
9657 @item @command{gcc} @asis{switches}
9658 @ifclear vms
9659 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9660 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9661 @end ifclear
9662 @ifset vms
9663 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9664 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9665 automatically treated as a compiler switch, and passed on to all
9666 compilations that are carried out.
9667 @end ifset
9668 @end table
9669
9670 @noindent
9671 Source and library search path switches:
9672
9673 @table @option
9674 @c !sort!
9675 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9676 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9677 When looking for source files also look in directory @var{dir}.
9678 The order in which source files search is undertaken is
9679 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9680
9681 @item ^-aL^/SKIP_MISSING=^@var{dir}
9682 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9683 Consider @var{dir} as being an externally provided Ada library.
9684 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9685 files have been located in directory @var{dir}. This allows you to have
9686 missing bodies for the units in @var{dir} and to ignore out of date bodies
9687 for the same units. You still need to specify
9688 the location of the specs for these units by using the switches
9689 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9690 or @option{^-I^/SEARCH=^@var{dir}}.
9691 Note: this switch is provided for compatibility with previous versions
9692 of @command{gnatmake}. The easier method of causing standard libraries
9693 to be excluded from consideration is to write-protect the corresponding
9694 ALI files.
9695
9696 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9697 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9698 When searching for library and object files, look in directory
9699 @var{dir}. The order in which library files are searched is described in
9700 @ref{Search Paths for gnatbind}.
9701
9702 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9703 @cindex Search paths, for @command{gnatmake}
9704 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9705 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9706 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9707
9708 @item ^-I^/SEARCH=^@var{dir}
9709 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9710 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9711 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9712
9713 @item ^-I-^/NOCURRENT_DIRECTORY^
9714 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9715 @cindex Source files, suppressing search
9716 Do not look for source files in the directory containing the source
9717 file named in the command line.
9718 Do not look for ALI or object files in the directory
9719 where @command{gnatmake} was invoked.
9720
9721 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9722 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9723 @cindex Linker libraries
9724 Add directory @var{dir} to the list of directories in which the linker
9725 will search for libraries. This is equivalent to
9726 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9727 @ifclear vms
9728 Furthermore, under Windows, the sources pointed to by the libraries path
9729 set in the registry are not searched for.
9730 @end ifclear
9731
9732 @item -nostdinc
9733 @cindex @option{-nostdinc} (@command{gnatmake})
9734 Do not look for source files in the system default directory.
9735
9736 @item -nostdlib
9737 @cindex @option{-nostdlib} (@command{gnatmake})
9738 Do not look for library files in the system default directory.
9739
9740 @item --RTS=@var{rts-path}
9741 @cindex @option{--RTS} (@command{gnatmake})
9742 Specifies the default location of the runtime library. GNAT looks for the
9743 runtime
9744 in the following directories, and stops as soon as a valid runtime is found
9745 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9746 @file{ada_object_path} present):
9747
9748 @itemize @bullet
9749 @item <current directory>/$rts_path
9750
9751 @item <default-search-dir>/$rts_path
9752
9753 @item <default-search-dir>/rts-$rts_path
9754 @end itemize
9755
9756 @noindent
9757 The selected path is handled like a normal RTS path.
9758
9759 @end table
9760
9761 @node Mode Switches for gnatmake
9762 @section Mode Switches for @command{gnatmake}
9763
9764 @noindent
9765 The mode switches (referred to as @code{mode_switches}) allow the
9766 inclusion of switches that are to be passed to the compiler itself, the
9767 binder or the linker. The effect of a mode switch is to cause all
9768 subsequent switches up to the end of the switch list, or up to the next
9769 mode switch, to be interpreted as switches to be passed on to the
9770 designated component of GNAT.
9771
9772 @table @option
9773 @c !sort!
9774 @item -cargs @var{switches}
9775 @cindex @option{-cargs} (@command{gnatmake})
9776 Compiler switches. Here @var{switches} is a list of switches
9777 that are valid switches for @command{gcc}. They will be passed on to
9778 all compile steps performed by @command{gnatmake}.
9779
9780 @item -bargs @var{switches}
9781 @cindex @option{-bargs} (@command{gnatmake})
9782 Binder switches. Here @var{switches} is a list of switches
9783 that are valid switches for @code{gnatbind}. They will be passed on to
9784 all bind steps performed by @command{gnatmake}.
9785
9786 @item -largs @var{switches}
9787 @cindex @option{-largs} (@command{gnatmake})
9788 Linker switches. Here @var{switches} is a list of switches
9789 that are valid switches for @command{gnatlink}. They will be passed on to
9790 all link steps performed by @command{gnatmake}.
9791
9792 @item -margs @var{switches}
9793 @cindex @option{-margs} (@command{gnatmake})
9794 Make switches. The switches are directly interpreted by @command{gnatmake},
9795 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9796 or @option{-largs}.
9797 @end table
9798
9799 @node Notes on the Command Line
9800 @section Notes on the Command Line
9801
9802 @noindent
9803 This section contains some additional useful notes on the operation
9804 of the @command{gnatmake} command.
9805
9806 @itemize @bullet
9807 @item
9808 @cindex Recompilation, by @command{gnatmake}
9809 If @command{gnatmake} finds no ALI files, it recompiles the main program
9810 and all other units required by the main program.
9811 This means that @command{gnatmake}
9812 can be used for the initial compile, as well as during subsequent steps of
9813 the development cycle.
9814
9815 @item
9816 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9817 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9818 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9819 warning.
9820
9821 @item
9822 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9823 is used to specify both source and
9824 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9825 instead if you just want to specify
9826 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9827 if you want to specify library paths
9828 only.
9829
9830 @item
9831 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9832 This may conveniently be used to exclude standard libraries from
9833 consideration and in particular it means that the use of the
9834 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9835 unless @option{^-a^/ALL_FILES^} is also specified.
9836
9837 @item
9838 @command{gnatmake} has been designed to make the use of Ada libraries
9839 particularly convenient. Assume you have an Ada library organized
9840 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9841 of your Ada compilation units,
9842 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9843 specs of these units, but no bodies. Then to compile a unit
9844 stored in @code{main.adb}, which uses this Ada library you would just type
9845
9846 @smallexample
9847 @ifclear vms
9848 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9849 @end ifclear
9850 @ifset vms
9851 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9852            /SKIP_MISSING=@i{[OBJ_DIR]} main
9853 @end ifset
9854 @end smallexample
9855
9856 @item
9857 Using @command{gnatmake} along with the
9858 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9859 switch provides a mechanism for avoiding unnecessary recompilations. Using
9860 this switch,
9861 you can update the comments/format of your
9862 source files without having to recompile everything. Note, however, that
9863 adding or deleting lines in a source files may render its debugging
9864 info obsolete. If the file in question is a spec, the impact is rather
9865 limited, as that debugging info will only be useful during the
9866 elaboration phase of your program. For bodies the impact can be more
9867 significant. In all events, your debugger will warn you if a source file
9868 is more recent than the corresponding object, and alert you to the fact
9869 that the debugging information may be out of date.
9870 @end itemize
9871
9872 @node How gnatmake Works
9873 @section How @command{gnatmake} Works
9874
9875 @noindent
9876 Generally @command{gnatmake} automatically performs all necessary
9877 recompilations and you don't need to worry about how it works. However,
9878 it may be useful to have some basic understanding of the @command{gnatmake}
9879 approach and in particular to understand how it uses the results of
9880 previous compilations without incorrectly depending on them.
9881
9882 First a definition: an object file is considered @dfn{up to date} if the
9883 corresponding ALI file exists and if all the source files listed in the
9884 dependency section of this ALI file have time stamps matching those in
9885 the ALI file. This means that neither the source file itself nor any
9886 files that it depends on have been modified, and hence there is no need
9887 to recompile this file.
9888
9889 @command{gnatmake} works by first checking if the specified main unit is up
9890 to date. If so, no compilations are required for the main unit. If not,
9891 @command{gnatmake} compiles the main program to build a new ALI file that
9892 reflects the latest sources. Then the ALI file of the main unit is
9893 examined to find all the source files on which the main program depends,
9894 and @command{gnatmake} recursively applies the above procedure on all these
9895 files.
9896
9897 This process ensures that @command{gnatmake} only trusts the dependencies
9898 in an existing ALI file if they are known to be correct. Otherwise it
9899 always recompiles to determine a new, guaranteed accurate set of
9900 dependencies. As a result the program is compiled ``upside down'' from what may
9901 be more familiar as the required order of compilation in some other Ada
9902 systems. In particular, clients are compiled before the units on which
9903 they depend. The ability of GNAT to compile in any order is critical in
9904 allowing an order of compilation to be chosen that guarantees that
9905 @command{gnatmake} will recompute a correct set of new dependencies if
9906 necessary.
9907
9908 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9909 imported by several of the executables, it will be recompiled at most once.
9910
9911 Note: when using non-standard naming conventions
9912 (@pxref{Using Other File Names}), changing through a configuration pragmas
9913 file the version of a source and invoking @command{gnatmake} to recompile may
9914 have no effect, if the previous version of the source is still accessible
9915 by @command{gnatmake}. It may be necessary to use the switch
9916 ^-f^/FORCE_COMPILE^.
9917
9918 @node Examples of gnatmake Usage
9919 @section Examples of @command{gnatmake} Usage
9920
9921 @table @code
9922 @item gnatmake hello.adb
9923 Compile all files necessary to bind and link the main program
9924 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9925 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9926
9927 @item gnatmake main1 main2 main3
9928 Compile all files necessary to bind and link the main programs
9929 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9930 (containing unit @code{Main2}) and @file{main3.adb}
9931 (containing unit @code{Main3}) and bind and link the resulting object files
9932 to generate three executable files @file{^main1^MAIN1.EXE^},
9933 @file{^main2^MAIN2.EXE^}
9934 and @file{^main3^MAIN3.EXE^}.
9935
9936 @ifclear vms
9937 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9938 @end ifclear
9939
9940 @ifset vms
9941 @item gnatmake Main_Unit /QUIET
9942 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9943 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9944 @end ifset
9945 Compile all files necessary to bind and link the main program unit
9946 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9947 be done with optimization level 2 and the order of elaboration will be
9948 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9949 displaying commands it is executing.
9950 @end table
9951
9952 @c *************************
9953 @node Improving Performance
9954 @chapter Improving Performance
9955 @cindex Improving performance
9956
9957 @noindent
9958 This chapter presents several topics related to program performance.
9959 It first describes some of the tradeoffs that need to be considered
9960 and some of the techniques for making your program run faster.
9961 It then documents the @command{gnatelim} tool and unused subprogram/data
9962 elimination feature, which can reduce the size of program executables.
9963
9964 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9965 driver (see @ref{The GNAT Driver and Project Files}).
9966
9967 @ifnottex
9968 @menu
9969 * Performance Considerations::
9970 * Text_IO Suggestions::
9971 * Reducing Size of Ada Executables with gnatelim::
9972 * Reducing Size of Executables with unused subprogram/data elimination::
9973 @end menu
9974 @end ifnottex
9975
9976 @c *****************************
9977 @node Performance Considerations
9978 @section Performance Considerations
9979
9980 @noindent
9981 The GNAT system provides a number of options that allow a trade-off
9982 between
9983
9984 @itemize @bullet
9985 @item
9986 performance of the generated code
9987
9988 @item
9989 speed of compilation
9990
9991 @item
9992 minimization of dependences and recompilation
9993
9994 @item
9995 the degree of run-time checking.
9996 @end itemize
9997
9998 @noindent
9999 The defaults (if no options are selected) aim at improving the speed
10000 of compilation and minimizing dependences, at the expense of performance
10001 of the generated code:
10002
10003 @itemize @bullet
10004 @item
10005 no optimization
10006
10007 @item
10008 no inlining of subprogram calls
10009
10010 @item
10011 all run-time checks enabled except overflow and elaboration checks
10012 @end itemize
10013
10014 @noindent
10015 These options are suitable for most program development purposes. This
10016 chapter describes how you can modify these choices, and also provides
10017 some guidelines on debugging optimized code.
10018
10019 @menu
10020 * Controlling Run-Time Checks::
10021 * Use of Restrictions::
10022 * Optimization Levels::
10023 * Debugging Optimized Code::
10024 * Inlining of Subprograms::
10025 * Other Optimization Switches::
10026 * Optimization and Strict Aliasing::
10027
10028 @ifset vms
10029 * Coverage Analysis::
10030 @end ifset
10031 @end menu
10032
10033 @node Controlling Run-Time Checks
10034 @subsection Controlling Run-Time Checks
10035
10036 @noindent
10037 By default, GNAT generates all run-time checks, except integer overflow
10038 checks, stack overflow checks, and checks for access before elaboration on
10039 subprogram calls. The latter are not required in default mode, because all
10040 necessary checking is done at compile time.
10041 @cindex @option{-gnatp} (@command{gcc})
10042 @cindex @option{-gnato} (@command{gcc})
10043 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10044 be modified. @xref{Run-Time Checks}.
10045
10046 Our experience is that the default is suitable for most development
10047 purposes.
10048
10049 We treat integer overflow specially because these
10050 are quite expensive and in our experience are not as important as other
10051 run-time checks in the development process. Note that division by zero
10052 is not considered an overflow check, and divide by zero checks are
10053 generated where required by default.
10054
10055 Elaboration checks are off by default, and also not needed by default, since
10056 GNAT uses a static elaboration analysis approach that avoids the need for
10057 run-time checking. This manual contains a full chapter discussing the issue
10058 of elaboration checks, and if the default is not satisfactory for your use,
10059 you should read this chapter.
10060
10061 For validity checks, the minimal checks required by the Ada Reference
10062 Manual (for case statements and assignments to array elements) are on
10063 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10064 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10065 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10066 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10067 are also suppressed entirely if @option{-gnatp} is used.
10068
10069 @cindex Overflow checks
10070 @cindex Checks, overflow
10071 @findex Suppress
10072 @findex Unsuppress
10073 @cindex pragma Suppress
10074 @cindex pragma Unsuppress
10075 Note that the setting of the switches controls the default setting of
10076 the checks. They may be modified using either @code{pragma Suppress} (to
10077 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10078 checks) in the program source.
10079
10080 @node Use of Restrictions
10081 @subsection Use of Restrictions
10082
10083 @noindent
10084 The use of pragma Restrictions allows you to control which features are
10085 permitted in your program. Apart from the obvious point that if you avoid
10086 relatively expensive features like finalization (enforceable by the use
10087 of pragma Restrictions (No_Finalization), the use of this pragma does not
10088 affect the generated code in most cases.
10089
10090 One notable exception to this rule is that the possibility of task abort
10091 results in some distributed overhead, particularly if finalization or
10092 exception handlers are used. The reason is that certain sections of code
10093 have to be marked as non-abortable.
10094
10095 If you use neither the @code{abort} statement, nor asynchronous transfer
10096 of control (@code{select @dots{} then abort}), then this distributed overhead
10097 is removed, which may have a general positive effect in improving
10098 overall performance.  Especially code involving frequent use of tasking
10099 constructs and controlled types will show much improved performance.
10100 The relevant restrictions pragmas are
10101
10102 @smallexample @c ada
10103    pragma Restrictions (No_Abort_Statements);
10104    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10105 @end smallexample
10106
10107 @noindent
10108 It is recommended that these restriction pragmas be used if possible. Note
10109 that this also means that you can write code without worrying about the
10110 possibility of an immediate abort at any point.
10111
10112 @node Optimization Levels
10113 @subsection Optimization Levels
10114 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10115
10116 @noindent
10117 Without any optimization ^option,^qualifier,^
10118 the compiler's goal is to reduce the cost of
10119 compilation and to make debugging produce the expected results.
10120 Statements are independent: if you stop the program with a breakpoint between
10121 statements, you can then assign a new value to any variable or change
10122 the program counter to any other statement in the subprogram and get exactly
10123 the results you would expect from the source code.
10124
10125 Turning on optimization makes the compiler attempt to improve the
10126 performance and/or code size at the expense of compilation time and
10127 possibly the ability to debug the program.
10128
10129 If you use multiple
10130 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10131 the last such option is the one that is effective.
10132
10133 @noindent
10134 The default is optimization off. This results in the fastest compile
10135 times, but GNAT makes absolutely no attempt to optimize, and the
10136 generated programs are considerably larger and slower than when
10137 optimization is enabled. You can use the
10138 @ifclear vms
10139 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10140 @option{-O2}, @option{-O3}, and @option{-Os})
10141 @end ifclear
10142 @ifset vms
10143 @code{OPTIMIZE} qualifier
10144 @end ifset
10145 to @command{gcc} to control the optimization level:
10146
10147 @table @option
10148 @item ^-O0^/OPTIMIZE=NONE^
10149 No optimization (the default);
10150 generates unoptimized code but has
10151 the fastest compilation time.
10152
10153 Note that many other compilers do fairly extensive optimization
10154 even if ``no optimization'' is specified. With gcc, it is
10155 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10156 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10157 really does mean no optimization at all. This difference between
10158 gcc and other compilers should be kept in mind when doing
10159 performance comparisons.
10160
10161 @item ^-O1^/OPTIMIZE=SOME^
10162 Moderate optimization;
10163 optimizes reasonably well but does not
10164 degrade compilation time significantly.
10165
10166 @item ^-O2^/OPTIMIZE=ALL^
10167 @ifset vms
10168 @itemx /OPTIMIZE=DEVELOPMENT
10169 @end ifset
10170 Full optimization;
10171 generates highly optimized code and has
10172 the slowest compilation time.
10173
10174 @item ^-O3^/OPTIMIZE=INLINING^
10175 Full optimization as in @option{-O2};
10176 also uses more aggressive automatic inlining of subprograms within a unit
10177 (@pxref{Inlining of Subprograms}) and attemps to vectorize loops.
10178
10179 @item ^-Os^/OPTIMIZE=SPACE^
10180 Optimize space usage (code and data) of resulting program.
10181 @end table
10182
10183 @noindent
10184 Higher optimization levels perform more global transformations on the
10185 program and apply more expensive analysis algorithms in order to generate
10186 faster and more compact code. The price in compilation time, and the
10187 resulting improvement in execution time,
10188 both depend on the particular application and the hardware environment.
10189 You should experiment to find the best level for your application.
10190
10191 Since the precise set of optimizations done at each level will vary from
10192 release to release (and sometime from target to target), it is best to think
10193 of the optimization settings in general terms.
10194 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10195 the GNU Compiler Collection (GCC)}, for details about
10196 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10197 individually enable or disable specific optimizations.
10198
10199 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10200 been tested extensively at all optimization levels. There are some bugs
10201 which appear only with optimization turned on, but there have also been
10202 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10203 level of optimization does not improve the reliability of the code
10204 generator, which in practice is highly reliable at all optimization
10205 levels.
10206
10207 Note regarding the use of @option{-O3}: The use of this optimization level
10208 is generally discouraged with GNAT, since it often results in larger
10209 executables which may run more slowly. See further discussion of this point
10210 in @ref{Inlining of Subprograms}.
10211
10212 @node Debugging Optimized Code
10213 @subsection Debugging Optimized Code
10214 @cindex Debugging optimized code
10215 @cindex Optimization and debugging
10216
10217 @noindent
10218 Although it is possible to do a reasonable amount of debugging at
10219 @ifclear vms
10220 nonzero optimization levels,
10221 the higher the level the more likely that
10222 @end ifclear
10223 @ifset vms
10224 @option{/OPTIMIZE} settings other than @code{NONE},
10225 such settings will make it more likely that
10226 @end ifset
10227 source-level constructs will have been eliminated by optimization.
10228 For example, if a loop is strength-reduced, the loop
10229 control variable may be completely eliminated and thus cannot be
10230 displayed in the debugger.
10231 This can only happen at @option{-O2} or @option{-O3}.
10232 Explicit temporary variables that you code might be eliminated at
10233 ^level^setting^ @option{-O1} or higher.
10234
10235 The use of the @option{^-g^/DEBUG^} switch,
10236 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10237 which is needed for source-level debugging,
10238 affects the size of the program executable on disk,
10239 and indeed the debugging information can be quite large.
10240 However, it has no effect on the generated code (and thus does not
10241 degrade performance)
10242
10243 Since the compiler generates debugging tables for a compilation unit before
10244 it performs optimizations, the optimizing transformations may invalidate some
10245 of the debugging data.  You therefore need to anticipate certain
10246 anomalous situations that may arise while debugging optimized code.
10247 These are the most common cases:
10248
10249 @enumerate
10250 @item
10251 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10252 commands show
10253 the PC bouncing back and forth in the code.  This may result from any of
10254 the following optimizations:
10255
10256 @itemize @bullet
10257 @item
10258 @i{Common subexpression elimination:} using a single instance of code for a
10259 quantity that the source computes several times.  As a result you
10260 may not be able to stop on what looks like a statement.
10261
10262 @item
10263 @i{Invariant code motion:} moving an expression that does not change within a
10264 loop, to the beginning of the loop.
10265
10266 @item
10267 @i{Instruction scheduling:} moving instructions so as to
10268 overlap loads and stores (typically) with other code, or in
10269 general to move computations of values closer to their uses. Often
10270 this causes you to pass an assignment statement without the assignment
10271 happening and then later bounce back to the statement when the
10272 value is actually needed.  Placing a breakpoint on a line of code
10273 and then stepping over it may, therefore, not always cause all the
10274 expected side-effects.
10275 @end itemize
10276
10277 @item
10278 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10279 two identical pieces of code are merged and the program counter suddenly
10280 jumps to a statement that is not supposed to be executed, simply because
10281 it (and the code following) translates to the same thing as the code
10282 that @emph{was} supposed to be executed.  This effect is typically seen in
10283 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10284 a @code{break} in a C @code{^switch^switch^} statement.
10285
10286 @item
10287 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10288 There are various reasons for this effect:
10289
10290 @itemize @bullet
10291 @item
10292 In a subprogram prologue, a parameter may not yet have been moved to its
10293 ``home''.
10294
10295 @item
10296 A variable may be dead, and its register re-used.  This is
10297 probably the most common cause.
10298
10299 @item
10300 As mentioned above, the assignment of a value to a variable may
10301 have been moved.
10302
10303 @item
10304 A variable may be eliminated entirely by value propagation or
10305 other means.  In this case, GCC may incorrectly generate debugging
10306 information for the variable
10307 @end itemize
10308
10309 @noindent
10310 In general, when an unexpected value appears for a local variable or parameter
10311 you should first ascertain if that value was actually computed by
10312 your program, as opposed to being incorrectly reported by the debugger.
10313 Record fields or
10314 array elements in an object designated by an access value
10315 are generally less of a problem, once you have ascertained that the access
10316 value is sensible.
10317 Typically, this means checking variables in the preceding code and in the
10318 calling subprogram to verify that the value observed is explainable from other
10319 values (one must apply the procedure recursively to those
10320 other values); or re-running the code and stopping a little earlier
10321 (perhaps before the call) and stepping to better see how the variable obtained
10322 the value in question; or continuing to step @emph{from} the point of the
10323 strange value to see if code motion had simply moved the variable's
10324 assignments later.
10325 @end enumerate
10326
10327 @noindent
10328 In light of such anomalies, a recommended technique is to use @option{-O0}
10329 early in the software development cycle, when extensive debugging capabilities
10330 are most needed, and then move to @option{-O1} and later @option{-O2} as
10331 the debugger becomes less critical.
10332 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10333 a release management issue.
10334 @ifclear vms
10335 Note that if you use @option{-g} you can then use the @command{strip} program
10336 on the resulting executable,
10337 which removes both debugging information and global symbols.
10338 @end ifclear
10339
10340 @node Inlining of Subprograms
10341 @subsection Inlining of Subprograms
10342
10343 @noindent
10344 A call to a subprogram in the current unit is inlined if all the
10345 following conditions are met:
10346
10347 @itemize @bullet
10348 @item
10349 The optimization level is at least @option{-O1}.
10350
10351 @item
10352 The called subprogram is suitable for inlining: It must be small enough
10353 and not contain something that @command{gcc} cannot support in inlined
10354 subprograms.
10355
10356 @item
10357 @cindex pragma Inline
10358 @findex Inline
10359 Either @code{pragma Inline} applies to the subprogram, or it is local to
10360 the unit and called once from within it, or it is small and optimization
10361 level @option{-O2} is specified, or automatic inlining (optimization level
10362 @option{-O3}) is specified.
10363 @end itemize
10364
10365 @noindent
10366 Calls to subprograms in @code{with}'ed units are normally not inlined.
10367 To achieve actual inlining (that is, replacement of the call by the code
10368 in the body of the subprogram), the following conditions must all be true.
10369
10370 @itemize @bullet
10371 @item
10372 The optimization level is at least @option{-O1}.
10373
10374 @item
10375 The called subprogram is suitable for inlining: It must be small enough
10376 and not contain something that @command{gcc} cannot support in inlined
10377 subprograms.
10378
10379 @item
10380 The call appears in a body (not in a package spec).
10381
10382 @item
10383 There is a @code{pragma Inline} for the subprogram.
10384
10385 @item
10386 @cindex @option{-gnatn} (@command{gcc})
10387 The @option{^-gnatn^/INLINE^} switch
10388 is used in the @command{gcc} command line
10389 @end itemize
10390
10391 Even if all these conditions are met, it may not be possible for
10392 the compiler to inline the call, due to the length of the body,
10393 or features in the body that make it impossible for the compiler
10394 to do the inlining.
10395
10396 Note that specifying the @option{-gnatn} switch causes additional
10397 compilation dependencies. Consider the following:
10398
10399 @smallexample @c ada
10400 @cartouche
10401 package R is
10402    procedure Q;
10403    pragma Inline (Q);
10404 end R;
10405 package body R is
10406    @dots{}
10407 end R;
10408
10409 with R;
10410 procedure Main is
10411 begin
10412    @dots{}
10413    R.Q;
10414 end Main;
10415 @end cartouche
10416 @end smallexample
10417
10418 @noindent
10419 With the default behavior (no @option{-gnatn} switch specified), the
10420 compilation of the @code{Main} procedure depends only on its own source,
10421 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10422 means that editing the body of @code{R} does not require recompiling
10423 @code{Main}.
10424
10425 On the other hand, the call @code{R.Q} is not inlined under these
10426 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10427 is compiled, the call will be inlined if the body of @code{Q} is small
10428 enough, but now @code{Main} depends on the body of @code{R} in
10429 @file{r.adb} as well as on the spec. This means that if this body is edited,
10430 the main program must be recompiled. Note that this extra dependency
10431 occurs whether or not the call is in fact inlined by @command{gcc}.
10432
10433 The use of front end inlining with @option{-gnatN} generates similar
10434 additional dependencies.
10435
10436 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10437 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10438 can be used to prevent
10439 all inlining. This switch overrides all other conditions and ensures
10440 that no inlining occurs. The extra dependences resulting from
10441 @option{-gnatn} will still be active, even if
10442 this switch is used to suppress the resulting inlining actions.
10443
10444 @cindex @option{-fno-inline-functions} (@command{gcc})
10445 Note: The @option{-fno-inline-functions} switch can be used to prevent
10446 automatic inlining of subprograms if @option{-O3} is used.
10447
10448 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10449 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10450 automatic inlining of small subprograms if @option{-O2} is used.
10451
10452 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10453 Note: The @option{-fno-inline-functions-called-once} switch
10454 can be used to prevent inlining of subprograms local to the unit
10455 and called once from within it if @option{-O1} is used.
10456
10457 Note regarding the use of @option{-O3}: There is no difference in inlining
10458 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10459 pragma @code{Inline} assuming the use of @option{-gnatn}
10460 or @option{-gnatN} (the switches that activate inlining). If you have used
10461 pragma @code{Inline} in appropriate cases, then it is usually much better
10462 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10463 in this case only has the effect of inlining subprograms you did not
10464 think should be inlined. We often find that the use of @option{-O3} slows
10465 down code by performing excessive inlining, leading to increased instruction
10466 cache pressure from the increased code size. So the bottom line here is
10467 that you should not automatically assume that @option{-O3} is better than
10468 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10469 it actually improves performance.
10470
10471 @node Other Optimization Switches
10472 @subsection Other Optimization Switches
10473 @cindex Optimization Switches
10474
10475 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10476 @command{gcc} optimization switches are potentially usable. These switches
10477 have not been extensively tested with GNAT but can generally be expected
10478 to work. Examples of switches in this category are
10479 @option{-funroll-loops} and
10480 the various target-specific @option{-m} options (in particular, it has been
10481 observed that @option{-march=pentium4} can significantly improve performance
10482 on appropriate machines). For full details of these switches, see
10483 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10484 the GNU Compiler Collection (GCC)}.
10485
10486 @node Optimization and Strict Aliasing
10487 @subsection Optimization and Strict Aliasing
10488 @cindex Aliasing
10489 @cindex Strict Aliasing
10490 @cindex No_Strict_Aliasing
10491
10492 @noindent
10493 The strong typing capabilities of Ada allow an optimizer to generate
10494 efficient code in situations where other languages would be forced to
10495 make worst case assumptions preventing such optimizations. Consider
10496 the following example:
10497
10498 @smallexample @c ada
10499 @cartouche
10500 procedure R is
10501    type Int1 is new Integer;
10502    type Int2 is new Integer;
10503    type Int1A is access Int1;
10504    type Int2A is access Int2;
10505    Int1V : Int1A;
10506    Int2V : Int2A;
10507    @dots{}
10508
10509 begin
10510    @dots{}
10511    for J in Data'Range loop
10512       if Data (J) = Int1V.all then
10513          Int2V.all := Int2V.all + 1;
10514       end if;
10515    end loop;
10516    @dots{}
10517 end R;
10518 @end cartouche
10519 @end smallexample
10520
10521 @noindent
10522 In this example, since the variable @code{Int1V} can only access objects
10523 of type @code{Int1}, and @code{Int2V} can only access objects of type
10524 @code{Int2}, there is no possibility that the assignment to
10525 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10526 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10527 for all iterations of the loop and avoid the extra memory reference
10528 required to dereference it each time through the loop.
10529
10530 This kind of optimization, called strict aliasing analysis, is
10531 triggered by specifying an optimization level of @option{-O2} or
10532 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10533 when access values are involved.
10534
10535 However, although this optimization is always correct in terms of
10536 the formal semantics of the Ada Reference Manual, difficulties can
10537 arise if features like @code{Unchecked_Conversion} are used to break
10538 the typing system. Consider the following complete program example:
10539
10540 @smallexample @c ada
10541 @cartouche
10542 package p1 is
10543    type int1 is new integer;
10544    type int2 is new integer;
10545    type a1 is access int1;
10546    type a2 is access int2;
10547 end p1;
10548
10549 with p1; use p1;
10550 package p2 is
10551    function to_a2 (Input : a1) return a2;
10552 end p2;
10553
10554 with Unchecked_Conversion;
10555 package body p2 is
10556    function to_a2 (Input : a1) return a2 is
10557       function to_a2u is
10558         new Unchecked_Conversion (a1, a2);
10559    begin
10560       return to_a2u (Input);
10561    end to_a2;
10562 end p2;
10563
10564 with p2; use p2;
10565 with p1; use p1;
10566 with Text_IO; use Text_IO;
10567 procedure m is
10568    v1 : a1 := new int1;
10569    v2 : a2 := to_a2 (v1);
10570 begin
10571    v1.all := 1;
10572    v2.all := 0;
10573    put_line (int1'image (v1.all));
10574 end;
10575 @end cartouche
10576 @end smallexample
10577
10578 @noindent
10579 This program prints out 0 in @option{-O0} or @option{-O1}
10580 mode, but it prints out 1 in @option{-O2} mode. That's
10581 because in strict aliasing mode, the compiler can and
10582 does assume that the assignment to @code{v2.all} could not
10583 affect the value of @code{v1.all}, since different types
10584 are involved.
10585
10586 This behavior is not a case of non-conformance with the standard, since
10587 the Ada RM specifies that an unchecked conversion where the resulting
10588 bit pattern is not a correct value of the target type can result in an
10589 abnormal value and attempting to reference an abnormal value makes the
10590 execution of a program erroneous.  That's the case here since the result
10591 does not point to an object of type @code{int2}.  This means that the
10592 effect is entirely unpredictable.
10593
10594 However, although that explanation may satisfy a language
10595 lawyer, in practice an applications programmer expects an
10596 unchecked conversion involving pointers to create true
10597 aliases and the behavior of printing 1 seems plain wrong.
10598 In this case, the strict aliasing optimization is unwelcome.
10599
10600 Indeed the compiler recognizes this possibility, and the
10601 unchecked conversion generates a warning:
10602
10603 @smallexample
10604 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10605 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10606 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10607 @end smallexample
10608
10609 @noindent
10610 Unfortunately the problem is recognized when compiling the body of
10611 package @code{p2}, but the actual "bad" code is generated while
10612 compiling the body of @code{m} and this latter compilation does not see
10613 the suspicious @code{Unchecked_Conversion}.
10614
10615 As implied by the warning message, there are approaches you can use to
10616 avoid the unwanted strict aliasing optimization in a case like this.
10617
10618 One possibility is to simply avoid the use of @option{-O2}, but
10619 that is a bit drastic, since it throws away a number of useful
10620 optimizations that do not involve strict aliasing assumptions.
10621
10622 A less drastic approach is to compile the program using the
10623 option @option{-fno-strict-aliasing}. Actually it is only the
10624 unit containing the dereferencing of the suspicious pointer
10625 that needs to be compiled. So in this case, if we compile
10626 unit @code{m} with this switch, then we get the expected
10627 value of zero printed. Analyzing which units might need
10628 the switch can be painful, so a more reasonable approach
10629 is to compile the entire program with options @option{-O2}
10630 and @option{-fno-strict-aliasing}. If the performance is
10631 satisfactory with this combination of options, then the
10632 advantage is that the entire issue of possible "wrong"
10633 optimization due to strict aliasing is avoided.
10634
10635 To avoid the use of compiler switches, the configuration
10636 pragma @code{No_Strict_Aliasing} with no parameters may be
10637 used to specify that for all access types, the strict
10638 aliasing optimization should be suppressed.
10639
10640 However, these approaches are still overkill, in that they causes
10641 all manipulations of all access values to be deoptimized. A more
10642 refined approach is to concentrate attention on the specific
10643 access type identified as problematic.
10644
10645 First, if a careful analysis of uses of the pointer shows
10646 that there are no possible problematic references, then
10647 the warning can be suppressed by bracketing the
10648 instantiation of @code{Unchecked_Conversion} to turn
10649 the warning off:
10650
10651 @smallexample @c ada
10652    pragma Warnings (Off);
10653    function to_a2u is
10654      new Unchecked_Conversion (a1, a2);
10655    pragma Warnings (On);
10656 @end smallexample
10657
10658 @noindent
10659 Of course that approach is not appropriate for this particular
10660 example, since indeed there is a problematic reference. In this
10661 case we can take one of two other approaches.
10662
10663 The first possibility is to move the instantiation of unchecked
10664 conversion to the unit in which the type is declared. In
10665 this example, we would move the instantiation of
10666 @code{Unchecked_Conversion} from the body of package
10667 @code{p2} to the spec of package @code{p1}. Now the
10668 warning disappears. That's because any use of the
10669 access type knows there is a suspicious unchecked
10670 conversion, and the strict aliasing optimization
10671 is automatically suppressed for the type.
10672
10673 If it is not practical to move the unchecked conversion to the same unit
10674 in which the destination access type is declared (perhaps because the
10675 source type is not visible in that unit), you may use pragma
10676 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10677 same declarative sequence as the declaration of the access type:
10678
10679 @smallexample @c ada
10680    type a2 is access int2;
10681    pragma No_Strict_Aliasing (a2);
10682 @end smallexample
10683
10684 @noindent
10685 Here again, the compiler now knows that the strict aliasing optimization
10686 should be suppressed for any reference to type @code{a2} and the
10687 expected behavior is obtained.
10688
10689 Finally, note that although the compiler can generate warnings for
10690 simple cases of unchecked conversions, there are tricker and more
10691 indirect ways of creating type incorrect aliases which the compiler
10692 cannot detect. Examples are the use of address overlays and unchecked
10693 conversions involving composite types containing access types as
10694 components. In such cases, no warnings are generated, but there can
10695 still be aliasing problems. One safe coding practice is to forbid the
10696 use of address clauses for type overlaying, and to allow unchecked
10697 conversion only for primitive types. This is not really a significant
10698 restriction since any possible desired effect can be achieved by
10699 unchecked conversion of access values.
10700
10701 The aliasing analysis done in strict aliasing mode can certainly
10702 have significant benefits. We have seen cases of large scale
10703 application code where the time is increased by up to 5% by turning
10704 this optimization off. If you have code that includes significant
10705 usage of unchecked conversion, you might want to just stick with
10706 @option{-O1} and avoid the entire issue. If you get adequate
10707 performance at this level of optimization level, that's probably
10708 the safest approach. If tests show that you really need higher
10709 levels of optimization, then you can experiment with @option{-O2}
10710 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10711 has on size and speed of the code. If you really need to use
10712 @option{-O2} with strict aliasing in effect, then you should
10713 review any uses of unchecked conversion of access types,
10714 particularly if you are getting the warnings described above.
10715
10716 @ifset vms
10717 @node Coverage Analysis
10718 @subsection Coverage Analysis
10719
10720 @noindent
10721 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10722 the user to determine the distribution of execution time across a program,
10723 @pxref{Profiling} for details of usage.
10724 @end ifset
10725
10726
10727 @node Text_IO Suggestions
10728 @section @code{Text_IO} Suggestions
10729 @cindex @code{Text_IO} and performance
10730
10731 @noindent
10732 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10733 the requirement of maintaining page and line counts. If performance
10734 is critical, a recommendation is to use @code{Stream_IO} instead of
10735 @code{Text_IO} for volume output, since this package has less overhead.
10736
10737 If @code{Text_IO} must be used, note that by default output to the standard
10738 output and standard error files is unbuffered (this provides better
10739 behavior when output statements are used for debugging, or if the
10740 progress of a program is observed by tracking the output, e.g. by
10741 using the Unix @command{tail -f} command to watch redirected output.
10742
10743 If you are generating large volumes of output with @code{Text_IO} and
10744 performance is an important factor, use a designated file instead
10745 of the standard output file, or change the standard output file to
10746 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10747
10748
10749
10750 @node Reducing Size of Ada Executables with gnatelim
10751 @section Reducing Size of Ada Executables with @code{gnatelim}
10752 @findex gnatelim
10753
10754 @noindent
10755 This section describes @command{gnatelim}, a tool which detects unused
10756 subprograms and helps the compiler to create a smaller executable for your
10757 program.
10758
10759 @menu
10760 * About gnatelim::
10761 * Running gnatelim::
10762 * Processing Precompiled Libraries::
10763 * Correcting the List of Eliminate Pragmas::
10764 * Making Your Executables Smaller::
10765 * Summary of the gnatelim Usage Cycle::
10766 @end menu
10767
10768 @node About gnatelim
10769 @subsection About @code{gnatelim}
10770
10771 @noindent
10772 When a program shares a set of Ada
10773 packages with other programs, it may happen that this program uses
10774 only a fraction of the subprograms defined in these packages. The code
10775 created for these unused subprograms increases the size of the executable.
10776
10777 @code{gnatelim} tracks unused subprograms in an Ada program and
10778 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10779 subprograms that are declared but never called. By placing the list of
10780 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10781 recompiling your program, you may decrease the size of its executable,
10782 because the compiler will not generate the code for 'eliminated' subprograms.
10783 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10784 information about this pragma.
10785
10786 @code{gnatelim} needs as its input data the name of the main subprogram.
10787
10788 If a set of source files is specified as @code{gnatelim} arguments, it
10789 treats these files as a complete set of sources making up a program to
10790 analyse, and analyses only these sources.
10791
10792 After a full successful build of the main subprogram @code{gnatelim} can be
10793 called without  specifying sources to analyse, in this case it computes
10794 the source closure of the main unit from the @file{ALI} files.
10795
10796 The following command will create the set of @file{ALI} files needed for
10797 @code{gnatelim}:
10798
10799 @smallexample
10800 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10801 @end smallexample
10802
10803 Note that @code{gnatelim} does not need object files.
10804
10805 @node Running gnatelim
10806 @subsection Running @code{gnatelim}
10807
10808 @noindent
10809 @code{gnatelim} has the following command-line interface:
10810
10811 @smallexample
10812 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10813 @end smallexample
10814
10815 @noindent
10816 @var{main_unit_name} should be a name of a source file that contains the main
10817 subprogram of a program (partition).
10818
10819 Each @var{filename} is the name (including the extension) of a source
10820 file to process. ``Wildcards'' are allowed, and
10821 the file name may contain path information.
10822
10823 @samp{@var{gcc_switches}} is a list of switches for
10824 @command{gcc}. They will be passed on to all compiler invocations made by
10825 @command{gnatelim} to generate the ASIS trees. Here you can provide
10826 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10827 use the @option{-gnatec} switch to set the configuration file,
10828 use the @option{-gnat05} switch if sources should be compiled in
10829 Ada 2005 mode etc.
10830
10831 @code{gnatelim} has the following switches:
10832
10833 @table @option
10834 @c !sort!
10835 @item ^-files^/FILES^=@var{filename}
10836 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10837 Take the argument source files from the specified file. This file should be an
10838 ordinary text file containing file names separated by spaces or
10839 line breaks. You can use this switch more than once in the same call to
10840 @command{gnatelim}. You also can combine this switch with
10841 an explicit list of files.
10842
10843 @item ^-log^/LOG^
10844 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10845 Duplicate all the output sent to @file{stderr} into a log file. The log file
10846 is named @file{gnatelim.log} and is located in the current directory.
10847
10848 @item ^-log^/LOGFILE^=@var{filename}
10849 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10850 Duplicate all the output sent to @file{stderr} into a specified log file.
10851
10852 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10853 @item ^--no-elim-dispatch^/NO_DISPATCH^
10854 Do not generate pragmas for dispatching operations.
10855
10856 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10857 @item ^-o^/OUTPUT^=@var{report_file}
10858 Put @command{gnatelim} output into a specified file. If this file already exists,
10859 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10860 into @file{stderr}
10861
10862 @item ^-q^/QUIET^
10863 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10864 Quiet mode: by default @code{gnatelim} outputs to the standard error
10865 stream the number of program units left to be processed. This option turns
10866 this trace off.
10867
10868 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10869 @item ^-t^/TIME^
10870 Print out execution time.
10871
10872 @item ^-v^/VERBOSE^
10873 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10874 Verbose mode: @code{gnatelim} version information is printed as Ada
10875 comments to the standard output stream. Also, in addition to the number of
10876 program units left @code{gnatelim} will output the name of the current unit
10877 being processed.
10878
10879 @item ^-wq^/WARNINGS=QUIET^
10880 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10881 Quet warning mode - some warnings are suppressed. In particular warnings that
10882 indicate that the analysed set of sources is incomplete to make up a
10883 partition and that some subprogram bodies are missing are not generated.
10884 @end table
10885
10886 @node Processing Precompiled Libraries
10887 @subsection Processing Precompiled Libraries
10888
10889 @noindent
10890 If some program uses a precompiled Ada library, it can be processed by
10891 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10892 Eliminate pragma for a subprogram if the body of this subprogram has not
10893 been analysed, this is a typical case for subprograms from precompiled
10894 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10895 warnings about missing source files and non-analyzed subprogram bodies
10896 that can be generated when processing precompiled Ada libraries.
10897
10898 @node Correcting the List of Eliminate Pragmas
10899 @subsection Correcting the List of Eliminate Pragmas
10900
10901 @noindent
10902 In some rare cases @code{gnatelim} may try to eliminate
10903 subprograms that are actually called in the program. In this case, the
10904 compiler will generate an error message of the form:
10905
10906 @smallexample
10907 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10908 @end smallexample
10909
10910 @noindent
10911 You will need to manually remove the wrong @code{Eliminate} pragmas from
10912 the configuration file indicated in the error message. You should recompile
10913 your program from scratch after that, because you need a consistent
10914 configuration file(s) during the entire compilation.
10915
10916 @node Making Your Executables Smaller
10917 @subsection Making Your Executables Smaller
10918
10919 @noindent
10920 In order to get a smaller executable for your program you now have to
10921 recompile the program completely with the configuration file containing
10922 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10923 @file{gnat.adc} file located in your current directory, just do:
10924
10925 @smallexample
10926 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10927 @end smallexample
10928
10929 @noindent
10930 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10931 recompile everything
10932 with the set of pragmas @code{Eliminate} that you have obtained with
10933 @command{gnatelim}).
10934
10935 Be aware that the set of @code{Eliminate} pragmas is specific to each
10936 program. It is not recommended to merge sets of @code{Eliminate}
10937 pragmas created for different programs in one configuration file.
10938
10939 @node Summary of the gnatelim Usage Cycle
10940 @subsection Summary of the @code{gnatelim} Usage Cycle
10941
10942 @noindent
10943 Here is a quick summary of the steps to be taken in order to reduce
10944 the size of your executables with @code{gnatelim}. You may use
10945 other GNAT options to control the optimization level,
10946 to produce the debugging information, to set search path, etc.
10947
10948 @enumerate
10949 @item
10950 Create a complete set of @file{ALI} files (if the program has not been
10951 built already)
10952
10953 @smallexample
10954 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10955 @end smallexample
10956
10957 @item
10958 Generate a list of @code{Eliminate} pragmas in default configuration file
10959 @file{gnat.adc} in the current directory
10960 @smallexample
10961 @ifset vms
10962 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10963 @end ifset
10964 @ifclear vms
10965 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10966 @end ifclear
10967 @end smallexample
10968
10969 @item
10970 Recompile the application
10971
10972 @smallexample
10973 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10974 @end smallexample
10975
10976 @end enumerate
10977
10978 @node Reducing Size of Executables with unused subprogram/data elimination
10979 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10980 @findex unused subprogram/data elimination
10981
10982 @noindent
10983 This section describes how you can eliminate unused subprograms and data from
10984 your executable just by setting options at compilation time.
10985
10986 @menu
10987 * About unused subprogram/data elimination::
10988 * Compilation options::
10989 * Example of unused subprogram/data elimination::
10990 @end menu
10991
10992 @node About unused subprogram/data elimination
10993 @subsection About unused subprogram/data elimination
10994
10995 @noindent
10996 By default, an executable contains all code and data of its composing objects
10997 (directly linked or coming from statically linked libraries), even data or code
10998 never used by this executable.
10999
11000 This feature will allow you to eliminate such unused code from your
11001 executable, making it smaller (in disk and in memory).
11002
11003 This functionality is available on all Linux platforms except for the IA-64
11004 architecture and on all cross platforms using the ELF binary file format.
11005 In both cases GNU binutils version 2.16 or later are required to enable it.
11006
11007 @node Compilation options
11008 @subsection Compilation options
11009
11010 @noindent
11011 The operation of eliminating the unused code and data from the final executable
11012 is directly performed by the linker.
11013
11014 In order to do this, it has to work with objects compiled with the
11015 following options:
11016 @option{-ffunction-sections} @option{-fdata-sections}.
11017 @cindex @option{-ffunction-sections} (@command{gcc})
11018 @cindex @option{-fdata-sections} (@command{gcc})
11019 These options are usable with C and Ada files.
11020 They will place respectively each
11021 function or data in a separate section in the resulting object file.
11022
11023 Once the objects and static libraries are created with these options, the
11024 linker can perform the dead code elimination. You can do this by setting
11025 the @option{-Wl,--gc-sections} option to gcc command or in the
11026 @option{-largs} section of @command{gnatmake}. This will perform a
11027 garbage collection of code and data never referenced.
11028
11029 If the linker performs a partial link (@option{-r} ld linker option), then you
11030 will need to provide one or several entry point using the
11031 @option{-e} / @option{--entry} ld option.
11032
11033 Note that objects compiled without the @option{-ffunction-sections} and
11034 @option{-fdata-sections} options can still be linked with the executable.
11035 However, no dead code elimination will be performed on those objects (they will
11036 be linked as is).
11037
11038 The GNAT static library is now compiled with -ffunction-sections and
11039 -fdata-sections on some platforms. This allows you to eliminate the unused code
11040 and data of the GNAT library from your executable.
11041
11042 @node Example of unused subprogram/data elimination
11043 @subsection Example of unused subprogram/data elimination
11044
11045 @noindent
11046 Here is a simple example:
11047
11048 @smallexample @c ada
11049 with Aux;
11050
11051 procedure Test is
11052 begin
11053    Aux.Used (10);
11054 end Test;
11055
11056 package Aux is
11057    Used_Data   : Integer;
11058    Unused_Data : Integer;
11059
11060    procedure Used   (Data : Integer);
11061    procedure Unused (Data : Integer);
11062 end Aux;
11063
11064 package body Aux is
11065    procedure Used (Data : Integer) is
11066    begin
11067       Used_Data := Data;
11068    end Used;
11069
11070    procedure Unused (Data : Integer) is
11071    begin
11072       Unused_Data := Data;
11073    end Unused;
11074 end Aux;
11075 @end smallexample
11076
11077 @noindent
11078 @code{Unused} and @code{Unused_Data} are never referenced in this code
11079 excerpt, and hence they may be safely removed from the final executable.
11080
11081 @smallexample
11082 $ gnatmake test
11083
11084 $ nm test | grep used
11085 020015f0 T aux__unused
11086 02005d88 B aux__unused_data
11087 020015cc T aux__used
11088 02005d84 B aux__used_data
11089
11090 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11091      -largs -Wl,--gc-sections
11092
11093 $ nm test | grep used
11094 02005350 T aux__used
11095 0201ffe0 B aux__used_data
11096 @end smallexample
11097
11098 @noindent
11099 It can be observed that the procedure @code{Unused} and the object
11100 @code{Unused_Data} are removed by the linker when using the
11101 appropriate options.
11102
11103 @c ********************************
11104 @node Renaming Files Using gnatchop
11105 @chapter Renaming Files Using @code{gnatchop}
11106 @findex gnatchop
11107
11108 @noindent
11109 This chapter discusses how to handle files with multiple units by using
11110 the @code{gnatchop} utility. This utility is also useful in renaming
11111 files to meet the standard GNAT default file naming conventions.
11112
11113 @menu
11114 * Handling Files with Multiple Units::
11115 * Operating gnatchop in Compilation Mode::
11116 * Command Line for gnatchop::
11117 * Switches for gnatchop::
11118 * Examples of gnatchop Usage::
11119 @end menu
11120
11121 @node Handling Files with Multiple Units
11122 @section Handling Files with Multiple Units
11123
11124 @noindent
11125 The basic compilation model of GNAT requires that a file submitted to the
11126 compiler have only one unit and there be a strict correspondence
11127 between the file name and the unit name.
11128
11129 The @code{gnatchop} utility allows both of these rules to be relaxed,
11130 allowing GNAT to process files which contain multiple compilation units
11131 and files with arbitrary file names. @code{gnatchop}
11132 reads the specified file and generates one or more output files,
11133 containing one unit per file. The unit and the file name correspond,
11134 as required by GNAT.
11135
11136 If you want to permanently restructure a set of ``foreign'' files so that
11137 they match the GNAT rules, and do the remaining development using the
11138 GNAT structure, you can simply use @command{gnatchop} once, generate the
11139 new set of files and work with them from that point on.
11140
11141 Alternatively, if you want to keep your files in the ``foreign'' format,
11142 perhaps to maintain compatibility with some other Ada compilation
11143 system, you can set up a procedure where you use @command{gnatchop} each
11144 time you compile, regarding the source files that it writes as temporary
11145 files that you throw away.
11146
11147 Note that if your file containing multiple units starts with a byte order
11148 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11149 will each start with a copy of this BOM, meaning that they can be compiled
11150 automatically in UTF-8 mode without needing to specify an explicit encoding.
11151
11152 @node Operating gnatchop in Compilation Mode
11153 @section Operating gnatchop in Compilation Mode
11154
11155 @noindent
11156 The basic function of @code{gnatchop} is to take a file with multiple units
11157 and split it into separate files. The boundary between files is reasonably
11158 clear, except for the issue of comments and pragmas. In default mode, the
11159 rule is that any pragmas between units belong to the previous unit, except
11160 that configuration pragmas always belong to the following unit. Any comments
11161 belong to the following unit. These rules
11162 almost always result in the right choice of
11163 the split point without needing to mark it explicitly and most users will
11164 find this default to be what they want. In this default mode it is incorrect to
11165 submit a file containing only configuration pragmas, or one that ends in
11166 configuration pragmas, to @code{gnatchop}.
11167
11168 However, using a special option to activate ``compilation mode'',
11169 @code{gnatchop}
11170 can perform another function, which is to provide exactly the semantics
11171 required by the RM for handling of configuration pragmas in a compilation.
11172 In the absence of configuration pragmas (at the main file level), this
11173 option has no effect, but it causes such configuration pragmas to be handled
11174 in a quite different manner.
11175
11176 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11177 only configuration pragmas, then this file is appended to the
11178 @file{gnat.adc} file in the current directory. This behavior provides
11179 the required behavior described in the RM for the actions to be taken
11180 on submitting such a file to the compiler, namely that these pragmas
11181 should apply to all subsequent compilations in the same compilation
11182 environment. Using GNAT, the current directory, possibly containing a
11183 @file{gnat.adc} file is the representation
11184 of a compilation environment. For more information on the
11185 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11186
11187 Second, in compilation mode, if @code{gnatchop}
11188 is given a file that starts with
11189 configuration pragmas, and contains one or more units, then these
11190 configuration pragmas are prepended to each of the chopped files. This
11191 behavior provides the required behavior described in the RM for the
11192 actions to be taken on compiling such a file, namely that the pragmas
11193 apply to all units in the compilation, but not to subsequently compiled
11194 units.
11195
11196 Finally, if configuration pragmas appear between units, they are appended
11197 to the previous unit. This results in the previous unit being illegal,
11198 since the compiler does not accept configuration pragmas that follow
11199 a unit. This provides the required RM behavior that forbids configuration
11200 pragmas other than those preceding the first compilation unit of a
11201 compilation.
11202
11203 For most purposes, @code{gnatchop} will be used in default mode. The
11204 compilation mode described above is used only if you need exactly
11205 accurate behavior with respect to compilations, and you have files
11206 that contain multiple units and configuration pragmas. In this
11207 circumstance the use of @code{gnatchop} with the compilation mode
11208 switch provides the required behavior, and is for example the mode
11209 in which GNAT processes the ACVC tests.
11210
11211 @node Command Line for gnatchop
11212 @section Command Line for @code{gnatchop}
11213
11214 @noindent
11215 The @code{gnatchop} command has the form:
11216
11217 @smallexample
11218 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11219 @c      @ovar{directory}
11220 @c Expanding @ovar macro inline (explanation in macro def comments)
11221 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11222       @r{[}@var{directory}@r{]}
11223 @end smallexample
11224
11225 @noindent
11226 The only required argument is the file name of the file to be chopped.
11227 There are no restrictions on the form of this file name. The file itself
11228 contains one or more Ada units, in normal GNAT format, concatenated
11229 together. As shown, more than one file may be presented to be chopped.
11230
11231 When run in default mode, @code{gnatchop} generates one output file in
11232 the current directory for each unit in each of the files.
11233
11234 @var{directory}, if specified, gives the name of the directory to which
11235 the output files will be written. If it is not specified, all files are
11236 written to the current directory.
11237
11238 For example, given a
11239 file called @file{hellofiles} containing
11240
11241 @smallexample @c ada
11242 @group
11243 @cartouche
11244 procedure hello;
11245
11246 with Text_IO; use Text_IO;
11247 procedure hello is
11248 begin
11249    Put_Line ("Hello");
11250 end hello;
11251 @end cartouche
11252 @end group
11253 @end smallexample
11254
11255 @noindent
11256 the command
11257
11258 @smallexample
11259 $ gnatchop ^hellofiles^HELLOFILES.^
11260 @end smallexample
11261
11262 @noindent
11263 generates two files in the current directory, one called
11264 @file{hello.ads} containing the single line that is the procedure spec,
11265 and the other called @file{hello.adb} containing the remaining text. The
11266 original file is not affected. The generated files can be compiled in
11267 the normal manner.
11268
11269 @noindent
11270 When gnatchop is invoked on a file that is empty or that contains only empty
11271 lines and/or comments, gnatchop will not fail, but will not produce any
11272 new sources.
11273
11274 For example, given a
11275 file called @file{toto.txt} containing
11276
11277 @smallexample @c ada
11278 @group
11279 @cartouche
11280 --  Just a comment
11281 @end cartouche
11282 @end group
11283 @end smallexample
11284
11285 @noindent
11286 the command
11287
11288 @smallexample
11289 $ gnatchop ^toto.txt^TOT.TXT^
11290 @end smallexample
11291
11292 @noindent
11293 will not produce any new file and will result in the following warnings:
11294
11295 @smallexample
11296 toto.txt:1:01: warning: empty file, contains no compilation units
11297 no compilation units found
11298 no source files written
11299 @end smallexample
11300
11301 @node Switches for gnatchop
11302 @section Switches for @code{gnatchop}
11303
11304 @noindent
11305 @command{gnatchop} recognizes the following switches:
11306
11307 @table @option
11308 @c !sort!
11309
11310 @item --version
11311 @cindex @option{--version} @command{gnatchop}
11312 Display Copyright and version, then exit disregarding all other options.
11313
11314 @item --help
11315 @cindex @option{--help} @command{gnatchop}
11316 If @option{--version} was not used, display usage, then exit disregarding
11317 all other options.
11318
11319 @item ^-c^/COMPILATION^
11320 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11321 Causes @code{gnatchop} to operate in compilation mode, in which
11322 configuration pragmas are handled according to strict RM rules. See
11323 previous section for a full description of this mode.
11324
11325 @ifclear vms
11326 @item -gnat@var{xxx}
11327 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11328 used to parse the given file. Not all @var{xxx} options make sense,
11329 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11330 process a source file that uses Latin-2 coding for identifiers.
11331 @end ifclear
11332
11333 @item ^-h^/HELP^
11334 Causes @code{gnatchop} to generate a brief help summary to the standard
11335 output file showing usage information.
11336
11337 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11338 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11339 Limit generated file names to the specified number @code{mm}
11340 of characters.
11341 This is useful if the
11342 resulting set of files is required to be interoperable with systems
11343 which limit the length of file names.
11344 @ifset vms
11345 If no value is given, or
11346 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11347 a default of 39, suitable for OpenVMS Alpha
11348 Systems, is assumed
11349 @end ifset
11350 @ifclear vms
11351 No space is allowed between the @option{-k} and the numeric value. The numeric
11352 value may be omitted in which case a default of @option{-k8},
11353 suitable for use
11354 with DOS-like file systems, is used. If no @option{-k} switch
11355 is present then
11356 there is no limit on the length of file names.
11357 @end ifclear
11358
11359 @item ^-p^/PRESERVE^
11360 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11361 Causes the file ^modification^creation^ time stamp of the input file to be
11362 preserved and used for the time stamp of the output file(s). This may be
11363 useful for preserving coherency of time stamps in an environment where
11364 @code{gnatchop} is used as part of a standard build process.
11365
11366 @item ^-q^/QUIET^
11367 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11368 Causes output of informational messages indicating the set of generated
11369 files to be suppressed. Warnings and error messages are unaffected.
11370
11371 @item ^-r^/REFERENCE^
11372 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11373 @findex Source_Reference
11374 Generate @code{Source_Reference} pragmas. Use this switch if the output
11375 files are regarded as temporary and development is to be done in terms
11376 of the original unchopped file. This switch causes
11377 @code{Source_Reference} pragmas to be inserted into each of the
11378 generated files to refers back to the original file name and line number.
11379 The result is that all error messages refer back to the original
11380 unchopped file.
11381 In addition, the debugging information placed into the object file (when
11382 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11383 specified)
11384 also refers back to this original file so that tools like profilers and
11385 debuggers will give information in terms of the original unchopped file.
11386
11387 If the original file to be chopped itself contains
11388 a @code{Source_Reference}
11389 pragma referencing a third file, then gnatchop respects
11390 this pragma, and the generated @code{Source_Reference} pragmas
11391 in the chopped file refer to the original file, with appropriate
11392 line numbers. This is particularly useful when @code{gnatchop}
11393 is used in conjunction with @code{gnatprep} to compile files that
11394 contain preprocessing statements and multiple units.
11395
11396 @item ^-v^/VERBOSE^
11397 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11398 Causes @code{gnatchop} to operate in verbose mode. The version
11399 number and copyright notice are output, as well as exact copies of
11400 the gnat1 commands spawned to obtain the chop control information.
11401
11402 @item ^-w^/OVERWRITE^
11403 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11404 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11405 fatal error if there is already a file with the same name as a
11406 file it would otherwise output, in other words if the files to be
11407 chopped contain duplicated units. This switch bypasses this
11408 check, and causes all but the last instance of such duplicated
11409 units to be skipped.
11410
11411 @ifclear vms
11412 @item --GCC=@var{xxxx}
11413 @cindex @option{--GCC=} (@code{gnatchop})
11414 Specify the path of the GNAT parser to be used. When this switch is used,
11415 no attempt is made to add the prefix to the GNAT parser executable.
11416 @end ifclear
11417 @end table
11418
11419 @node Examples of gnatchop Usage
11420 @section Examples of @code{gnatchop} Usage
11421
11422 @table @code
11423 @ifset vms
11424 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11425 @end ifset
11426 @ifclear vms
11427 @item gnatchop -w hello_s.ada prerelease/files
11428 @end ifclear
11429
11430 Chops the source file @file{hello_s.ada}. The output files will be
11431 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11432 overwriting any
11433 files with matching names in that directory (no files in the current
11434 directory are modified).
11435
11436 @item gnatchop ^archive^ARCHIVE.^
11437 Chops the source file @file{^archive^ARCHIVE.^}
11438 into the current directory. One
11439 useful application of @code{gnatchop} is in sending sets of sources
11440 around, for example in email messages. The required sources are simply
11441 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11442 command), and then
11443 @command{gnatchop} is used at the other end to reconstitute the original
11444 file names.
11445
11446 @item gnatchop file1 file2 file3 direc
11447 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11448 the resulting files in the directory @file{direc}. Note that if any units
11449 occur more than once anywhere within this set of files, an error message
11450 is generated, and no files are written. To override this check, use the
11451 @option{^-w^/OVERWRITE^} switch,
11452 in which case the last occurrence in the last file will
11453 be the one that is output, and earlier duplicate occurrences for a given
11454 unit will be skipped.
11455 @end table
11456
11457 @node Configuration Pragmas
11458 @chapter Configuration Pragmas
11459 @cindex Configuration pragmas
11460 @cindex Pragmas, configuration
11461
11462 @noindent
11463 Configuration pragmas include those pragmas described as
11464 such in the Ada Reference Manual, as well as
11465 implementation-dependent pragmas that are configuration pragmas.
11466 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11467 for details on these additional GNAT-specific configuration pragmas.
11468 Most notably, the pragma @code{Source_File_Name}, which allows
11469 specifying non-default names for source files, is a configuration
11470 pragma. The following is a complete list of configuration pragmas
11471 recognized by GNAT:
11472
11473 @smallexample
11474    Ada_83
11475    Ada_95
11476    Ada_05
11477    Ada_2005
11478    Ada_12
11479    Ada_2012
11480    Assertion_Policy
11481    Assume_No_Invalid_Values
11482    C_Pass_By_Copy
11483    Check_Name
11484    Check_Policy
11485    Compile_Time_Error
11486    Compile_Time_Warning
11487    Compiler_Unit
11488    Component_Alignment
11489    Convention_Identifier
11490    Debug_Policy
11491    Detect_Blocking
11492    Discard_Names
11493    Elaboration_Checks
11494    Eliminate
11495    Extend_System
11496    Extensions_Allowed
11497    External_Name_Casing
11498    Fast_Math
11499    Favor_Top_Level
11500    Float_Representation
11501    Implicit_Packing
11502    Initialize_Scalars
11503    Interrupt_State
11504    License
11505    Locking_Policy
11506    Long_Float
11507    No_Run_Time
11508    No_Strict_Aliasing
11509    Normalize_Scalars
11510    Optimize_Alignment
11511    Persistent_BSS
11512    Polling
11513    Priority_Specific_Dispatching
11514    Profile
11515    Profile_Warnings
11516    Propagate_Exceptions
11517    Queuing_Policy
11518    Ravenscar
11519    Restricted_Run_Time
11520    Restrictions
11521    Restrictions_Warnings
11522    Reviewable
11523    Short_Circuit_And_Or
11524    Source_File_Name
11525    Source_File_Name_Project
11526    Style_Checks
11527    Suppress
11528    Suppress_Exception_Locations
11529    Task_Dispatching_Policy
11530    Universal_Data
11531    Unsuppress
11532    Use_VADS_Size
11533    Validity_Checks
11534    Warnings
11535    Wide_Character_Encoding
11536
11537 @end smallexample
11538
11539 @menu
11540 * Handling of Configuration Pragmas::
11541 * The Configuration Pragmas Files::
11542 @end menu
11543
11544 @node Handling of Configuration Pragmas
11545 @section Handling of Configuration Pragmas
11546
11547 Configuration pragmas may either appear at the start of a compilation
11548 unit, in which case they apply only to that unit, or they may apply to
11549 all compilations performed in a given compilation environment.
11550
11551 GNAT also provides the @code{gnatchop} utility to provide an automatic
11552 way to handle configuration pragmas following the semantics for
11553 compilations (that is, files with multiple units), described in the RM.
11554 See @ref{Operating gnatchop in Compilation Mode} for details.
11555 However, for most purposes, it will be more convenient to edit the
11556 @file{gnat.adc} file that contains configuration pragmas directly,
11557 as described in the following section.
11558
11559 @node The Configuration Pragmas Files
11560 @section The Configuration Pragmas Files
11561 @cindex @file{gnat.adc}
11562
11563 @noindent
11564 In GNAT a compilation environment is defined by the current
11565 directory at the time that a compile command is given. This current
11566 directory is searched for a file whose name is @file{gnat.adc}. If
11567 this file is present, it is expected to contain one or more
11568 configuration pragmas that will be applied to the current compilation.
11569 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11570 considered.
11571
11572 Configuration pragmas may be entered into the @file{gnat.adc} file
11573 either by running @code{gnatchop} on a source file that consists only of
11574 configuration pragmas, or more conveniently  by
11575 direct editing of the @file{gnat.adc} file, which is a standard format
11576 source file.
11577
11578 In addition to @file{gnat.adc}, additional files containing configuration
11579 pragmas may be applied to the current compilation using the switch
11580 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11581 contains only configuration pragmas. These configuration pragmas are
11582 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11583 is present and switch @option{-gnatA} is not used).
11584
11585 It is allowed to specify several switches @option{-gnatec}, all of which
11586 will be taken into account.
11587
11588 If you are using project file, a separate mechanism is provided using
11589 project attributes, see @ref{Specifying Configuration Pragmas} for more
11590 details.
11591
11592 @ifset vms
11593 Of special interest to GNAT OpenVMS Alpha is the following
11594 configuration pragma:
11595
11596 @smallexample @c ada
11597 @cartouche
11598 pragma Extend_System (Aux_DEC);
11599 @end cartouche
11600 @end smallexample
11601
11602 @noindent
11603 In the presence of this pragma, GNAT adds to the definition of the
11604 predefined package SYSTEM all the additional types and subprograms that are
11605 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11606 @end ifset
11607
11608 @node Handling Arbitrary File Naming Conventions Using gnatname
11609 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11610 @cindex Arbitrary File Naming Conventions
11611
11612 @menu
11613 * Arbitrary File Naming Conventions::
11614 * Running gnatname::
11615 * Switches for gnatname::
11616 * Examples of gnatname Usage::
11617 @end menu
11618
11619 @node Arbitrary File Naming Conventions
11620 @section Arbitrary File Naming Conventions
11621
11622 @noindent
11623 The GNAT compiler must be able to know the source file name of a compilation
11624 unit.  When using the standard GNAT default file naming conventions
11625 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11626 does not need additional information.
11627
11628 @noindent
11629 When the source file names do not follow the standard GNAT default file naming
11630 conventions, the GNAT compiler must be given additional information through
11631 a configuration pragmas file (@pxref{Configuration Pragmas})
11632 or a project file.
11633 When the non-standard file naming conventions are well-defined,
11634 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11635 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11636 if the file naming conventions are irregular or arbitrary, a number
11637 of pragma @code{Source_File_Name} for individual compilation units
11638 must be defined.
11639 To help maintain the correspondence between compilation unit names and
11640 source file names within the compiler,
11641 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11642 set of files.
11643
11644 @node Running gnatname
11645 @section Running @code{gnatname}
11646
11647 @noindent
11648 The usual form of the @code{gnatname} command is
11649
11650 @smallexample
11651 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11652 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11653 @c Expanding @ovar macro inline (explanation in macro def comments)
11654 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11655       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11656 @end smallexample
11657
11658 @noindent
11659 All of the arguments are optional. If invoked without any argument,
11660 @code{gnatname} will display its usage.
11661
11662 @noindent
11663 When used with at least one naming pattern, @code{gnatname} will attempt to
11664 find all the compilation units in files that follow at least one of the
11665 naming patterns. To find these compilation units,
11666 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11667 regular files.
11668
11669 @noindent
11670 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11671 Each Naming Pattern is enclosed between double quotes (or single
11672 quotes on Windows).
11673 A Naming Pattern is a regular expression similar to the wildcard patterns
11674 used in file names by the Unix shells or the DOS prompt.
11675
11676 @noindent
11677 @code{gnatname} may be called with several sections of directories/patterns.
11678 Sections are separated by switch @code{--and}. In each section, there must be
11679 at least one pattern. If no directory is specified in a section, the current
11680 directory (or the project directory is @code{-P} is used) is implied.
11681 The options other that the directory switches and the patterns apply globally
11682 even if they are in different sections.
11683
11684 @noindent
11685 Examples of Naming Patterns are
11686
11687 @smallexample
11688    "*.[12].ada"
11689    "*.ad[sb]*"
11690    "body_*"    "spec_*"
11691 @end smallexample
11692
11693 @noindent
11694 For a more complete description of the syntax of Naming Patterns,
11695 see the second kind of regular expressions described in @file{g-regexp.ads}
11696 (the ``Glob'' regular expressions).
11697
11698 @noindent
11699 When invoked with no switch @code{-P}, @code{gnatname} will create a
11700 configuration pragmas file @file{gnat.adc} in the current working directory,
11701 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11702 unit.
11703
11704 @node Switches for gnatname
11705 @section Switches for @code{gnatname}
11706
11707 @noindent
11708 Switches for @code{gnatname} must precede any specified Naming Pattern.
11709
11710 @noindent
11711 You may specify any of the following switches to @code{gnatname}:
11712
11713 @table @option
11714 @c !sort!
11715
11716 @item --version
11717 @cindex @option{--version} @command{gnatname}
11718 Display Copyright and version, then exit disregarding all other options.
11719
11720 @item --help
11721 @cindex @option{--help} @command{gnatname}
11722 If @option{--version} was not used, display usage, then exit disregarding
11723 all other options.
11724
11725 @item --and
11726 Start another section of directories/patterns.
11727
11728 @item ^-c^/CONFIG_FILE=^@file{file}
11729 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11730 Create a configuration pragmas file @file{file} (instead of the default
11731 @file{gnat.adc}).
11732 @ifclear vms
11733 There may be zero, one or more space between @option{-c} and
11734 @file{file}.
11735 @end ifclear
11736 @file{file} may include directory information. @file{file} must be
11737 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11738 When a switch @option{^-c^/CONFIG_FILE^} is
11739 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11740
11741 @item ^-d^/SOURCE_DIRS=^@file{dir}
11742 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11743 Look for source files in directory @file{dir}. There may be zero, one or more
11744 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11745 When a switch @option{^-d^/SOURCE_DIRS^}
11746 is specified, the current working directory will not be searched for source
11747 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11748 or @option{^-D^/DIR_FILES^} switch.
11749 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11750 If @file{dir} is a relative path, it is relative to the directory of
11751 the configuration pragmas file specified with switch
11752 @option{^-c^/CONFIG_FILE^},
11753 or to the directory of the project file specified with switch
11754 @option{^-P^/PROJECT_FILE^} or,
11755 if neither switch @option{^-c^/CONFIG_FILE^}
11756 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11757 current working directory. The directory
11758 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11759
11760 @item ^-D^/DIRS_FILE=^@file{file}
11761 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11762 Look for source files in all directories listed in text file @file{file}.
11763 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11764 and @file{file}.
11765 @file{file} must be an existing, readable text file.
11766 Each nonempty line in @file{file} must be a directory.
11767 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11768 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11769 @file{file}.
11770
11771 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11772 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11773 Foreign patterns. Using this switch, it is possible to add sources of languages
11774 other than Ada to the list of sources of a project file.
11775 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11776 For example,
11777 @smallexample
11778 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11779 @end smallexample
11780 @noindent
11781 will look for Ada units in all files with the @file{.ada} extension,
11782 and will add to the list of file for project @file{prj.gpr} the C files
11783 with extension @file{.^c^C^}.
11784
11785 @item ^-h^/HELP^
11786 @cindex @option{^-h^/HELP^} (@code{gnatname})
11787 Output usage (help) information. The output is written to @file{stdout}.
11788
11789 @item ^-P^/PROJECT_FILE=^@file{proj}
11790 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11791 Create or update project file @file{proj}. There may be zero, one or more space
11792 between @option{-P} and @file{proj}. @file{proj} may include directory
11793 information. @file{proj} must be writable.
11794 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11795 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11796 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11797
11798 @item ^-v^/VERBOSE^
11799 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11800 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11801 This includes name of the file written, the name of the directories to search
11802 and, for each file in those directories whose name matches at least one of
11803 the Naming Patterns, an indication of whether the file contains a unit,
11804 and if so the name of the unit.
11805
11806 @item ^-v -v^/VERBOSE /VERBOSE^
11807 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11808 Very Verbose mode. In addition to the output produced in verbose mode,
11809 for each file in the searched directories whose name matches none of
11810 the Naming Patterns, an indication is given that there is no match.
11811
11812 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11813 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11814 Excluded patterns. Using this switch, it is possible to exclude some files
11815 that would match the name patterns. For example,
11816 @smallexample
11817 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11818 @end smallexample
11819 @noindent
11820 will look for Ada units in all files with the @file{.ada} extension,
11821 except those whose names end with @file{_nt.ada}.
11822
11823 @end table
11824
11825 @node Examples of gnatname Usage
11826 @section Examples of @code{gnatname} Usage
11827
11828 @ifset vms
11829 @smallexample
11830 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11831 @end smallexample
11832 @end ifset
11833
11834 @ifclear vms
11835 @smallexample
11836 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11837 @end smallexample
11838 @end ifclear
11839
11840 @noindent
11841 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11842 and be writable. In addition, the directory
11843 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11844 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11845
11846 @ifclear vms
11847 Note the optional spaces after @option{-c} and @option{-d}.
11848 @end ifclear
11849
11850 @smallexample
11851 @ifclear vms
11852 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11853   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11854 @end ifclear
11855 @ifset vms
11856 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11857   /EXCLUDED_PATTERN=*_nt_body.ada
11858   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11859   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11860 @end ifset
11861 @end smallexample
11862
11863 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11864 even in conjunction with one or several switches
11865 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11866 are used in this example.
11867
11868 @c *****************************************
11869 @c * G N A T  P r o j e c t  M a n a g e r *
11870 @c *****************************************
11871
11872 @c ------ macros for projects.texi
11873 @c These macros are needed when building the gprbuild documentation, but
11874 @c should have no effect in the gnat user's guide
11875
11876 @macro CODESAMPLE{TXT}
11877 @smallexample
11878 @group
11879 \TXT\
11880 @end group
11881 @end smallexample
11882 @end macro
11883
11884 @macro PROJECTFILE{TXT}
11885 @CODESAMPLE{\TXT\}
11886 @end macro
11887
11888 @c simulates a newline when in a @CODESAMPLE
11889 @macro NL{}
11890 @end macro
11891
11892 @macro TIP{TXT}
11893 @quotation
11894 @noindent
11895 \TXT\
11896 @end quotation
11897 @end macro
11898
11899 @macro TIPHTML{TXT}
11900 \TXT\
11901 @end macro
11902
11903 @macro IMPORTANT{TXT}
11904 @quotation
11905 @noindent
11906 \TXT\
11907 @end quotation
11908
11909 @end macro
11910
11911 @macro NOTE{TXT}
11912 @quotation
11913 @noindent
11914 \TXT\
11915 @end quotation
11916 @end macro
11917
11918 @include projects.texi
11919
11920 @c *****************************************
11921 @c * Cross-referencing tools
11922 @c *****************************************
11923
11924 @node The Cross-Referencing Tools gnatxref and gnatfind
11925 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11926 @findex gnatxref
11927 @findex gnatfind
11928
11929 @noindent
11930 The compiler generates cross-referencing information (unless
11931 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
11932 This information indicates where in the source each entity is declared and
11933 referenced. Note that entities in package Standard are not included, but
11934 entities in all other predefined units are included in the output.
11935
11936 Before using any of these two tools, you need to compile successfully your
11937 application, so that GNAT gets a chance to generate the cross-referencing
11938 information.
11939
11940 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
11941 information to provide the user with the capability to easily locate the
11942 declaration and references to an entity. These tools are quite similar,
11943 the difference being that @code{gnatfind} is intended for locating
11944 definitions and/or references to a specified entity or entities, whereas
11945 @code{gnatxref} is oriented to generating a full report of all
11946 cross-references.
11947
11948 To use these tools, you must not compile your application using the
11949 @option{-gnatx} switch on the @command{gnatmake} command line
11950 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
11951 information will not be generated.
11952
11953 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
11954 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
11955
11956 @menu
11957 * Switches for gnatxref::
11958 * Switches for gnatfind::
11959 * Project Files for gnatxref and gnatfind::
11960 * Regular Expressions in gnatfind and gnatxref::
11961 * Examples of gnatxref Usage::
11962 * Examples of gnatfind Usage::
11963 @end menu
11964
11965 @node Switches for gnatxref
11966 @section @code{gnatxref} Switches
11967
11968 @noindent
11969 The command invocation for @code{gnatxref} is:
11970 @smallexample
11971 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11972 @c Expanding @ovar macro inline (explanation in macro def comments)
11973 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
11974 @end smallexample
11975
11976 @noindent
11977 where
11978
11979 @table @var
11980 @item sourcefile1
11981 @itemx sourcefile2
11982 identifies the source files for which a report is to be generated. The
11983 ``with''ed units will be processed too. You must provide at least one file.
11984
11985 These file names are considered to be regular expressions, so for instance
11986 specifying @file{source*.adb} is the same as giving every file in the current
11987 directory whose name starts with @file{source} and whose extension is
11988 @file{adb}.
11989
11990 You shouldn't specify any directory name, just base names. @command{gnatxref}
11991 and @command{gnatfind} will be able to locate these files by themselves using
11992 the source path. If you specify directories, no result is produced.
11993
11994 @end table
11995
11996 @noindent
11997 The switches can be:
11998 @table @option
11999 @c !sort!
12000 @item --version
12001 @cindex @option{--version} @command{gnatxref}
12002 Display Copyright and version, then exit disregarding all other options.
12003
12004 @item --help
12005 @cindex @option{--help} @command{gnatxref}
12006 If @option{--version} was not used, display usage, then exit disregarding
12007 all other options.
12008
12009 @item ^-a^/ALL_FILES^
12010 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12011 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12012 the read-only files found in the library search path. Otherwise, these files
12013 will be ignored. This option can be used to protect Gnat sources or your own
12014 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12015 much faster, and their output much smaller. Read-only here refers to access
12016 or permissions status in the file system for the current user.
12017
12018 @item -aIDIR
12019 @cindex @option{-aIDIR} (@command{gnatxref})
12020 When looking for source files also look in directory DIR. The order in which
12021 source file search is undertaken is the same as for @command{gnatmake}.
12022
12023 @item -aODIR
12024 @cindex @option{-aODIR} (@command{gnatxref})
12025 When searching for library and object files, look in directory
12026 DIR. The order in which library files are searched is the same as for
12027 @command{gnatmake}.
12028
12029 @item -nostdinc
12030 @cindex @option{-nostdinc} (@command{gnatxref})
12031 Do not look for sources in the system default directory.
12032
12033 @item -nostdlib
12034 @cindex @option{-nostdlib} (@command{gnatxref})
12035 Do not look for library files in the system default directory.
12036
12037 @item --ext=@var{extension}
12038 @cindex @option{--ext} (@command{gnatxref})
12039 Specify an alternate ali file extension. The default is @code{ali} and other
12040 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12041 switch. Note that if this switch overrides the default, which means that only
12042 the new extension will be considered.
12043
12044 @item --RTS=@var{rts-path}
12045 @cindex @option{--RTS} (@command{gnatxref})
12046 Specifies the default location of the runtime library. Same meaning as the
12047 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12048
12049 @item ^-d^/DERIVED_TYPES^
12050 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12051 If this switch is set @code{gnatxref} will output the parent type
12052 reference for each matching derived types.
12053
12054 @item ^-f^/FULL_PATHNAME^
12055 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12056 If this switch is set, the output file names will be preceded by their
12057 directory (if the file was found in the search path). If this switch is
12058 not set, the directory will not be printed.
12059
12060 @item ^-g^/IGNORE_LOCALS^
12061 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12062 If this switch is set, information is output only for library-level
12063 entities, ignoring local entities. The use of this switch may accelerate
12064 @code{gnatfind} and @code{gnatxref}.
12065
12066 @item -IDIR
12067 @cindex @option{-IDIR} (@command{gnatxref})
12068 Equivalent to @samp{-aODIR -aIDIR}.
12069
12070 @item -pFILE
12071 @cindex @option{-pFILE} (@command{gnatxref})
12072 Specify a project file to use @xref{GNAT Project Manager}.
12073 If you need to use the @file{.gpr}
12074 project files, you should use gnatxref through the GNAT driver
12075 (@command{gnat xref -Pproject}).
12076
12077 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12078 project file in the current directory.
12079
12080 If a project file is either specified or found by the tools, then the content
12081 of the source directory and object directory lines are added as if they
12082 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12083 and @samp{^-aO^OBJECT_SEARCH^}.
12084 @item ^-u^/UNUSED^
12085 Output only unused symbols. This may be really useful if you give your
12086 main compilation unit on the command line, as @code{gnatxref} will then
12087 display every unused entity and 'with'ed package.
12088
12089 @ifclear vms
12090 @item -v
12091 Instead of producing the default output, @code{gnatxref} will generate a
12092 @file{tags} file that can be used by vi. For examples how to use this
12093 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12094 to the standard output, thus you will have to redirect it to a file.
12095 @end ifclear
12096
12097 @end table
12098
12099 @noindent
12100 All these switches may be in any order on the command line, and may even
12101 appear after the file names. They need not be separated by spaces, thus
12102 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12103 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12104
12105 @node Switches for gnatfind
12106 @section @code{gnatfind} Switches
12107
12108 @noindent
12109 The command line for @code{gnatfind} is:
12110
12111 @smallexample
12112 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12113 @c       @r{[}@var{file1} @var{file2} @dots{}]
12114 @c Expanding @ovar macro inline (explanation in macro def comments)
12115 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12116       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12117 @end smallexample
12118
12119 @noindent
12120 where
12121
12122 @table @var
12123 @item pattern
12124 An entity will be output only if it matches the regular expression found
12125 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12126
12127 Omitting the pattern is equivalent to specifying @samp{*}, which
12128 will match any entity. Note that if you do not provide a pattern, you
12129 have to provide both a sourcefile and a line.
12130
12131 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12132 for matching purposes. At the current time there is no support for
12133 8-bit codes other than Latin-1, or for wide characters in identifiers.
12134
12135 @item sourcefile
12136 @code{gnatfind} will look for references, bodies or declarations
12137 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12138 and column @var{column}. See @ref{Examples of gnatfind Usage}
12139 for syntax examples.
12140
12141 @item line
12142 is a decimal integer identifying the line number containing
12143 the reference to the entity (or entities) to be located.
12144
12145 @item column
12146 is a decimal integer identifying the exact location on the
12147 line of the first character of the identifier for the
12148 entity reference. Columns are numbered from 1.
12149
12150 @item file1 file2 @dots{}
12151 The search will be restricted to these source files. If none are given, then
12152 the search will be done for every library file in the search path.
12153 These file must appear only after the pattern or sourcefile.
12154
12155 These file names are considered to be regular expressions, so for instance
12156 specifying @file{source*.adb} is the same as giving every file in the current
12157 directory whose name starts with @file{source} and whose extension is
12158 @file{adb}.
12159
12160 The location of the spec of the entity will always be displayed, even if it
12161 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12162 occurrences of the entity in the separate units of the ones given on the
12163 command line will also be displayed.
12164
12165 Note that if you specify at least one file in this part, @code{gnatfind} may
12166 sometimes not be able to find the body of the subprograms.
12167
12168 @end table
12169
12170 @noindent
12171 At least one of 'sourcefile' or 'pattern' has to be present on
12172 the command line.
12173
12174 The following switches are available:
12175 @table @option
12176 @c !sort!
12177
12178 @cindex @option{--version} @command{gnatfind}
12179 Display Copyright and version, then exit disregarding all other options.
12180
12181 @item --help
12182 @cindex @option{--help} @command{gnatfind}
12183 If @option{--version} was not used, display usage, then exit disregarding
12184 all other options.
12185
12186 @item ^-a^/ALL_FILES^
12187 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12188 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12189 the read-only files found in the library search path. Otherwise, these files
12190 will be ignored. This option can be used to protect Gnat sources or your own
12191 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12192 much faster, and their output much smaller. Read-only here refers to access
12193 or permission status in the file system for the current user.
12194
12195 @item -aIDIR
12196 @cindex @option{-aIDIR} (@command{gnatfind})
12197 When looking for source files also look in directory DIR. The order in which
12198 source file search is undertaken is the same as for @command{gnatmake}.
12199
12200 @item -aODIR
12201 @cindex @option{-aODIR} (@command{gnatfind})
12202 When searching for library and object files, look in directory
12203 DIR. The order in which library files are searched is the same as for
12204 @command{gnatmake}.
12205
12206 @item -nostdinc
12207 @cindex @option{-nostdinc} (@command{gnatfind})
12208 Do not look for sources in the system default directory.
12209
12210 @item -nostdlib
12211 @cindex @option{-nostdlib} (@command{gnatfind})
12212 Do not look for library files in the system default directory.
12213
12214 @item --ext=@var{extension}
12215 @cindex @option{--ext} (@command{gnatfind})
12216 Specify an alternate ali file extension. The default is @code{ali} and other
12217 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12218 switch. Note that if this switch overrides the default, which means that only
12219 the new extension will be considered.
12220
12221 @item --RTS=@var{rts-path}
12222 @cindex @option{--RTS} (@command{gnatfind})
12223 Specifies the default location of the runtime library. Same meaning as the
12224 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12225
12226 @item ^-d^/DERIVED_TYPE_INFORMATION^
12227 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12228 If this switch is set, then @code{gnatfind} will output the parent type
12229 reference for each matching derived types.
12230
12231 @item ^-e^/EXPRESSIONS^
12232 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12233 By default, @code{gnatfind} accept the simple regular expression set for
12234 @samp{pattern}. If this switch is set, then the pattern will be
12235 considered as full Unix-style regular expression.
12236
12237 @item ^-f^/FULL_PATHNAME^
12238 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12239 If this switch is set, the output file names will be preceded by their
12240 directory (if the file was found in the search path). If this switch is
12241 not set, the directory will not be printed.
12242
12243 @item ^-g^/IGNORE_LOCALS^
12244 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12245 If this switch is set, information is output only for library-level
12246 entities, ignoring local entities. The use of this switch may accelerate
12247 @code{gnatfind} and @code{gnatxref}.
12248
12249 @item -IDIR
12250 @cindex @option{-IDIR} (@command{gnatfind})
12251 Equivalent to @samp{-aODIR -aIDIR}.
12252
12253 @item -pFILE
12254 @cindex @option{-pFILE} (@command{gnatfind})
12255 Specify a project file (@pxref{GNAT Project Manager}) to use.
12256 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12257 project file in the current directory.
12258
12259 If a project file is either specified or found by the tools, then the content
12260 of the source directory and object directory lines are added as if they
12261 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12262 @samp{^-aO^/OBJECT_SEARCH^}.
12263
12264 @item ^-r^/REFERENCES^
12265 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12266 By default, @code{gnatfind} will output only the information about the
12267 declaration, body or type completion of the entities. If this switch is
12268 set, the @code{gnatfind} will locate every reference to the entities in
12269 the files specified on the command line (or in every file in the search
12270 path if no file is given on the command line).
12271
12272 @item ^-s^/PRINT_LINES^
12273 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12274 If this switch is set, then @code{gnatfind} will output the content
12275 of the Ada source file lines were the entity was found.
12276
12277 @item ^-t^/TYPE_HIERARCHY^
12278 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12279 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12280 the specified type. It act like -d option but recursively from parent
12281 type to parent type. When this switch is set it is not possible to
12282 specify more than one file.
12283
12284 @end table
12285
12286 @noindent
12287 All these switches may be in any order on the command line, and may even
12288 appear after the file names. They need not be separated by spaces, thus
12289 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12290 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12291
12292 As stated previously, gnatfind will search in every directory in the
12293 search path. You can force it to look only in the current directory if
12294 you specify @code{*} at the end of the command line.
12295
12296 @node Project Files for gnatxref and gnatfind
12297 @section Project Files for @command{gnatxref} and @command{gnatfind}
12298
12299 @noindent
12300 Project files allow a programmer to specify how to compile its
12301 application, where to find sources, etc.  These files are used
12302 @ifclear vms
12303 primarily by GPS, but they can also be used
12304 @end ifclear
12305 by the two tools
12306 @code{gnatxref} and @code{gnatfind}.
12307
12308 A project file name must end with @file{.gpr}. If a single one is
12309 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12310 extract the information from it. If multiple project files are found, none of
12311 them is read, and you have to use the @samp{-p} switch to specify the one
12312 you want to use.
12313
12314 The following lines can be included, even though most of them have default
12315 values which can be used in most cases.
12316 The lines can be entered in any order in the file.
12317 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12318 each line. If you have multiple instances, only the last one is taken into
12319 account.
12320
12321 @table @code
12322 @item src_dir=DIR
12323 [default: @code{"^./^[]^"}]
12324 specifies a directory where to look for source files. Multiple @code{src_dir}
12325 lines can be specified and they will be searched in the order they
12326 are specified.
12327
12328 @item obj_dir=DIR
12329 [default: @code{"^./^[]^"}]
12330 specifies a directory where to look for object and library files. Multiple
12331 @code{obj_dir} lines can be specified, and they will be searched in the order
12332 they are specified
12333
12334 @item comp_opt=SWITCHES
12335 [default: @code{""}]
12336 creates a variable which can be referred to subsequently by using
12337 the @code{$@{comp_opt@}} notation. This is intended to store the default
12338 switches given to @command{gnatmake} and @command{gcc}.
12339
12340 @item bind_opt=SWITCHES
12341 [default: @code{""}]
12342 creates a variable which can be referred to subsequently by using
12343 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12344 switches given to @command{gnatbind}.
12345
12346 @item link_opt=SWITCHES
12347 [default: @code{""}]
12348 creates a variable which can be referred to subsequently by using
12349 the @samp{$@{link_opt@}} notation. This is intended to store the default
12350 switches given to @command{gnatlink}.
12351
12352 @item main=EXECUTABLE
12353 [default: @code{""}]
12354 specifies the name of the executable for the application. This variable can
12355 be referred to in the following lines by using the @samp{$@{main@}} notation.
12356
12357 @ifset vms
12358 @item comp_cmd=COMMAND
12359 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12360 @end ifset
12361 @ifclear vms
12362 @item comp_cmd=COMMAND
12363 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12364 @end ifclear
12365 specifies the command used to compile a single file in the application.
12366
12367 @ifset vms
12368 @item make_cmd=COMMAND
12369 [default: @code{"GNAT MAKE $@{main@}
12370 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12371 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12372 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12373 @end ifset
12374 @ifclear vms
12375 @item make_cmd=COMMAND
12376 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12377 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12378 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12379 @end ifclear
12380 specifies the command used to recompile the whole application.
12381
12382 @item run_cmd=COMMAND
12383 [default: @code{"$@{main@}"}]
12384 specifies the command used to run the application.
12385
12386 @item debug_cmd=COMMAND
12387 [default: @code{"gdb $@{main@}"}]
12388 specifies the command used to debug the application
12389
12390 @end table
12391
12392 @noindent
12393 @command{gnatxref} and @command{gnatfind} only take into account the
12394 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12395
12396 @node Regular Expressions in gnatfind and gnatxref
12397 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12398
12399 @noindent
12400 As specified in the section about @command{gnatfind}, the pattern can be a
12401 regular expression. Actually, there are to set of regular expressions
12402 which are recognized by the program:
12403
12404 @table @code
12405 @item globbing patterns
12406 These are the most usual regular expression. They are the same that you
12407 generally used in a Unix shell command line, or in a DOS session.
12408
12409 Here is a more formal grammar:
12410 @smallexample
12411 @group
12412 @iftex
12413 @leftskip=.5cm
12414 @end iftex
12415 regexp ::= term
12416 term   ::= elmt            -- matches elmt
12417 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12418 term   ::= *               -- any string of 0 or more characters
12419 term   ::= ?               -- matches any character
12420 term   ::= [char @{char@}]   -- matches any character listed
12421 term   ::= [char - char]   -- matches any character in range
12422 @end group
12423 @end smallexample
12424
12425 @item full regular expression
12426 The second set of regular expressions is much more powerful. This is the
12427 type of regular expressions recognized by utilities such a @file{grep}.
12428
12429 The following is the form of a regular expression, expressed in Ada
12430 reference manual style BNF is as follows
12431
12432 @smallexample
12433 @iftex
12434 @leftskip=.5cm
12435 @end iftex
12436 @group
12437 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12438
12439 term ::= item @{item@}       -- concatenation (item then item)
12440
12441 item ::= elmt              -- match elmt
12442 item ::= elmt *            -- zero or more elmt's
12443 item ::= elmt +            -- one or more elmt's
12444 item ::= elmt ?            -- matches elmt or nothing
12445 @end group
12446 @group
12447 elmt ::= nschar            -- matches given character
12448 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12449 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12450 elmt ::= [char - char]     -- matches chars in given range
12451 elmt ::= \ char            -- matches given character
12452 elmt ::= .                 -- matches any single character
12453 elmt ::= ( regexp )        -- parens used for grouping
12454
12455 char ::= any character, including special characters
12456 nschar ::= any character except ()[].*+?^^^
12457 @end group
12458 @end smallexample
12459
12460 Following are a few examples:
12461
12462 @table @samp
12463 @item abcde|fghi
12464 will match any of the two strings @samp{abcde} and @samp{fghi},
12465
12466 @item abc*d
12467 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12468 @samp{abcccd}, and so on,
12469
12470 @item [a-z]+
12471 will match any string which has only lowercase characters in it (and at
12472 least one character.
12473
12474 @end table
12475 @end table
12476
12477 @node Examples of gnatxref Usage
12478 @section Examples of @code{gnatxref} Usage
12479
12480 @subsection General Usage
12481
12482 @noindent
12483 For the following examples, we will consider the following units:
12484
12485 @smallexample @c ada
12486 @group
12487 @cartouche
12488 main.ads:
12489 1: with Bar;
12490 2: package Main is
12491 3:     procedure Foo (B : in Integer);
12492 4:     C : Integer;
12493 5: private
12494 6:     D : Integer;
12495 7: end Main;
12496
12497 main.adb:
12498 1: package body Main is
12499 2:     procedure Foo (B : in Integer) is
12500 3:     begin
12501 4:        C := B;
12502 5:        D := B;
12503 6:        Bar.Print (B);
12504 7:        Bar.Print (C);
12505 8:     end Foo;
12506 9: end Main;
12507
12508 bar.ads:
12509 1: package Bar is
12510 2:     procedure Print (B : Integer);
12511 3: end bar;
12512 @end cartouche
12513 @end group
12514 @end smallexample
12515
12516 @table @code
12517
12518 @noindent
12519 The first thing to do is to recompile your application (for instance, in
12520 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12521 the cross-referencing information.
12522 You can then issue any of the following commands:
12523
12524 @item gnatxref main.adb
12525 @code{gnatxref} generates cross-reference information for main.adb
12526 and every unit 'with'ed by main.adb.
12527
12528 The output would be:
12529 @smallexample
12530 @iftex
12531 @leftskip=0cm
12532 @end iftex
12533 B                                                      Type: Integer
12534   Decl: bar.ads           2:22
12535 B                                                      Type: Integer
12536   Decl: main.ads          3:20
12537   Body: main.adb          2:20
12538   Ref:  main.adb          4:13     5:13     6:19
12539 Bar                                                    Type: Unit
12540   Decl: bar.ads           1:9
12541   Ref:  main.adb          6:8      7:8
12542        main.ads           1:6
12543 C                                                      Type: Integer
12544   Decl: main.ads          4:5
12545   Modi: main.adb          4:8
12546   Ref:  main.adb          7:19
12547 D                                                      Type: Integer
12548   Decl: main.ads          6:5
12549   Modi: main.adb          5:8
12550 Foo                                                    Type: Unit
12551   Decl: main.ads          3:15
12552   Body: main.adb          2:15
12553 Main                                                    Type: Unit
12554   Decl: main.ads          2:9
12555   Body: main.adb          1:14
12556 Print                                                   Type: Unit
12557   Decl: bar.ads           2:15
12558   Ref:  main.adb          6:12     7:12
12559 @end smallexample
12560
12561 @noindent
12562 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12563 its body is in main.adb, line 1, column 14 and is not referenced any where.
12564
12565 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12566 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12567
12568 @item gnatxref package1.adb package2.ads
12569 @code{gnatxref} will generates cross-reference information for
12570 package1.adb, package2.ads and any other package 'with'ed by any
12571 of these.
12572
12573 @end table
12574
12575 @ifclear vms
12576 @subsection Using gnatxref with vi
12577
12578 @code{gnatxref} can generate a tags file output, which can be used
12579 directly from @command{vi}. Note that the standard version of @command{vi}
12580 will not work properly with overloaded symbols. Consider using another
12581 free implementation of @command{vi}, such as @command{vim}.
12582
12583 @smallexample
12584 $ gnatxref -v gnatfind.adb > tags
12585 @end smallexample
12586
12587 @noindent
12588 will generate the tags file for @code{gnatfind} itself (if the sources
12589 are in the search path!).
12590
12591 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12592 (replacing @var{entity} by whatever you are looking for), and vi will
12593 display a new file with the corresponding declaration of entity.
12594 @end ifclear
12595
12596 @node Examples of gnatfind Usage
12597 @section Examples of @code{gnatfind} Usage
12598
12599 @table @code
12600
12601 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12602 Find declarations for all entities xyz referenced at least once in
12603 main.adb. The references are search in every library file in the search
12604 path.
12605
12606 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12607 switch is set)
12608
12609 The output will look like:
12610 @smallexample
12611 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12612 ^directory/^[directory]^main.adb:24:10: xyz <= body
12613 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12614 @end smallexample
12615
12616 @noindent
12617 that is to say, one of the entities xyz found in main.adb is declared at
12618 line 12 of main.ads (and its body is in main.adb), and another one is
12619 declared at line 45 of foo.ads
12620
12621 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12622 This is the same command as the previous one, instead @code{gnatfind} will
12623 display the content of the Ada source file lines.
12624
12625 The output will look like:
12626
12627 @smallexample
12628 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12629    procedure xyz;
12630 ^directory/^[directory]^main.adb:24:10: xyz <= body
12631    procedure xyz is
12632 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12633    xyz : Integer;
12634 @end smallexample
12635
12636 @noindent
12637 This can make it easier to find exactly the location your are looking
12638 for.
12639
12640 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12641 Find references to all entities containing an x that are
12642 referenced on line 123 of main.ads.
12643 The references will be searched only in main.ads and foo.adb.
12644
12645 @item gnatfind main.ads:123
12646 Find declarations and bodies for all entities that are referenced on
12647 line 123 of main.ads.
12648
12649 This is the same as @code{gnatfind "*":main.adb:123}.
12650
12651 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12652 Find the declaration for the entity referenced at column 45 in
12653 line 123 of file main.adb in directory mydir. Note that it
12654 is usual to omit the identifier name when the column is given,
12655 since the column position identifies a unique reference.
12656
12657 The column has to be the beginning of the identifier, and should not
12658 point to any character in the middle of the identifier.
12659
12660 @end table
12661
12662 @c *********************************
12663 @node The GNAT Pretty-Printer gnatpp
12664 @chapter The GNAT Pretty-Printer @command{gnatpp}
12665 @findex gnatpp
12666 @cindex Pretty-Printer
12667
12668 @noindent
12669 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12670 for source reformatting / pretty-printing.
12671 It takes an Ada source file as input and generates a reformatted
12672 version as output.
12673 You can specify various style directives via switches; e.g.,
12674 identifier case conventions, rules of indentation, and comment layout.
12675
12676 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12677 tree for the input source and thus requires the input to be syntactically and
12678 semantically legal.
12679 If this condition is not met, @command{gnatpp} will terminate with an
12680 error message; no output file will be generated.
12681
12682 If the source files presented to @command{gnatpp} contain
12683 preprocessing directives, then the output file will
12684 correspond to the generated source after all
12685 preprocessing is carried out. There is no way
12686 using @command{gnatpp} to obtain pretty printed files that
12687 include the preprocessing directives.
12688
12689 If the compilation unit
12690 contained in the input source depends semantically upon units located
12691 outside the current directory, you have to provide the source search path
12692 when invoking @command{gnatpp}, if these units are contained in files with
12693 names that do not follow the GNAT file naming rules, you have to provide
12694 the configuration file describing the corresponding naming scheme;
12695 see the description of the @command{gnatpp}
12696 switches below. Another possibility is to use a project file and to
12697 call @command{gnatpp} through the @command{gnat} driver
12698
12699 The @command{gnatpp} command has the form
12700
12701 @smallexample
12702 @c $ gnatpp @ovar{switches} @var{filename}
12703 @c Expanding @ovar macro inline (explanation in macro def comments)
12704 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12705 @end smallexample
12706
12707 @noindent
12708 where
12709 @itemize @bullet
12710 @item
12711 @var{switches} is an optional sequence of switches defining such properties as
12712 the formatting rules, the source search path, and the destination for the
12713 output source file
12714
12715 @item
12716 @var{filename} is the name (including the extension) of the source file to
12717 reformat; ``wildcards'' or several file names on the same gnatpp command are
12718 allowed.  The file name may contain path information; it does not have to
12719 follow the GNAT file naming rules
12720
12721 @item
12722 @samp{@var{gcc_switches}} is a list of switches for
12723 @command{gcc}. They will be passed on to all compiler invocations made by
12724 @command{gnatelim} to generate the ASIS trees. Here you can provide
12725 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12726 use the @option{-gnatec} switch to set the configuration file,
12727 use the @option{-gnat05} switch if sources should be compiled in
12728 Ada 2005 mode  etc.
12729 @end itemize
12730
12731 @menu
12732 * Switches for gnatpp::
12733 * Formatting Rules::
12734 @end menu
12735
12736 @node Switches for gnatpp
12737 @section Switches for @command{gnatpp}
12738
12739 @noindent
12740 The following subsections describe the various switches accepted by
12741 @command{gnatpp}, organized by category.
12742
12743 @ifclear vms
12744 You specify a switch by supplying a name and generally also a value.
12745 In many cases the values for a switch with a given name are incompatible with
12746 each other
12747 (for example the switch that controls the casing of a reserved word may have
12748 exactly one value: upper case, lower case, or
12749 mixed case) and thus exactly one such switch can be in effect for an
12750 invocation of @command{gnatpp}.
12751 If more than one is supplied, the last one is used.
12752 However, some values for the same switch are mutually compatible.
12753 You may supply several such switches to @command{gnatpp}, but then
12754 each must be specified in full, with both the name and the value.
12755 Abbreviated forms (the name appearing once, followed by each value) are
12756 not permitted.
12757 For example, to set
12758 the alignment of the assignment delimiter both in declarations and in
12759 assignment statements, you must write @option{-A2A3}
12760 (or @option{-A2 -A3}), but not @option{-A23}.
12761 @end ifclear
12762
12763 @ifset vms
12764 In many cases the set of options for a given qualifier are incompatible with
12765 each other (for example the qualifier that controls the casing of a reserved
12766 word may have exactly one option, which specifies either upper case, lower
12767 case, or mixed case), and thus exactly one such option can be in effect for
12768 an invocation of @command{gnatpp}.
12769 If more than one is supplied, the last one is used.
12770 However, some qualifiers have options that are mutually compatible,
12771 and then you may then supply several such options when invoking
12772 @command{gnatpp}.
12773 @end ifset
12774
12775 In most cases, it is obvious whether or not the
12776 ^values for a switch with a given name^options for a given qualifier^
12777 are compatible with each other.
12778 When the semantics might not be evident, the summaries below explicitly
12779 indicate the effect.
12780
12781 @menu
12782 * Alignment Control::
12783 * Casing Control::
12784 * Construct Layout Control::
12785 * General Text Layout Control::
12786 * Other Formatting Options::
12787 * Setting the Source Search Path::
12788 * Output File Control::
12789 * Other gnatpp Switches::
12790 @end menu
12791
12792 @node Alignment Control
12793 @subsection Alignment Control
12794 @cindex Alignment control in @command{gnatpp}
12795
12796 @noindent
12797 Programs can be easier to read if certain constructs are vertically aligned.
12798 By default all alignments are set ON.
12799 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12800 OFF, and then use one or more of the other
12801 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12802 to activate alignment for specific constructs.
12803
12804 @table @option
12805 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12806
12807 @ifset vms
12808 @item /ALIGN=ON
12809 Set all alignments to ON
12810 @end ifset
12811
12812 @item ^-A0^/ALIGN=OFF^
12813 Set all alignments to OFF
12814
12815 @item ^-A1^/ALIGN=COLONS^
12816 Align @code{:} in declarations
12817
12818 @item ^-A2^/ALIGN=DECLARATIONS^
12819 Align @code{:=} in initializations in declarations
12820
12821 @item ^-A3^/ALIGN=STATEMENTS^
12822 Align @code{:=} in assignment statements
12823
12824 @item ^-A4^/ALIGN=ARROWS^
12825 Align @code{=>} in associations
12826
12827 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12828 Align @code{at} keywords in the component clauses in record
12829 representation clauses
12830 @end table
12831
12832 @noindent
12833 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12834 is allowed.
12835
12836 @node Casing Control
12837 @subsection Casing Control
12838 @cindex Casing control in @command{gnatpp}
12839
12840 @noindent
12841 @command{gnatpp} allows you to specify the casing for reserved words,
12842 pragma names, attribute designators and identifiers.
12843 For identifiers you may define a
12844 general rule for name casing but also override this rule
12845 via a set of dictionary files.
12846
12847 Three types of casing are supported: lower case, upper case, and mixed case.
12848 Lower and upper case are self-explanatory (but since some letters in
12849 Latin1 and other GNAT-supported character sets
12850 exist only in lower-case form, an upper case conversion will have no
12851 effect on them.)
12852 ``Mixed case'' means that the first letter, and also each letter immediately
12853 following an underscore, are converted to their uppercase forms;
12854 all the other letters are converted to their lowercase forms.
12855
12856 @table @option
12857 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12858 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12859 Attribute designators are lower case
12860
12861 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12862 Attribute designators are upper case
12863
12864 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12865 Attribute designators are mixed case (this is the default)
12866
12867 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12868 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12869 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12870 lower case (this is the default)
12871
12872 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12873 Keywords are upper case
12874
12875 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12876 @item ^-nD^/NAME_CASING=AS_DECLARED^
12877 Name casing for defining occurrences are as they appear in the source file
12878 (this is the default)
12879
12880 @item ^-nU^/NAME_CASING=UPPER_CASE^
12881 Names are in upper case
12882
12883 @item ^-nL^/NAME_CASING=LOWER_CASE^
12884 Names are in lower case
12885
12886 @item ^-nM^/NAME_CASING=MIXED_CASE^
12887 Names are in mixed case
12888
12889 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12890 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12891 Pragma names are lower case
12892
12893 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12894 Pragma names are upper case
12895
12896 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12897 Pragma names are mixed case (this is the default)
12898
12899 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12900 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12901 Use @var{file} as a @emph{dictionary file} that defines
12902 the casing for a set of specified names,
12903 thereby overriding the effect on these names by
12904 any explicit or implicit
12905 ^-n^/NAME_CASING^ switch.
12906 To supply more than one dictionary file,
12907 use ^several @option{-D} switches^a list of files as options^.
12908
12909 @noindent
12910 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12911 to define the casing for the Ada predefined names and
12912 the names declared in the GNAT libraries.
12913
12914 @item ^-D-^/SPECIFIC_CASING^
12915 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12916 Do not use the default dictionary file;
12917 instead, use the casing
12918 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12919 dictionary file(s)
12920 @end table
12921
12922 @noindent
12923 The structure of a dictionary file, and details on the conventions
12924 used in the default dictionary file, are defined in @ref{Name Casing}.
12925
12926 The @option{^-D-^/SPECIFIC_CASING^} and
12927 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12928 compatible.
12929
12930 @node Construct Layout Control
12931 @subsection Construct Layout Control
12932 @cindex Layout control in @command{gnatpp}
12933
12934 @noindent
12935 This group of @command{gnatpp} switches controls the layout of comments and
12936 complex syntactic constructs.  See @ref{Formatting Comments} for details
12937 on their effect.
12938
12939 @table @option
12940 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
12941 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
12942 All the comments remain unchanged
12943
12944 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
12945 GNAT-style comment line indentation (this is the default).
12946
12947 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
12948 Reference-manual comment line indentation.
12949
12950 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
12951 GNAT-style comment beginning
12952
12953 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
12954 Reformat comment blocks
12955
12956 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
12957 Keep unchanged special form comments
12958
12959 Reformat comment blocks
12960
12961 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
12962 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
12963 GNAT-style layout (this is the default)
12964
12965 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
12966 Compact layout
12967
12968 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
12969 Uncompact layout
12970
12971 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
12972 @item ^-N^/NOTABS^
12973 All the VT characters are removed from the comment text. All the HT characters
12974 are expanded with the sequences of space characters to get to the next tab
12975 stops.
12976
12977 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
12978 @item ^--no-separate-is^/NO_SEPARATE_IS^
12979 Do not place the keyword @code{is} on a separate line in a subprogram body in
12980 case if the spec occupies more then one line.
12981
12982 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
12983 @item ^--separate-label^/SEPARATE_LABEL^
12984 Place statement label(s) on a separate line, with the following statement
12985 on the next line.
12986
12987 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
12988 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
12989 Place the keyword @code{loop} in FOR and WHILE loop statements and the
12990 keyword @code{then} in IF statements on a separate line.
12991
12992 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
12993 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
12994 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
12995 keyword @code{then} in IF statements on a separate line. This option is
12996 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
12997
12998 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
12999 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13000 Start each USE clause in a context clause from a separate line.
13001
13002 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13003 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13004 Use a separate line for a loop or block statement name, but do not use an extra
13005 indentation level for the statement itself.
13006
13007 @end table
13008
13009 @ifclear vms
13010 @noindent
13011 The @option{-c1} and @option{-c2} switches are incompatible.
13012 The @option{-c3} and @option{-c4} switches are compatible with each other and
13013 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13014 the other comment formatting switches.
13015
13016 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13017 @end ifclear
13018
13019 @ifset vms
13020 @noindent
13021 For the @option{/COMMENTS_LAYOUT} qualifier:
13022 @itemize @bullet
13023 @item
13024 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13025 @item
13026 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13027 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13028 @end itemize
13029
13030 @noindent
13031 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13032 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13033 @end ifset
13034
13035 @node General Text Layout Control
13036 @subsection General Text Layout Control
13037
13038 @noindent
13039 These switches allow control over line length and indentation.
13040
13041 @table @option
13042 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13043 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13044 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13045
13046 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13047 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13048 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13049
13050 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13051 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13052 Indentation level for continuation lines (relative to the line being
13053 continued), @var{nnn} from 1@dots{}9.
13054 The default
13055 value is one less then the (normal) indentation level, unless the
13056 indentation is set to 1 (in which case the default value for continuation
13057 line indentation is also 1)
13058 @end table
13059
13060 @node Other Formatting Options
13061 @subsection Other Formatting Options
13062
13063 @noindent
13064 These switches control the inclusion of missing end/exit labels, and
13065 the indentation level in @b{case} statements.
13066
13067 @table @option
13068 @item ^-e^/NO_MISSED_LABELS^
13069 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13070 Do not insert missing end/exit labels. An end label is the name of
13071 a construct that may optionally be repeated at the end of the
13072 construct's declaration;
13073 e.g., the names of packages, subprograms, and tasks.
13074 An exit label is the name of a loop that may appear as target
13075 of an exit statement within the loop.
13076 By default, @command{gnatpp} inserts these end/exit labels when
13077 they are absent from the original source. This option suppresses such
13078 insertion, so that the formatted source reflects the original.
13079
13080 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13081 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13082 Insert a Form Feed character after a pragma Page.
13083
13084 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13085 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13086 Do not use an additional indentation level for @b{case} alternatives
13087 and variants if there are @var{nnn} or more (the default
13088 value is 10).
13089 If @var{nnn} is 0, an additional indentation level is
13090 used for @b{case} alternatives and variants regardless of their number.
13091 @end table
13092
13093 @node Setting the Source Search Path
13094 @subsection Setting the Source Search Path
13095
13096 @noindent
13097 To define the search path for the input source file, @command{gnatpp}
13098 uses the same switches as the GNAT compiler, with the same effects.
13099
13100 @table @option
13101 @item ^-I^/SEARCH=^@var{dir}
13102 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13103 The same as the corresponding gcc switch
13104
13105 @item ^-I-^/NOCURRENT_DIRECTORY^
13106 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13107 The same as the corresponding gcc switch
13108
13109 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13110 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13111 The same as the corresponding gcc switch
13112
13113 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13114 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13115 The same as the corresponding gcc switch
13116
13117 @end table
13118
13119 @node Output File Control
13120 @subsection Output File Control
13121
13122 @noindent
13123 By default the output is sent to the file whose name is obtained by appending
13124 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13125 (if the file with this name already exists, it is unconditionally overwritten).
13126 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13127 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13128 as output file.
13129 The output may be redirected by the following switches:
13130
13131 @table @option
13132 @item ^-pipe^/STANDARD_OUTPUT^
13133 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13134 Send the output to @code{Standard_Output}
13135
13136 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13137 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13138 Write the output into @var{output_file}.
13139 If @var{output_file} already exists, @command{gnatpp} terminates without
13140 reading or processing the input file.
13141
13142 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13143 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13144 Write the output into @var{output_file}, overwriting the existing file
13145 (if one is present).
13146
13147 @item ^-r^/REPLACE^
13148 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13149 Replace the input source file with the reformatted output, and copy the
13150 original input source into the file whose name is obtained by appending the
13151 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13152 If a file with this name already exists, @command{gnatpp} terminates without
13153 reading or processing the input file.
13154
13155 @item ^-rf^/OVERRIDING_REPLACE^
13156 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13157 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13158 already exists, it is overwritten.
13159
13160 @item ^-rnb^/REPLACE_NO_BACKUP^
13161 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13162 Replace the input source file with the reformatted output without
13163 creating any backup copy of the input source.
13164
13165 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13166 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13167 Specifies the format of the reformatted output file. The @var{xxx}
13168 ^string specified with the switch^option^ may be either
13169 @itemize @bullet
13170 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13171 @item ``@option{^crlf^CRLF^}''
13172 the same as @option{^crlf^CRLF^}
13173 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13174 @item ``@option{^lf^LF^}''
13175 the same as @option{^unix^UNIX^}
13176 @end itemize
13177
13178 @item ^-W^/RESULT_ENCODING=^@var{e}
13179 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13180 Specify the wide character encoding method used to write the code in the
13181 result file
13182 @var{e} is one of the following:
13183
13184 @itemize @bullet
13185
13186 @item ^h^HEX^
13187 Hex encoding
13188
13189 @item ^u^UPPER^
13190 Upper half encoding
13191
13192 @item ^s^SHIFT_JIS^
13193 Shift/JIS encoding
13194
13195 @item ^e^EUC^
13196 EUC encoding
13197
13198 @item ^8^UTF8^
13199 UTF-8 encoding
13200
13201 @item ^b^BRACKETS^
13202 Brackets encoding (default value)
13203 @end itemize
13204
13205 @end table
13206
13207 @noindent
13208 Options @option{^-pipe^/STANDARD_OUTPUT^},
13209 @option{^-o^/OUTPUT^} and
13210 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13211 contains only one file to reformat.
13212 Option
13213 @option{^--eol^/END_OF_LINE^}
13214 and
13215 @option{^-W^/RESULT_ENCODING^}
13216 cannot be used together
13217 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13218
13219 @node Other gnatpp Switches
13220 @subsection Other @code{gnatpp} Switches
13221
13222 @noindent
13223 The additional @command{gnatpp} switches are defined in this subsection.
13224
13225 @table @option
13226 @item ^-files @var{filename}^/FILES=@var{filename}^
13227 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13228 Take the argument source files from the specified file. This file should be an
13229 ordinary text file containing file names separated by spaces or
13230 line breaks. You can use this switch more than once in the same call to
13231 @command{gnatpp}. You also can combine this switch with an explicit list of
13232 files.
13233
13234 @item ^-v^/VERBOSE^
13235 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13236 Verbose mode;
13237 @command{gnatpp} generates version information and then
13238 a trace of the actions it takes to produce or obtain the ASIS tree.
13239
13240 @item ^-w^/WARNINGS^
13241 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13242 Warning mode;
13243 @command{gnatpp} generates a warning whenever it cannot provide
13244 a required layout in the result source.
13245 @end table
13246
13247 @node Formatting Rules
13248 @section Formatting Rules
13249
13250 @noindent
13251 The following subsections show how @command{gnatpp} treats ``white space'',
13252 comments, program layout, and name casing.
13253 They provide the detailed descriptions of the switches shown above.
13254
13255 @menu
13256 * White Space and Empty Lines::
13257 * Formatting Comments::
13258 * Construct Layout::
13259 * Name Casing::
13260 @end menu
13261
13262 @node White Space and Empty Lines
13263 @subsection White Space and Empty Lines
13264
13265 @noindent
13266 @command{gnatpp} does not have an option to control space characters.
13267 It will add or remove spaces according to the style illustrated by the
13268 examples in the @cite{Ada Reference Manual}.
13269
13270 The only format effectors
13271 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13272 that will appear in the output file are platform-specific line breaks,
13273 and also format effectors within (but not at the end of) comments.
13274 In particular, each horizontal tab character that is not inside
13275 a comment will be treated as a space and thus will appear in the
13276 output file as zero or more spaces depending on
13277 the reformatting of the line in which it appears.
13278 The only exception is a Form Feed character, which is inserted after a
13279 pragma @code{Page} when @option{-ff} is set.
13280
13281 The output file will contain no lines with trailing ``white space'' (spaces,
13282 format effectors).
13283
13284 Empty lines in the original source are preserved
13285 only if they separate declarations or statements.
13286 In such contexts, a
13287 sequence of two or more empty lines is replaced by exactly one empty line.
13288 Note that a blank line will be removed if it separates two ``comment blocks''
13289 (a comment block is a sequence of whole-line comments).
13290 In order to preserve a visual separation between comment blocks, use an
13291 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13292 Likewise, if for some reason you wish to have a sequence of empty lines,
13293 use a sequence of empty comments instead.
13294
13295 @node Formatting Comments
13296 @subsection Formatting Comments
13297
13298 @noindent
13299 Comments in Ada code are of two kinds:
13300 @itemize @bullet
13301 @item
13302 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13303 ``white space'') on a line
13304
13305 @item
13306 an @emph{end-of-line comment}, which follows some other Ada lexical element
13307 on the same line.
13308 @end itemize
13309
13310 @noindent
13311 The indentation of a whole-line comment is that of either
13312 the preceding or following line in
13313 the formatted source, depending on switch settings as will be described below.
13314
13315 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13316 between the end of the preceding Ada lexical element and the beginning
13317 of the comment as appear in the original source,
13318 unless either the comment has to be split to
13319 satisfy the line length limitation, or else the next line contains a
13320 whole line comment that is considered a continuation of this end-of-line
13321 comment (because it starts at the same position).
13322 In the latter two
13323 cases, the start of the end-of-line comment is moved right to the nearest
13324 multiple of the indentation level.
13325 This may result in a ``line overflow'' (the right-shifted comment extending
13326 beyond the maximum line length), in which case the comment is split as
13327 described below.
13328
13329 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13330 (GNAT-style comment line indentation)
13331 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13332 (reference-manual comment line indentation).
13333 With reference-manual style, a whole-line comment is indented as if it
13334 were a declaration or statement at the same place
13335 (i.e., according to the indentation of the preceding line(s)).
13336 With GNAT style, a whole-line comment that is immediately followed by an
13337 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13338 word @b{begin}, is indented based on the construct that follows it.
13339
13340 For example:
13341 @smallexample @c ada
13342 @cartouche
13343 if A then
13344     null;
13345        -- some comment
13346 else
13347    null;
13348 end if;
13349 @end cartouche
13350 @end smallexample
13351
13352 @noindent
13353 Reference-manual indentation produces:
13354
13355 @smallexample @c ada
13356 @cartouche
13357 if A then
13358    null;
13359    --  some comment
13360 else
13361    null;
13362 end if;
13363 @end cartouche
13364 @end smallexample
13365
13366 @noindent
13367 while GNAT-style indentation produces:
13368
13369 @smallexample @c ada
13370 @cartouche
13371 if A then
13372    null;
13373 --  some comment
13374 else
13375    null;
13376 end if;
13377 @end cartouche
13378 @end smallexample
13379
13380 @noindent
13381 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13382 (GNAT style comment beginning) has the following
13383 effect:
13384
13385 @itemize @bullet
13386 @item
13387 For each whole-line comment that does not end with two hyphens,
13388 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13389 to ensure that there are at least two spaces between these hyphens and the
13390 first non-blank character of the comment.
13391 @end itemize
13392
13393 @noindent
13394 For an end-of-line comment, if in the original source the next line is a
13395 whole-line comment that starts at the same position
13396 as the end-of-line comment,
13397 then the whole-line comment (and all whole-line comments
13398 that follow it and that start at the same position)
13399 will start at this position in the output file.
13400
13401 @noindent
13402 That is, if in the original source we have:
13403
13404 @smallexample @c ada
13405 @cartouche
13406 begin
13407 A := B + C;            --  B must be in the range Low1..High1
13408                        --  C must be in the range Low2..High2
13409              --B+C will be in the range Low1+Low2..High1+High2
13410 X := X + 1;
13411 @end cartouche
13412 @end smallexample
13413
13414 @noindent
13415 Then in the formatted source we get
13416
13417 @smallexample @c ada
13418 @cartouche
13419 begin
13420    A := B + C;            --  B must be in the range Low1..High1
13421                           --  C must be in the range Low2..High2
13422    --  B+C will be in the range Low1+Low2..High1+High2
13423    X := X + 1;
13424 @end cartouche
13425 @end smallexample
13426
13427 @noindent
13428 A comment that exceeds the line length limit will be split.
13429 Unless switch
13430 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13431 the line belongs to a reformattable block, splitting the line generates a
13432 @command{gnatpp} warning.
13433 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13434 comments may be reformatted in typical
13435 word processor style (that is, moving words between lines and putting as
13436 many words in a line as possible).
13437
13438 @noindent
13439 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13440 that has a special format (that is, a character that is neither a letter nor digit
13441 not white space nor line break immediately following the leading @code{--} of
13442 the comment) should be without any change moved from the argument source
13443 into reformatted source. This switch allows to preserve comments that are used
13444 as a special marks in the code (e.g.@: SPARK annotation).
13445
13446 @node Construct Layout
13447 @subsection Construct Layout
13448
13449 @noindent
13450 In several cases the suggested layout in the Ada Reference Manual includes
13451 an extra level of indentation that many programmers prefer to avoid. The
13452 affected cases include:
13453
13454 @itemize @bullet
13455
13456 @item Record type declaration (RM 3.8)
13457
13458 @item Record representation clause (RM 13.5.1)
13459
13460 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13461
13462 @item Block statement in case if a block has a statement identifier (RM 5.6)
13463 @end itemize
13464
13465 @noindent
13466 In compact mode (when GNAT style layout or compact layout is set),
13467 the pretty printer uses one level of indentation instead
13468 of two. This is achieved in the record definition and record representation
13469 clause cases by putting the @code{record} keyword on the same line as the
13470 start of the declaration or representation clause, and in the block and loop
13471 case by putting the block or loop header on the same line as the statement
13472 identifier.
13473
13474 @noindent
13475 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13476 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13477 layout on the one hand, and uncompact layout
13478 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13479 can be illustrated by the following examples:
13480
13481 @iftex
13482 @cartouche
13483 @multitable @columnfractions .5 .5
13484 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13485
13486 @item
13487 @smallexample @c ada
13488 type q is record
13489    a : integer;
13490    b : integer;
13491 end record;
13492 @end smallexample
13493 @tab
13494 @smallexample @c ada
13495 type q is
13496    record
13497       a : integer;
13498       b : integer;
13499    end record;
13500 @end smallexample
13501
13502 @item
13503 @smallexample @c ada
13504 for q use record
13505    a at 0 range  0 .. 31;
13506    b at 4 range  0 .. 31;
13507 end record;
13508 @end smallexample
13509 @tab
13510 @smallexample @c ada
13511 for q use
13512    record
13513       a at 0 range  0 .. 31;
13514       b at 4 range  0 .. 31;
13515    end record;
13516 @end smallexample
13517
13518 @item
13519 @smallexample @c ada
13520 Block : declare
13521    A : Integer := 3;
13522 begin
13523    Proc (A, A);
13524 end Block;
13525 @end smallexample
13526 @tab
13527 @smallexample @c ada
13528 Block :
13529    declare
13530       A : Integer := 3;
13531    begin
13532       Proc (A, A);
13533    end Block;
13534 @end smallexample
13535
13536 @item
13537 @smallexample @c ada
13538 Clear : for J in 1 .. 10 loop
13539    A (J) := 0;
13540 end loop Clear;
13541 @end smallexample
13542 @tab
13543 @smallexample @c ada
13544 Clear :
13545    for J in 1 .. 10 loop
13546       A (J) := 0;
13547    end loop Clear;
13548 @end smallexample
13549 @end multitable
13550 @end cartouche
13551 @end iftex
13552
13553 @ifnottex
13554 @smallexample
13555 @cartouche
13556 GNAT style, compact layout              Uncompact layout
13557
13558 type q is record                        type q is
13559    a : integer;                            record
13560    b : integer;                               a : integer;
13561 end record;                                   b : integer;
13562                                            end record;
13563
13564 for q use record                        for q use
13565    a at 0 range  0 .. 31;                  record
13566    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13567 end record;                                   b at 4 range  0 .. 31;
13568                                            end record;
13569
13570 Block : declare                         Block :
13571    A : Integer := 3;                       declare
13572 begin                                         A : Integer := 3;
13573    Proc (A, A);                            begin
13574 end Block;                                    Proc (A, A);
13575                                            end Block;
13576
13577 Clear : for J in 1 .. 10 loop           Clear :
13578    A (J) := 0;                             for J in 1 .. 10 loop
13579 end loop Clear;                               A (J) := 0;
13580                                            end loop Clear;
13581 @end cartouche
13582 @end smallexample
13583 @end ifnottex
13584
13585 @noindent
13586 A further difference between GNAT style layout and compact layout is that
13587 GNAT style layout inserts empty lines as separation for
13588 compound statements, return statements and bodies.
13589
13590 Note that the layout specified by
13591 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13592 for named block and loop statements overrides the layout defined by these
13593 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13594 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13595 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13596
13597 @node Name Casing
13598 @subsection Name Casing
13599
13600 @noindent
13601 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13602 the same casing as the corresponding defining identifier.
13603
13604 You control the casing for defining occurrences via the
13605 @option{^-n^/NAME_CASING^} switch.
13606 @ifclear vms
13607 With @option{-nD} (``as declared'', which is the default),
13608 @end ifclear
13609 @ifset vms
13610 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13611 @end ifset
13612 defining occurrences appear exactly as in the source file
13613 where they are declared.
13614 The other ^values for this switch^options for this qualifier^ ---
13615 @option{^-nU^UPPER_CASE^},
13616 @option{^-nL^LOWER_CASE^},
13617 @option{^-nM^MIXED_CASE^} ---
13618 result in
13619 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13620 If @command{gnatpp} changes the casing of a defining
13621 occurrence, it analogously changes the casing of all the
13622 usage occurrences of this name.
13623
13624 If the defining occurrence of a name is not in the source compilation unit
13625 currently being processed by @command{gnatpp}, the casing of each reference to
13626 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13627 switch (subject to the dictionary file mechanism described below).
13628 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13629 had affected the
13630 casing for the defining occurrence of the name.
13631
13632 Some names may need to be spelled with casing conventions that are not
13633 covered by the upper-, lower-, and mixed-case transformations.
13634 You can arrange correct casing by placing such names in a
13635 @emph{dictionary file},
13636 and then supplying a @option{^-D^/DICTIONARY^} switch.
13637 The casing of names from dictionary files overrides
13638 any @option{^-n^/NAME_CASING^} switch.
13639
13640 To handle the casing of Ada predefined names and the names from GNAT libraries,
13641 @command{gnatpp} assumes a default dictionary file.
13642 The name of each predefined entity is spelled with the same casing as is used
13643 for the entity in the @cite{Ada Reference Manual}.
13644 The name of each entity in the GNAT libraries is spelled with the same casing
13645 as is used in the declaration of that entity.
13646
13647 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13648 default dictionary file.
13649 Instead, the casing for predefined and GNAT-defined names will be established
13650 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13651 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13652 will appear as just shown,
13653 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13654 To ensure that even such names are rendered in uppercase,
13655 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13656 (or else, less conveniently, place these names in upper case in a dictionary
13657 file).
13658
13659 A dictionary file is
13660 a plain text file; each line in this file can be either a blank line
13661 (containing only space characters and ASCII.HT characters), an Ada comment
13662 line, or the specification of exactly one @emph{casing schema}.
13663
13664 A casing schema is a string that has the following syntax:
13665
13666 @smallexample
13667 @cartouche
13668   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13669
13670   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13671 @end cartouche
13672 @end smallexample
13673
13674 @noindent
13675 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13676 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13677
13678 The casing schema string can be followed by white space and/or an Ada-style
13679 comment; any amount of white space is allowed before the string.
13680
13681 If a dictionary file is passed as
13682 @ifclear vms
13683 the value of a @option{-D@var{file}} switch
13684 @end ifclear
13685 @ifset vms
13686 an option to the @option{/DICTIONARY} qualifier
13687 @end ifset
13688 then for every
13689 simple name and every identifier, @command{gnatpp} checks if the dictionary
13690 defines the casing for the name or for some of its parts (the term ``subword''
13691 is used below to denote the part of a name which is delimited by ``_'' or by
13692 the beginning or end of the word and which does not contain any ``_'' inside):
13693
13694 @itemize @bullet
13695 @item
13696 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13697 the casing defined by the dictionary; no subwords are checked for this word
13698
13699 @item
13700 for every subword @command{gnatpp} checks if the dictionary contains the
13701 corresponding string of the form @code{*@var{simple_identifier}*},
13702 and if it does, the casing of this @var{simple_identifier} is used
13703 for this subword
13704
13705 @item
13706 if the whole name does not contain any ``_'' inside, and if for this name
13707 the dictionary contains two entries - one of the form @var{identifier},
13708 and another - of the form *@var{simple_identifier}*, then the first one
13709 is applied to define the casing of this name
13710
13711 @item
13712 if more than one dictionary file is passed as @command{gnatpp} switches, each
13713 dictionary adds new casing exceptions and overrides all the existing casing
13714 exceptions set by the previous dictionaries
13715
13716 @item
13717 when @command{gnatpp} checks if the word or subword is in the dictionary,
13718 this check is not case sensitive
13719 @end itemize
13720
13721 @noindent
13722 For example, suppose we have the following source to reformat:
13723
13724 @smallexample @c ada
13725 @cartouche
13726 procedure test is
13727    name1 : integer := 1;
13728    name4_name3_name2 : integer := 2;
13729    name2_name3_name4 : Boolean;
13730    name1_var : Float;
13731 begin
13732    name2_name3_name4 := name4_name3_name2 > name1;
13733 end;
13734 @end cartouche
13735 @end smallexample
13736
13737 @noindent
13738 And suppose we have two dictionaries:
13739
13740 @smallexample
13741 @cartouche
13742 @i{dict1:}
13743    NAME1
13744    *NaMe3*
13745    *Name1*
13746 @end cartouche
13747
13748 @cartouche
13749 @i{dict2:}
13750   *NAME3*
13751 @end cartouche
13752 @end smallexample
13753
13754 @noindent
13755 If @command{gnatpp} is called with the following switches:
13756
13757 @smallexample
13758 @ifclear vms
13759 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13760 @end ifclear
13761 @ifset vms
13762 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13763 @end ifset
13764 @end smallexample
13765
13766 @noindent
13767 then we will get the following name casing in the @command{gnatpp} output:
13768
13769 @smallexample @c ada
13770 @cartouche
13771 procedure Test is
13772    NAME1             : Integer := 1;
13773    Name4_NAME3_Name2 : Integer := 2;
13774    Name2_NAME3_Name4 : Boolean;
13775    Name1_Var         : Float;
13776 begin
13777    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13778 end Test;
13779 @end cartouche
13780 @end smallexample
13781
13782 @c *********************************
13783 @node The GNAT Metric Tool gnatmetric
13784 @chapter The GNAT Metric Tool @command{gnatmetric}
13785 @findex gnatmetric
13786 @cindex Metric tool
13787
13788 @noindent
13789 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13790 for computing various program metrics.
13791 It takes an Ada source file as input and generates a file containing the
13792 metrics data as output. Various switches control which
13793 metrics are computed and output.
13794
13795 @command{gnatmetric} generates and uses the ASIS
13796 tree for the input source and thus requires the input to be syntactically and
13797 semantically legal.
13798 If this condition is not met, @command{gnatmetric} will generate
13799 an error message; no metric information for this file will be
13800 computed and reported.
13801
13802 If the compilation unit contained in the input source depends semantically
13803 upon units in files located outside the current directory, you have to provide
13804 the source search path when invoking @command{gnatmetric}.
13805 If it depends semantically upon units that are contained
13806 in files with names that do not follow the GNAT file naming rules, you have to
13807 provide the configuration file describing the corresponding naming scheme (see
13808 the description of the @command{gnatmetric} switches below.)
13809 Alternatively, you may use a project file and invoke @command{gnatmetric}
13810 through the @command{gnat} driver.
13811
13812 The @command{gnatmetric} command has the form
13813
13814 @smallexample
13815 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13816 @c Expanding @ovar macro inline (explanation in macro def comments)
13817 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13818 @end smallexample
13819
13820 @noindent
13821 where
13822 @itemize @bullet
13823 @item
13824 @var{switches} specify the metrics to compute and define the destination for
13825 the output
13826
13827 @item
13828 Each @var{filename} is the name (including the extension) of a source
13829 file to process. ``Wildcards'' are allowed, and
13830 the file name may contain path information.
13831 If no @var{filename} is supplied, then the @var{switches} list must contain
13832 at least one
13833 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13834 Including both a @option{-files} switch and one or more
13835 @var{filename} arguments is permitted.
13836
13837 @item
13838 @samp{@var{gcc_switches}} is a list of switches for
13839 @command{gcc}. They will be passed on to all compiler invocations made by
13840 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13841 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13842 and use the @option{-gnatec} switch to set the configuration file,
13843 use the @option{-gnat05} switch if sources should be compiled in
13844 Ada 2005 mode etc.
13845 @end itemize
13846
13847 @menu
13848 * Switches for gnatmetric::
13849 @end menu
13850
13851 @node Switches for gnatmetric
13852 @section Switches for @command{gnatmetric}
13853
13854 @noindent
13855 The following subsections describe the various switches accepted by
13856 @command{gnatmetric}, organized by category.
13857
13858 @menu
13859 * Output Files Control::
13860 * Disable Metrics For Local Units::
13861 * Specifying a set of metrics to compute::
13862 * Other gnatmetric Switches::
13863 * Generate project-wide metrics::
13864 @end menu
13865
13866 @node Output Files Control
13867 @subsection Output File Control
13868 @cindex Output file control in @command{gnatmetric}
13869
13870 @noindent
13871 @command{gnatmetric} has two output formats. It can generate a
13872 textual (human-readable) form, and also XML. By default only textual
13873 output is generated.
13874
13875 When generating the output in textual form, @command{gnatmetric} creates
13876 for each Ada source file a corresponding text file
13877 containing the computed metrics, except for the case when the set of metrics
13878 specified by gnatmetric parameters consists only of metrics that are computed
13879 for the whole set of analyzed sources, but not for each Ada source.
13880 By default, this file is placed in the same directory as where the source
13881 file is located, and its name is obtained
13882 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13883 input file.
13884
13885 All the output information generated in XML format is placed in a single
13886 file. By default this file is placed in the current directory and has the
13887 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13888
13889 Some of the computed metrics are summed over the units passed to
13890 @command{gnatmetric}; for example, the total number of lines of code.
13891 By default this information is sent to @file{stdout}, but a file
13892 can be specified with the @option{-og} switch.
13893
13894 The following switches control the @command{gnatmetric} output:
13895
13896 @table @option
13897 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13898 @item ^-x^/XML^
13899 Generate the XML output
13900
13901 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13902 @item ^-xs^/XSD^
13903 Generate the XML output and the XML schema file that describes the structure
13904 of the XML metric report, this schema is assigned to the XML file. The schema
13905 file has the same name as the XML output file with @file{.xml} suffix replaced
13906 with @file{.xsd}
13907
13908 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13909 @item ^-nt^/NO_TEXT^
13910 Do not generate the output in text form (implies @option{^-x^/XML^})
13911
13912 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13913 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13914 Put text files with detailed metrics into @var{output_dir}
13915
13916 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13917 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13918 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13919 in the name of the output file.
13920
13921 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13922 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13923 Put global metrics into @var{file_name}
13924
13925 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13926 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13927 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13928
13929 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
13930 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
13931 Use ``short'' source file names in the output.  (The @command{gnatmetric}
13932 output includes the name(s) of the Ada source file(s) from which the metrics
13933 are computed.  By default each name includes the absolute path. The
13934 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
13935 to exclude all directory information from the file names that are output.)
13936
13937 @end table
13938
13939 @node Disable Metrics For Local Units
13940 @subsection Disable Metrics For Local Units
13941 @cindex Disable Metrics For Local Units in @command{gnatmetric}
13942
13943 @noindent
13944 @command{gnatmetric} relies on the GNAT compilation model @minus{}
13945 one compilation
13946 unit per one source file. It computes line metrics for the whole source
13947 file, and it also computes syntax
13948 and complexity metrics for the file's outermost unit.
13949
13950 By default, @command{gnatmetric} will also compute all metrics for certain
13951 kinds of locally declared program units:
13952
13953 @itemize @bullet
13954 @item
13955 subprogram (and generic subprogram) bodies;
13956
13957 @item
13958 package (and generic package) specs and bodies;
13959
13960 @item
13961 task object and type specifications and bodies;
13962
13963 @item
13964 protected object and type specifications and bodies.
13965 @end itemize
13966
13967 @noindent
13968 These kinds of entities will be referred to as
13969 @emph{eligible local program units}, or simply @emph{eligible local units},
13970 @cindex Eligible local unit (for @command{gnatmetric})
13971 in the discussion below.
13972
13973 Note that a subprogram declaration, generic instantiation,
13974 or renaming declaration only receives metrics
13975 computation when it appear as the outermost entity
13976 in a source file.
13977
13978 Suppression of metrics computation for eligible local units can be
13979 obtained via the following switch:
13980
13981 @table @option
13982 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
13983 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
13984 Do not compute detailed metrics for eligible local program units
13985
13986 @end table
13987
13988 @node Specifying a set of metrics to compute
13989 @subsection Specifying a set of metrics to compute
13990
13991 @noindent
13992 By default all the metrics are computed and reported. The switches
13993 described in this subsection allow you to control, on an individual
13994 basis, whether metrics are computed and
13995 reported. If at least one positive metric
13996 switch is specified (that is, a switch that defines that a given
13997 metric or set of metrics is to be computed), then only
13998 explicitly specified metrics are reported.
13999
14000 @menu
14001 * Line Metrics Control::
14002 * Syntax Metrics Control::
14003 * Complexity Metrics Control::
14004 * Object-Oriented Metrics Control::
14005 @end menu
14006
14007 @node Line Metrics Control
14008 @subsubsection Line Metrics Control
14009 @cindex Line metrics control in @command{gnatmetric}
14010
14011 @noindent
14012 For any (legal) source file, and for each of its
14013 eligible local program units, @command{gnatmetric} computes the following
14014 metrics:
14015
14016 @itemize @bullet
14017 @item
14018 the total number of lines;
14019
14020 @item
14021 the total number of code lines (i.e., non-blank lines that are not comments)
14022
14023 @item
14024 the number of comment lines
14025
14026 @item
14027 the number of code lines containing end-of-line comments;
14028
14029 @item
14030 the comment percentage: the ratio between the number of lines that contain
14031 comments and the number of all non-blank lines, expressed as a percentage;
14032
14033 @item
14034 the number of empty lines and lines containing only space characters and/or
14035 format effectors (blank lines)
14036
14037 @item
14038 the average number of code lines in subprogram bodies, task bodies, entry
14039 bodies and statement sequences in package bodies (this metric is only computed
14040 across the whole set of the analyzed units)
14041
14042 @end itemize
14043
14044 @noindent
14045 @command{gnatmetric} sums the values of the line metrics for all the
14046 files being processed and then generates the cumulative results. The tool
14047 also computes for all the files being processed the average number of code
14048 lines in bodies.
14049
14050 You can use the following switches to select the specific line metrics
14051 to be computed and reported.
14052
14053 @table @option
14054 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14055
14056 @ifclear vms
14057 @cindex @option{--no-lines@var{x}}
14058 @end ifclear
14059
14060 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14061 Report all the line metrics
14062
14063 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14064 Do not report any of line metrics
14065
14066 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14067 Report the number of all lines
14068
14069 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14070 Do not report the number of all lines
14071
14072 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14073 Report the number of code lines
14074
14075 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14076 Do not report the number of code lines
14077
14078 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14079 Report the number of comment lines
14080
14081 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14082 Do not report the number of comment lines
14083
14084 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14085 Report the number of code lines containing
14086 end-of-line comments
14087
14088 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14089 Do not report the number of code lines containing
14090 end-of-line comments
14091
14092 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14093 Report the comment percentage in the program text
14094
14095 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14096 Do not report the comment percentage in the program text
14097
14098 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14099 Report the number of blank lines
14100
14101 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14102 Do not report the number of blank lines
14103
14104 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14105 Report the average number of code lines in subprogram bodies, task bodies,
14106 entry bodies and statement sequences in package bodies. The metric is computed
14107 and reported for the whole set of processed Ada sources only.
14108
14109 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14110 Do not report the average number of code lines in subprogram bodies,
14111 task bodies, entry bodies and statement sequences in package bodies.
14112
14113 @end table
14114
14115 @node Syntax Metrics Control
14116 @subsubsection Syntax Metrics Control
14117 @cindex Syntax metrics control in @command{gnatmetric}
14118
14119 @noindent
14120 @command{gnatmetric} computes various syntactic metrics for the
14121 outermost unit and for each eligible local unit:
14122
14123 @table @emph
14124 @item LSLOC (``Logical Source Lines Of Code'')
14125 The total number of declarations and the total number of statements
14126
14127 @item Maximal static nesting level of inner program units
14128 According to
14129 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14130 package, a task unit, a protected unit, a
14131 protected entry, a generic unit, or an explicitly declared subprogram other
14132 than an enumeration literal.''
14133
14134 @item Maximal nesting level of composite syntactic constructs
14135 This corresponds to the notion of the
14136 maximum nesting level in the GNAT built-in style checks
14137 (@pxref{Style Checking})
14138 @end table
14139
14140 @noindent
14141 For the outermost unit in the file, @command{gnatmetric} additionally computes
14142 the following metrics:
14143
14144 @table @emph
14145 @item Public subprograms
14146 This metric is computed for package specs. It is the
14147 number of subprograms and generic subprograms declared in the visible
14148 part (including the visible part of nested packages, protected objects, and
14149 protected types).
14150
14151 @item All subprograms
14152 This metric is computed for bodies and subunits. The
14153 metric is equal to a total number of subprogram bodies in the compilation
14154 unit.
14155 Neither generic instantiations nor renamings-as-a-body nor body stubs
14156 are counted. Any subprogram body is counted, independently of its nesting
14157 level and enclosing constructs. Generic bodies and bodies of protected
14158 subprograms are counted in the same way as ``usual'' subprogram bodies.
14159
14160 @item Public types
14161 This metric is computed for package specs and
14162 generic package declarations. It is the total number of types
14163 that can be referenced from outside this compilation unit, plus the
14164 number of types from all the visible parts of all the visible generic
14165 packages. Generic formal types are not counted.  Only types, not subtypes,
14166 are included.
14167
14168 @noindent
14169 Along with the total number of public types, the following
14170 types are counted and reported separately:
14171
14172 @itemize @bullet
14173 @item
14174 Abstract types
14175
14176 @item
14177 Root tagged types (abstract, non-abstract, private, non-private). Type
14178 extensions are @emph{not} counted
14179
14180 @item
14181 Private types (including private extensions)
14182
14183 @item
14184 Task types
14185
14186 @item
14187 Protected types
14188
14189 @end itemize
14190
14191 @item All types
14192 This metric is computed for any compilation unit. It is equal to the total
14193 number of the declarations of different types given in the compilation unit.
14194 The private and the corresponding full type declaration are counted as one
14195 type declaration. Incomplete type declarations and generic formal types
14196 are not counted.
14197 No distinction is made among different kinds of types (abstract,
14198 private etc.); the total number of types is computed and reported.
14199
14200 @end table
14201
14202 @noindent
14203 By default, all the syntax metrics are computed and reported. You can use the
14204 following switches to select specific syntax metrics.
14205
14206 @table @option
14207
14208 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14209
14210 @ifclear vms
14211 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14212 @end ifclear
14213
14214 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14215 Report all the syntax metrics
14216
14217 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14218 Do not report any of syntax metrics
14219
14220 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14221 Report the total number of declarations
14222
14223 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14224 Do not report the total number of declarations
14225
14226 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14227 Report the total number of statements
14228
14229 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14230 Do not report the total number of statements
14231
14232 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14233 Report the number of public subprograms in a compilation unit
14234
14235 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14236 Do not report the number of public subprograms in a compilation unit
14237
14238 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14239 Report the number of all the subprograms in a compilation unit
14240
14241 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14242 Do not report the number of all the subprograms in a compilation unit
14243
14244 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14245 Report the number of public types in a compilation unit
14246
14247 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14248 Do not report the number of public types in a compilation unit
14249
14250 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14251 Report the number of all the types in a compilation unit
14252
14253 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14254 Do not report the number of all the types in a compilation unit
14255
14256 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14257 Report the maximal program unit nesting level
14258
14259 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14260 Do not report the maximal program unit nesting level
14261
14262 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14263 Report the maximal construct nesting level
14264
14265 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14266 Do not report the maximal construct nesting level
14267
14268 @end table
14269
14270 @node Complexity Metrics Control
14271 @subsubsection Complexity Metrics Control
14272 @cindex Complexity metrics control in @command{gnatmetric}
14273
14274 @noindent
14275 For a program unit that is an executable body (a subprogram body (including
14276 generic bodies), task body, entry body or a package body containing
14277 its own statement sequence) @command{gnatmetric} computes the following
14278 complexity metrics:
14279
14280 @itemize @bullet
14281 @item
14282 McCabe cyclomatic complexity;
14283
14284 @item
14285 McCabe essential complexity;
14286
14287 @item
14288 maximal loop nesting level
14289
14290 @end itemize
14291
14292 @noindent
14293 The McCabe complexity metrics are defined
14294 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14295
14296 According to McCabe, both control statements and short-circuit control forms
14297 should be taken into account when computing cyclomatic complexity. For each
14298 body, we compute three metric values:
14299
14300 @itemize @bullet
14301 @item
14302 the complexity introduced by control
14303 statements only, without taking into account short-circuit forms,
14304
14305 @item
14306 the complexity introduced by short-circuit control forms only, and
14307
14308 @item
14309 the total
14310 cyclomatic complexity, which is the sum of these two values.
14311 @end itemize
14312
14313 @noindent
14314 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14315 the code in the exception handlers and in all the nested program units.
14316
14317 By default, all the complexity metrics are computed and reported.
14318 For more fine-grained control you can use
14319 the following switches:
14320
14321 @table @option
14322 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14323
14324 @ifclear vms
14325 @cindex @option{--no-complexity@var{x}}
14326 @end ifclear
14327
14328 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14329 Report all the complexity metrics
14330
14331 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14332 Do not report any of complexity metrics
14333
14334 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14335 Report the McCabe Cyclomatic Complexity
14336
14337 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14338 Do not report the McCabe Cyclomatic Complexity
14339
14340 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14341 Report the Essential Complexity
14342
14343 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14344 Do not report the Essential Complexity
14345
14346 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14347 Report maximal loop nesting level
14348
14349 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14350 Do not report maximal loop nesting level
14351
14352 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14353 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14354 task bodies, entry bodies and statement sequences in package bodies.
14355 The metric is computed and reported for whole set of processed Ada sources
14356 only.
14357
14358 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14359 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14360 bodies, task bodies, entry bodies and statement sequences in package bodies
14361
14362 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14363 @item ^-ne^/NO_EXITS_AS_GOTOS^
14364 Do not consider @code{exit} statements as @code{goto}s when
14365 computing Essential Complexity
14366
14367 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14368 Report the extra exit points for subprogram bodies. As an exit point, this
14369 metric counts @code{return} statements and raise statements in case when the
14370 raised exception is not handled in the same body. In case of a function this
14371 metric subtracts 1 from the number of exit points, because a function body
14372 must contain at least one @code{return} statement.
14373
14374 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14375 Do not report the extra exit points for subprogram bodies
14376 @end table
14377
14378
14379 @node Object-Oriented Metrics Control
14380 @subsubsection Object-Oriented Metrics Control
14381 @cindex Object-Oriented metrics control in @command{gnatmetric}
14382
14383 @noindent
14384 @cindex Coupling metrics (in in @command{gnatmetric})
14385 Coupling metrics are object-oriented metrics that measure the
14386 dependencies between a given class (or a group of classes) and the
14387 ``external world'' (that is, the other classes in the program). In this
14388 subsection the term ``class'' is used in its
14389 traditional object-oriented programming sense
14390 (an instantiable module that contains data and/or method members).
14391 A @emph{category} (of classes)
14392 is a group of closely related classes that are reused and/or
14393 modified together.
14394
14395 A class @code{K}'s @emph{efferent coupling} is the number of classes
14396 that @code{K} depends upon.
14397 A category's efferent coupling is the number of classes outside the
14398 category that the classes inside the category depend upon.
14399
14400 A class @code{K}'s @emph{afferent coupling} is the number of classes
14401 that depend upon @code{K}.
14402 A category's afferent coupling is the number of classes outside the
14403 category that depend on classes belonging to the category.
14404
14405 Ada's implementation of the object-oriented paradigm does not use the
14406 traditional class notion, so the definition of the coupling
14407 metrics for Ada maps the class and class category notions
14408 onto Ada constructs.
14409
14410 For the coupling metrics, several kinds of modules -- a library package,
14411 a library generic package, and a library generic package instantiation --
14412 that define a tagged type or an interface type are
14413 considered to be a class. A category consists of a library package (or
14414 a library generic package) that defines a tagged or an interface type,
14415 together with all its descendant (generic) packages that define tagged
14416 or interface types. For any package counted as a class,
14417 its body and subunits (if any) are considered
14418 together with its spec when counting the dependencies, and coupling
14419 metrics are reported for spec units only. For dependencies
14420 between classes, the Ada semantic dependencies are considered.
14421 For coupling metrics, only dependencies on units that are considered as
14422 classes, are considered.
14423
14424 When computing coupling metrics, @command{gnatmetric} counts only
14425 dependencies between units that are arguments of the gnatmetric call.
14426 Coupling metrics are program-wide (or project-wide) metrics, so to
14427 get a valid result, you should call @command{gnatmetric} for
14428 the whole set of sources that make up your program. It can be done
14429 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14430 option (see See @ref{The GNAT Driver and Project Files} for details.
14431
14432 By default, all the coupling metrics are disabled. You can use the following
14433 switches to specify the coupling metrics to be computed and reported:
14434
14435 @table @option
14436
14437 @ifclear vms
14438 @cindex @option{--package@var{x}} (@command{gnatmetric})
14439 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14440 @cindex @option{--category@var{x}} (@command{gnatmetric})
14441 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14442 @end ifclear
14443
14444 @ifset vms
14445 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14446 @end ifset
14447
14448 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14449 Report all the coupling metrics
14450
14451 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14452 Do not report any of  metrics
14453
14454 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14455 Report package efferent coupling
14456
14457 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14458 Do not report package efferent coupling
14459
14460 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14461 Report package afferent coupling
14462
14463 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14464 Do not report package afferent coupling
14465
14466 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14467 Report category efferent coupling
14468
14469 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14470 Do not report category efferent coupling
14471
14472 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14473 Report category afferent coupling
14474
14475 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14476 Do not report category afferent coupling
14477
14478 @end table
14479
14480 @node Other gnatmetric Switches
14481 @subsection Other @code{gnatmetric} Switches
14482
14483 @noindent
14484 Additional @command{gnatmetric} switches are as follows:
14485
14486 @table @option
14487 @item ^-files @var{filename}^/FILES=@var{filename}^
14488 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14489 Take the argument source files from the specified file. This file should be an
14490 ordinary text file containing file names separated by spaces or
14491 line breaks. You can use this switch more than once in the same call to
14492 @command{gnatmetric}. You also can combine this switch with
14493 an explicit list of files.
14494
14495 @item ^-v^/VERBOSE^
14496 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14497 Verbose mode;
14498 @command{gnatmetric} generates version information and then
14499 a trace of sources being processed.
14500
14501 @item ^-dv^/DEBUG_OUTPUT^
14502 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
14503 Debug mode;
14504 @command{gnatmetric} generates various messages useful to understand what
14505 happens during the metrics computation
14506
14507 @item ^-q^/QUIET^
14508 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14509 Quiet mode.
14510 @end table
14511
14512 @node Generate project-wide metrics
14513 @subsection Generate project-wide metrics
14514
14515 In order to compute metrics on all units of a given project, you can use
14516 the @command{gnat} driver along with the @option{-P} option:
14517 @smallexample
14518    gnat metric -Pproj
14519 @end smallexample
14520
14521 @noindent
14522 If the project @code{proj} depends upon other projects, you can compute
14523 the metrics on the project closure using the @option{-U} option:
14524 @smallexample
14525    gnat metric -Pproj -U
14526 @end smallexample
14527
14528 @noindent
14529 Finally, if not all the units are relevant to a particular main
14530 program in the project closure, you can generate metrics for the set
14531 of units needed to create a given main program (unit closure) using
14532 the @option{-U} option followed by the name of the main unit:
14533 @smallexample
14534    gnat metric -Pproj -U main
14535 @end smallexample
14536
14537
14538 @c ***********************************
14539 @node File Name Krunching Using gnatkr
14540 @chapter File Name Krunching Using @code{gnatkr}
14541 @findex gnatkr
14542
14543 @noindent
14544 This chapter discusses the method used by the compiler to shorten
14545 the default file names chosen for Ada units so that they do not
14546 exceed the maximum length permitted. It also describes the
14547 @code{gnatkr} utility that can be used to determine the result of
14548 applying this shortening.
14549 @menu
14550 * About gnatkr::
14551 * Using gnatkr::
14552 * Krunching Method::
14553 * Examples of gnatkr Usage::
14554 @end menu
14555
14556 @node About gnatkr
14557 @section About @code{gnatkr}
14558
14559 @noindent
14560 The default file naming rule in GNAT
14561 is that the file name must be derived from
14562 the unit name. The exact default rule is as follows:
14563 @itemize @bullet
14564 @item
14565 Take the unit name and replace all dots by hyphens.
14566 @item
14567 If such a replacement occurs in the
14568 second character position of a name, and the first character is
14569 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14570 then replace the dot by the character
14571 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14572 instead of a minus.
14573 @end itemize
14574 The reason for this exception is to avoid clashes
14575 with the standard names for children of System, Ada, Interfaces,
14576 and GNAT, which use the prefixes
14577 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14578 respectively.
14579
14580 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14581 switch of the compiler activates a ``krunching''
14582 circuit that limits file names to nn characters (where nn is a decimal
14583 integer). For example, using OpenVMS,
14584 where the maximum file name length is
14585 39, the value of nn is usually set to 39, but if you want to generate
14586 a set of files that would be usable if ported to a system with some
14587 different maximum file length, then a different value can be specified.
14588 The default value of 39 for OpenVMS need not be specified.
14589
14590 The @code{gnatkr} utility can be used to determine the krunched name for
14591 a given file, when krunched to a specified maximum length.
14592
14593 @node Using gnatkr
14594 @section Using @code{gnatkr}
14595
14596 @noindent
14597 The @code{gnatkr} command has the form
14598
14599 @ifclear vms
14600 @smallexample
14601 @c $ gnatkr @var{name} @ovar{length}
14602 @c Expanding @ovar macro inline (explanation in macro def comments)
14603 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14604 @end smallexample
14605 @end ifclear
14606
14607 @ifset vms
14608 @smallexample
14609 $ gnatkr @var{name} /COUNT=nn
14610 @end smallexample
14611 @end ifset
14612
14613 @noindent
14614 @var{name} is the uncrunched file name, derived from the name of the unit
14615 in the standard manner described in the previous section (i.e., in particular
14616 all dots are replaced by hyphens). The file name may or may not have an
14617 extension (defined as a suffix of the form period followed by arbitrary
14618 characters other than period). If an extension is present then it will
14619 be preserved in the output. For example, when krunching @file{hellofile.ads}
14620 to eight characters, the result will be hellofil.ads.
14621
14622 Note: for compatibility with previous versions of @code{gnatkr} dots may
14623 appear in the name instead of hyphens, but the last dot will always be
14624 taken as the start of an extension. So if @code{gnatkr} is given an argument
14625 such as @file{Hello.World.adb} it will be treated exactly as if the first
14626 period had been a hyphen, and for example krunching to eight characters
14627 gives the result @file{hellworl.adb}.
14628
14629 Note that the result is always all lower case (except on OpenVMS where it is
14630 all upper case). Characters of the other case are folded as required.
14631
14632 @var{length} represents the length of the krunched name. The default
14633 when no argument is given is ^8^39^ characters. A length of zero stands for
14634 unlimited, in other words do not chop except for system files where the
14635 implied crunching length is always eight characters.
14636
14637 @noindent
14638 The output is the krunched name. The output has an extension only if the
14639 original argument was a file name with an extension.
14640
14641 @node Krunching Method
14642 @section Krunching Method
14643
14644 @noindent
14645 The initial file name is determined by the name of the unit that the file
14646 contains. The name is formed by taking the full expanded name of the
14647 unit and replacing the separating dots with hyphens and
14648 using ^lowercase^uppercase^
14649 for all letters, except that a hyphen in the second character position is
14650 replaced by a ^tilde^dollar sign^ if the first character is
14651 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14652 The extension is @code{.ads} for a
14653 spec and @code{.adb} for a body.
14654 Krunching does not affect the extension, but the file name is shortened to
14655 the specified length by following these rules:
14656
14657 @itemize @bullet
14658 @item
14659 The name is divided into segments separated by hyphens, tildes or
14660 underscores and all hyphens, tildes, and underscores are
14661 eliminated. If this leaves the name short enough, we are done.
14662
14663 @item
14664 If the name is too long, the longest segment is located (left-most
14665 if there are two of equal length), and shortened by dropping
14666 its last character. This is repeated until the name is short enough.
14667
14668 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14669 to fit the name into 8 characters as required by some operating systems.
14670
14671 @smallexample
14672 our-strings-wide_fixed 22
14673 our strings wide fixed 19
14674 our string  wide fixed 18
14675 our strin   wide fixed 17
14676 our stri    wide fixed 16
14677 our stri    wide fixe  15
14678 our str     wide fixe  14
14679 our str     wid  fixe  13
14680 our str     wid  fix   12
14681 ou  str     wid  fix   11
14682 ou  st      wid  fix   10
14683 ou  st      wi   fix   9
14684 ou  st      wi   fi    8
14685 Final file name: oustwifi.adb
14686 @end smallexample
14687
14688 @item
14689 The file names for all predefined units are always krunched to eight
14690 characters. The krunching of these predefined units uses the following
14691 special prefix replacements:
14692
14693 @table @file
14694 @item ada-
14695 replaced by @file{^a^A^-}
14696
14697 @item gnat-
14698 replaced by @file{^g^G^-}
14699
14700 @item interfaces-
14701 replaced by @file{^i^I^-}
14702
14703 @item system-
14704 replaced by @file{^s^S^-}
14705 @end table
14706
14707 These system files have a hyphen in the second character position. That
14708 is why normal user files replace such a character with a
14709 ^tilde^dollar sign^, to
14710 avoid confusion with system file names.
14711
14712 As an example of this special rule, consider
14713 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14714
14715 @smallexample
14716 ada-strings-wide_fixed 22
14717 a-  strings wide fixed 18
14718 a-  string  wide fixed 17
14719 a-  strin   wide fixed 16
14720 a-  stri    wide fixed 15
14721 a-  stri    wide fixe  14
14722 a-  str     wide fixe  13
14723 a-  str     wid  fixe  12
14724 a-  str     wid  fix   11
14725 a-  st      wid  fix   10
14726 a-  st      wi   fix   9
14727 a-  st      wi   fi    8
14728 Final file name: a-stwifi.adb
14729 @end smallexample
14730 @end itemize
14731
14732 Of course no file shortening algorithm can guarantee uniqueness over all
14733 possible unit names, and if file name krunching is used then it is your
14734 responsibility to ensure that no name clashes occur. The utility
14735 program @code{gnatkr} is supplied for conveniently determining the
14736 krunched name of a file.
14737
14738 @node Examples of gnatkr Usage
14739 @section Examples of @code{gnatkr} Usage
14740
14741 @smallexample
14742 @iftex
14743 @leftskip=0cm
14744 @end iftex
14745 @ifclear vms
14746 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14747 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14748 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14749 $ gnatkr grandparent-parent-child     --> grparchi
14750 @end ifclear
14751 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14752 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14753 @end smallexample
14754
14755 @node Preprocessing Using gnatprep
14756 @chapter Preprocessing Using @code{gnatprep}
14757 @findex gnatprep
14758
14759 @noindent
14760 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14761 preprocessing.
14762 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14763 special GNAT features.
14764 For further discussion of conditional compilation in general, see
14765 @ref{Conditional Compilation}.
14766
14767 @menu
14768 * Preprocessing Symbols::
14769 * Using gnatprep::
14770 * Switches for gnatprep::
14771 * Form of Definitions File::
14772 * Form of Input Text for gnatprep::
14773 @end menu
14774
14775 @node Preprocessing Symbols
14776 @section Preprocessing Symbols
14777
14778 @noindent
14779 Preprocessing symbols are defined in definition files and referred to in
14780 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14781 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14782 all characters need to be in the ASCII set (no accented letters).
14783
14784 @node Using gnatprep
14785 @section Using @code{gnatprep}
14786
14787 @noindent
14788 To call @code{gnatprep} use
14789
14790 @smallexample
14791 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14792 @c Expanding @ovar macro inline (explanation in macro def comments)
14793 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14794 @end smallexample
14795
14796 @noindent
14797 where
14798 @table @var
14799 @item switches
14800 is an optional sequence of switches as described in the next section.
14801
14802 @item infile
14803 is the full name of the input file, which is an Ada source
14804 file containing preprocessor directives.
14805
14806 @item outfile
14807 is the full name of the output file, which is an Ada source
14808 in standard Ada form. When used with GNAT, this file name will
14809 normally have an ads or adb suffix.
14810
14811 @item deffile
14812 is the full name of a text file containing definitions of
14813 preprocessing symbols to be referenced by the preprocessor. This argument is
14814 optional, and can be replaced by the use of the @option{-D} switch.
14815
14816 @end table
14817
14818 @node Switches for gnatprep
14819 @section Switches for @code{gnatprep}
14820
14821 @table @option
14822 @c !sort!
14823
14824 @item ^-b^/BLANK_LINES^
14825 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14826 Causes both preprocessor lines and the lines deleted by
14827 preprocessing to be replaced by blank lines in the output source file,
14828 preserving line numbers in the output file.
14829
14830 @item ^-c^/COMMENTS^
14831 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14832 Causes both preprocessor lines and the lines deleted
14833 by preprocessing to be retained in the output source as comments marked
14834 with the special string @code{"--! "}. This option will result in line numbers
14835 being preserved in the output file.
14836
14837 @item ^-C^/REPLACE_IN_COMMENTS^
14838 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14839 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14840 If this option is specified, then comments are scanned and any $symbol
14841 substitutions performed as in program text. This is particularly useful
14842 when structured comments are used (e.g., when writing programs in the
14843 SPARK dialect of Ada). Note that this switch is not available when
14844 doing integrated preprocessing (it would be useless in this context
14845 since comments are ignored by the compiler in any case).
14846
14847 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14848 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14849 Defines a new preprocessing symbol, associated with value. If no value is given
14850 on the command line, then symbol is considered to be @code{True}. This switch
14851 can be used in place of a definition file.
14852
14853 @ifset vms
14854 @item /REMOVE
14855 @cindex @option{/REMOVE} (@command{gnatprep})
14856 This is the default setting which causes lines deleted by preprocessing
14857 to be entirely removed from the output file.
14858 @end ifset
14859
14860 @item ^-r^/REFERENCE^
14861 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14862 Causes a @code{Source_Reference} pragma to be generated that
14863 references the original input file, so that error messages will use
14864 the file name of this original file. The use of this switch implies
14865 that preprocessor lines are not to be removed from the file, so its
14866 use will force @option{^-b^/BLANK_LINES^} mode if
14867 @option{^-c^/COMMENTS^}
14868 has not been specified explicitly.
14869
14870 Note that if the file to be preprocessed contains multiple units, then
14871 it will be necessary to @code{gnatchop} the output file from
14872 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14873 in the preprocessed file, it will be respected by
14874 @code{gnatchop ^-r^/REFERENCE^}
14875 so that the final chopped files will correctly refer to the original
14876 input source file for @code{gnatprep}.
14877
14878 @item ^-s^/SYMBOLS^
14879 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14880 Causes a sorted list of symbol names and values to be
14881 listed on the standard output file.
14882
14883 @item ^-u^/UNDEFINED^
14884 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14885 Causes undefined symbols to be treated as having the value FALSE in the context
14886 of a preprocessor test. In the absence of this option, an undefined symbol in
14887 a @code{#if} or @code{#elsif} test will be treated as an error.
14888
14889 @end table
14890
14891 @ifclear vms
14892 @noindent
14893 Note: if neither @option{-b} nor @option{-c} is present,
14894 then preprocessor lines and
14895 deleted lines are completely removed from the output, unless -r is
14896 specified, in which case -b is assumed.
14897 @end ifclear
14898
14899 @node Form of Definitions File
14900 @section Form of Definitions File
14901
14902 @noindent
14903 The definitions file contains lines of the form
14904
14905 @smallexample
14906 symbol := value
14907 @end smallexample
14908
14909 @noindent
14910 where symbol is a preprocessing symbol, and value is one of the following:
14911
14912 @itemize @bullet
14913 @item
14914 Empty, corresponding to a null substitution
14915 @item
14916 A string literal using normal Ada syntax
14917 @item
14918 Any sequence of characters from the set
14919 (letters, digits, period, underline).
14920 @end itemize
14921
14922 @noindent
14923 Comment lines may also appear in the definitions file, starting with
14924 the usual @code{--},
14925 and comments may be added to the definitions lines.
14926
14927 @node Form of Input Text for gnatprep
14928 @section Form of Input Text for @code{gnatprep}
14929
14930 @noindent
14931 The input text may contain preprocessor conditional inclusion lines,
14932 as well as general symbol substitution sequences.
14933
14934 The preprocessor conditional inclusion commands have the form
14935
14936 @smallexample
14937 @group
14938 @cartouche
14939 #if @i{expression} @r{[}then@r{]}
14940    lines
14941 #elsif @i{expression} @r{[}then@r{]}
14942    lines
14943 #elsif @i{expression} @r{[}then@r{]}
14944    lines
14945 @dots{}
14946 #else
14947    lines
14948 #end if;
14949 @end cartouche
14950 @end group
14951 @end smallexample
14952
14953 @noindent
14954 In this example, @i{expression} is defined by the following grammar:
14955 @smallexample
14956 @i{expression} ::=  <symbol>
14957 @i{expression} ::=  <symbol> = "<value>"
14958 @i{expression} ::=  <symbol> = <symbol>
14959 @i{expression} ::=  <symbol> 'Defined
14960 @i{expression} ::=  not @i{expression}
14961 @i{expression} ::=  @i{expression} and @i{expression}
14962 @i{expression} ::=  @i{expression} or @i{expression}
14963 @i{expression} ::=  @i{expression} and then @i{expression}
14964 @i{expression} ::=  @i{expression} or else @i{expression}
14965 @i{expression} ::=  ( @i{expression} )
14966 @end smallexample
14967
14968 The following restriction exists: it is not allowed to have "and" or "or"
14969 following "not" in the same expression without parentheses. For example, this
14970 is not allowed:
14971
14972 @smallexample
14973    not X or Y
14974 @end smallexample
14975
14976 This should be one of the following:
14977
14978 @smallexample
14979    (not X) or Y
14980    not (X or Y)
14981 @end smallexample
14982
14983 @noindent
14984 For the first test (@i{expression} ::= <symbol>) the symbol must have
14985 either the value true or false, that is to say the right-hand of the
14986 symbol definition must be one of the (case-insensitive) literals
14987 @code{True} or @code{False}. If the value is true, then the
14988 corresponding lines are included, and if the value is false, they are
14989 excluded.
14990
14991 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14992 the symbol has been defined in the definition file or by a @option{-D}
14993 switch on the command line. Otherwise, the test is false.
14994
14995 The equality tests are case insensitive, as are all the preprocessor lines.
14996
14997 If the symbol referenced is not defined in the symbol definitions file,
14998 then the effect depends on whether or not switch @option{-u}
14999 is specified. If so, then the symbol is treated as if it had the value
15000 false and the test fails. If this switch is not specified, then
15001 it is an error to reference an undefined symbol. It is also an error to
15002 reference a symbol that is defined with a value other than @code{True}
15003 or @code{False}.
15004
15005 The use of the @code{not} operator inverts the sense of this logical test.
15006 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15007 operators, without parentheses. For example, "if not X or Y then" is not
15008 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15009
15010 The @code{then} keyword is optional as shown
15011
15012 The @code{#} must be the first non-blank character on a line, but
15013 otherwise the format is free form. Spaces or tabs may appear between
15014 the @code{#} and the keyword. The keywords and the symbols are case
15015 insensitive as in normal Ada code. Comments may be used on a
15016 preprocessor line, but other than that, no other tokens may appear on a
15017 preprocessor line. Any number of @code{elsif} clauses can be present,
15018 including none at all. The @code{else} is optional, as in Ada.
15019
15020 The @code{#} marking the start of a preprocessor line must be the first
15021 non-blank character on the line, i.e., it must be preceded only by
15022 spaces or horizontal tabs.
15023
15024 Symbol substitution outside of preprocessor lines is obtained by using
15025 the sequence
15026
15027 @smallexample
15028 $symbol
15029 @end smallexample
15030
15031 @noindent
15032 anywhere within a source line, except in a comment or within a
15033 string literal. The identifier
15034 following the @code{$} must match one of the symbols defined in the symbol
15035 definition file, and the result is to substitute the value of the
15036 symbol in place of @code{$symbol} in the output file.
15037
15038 Note that although the substitution of strings within a string literal
15039 is not possible, it is possible to have a symbol whose defined value is
15040 a string literal. So instead of setting XYZ to @code{hello} and writing:
15041
15042 @smallexample
15043 Header : String := "$XYZ";
15044 @end smallexample
15045
15046 @noindent
15047 you should set XYZ to @code{"hello"} and write:
15048
15049 @smallexample
15050 Header : String := $XYZ;
15051 @end smallexample
15052
15053 @noindent
15054 and then the substitution will occur as desired.
15055
15056 @node The GNAT Library Browser gnatls
15057 @chapter The GNAT Library Browser @code{gnatls}
15058 @findex gnatls
15059 @cindex Library browser
15060
15061 @noindent
15062 @code{gnatls} is a tool that outputs information about compiled
15063 units. It gives the relationship between objects, unit names and source
15064 files. It can also be used to check the source dependencies of a unit
15065 as well as various characteristics.
15066
15067 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15068 driver (see @ref{The GNAT Driver and Project Files}).
15069
15070 @menu
15071 * Running gnatls::
15072 * Switches for gnatls::
15073 * Examples of gnatls Usage::
15074 @end menu
15075
15076 @node Running gnatls
15077 @section Running @code{gnatls}
15078
15079 @noindent
15080 The @code{gnatls} command has the form
15081
15082 @smallexample
15083 $ gnatls switches @var{object_or_ali_file}
15084 @end smallexample
15085
15086 @noindent
15087 The main argument is the list of object or @file{ali} files
15088 (@pxref{The Ada Library Information Files})
15089 for which information is requested.
15090
15091 In normal mode, without additional option, @code{gnatls} produces a
15092 four-column listing. Each line represents information for a specific
15093 object. The first column gives the full path of the object, the second
15094 column gives the name of the principal unit in this object, the third
15095 column gives the status of the source and the fourth column gives the
15096 full path of the source representing this unit.
15097 Here is a simple example of use:
15098
15099 @smallexample
15100 $ gnatls *.o
15101 ^./^[]^demo1.o            demo1            DIF demo1.adb
15102 ^./^[]^demo2.o            demo2             OK demo2.adb
15103 ^./^[]^hello.o            h1                OK hello.adb
15104 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15105 ^./^[]^instr.o            instr             OK instr.adb
15106 ^./^[]^tef.o              tef              DIF tef.adb
15107 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15108 ^./^[]^tgef.o             tgef             DIF tgef.adb
15109 @end smallexample
15110
15111 @noindent
15112 The first line can be interpreted as follows: the main unit which is
15113 contained in
15114 object file @file{demo1.o} is demo1, whose main source is in
15115 @file{demo1.adb}. Furthermore, the version of the source used for the
15116 compilation of demo1 has been modified (DIF). Each source file has a status
15117 qualifier which can be:
15118
15119 @table @code
15120 @item OK (unchanged)
15121 The version of the source file used for the compilation of the
15122 specified unit corresponds exactly to the actual source file.
15123
15124 @item MOK (slightly modified)
15125 The version of the source file used for the compilation of the
15126 specified unit differs from the actual source file but not enough to
15127 require recompilation. If you use gnatmake with the qualifier
15128 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15129 MOK will not be recompiled.
15130
15131 @item DIF (modified)
15132 No version of the source found on the path corresponds to the source
15133 used to build this object.
15134
15135 @item ??? (file not found)
15136 No source file was found for this unit.
15137
15138 @item HID (hidden,  unchanged version not first on PATH)
15139 The version of the source that corresponds exactly to the source used
15140 for compilation has been found on the path but it is hidden by another
15141 version of the same source that has been modified.
15142
15143 @end table
15144
15145 @node Switches for gnatls
15146 @section Switches for @code{gnatls}
15147
15148 @noindent
15149 @code{gnatls} recognizes the following switches:
15150
15151 @table @option
15152 @c !sort!
15153 @cindex @option{--version} @command{gnatls}
15154 Display Copyright and version, then exit disregarding all other options.
15155
15156 @item --help
15157 @cindex @option{--help} @command{gnatls}
15158 If @option{--version} was not used, display usage, then exit disregarding
15159 all other options.
15160
15161 @item ^-a^/ALL_UNITS^
15162 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15163 Consider all units, including those of the predefined Ada library.
15164 Especially useful with @option{^-d^/DEPENDENCIES^}.
15165
15166 @item ^-d^/DEPENDENCIES^
15167 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15168 List sources from which specified units depend on.
15169
15170 @item ^-h^/OUTPUT=OPTIONS^
15171 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15172 Output the list of options.
15173
15174 @item ^-o^/OUTPUT=OBJECTS^
15175 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15176 Only output information about object files.
15177
15178 @item ^-s^/OUTPUT=SOURCES^
15179 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15180 Only output information about source files.
15181
15182 @item ^-u^/OUTPUT=UNITS^
15183 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15184 Only output information about compilation units.
15185
15186 @item ^-files^/FILES^=@var{file}
15187 @cindex @option{^-files^/FILES^} (@code{gnatls})
15188 Take as arguments the files listed in text file @var{file}.
15189 Text file @var{file} may contain empty lines that are ignored.
15190 Each nonempty line should contain the name of an existing file.
15191 Several such switches may be specified simultaneously.
15192
15193 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15194 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15195 @itemx ^-I^/SEARCH=^@var{dir}
15196 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15197 @itemx -nostdinc
15198 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15199 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15200 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15201 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15202 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15203 flags (@pxref{Switches for gnatmake}).
15204
15205 @item --RTS=@var{rts-path}
15206 @cindex @option{--RTS} (@code{gnatls})
15207 Specifies the default location of the runtime library. Same meaning as the
15208 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15209
15210 @item ^-v^/OUTPUT=VERBOSE^
15211 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15212 Verbose mode. Output the complete source, object and project paths. Do not use
15213 the default column layout but instead use long format giving as much as
15214 information possible on each requested units, including special
15215 characteristics such as:
15216
15217 @table @code
15218 @item  Preelaborable
15219 The unit is preelaborable in the Ada sense.
15220
15221 @item No_Elab_Code
15222 No elaboration code has been produced by the compiler for this unit.
15223
15224 @item Pure
15225 The unit is pure in the Ada sense.
15226
15227 @item Elaborate_Body
15228 The unit contains a pragma Elaborate_Body.
15229
15230 @item Remote_Types
15231 The unit contains a pragma Remote_Types.
15232
15233 @item Shared_Passive
15234 The unit contains a pragma Shared_Passive.
15235
15236 @item Predefined
15237 This unit is part of the predefined environment and cannot be modified
15238 by the user.
15239
15240 @item Remote_Call_Interface
15241 The unit contains a pragma Remote_Call_Interface.
15242
15243 @end table
15244
15245 @end table
15246
15247 @node Examples of gnatls Usage
15248 @section Example of @code{gnatls} Usage
15249 @ifclear vms
15250
15251 @noindent
15252 Example of using the verbose switch. Note how the source and
15253 object paths are affected by the -I switch.
15254
15255 @smallexample
15256 $ gnatls -v -I.. demo1.o
15257
15258 GNATLS 5.03w (20041123-34)
15259 Copyright 1997-2004 Free Software Foundation, Inc.
15260
15261 Source Search Path:
15262    <Current_Directory>
15263    ../
15264    /home/comar/local/adainclude/
15265
15266 Object Search Path:
15267    <Current_Directory>
15268    ../
15269    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15270
15271 Project Search Path:
15272    <Current_Directory>
15273    /home/comar/local/lib/gnat/
15274
15275 ./demo1.o
15276    Unit =>
15277      Name   => demo1
15278      Kind   => subprogram body
15279      Flags  => No_Elab_Code
15280      Source => demo1.adb    modified
15281 @end smallexample
15282
15283 @noindent
15284 The following is an example of use of the dependency list.
15285 Note the use of the -s switch
15286 which gives a straight list of source files. This can be useful for
15287 building specialized scripts.
15288
15289 @smallexample
15290 $ gnatls -d demo2.o
15291 ./demo2.o   demo2        OK demo2.adb
15292                          OK gen_list.ads
15293                          OK gen_list.adb
15294                          OK instr.ads
15295                          OK instr-child.ads
15296
15297 $ gnatls -d -s -a demo1.o
15298 demo1.adb
15299 /home/comar/local/adainclude/ada.ads
15300 /home/comar/local/adainclude/a-finali.ads
15301 /home/comar/local/adainclude/a-filico.ads
15302 /home/comar/local/adainclude/a-stream.ads
15303 /home/comar/local/adainclude/a-tags.ads
15304 gen_list.ads
15305 gen_list.adb
15306 /home/comar/local/adainclude/gnat.ads
15307 /home/comar/local/adainclude/g-io.ads
15308 instr.ads
15309 /home/comar/local/adainclude/system.ads
15310 /home/comar/local/adainclude/s-exctab.ads
15311 /home/comar/local/adainclude/s-finimp.ads
15312 /home/comar/local/adainclude/s-finroo.ads
15313 /home/comar/local/adainclude/s-secsta.ads
15314 /home/comar/local/adainclude/s-stalib.ads
15315 /home/comar/local/adainclude/s-stoele.ads
15316 /home/comar/local/adainclude/s-stratt.ads
15317 /home/comar/local/adainclude/s-tasoli.ads
15318 /home/comar/local/adainclude/s-unstyp.ads
15319 /home/comar/local/adainclude/unchconv.ads
15320 @end smallexample
15321 @end ifclear
15322
15323 @ifset vms
15324 @smallexample
15325 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15326
15327 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15328 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15329 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15330 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15331 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15332 demo1.adb
15333 gen_list.ads
15334 gen_list.adb
15335 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15336 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15337 instr.ads
15338 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15339 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15340 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15341 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15342 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15343 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15344 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15345 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15346 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15347 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15348 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15349 @end smallexample
15350 @end ifset
15351
15352 @node Cleaning Up Using gnatclean
15353 @chapter Cleaning Up Using @code{gnatclean}
15354 @findex gnatclean
15355 @cindex Cleaning tool
15356
15357 @noindent
15358 @code{gnatclean} is a tool that allows the deletion of files produced by the
15359 compiler, binder and linker, including ALI files, object files, tree files,
15360 expanded source files, library files, interface copy source files, binder
15361 generated files and executable files.
15362
15363 @menu
15364 * Running gnatclean::
15365 * Switches for gnatclean::
15366 @c * Examples of gnatclean Usage::
15367 @end menu
15368
15369 @node Running gnatclean
15370 @section Running @code{gnatclean}
15371
15372 @noindent
15373 The @code{gnatclean} command has the form:
15374
15375 @smallexample
15376 $ gnatclean switches @var{names}
15377 @end smallexample
15378
15379 @noindent
15380 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15381 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15382 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15383
15384 @noindent
15385 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15386 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15387 the linker. In informative-only mode, specified by switch
15388 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15389 normal mode is listed, but no file is actually deleted.
15390
15391 @node Switches for gnatclean
15392 @section Switches for @code{gnatclean}
15393
15394 @noindent
15395 @code{gnatclean} recognizes the following switches:
15396
15397 @table @option
15398 @c !sort!
15399 @cindex @option{--version} @command{gnatclean}
15400 Display Copyright and version, then exit disregarding all other options.
15401
15402 @item --help
15403 @cindex @option{--help} @command{gnatclean}
15404 If @option{--version} was not used, display usage, then exit disregarding
15405 all other options.
15406
15407 @item ^--subdirs^/SUBDIRS^=subdir
15408 Actual object directory of each project file is the subdirectory subdir of the
15409 object directory specified or defauted in the project file.
15410
15411 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15412 By default, shared library projects are not allowed to import static library
15413 projects. When this switch is used on the command line, this restriction is
15414 relaxed.
15415
15416 @item ^-c^/COMPILER_FILES_ONLY^
15417 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15418 Only attempt to delete the files produced by the compiler, not those produced
15419 by the binder or the linker. The files that are not to be deleted are library
15420 files, interface copy files, binder generated files and executable files.
15421
15422 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15423 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15424 Indicate that ALI and object files should normally be found in directory
15425 @var{dir}.
15426
15427 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15428 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15429 When using project files, if some errors or warnings are detected during
15430 parsing and verbose mode is not in effect (no use of switch
15431 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15432 file, rather than its simple file name.
15433
15434 @item ^-h^/HELP^
15435 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15436 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15437
15438 @item ^-n^/NODELETE^
15439 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15440 Informative-only mode. Do not delete any files. Output the list of the files
15441 that would have been deleted if this switch was not specified.
15442
15443 @item ^-P^/PROJECT_FILE=^@var{project}
15444 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15445 Use project file @var{project}. Only one such switch can be used.
15446 When cleaning a project file, the files produced by the compilation of the
15447 immediate sources or inherited sources of the project files are to be
15448 deleted. This is not depending on the presence or not of executable names
15449 on the command line.
15450
15451 @item ^-q^/QUIET^
15452 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15453 Quiet output. If there are no errors, do not output anything, except in
15454 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15455 (switch ^-n^/NODELETE^).
15456
15457 @item ^-r^/RECURSIVE^
15458 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15459 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15460 clean all imported and extended project files, recursively. If this switch
15461 is not specified, only the files related to the main project file are to be
15462 deleted. This switch has no effect if no project file is specified.
15463
15464 @item ^-v^/VERBOSE^
15465 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15466 Verbose mode.
15467
15468 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15469 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15470 Indicates the verbosity of the parsing of GNAT project files.
15471 @xref{Switches Related to Project Files}.
15472
15473 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15474 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15475 Indicates that external variable @var{name} has the value @var{value}.
15476 The Project Manager will use this value for occurrences of
15477 @code{external(name)} when parsing the project file.
15478 @xref{Switches Related to Project Files}.
15479
15480 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15481 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15482 When searching for ALI and object files, look in directory
15483 @var{dir}.
15484
15485 @item ^-I^/SEARCH=^@var{dir}
15486 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15487 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15488
15489 @item ^-I-^/NOCURRENT_DIRECTORY^
15490 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15491 @cindex Source files, suppressing search
15492 Do not look for ALI or object files in the directory
15493 where @code{gnatclean} was invoked.
15494
15495 @end table
15496
15497 @c @node Examples of gnatclean Usage
15498 @c @section Examples of @code{gnatclean} Usage
15499
15500 @ifclear vms
15501 @node GNAT and Libraries
15502 @chapter GNAT and Libraries
15503 @cindex Library, building, installing, using
15504
15505 @noindent
15506 This chapter describes how to build and use libraries with GNAT, and also shows
15507 how to recompile the GNAT run-time library. You should be familiar with the
15508 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15509 chapter.
15510
15511 @menu
15512 * Introduction to Libraries in GNAT::
15513 * General Ada Libraries::
15514 * Stand-alone Ada Libraries::
15515 * Rebuilding the GNAT Run-Time Library::
15516 @end menu
15517
15518 @node Introduction to Libraries in GNAT
15519 @section Introduction to Libraries in GNAT
15520
15521 @noindent
15522 A library is, conceptually, a collection of objects which does not have its
15523 own main thread of execution, but rather provides certain services to the
15524 applications that use it. A library can be either statically linked with the
15525 application, in which case its code is directly included in the application,
15526 or, on platforms that support it, be dynamically linked, in which case
15527 its code is shared by all applications making use of this library.
15528
15529 GNAT supports both types of libraries.
15530 In the static case, the compiled code can be provided in different ways. The
15531 simplest approach is to provide directly the set of objects resulting from
15532 compilation of the library source files. Alternatively, you can group the
15533 objects into an archive using whatever commands are provided by the operating
15534 system. For the latter case, the objects are grouped into a shared library.
15535
15536 In the GNAT environment, a library has three types of components:
15537 @itemize @bullet
15538 @item
15539 Source files.
15540 @item
15541 @file{ALI} files.
15542 @xref{The Ada Library Information Files}.
15543 @item
15544 Object files, an archive or a shared library.
15545 @end itemize
15546
15547 @noindent
15548 A GNAT library may expose all its source files, which is useful for
15549 documentation purposes. Alternatively, it may expose only the units needed by
15550 an external user to make use of the library. That is to say, the specs
15551 reflecting the library services along with all the units needed to compile
15552 those specs, which can include generic bodies or any body implementing an
15553 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15554 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15555
15556 All compilation units comprising an application, including those in a library,
15557 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15558 computes the elaboration order from the @file{ALI} files and this is why they
15559 constitute a mandatory part of GNAT libraries.
15560 @emph{Stand-alone libraries} are the exception to this rule because a specific
15561 library elaboration routine is produced independently of the application(s)
15562 using the library.
15563
15564 @node General Ada Libraries
15565 @section General Ada Libraries
15566
15567 @menu
15568 * Building a library::
15569 * Installing a library::
15570 * Using a library::
15571 @end menu
15572
15573 @node Building a library
15574 @subsection Building a library
15575
15576 @noindent
15577 The easiest way to build a library is to use the Project Manager,
15578 which supports a special type of project called a @emph{Library Project}
15579 (@pxref{Library Projects}).
15580
15581 A project is considered a library project, when two project-level attributes
15582 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15583 control different aspects of library configuration, additional optional
15584 project-level attributes can be specified:
15585 @table @code
15586 @item Library_Kind
15587 This attribute controls whether the library is to be static or dynamic
15588
15589 @item Library_Version
15590 This attribute specifies the library version; this value is used
15591 during dynamic linking of shared libraries to determine if the currently
15592 installed versions of the binaries are compatible.
15593
15594 @item Library_Options
15595 @item Library_GCC
15596 These attributes specify additional low-level options to be used during
15597 library generation, and redefine the actual application used to generate
15598 library.
15599 @end table
15600
15601 @noindent
15602 The GNAT Project Manager takes full care of the library maintenance task,
15603 including recompilation of the source files for which objects do not exist
15604 or are not up to date, assembly of the library archive, and installation of
15605 the library (i.e., copying associated source, object and @file{ALI} files
15606 to the specified location).
15607
15608 Here is a simple library project file:
15609 @smallexample @c ada
15610 project My_Lib is
15611    for Source_Dirs use ("src1", "src2");
15612    for Object_Dir use "obj";
15613    for Library_Name use "mylib";
15614    for Library_Dir use "lib";
15615    for Library_Kind use "dynamic";
15616 end My_lib;
15617 @end smallexample
15618
15619 @noindent
15620 and the compilation command to build and install the library:
15621
15622 @smallexample @c ada
15623   $ gnatmake -Pmy_lib
15624 @end smallexample
15625
15626 @noindent
15627 It is not entirely trivial to perform manually all the steps required to
15628 produce a library. We recommend that you use the GNAT Project Manager
15629 for this task. In special cases where this is not desired, the necessary
15630 steps are discussed below.
15631
15632 There are various possibilities for compiling the units that make up the
15633 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15634 with a conventional script. For simple libraries, it is also possible to create
15635 a dummy main program which depends upon all the packages that comprise the
15636 interface of the library. This dummy main program can then be given to
15637 @command{gnatmake}, which will ensure that all necessary objects are built.
15638
15639 After this task is accomplished, you should follow the standard procedure
15640 of the underlying operating system to produce the static or shared library.
15641
15642 Here is an example of such a dummy program:
15643 @smallexample @c ada
15644 @group
15645 with My_Lib.Service1;
15646 with My_Lib.Service2;
15647 with My_Lib.Service3;
15648 procedure My_Lib_Dummy is
15649 begin
15650    null;
15651 end;
15652 @end group
15653 @end smallexample
15654
15655 @noindent
15656 Here are the generic commands that will build an archive or a shared library.
15657
15658 @smallexample
15659 # compiling the library
15660 $ gnatmake -c my_lib_dummy.adb
15661
15662 # we don't need the dummy object itself
15663 $ rm my_lib_dummy.o my_lib_dummy.ali
15664
15665 # create an archive with the remaining objects
15666 $ ar rc libmy_lib.a *.o
15667 # some systems may require "ranlib" to be run as well
15668
15669 # or create a shared library
15670 $ gcc -shared -o libmy_lib.so *.o
15671 # some systems may require the code to have been compiled with -fPIC
15672
15673 # remove the object files that are now in the library
15674 $ rm *.o
15675
15676 # Make the ALI files read-only so that gnatmake will not try to
15677 # regenerate the objects that are in the library
15678 $ chmod -w *.ali
15679 @end smallexample
15680
15681 @noindent
15682 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15683 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15684 be accessed by the directive @option{-l@var{xxx}} at link time.
15685
15686 @node Installing a library
15687 @subsection Installing a library
15688 @cindex @code{ADA_PROJECT_PATH}
15689 @cindex @code{GPR_PROJECT_PATH}
15690
15691 @noindent
15692 If you use project files, library installation is part of the library build
15693 process (@pxref{Installing a library with project files}).
15694
15695 When project files are not an option, it is also possible, but not recommended,
15696 to install the library so that the sources needed to use the library are on the
15697 Ada source path and the ALI files & libraries be on the Ada Object path (see
15698 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15699 administrator can place general-purpose libraries in the default compiler
15700 paths, by specifying the libraries' location in the configuration files
15701 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15702 must be located in the GNAT installation tree at the same place as the gcc spec
15703 file. The location of the gcc spec file can be determined as follows:
15704 @smallexample
15705 $ gcc -v
15706 @end smallexample
15707
15708 @noindent
15709 The configuration files mentioned above have a simple format: each line
15710 must contain one unique directory name.
15711 Those names are added to the corresponding path
15712 in their order of appearance in the file. The names can be either absolute
15713 or relative; in the latter case, they are relative to where theses files
15714 are located.
15715
15716 The files @file{ada_source_path} and @file{ada_object_path} might not be
15717 present in a
15718 GNAT installation, in which case, GNAT will look for its run-time library in
15719 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15720 objects and @file{ALI} files). When the files exist, the compiler does not
15721 look in @file{adainclude} and @file{adalib}, and thus the
15722 @file{ada_source_path} file
15723 must contain the location for the GNAT run-time sources (which can simply
15724 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15725 contain the location for the GNAT run-time objects (which can simply
15726 be @file{adalib}).
15727
15728 You can also specify a new default path to the run-time library at compilation
15729 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15730 the run-time library you want your program to be compiled with. This switch is
15731 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15732 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15733
15734 It is possible to install a library before or after the standard GNAT
15735 library, by reordering the lines in the configuration files. In general, a
15736 library must be installed before the GNAT library if it redefines
15737 any part of it.
15738
15739 @node Using a library
15740 @subsection Using a library
15741
15742 @noindent Once again, the project facility greatly simplifies the use of
15743 libraries. In this context, using a library is just a matter of adding a
15744 @code{with} clause in the user project. For instance, to make use of the
15745 library @code{My_Lib} shown in examples in earlier sections, you can
15746 write:
15747
15748 @smallexample @c projectfile
15749 with "my_lib";
15750 project My_Proj is
15751   @dots{}
15752 end My_Proj;
15753 @end smallexample
15754
15755 Even if you have a third-party, non-Ada library, you can still use GNAT's
15756 Project Manager facility to provide a wrapper for it. For example, the
15757 following project, when @code{with}ed by your main project, will link with the
15758 third-party library @file{liba.a}:
15759
15760 @smallexample @c projectfile
15761 @group
15762 project Liba is
15763    for Externally_Built use "true";
15764    for Source_Files use ();
15765    for Library_Dir use "lib";
15766    for Library_Name use "a";
15767    for Library_Kind use "static";
15768 end Liba;
15769 @end group
15770 @end smallexample
15771 This is an alternative to the use of @code{pragma Linker_Options}. It is
15772 especially interesting in the context of systems with several interdependent
15773 static libraries where finding a proper linker order is not easy and best be
15774 left to the tools having visibility over project dependence information.
15775
15776 @noindent
15777 In order to use an Ada library manually, you need to make sure that this
15778 library is on both your source and object path
15779 (see @ref{Search Paths and the Run-Time Library (RTL)}
15780 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15781 in an archive or a shared library, you need to specify the desired
15782 library at link time.
15783
15784 For example, you can use the library @file{mylib} installed in
15785 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15786
15787 @smallexample
15788 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15789   -largs -lmy_lib
15790 @end smallexample
15791
15792 @noindent
15793 This can be expressed more simply:
15794 @smallexample
15795 $ gnatmake my_appl
15796 @end smallexample
15797 @noindent
15798 when the following conditions are met:
15799 @itemize @bullet
15800 @item
15801 @file{/dir/my_lib_src} has been added by the user to the environment
15802 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15803 @file{ada_source_path}
15804 @item
15805 @file{/dir/my_lib_obj} has been added by the user to the environment
15806 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15807 @file{ada_object_path}
15808 @item
15809 a pragma @code{Linker_Options} has been added to one of the sources.
15810 For example:
15811
15812 @smallexample @c ada
15813 pragma Linker_Options ("-lmy_lib");
15814 @end smallexample
15815 @end itemize
15816
15817 @node Stand-alone Ada Libraries
15818 @section Stand-alone Ada Libraries
15819 @cindex Stand-alone library, building, using
15820
15821 @menu
15822 * Introduction to Stand-alone Libraries::
15823 * Building a Stand-alone Library::
15824 * Creating a Stand-alone Library to be used in a non-Ada context::
15825 * Restrictions in Stand-alone Libraries::
15826 @end menu
15827
15828 @node Introduction to Stand-alone Libraries
15829 @subsection Introduction to Stand-alone Libraries
15830
15831 @noindent
15832 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15833 necessary code to
15834 elaborate the Ada units that are included in the library. In contrast with
15835 an ordinary library, which consists of all sources, objects and @file{ALI}
15836 files of the
15837 library, a SAL may specify a restricted subset of compilation units
15838 to serve as a library interface. In this case, the fully
15839 self-sufficient set of files will normally consist of an objects
15840 archive, the sources of interface units' specs, and the @file{ALI}
15841 files of interface units.
15842 If an interface spec contains a generic unit or an inlined subprogram,
15843 the body's
15844 source must also be provided; if the units that must be provided in the source
15845 form depend on other units, the source and @file{ALI} files of those must
15846 also be provided.
15847
15848 The main purpose of a SAL is to minimize the recompilation overhead of client
15849 applications when a new version of the library is installed. Specifically,
15850 if the interface sources have not changed, client applications do not need to
15851 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15852 version, controlled by @code{Library_Version} attribute, is not changed,
15853 then the clients do not need to be relinked.
15854
15855 SALs also allow the library providers to minimize the amount of library source
15856 text exposed to the clients.  Such ``information hiding'' might be useful or
15857 necessary for various reasons.
15858
15859 Stand-alone libraries are also well suited to be used in an executable whose
15860 main routine is not written in Ada.
15861
15862 @node Building a Stand-alone Library
15863 @subsection Building a Stand-alone Library
15864
15865 @noindent
15866 GNAT's Project facility provides a simple way of building and installing
15867 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15868 To be a Stand-alone Library Project, in addition to the two attributes
15869 that make a project a Library Project (@code{Library_Name} and
15870 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15871 @code{Library_Interface} must be defined.  For example:
15872
15873 @smallexample @c projectfile
15874 @group
15875    for Library_Dir use "lib_dir";
15876    for Library_Name use "dummy";
15877    for Library_Interface use ("int1", "int1.child");
15878 @end group
15879 @end smallexample
15880
15881 @noindent
15882 Attribute @code{Library_Interface} has a non-empty string list value,
15883 each string in the list designating a unit contained in an immediate source
15884 of the project file.
15885
15886 When a Stand-alone Library is built, first the binder is invoked to build
15887 a package whose name depends on the library name
15888 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15889 This binder-generated package includes initialization and
15890 finalization procedures whose
15891 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15892 in the example
15893 above). The object corresponding to this package is included in the library.
15894
15895 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15896 calling of these procedures if a static SAL is built, or if a shared SAL
15897 is built
15898 with the project-level attribute @code{Library_Auto_Init} set to
15899 @code{"false"}.
15900
15901 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15902 (those that are listed in attribute @code{Library_Interface}) are copied to
15903 the Library Directory. As a consequence, only the Interface Units may be
15904 imported from Ada units outside of the library. If other units are imported,
15905 the binding phase will fail.
15906
15907 The attribute @code{Library_Src_Dir} may be specified for a
15908 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15909 single string value. Its value must be the path (absolute or relative to the
15910 project directory) of an existing directory. This directory cannot be the
15911 object directory or one of the source directories, but it can be the same as
15912 the library directory. The sources of the Interface
15913 Units of the library that are needed by an Ada client of the library will be
15914 copied to the designated directory, called the Interface Copy directory.
15915 These sources include the specs of the Interface Units, but they may also
15916 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15917 are used, or when there is a generic unit in the spec. Before the sources
15918 are copied to the Interface Copy directory, an attempt is made to delete all
15919 files in the Interface Copy directory.
15920
15921 Building stand-alone libraries by hand is somewhat tedious, but for those
15922 occasions when it is necessary here are the steps that you need to perform:
15923 @itemize @bullet
15924 @item
15925 Compile all library sources.
15926
15927 @item
15928 Invoke the binder with the switch @option{-n} (No Ada main program),
15929 with all the @file{ALI} files of the interfaces, and
15930 with the switch @option{-L} to give specific names to the @code{init}
15931 and @code{final} procedures.  For example:
15932 @smallexample
15933   gnatbind -n int1.ali int2.ali -Lsal1
15934 @end smallexample
15935
15936 @item
15937 Compile the binder generated file:
15938 @smallexample
15939   gcc -c b~int2.adb
15940 @end smallexample
15941
15942 @item
15943 Link the dynamic library with all the necessary object files,
15944 indicating to the linker the names of the @code{init} (and possibly
15945 @code{final}) procedures for automatic initialization (and finalization).
15946 The built library should be placed in a directory different from
15947 the object directory.
15948
15949 @item
15950 Copy the @code{ALI} files of the interface to the library directory,
15951 add in this copy an indication that it is an interface to a SAL
15952 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
15953 with letter ``P'') and make the modified copy of the @file{ALI} file
15954 read-only.
15955 @end itemize
15956
15957 @noindent
15958 Using SALs is not different from using other libraries
15959 (see @ref{Using a library}).
15960
15961 @node Creating a Stand-alone Library to be used in a non-Ada context
15962 @subsection Creating a Stand-alone Library to be used in a non-Ada context
15963
15964 @noindent
15965 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
15966 a non-Ada context.
15967
15968 The only extra step required is to ensure that library interface subprograms
15969 are compatible with the main program, by means of @code{pragma Export}
15970 or @code{pragma Convention}.
15971
15972 Here is an example of simple library interface for use with C main program:
15973
15974 @smallexample @c ada
15975 package My_Package is
15976
15977    procedure Do_Something;
15978    pragma Export (C, Do_Something, "do_something");
15979
15980    procedure Do_Something_Else;
15981    pragma Export (C, Do_Something_Else, "do_something_else");
15982
15983 end My_Package;
15984 @end smallexample
15985
15986 @noindent
15987 On the foreign language side, you must provide a ``foreign'' view of the
15988 library interface; remember that it should contain elaboration routines in
15989 addition to interface subprograms.
15990
15991 The example below shows the content of @code{mylib_interface.h} (note
15992 that there is no rule for the naming of this file, any name can be used)
15993 @smallexample
15994 /* the library elaboration procedure */
15995 extern void mylibinit (void);
15996
15997 /* the library finalization procedure */
15998 extern void mylibfinal (void);
15999
16000 /* the interface exported by the library */
16001 extern void do_something (void);
16002 extern void do_something_else (void);
16003 @end smallexample
16004
16005 @noindent
16006 Libraries built as explained above can be used from any program, provided
16007 that the elaboration procedures (named @code{mylibinit} in the previous
16008 example) are called before the library services are used. Any number of
16009 libraries can be used simultaneously, as long as the elaboration
16010 procedure of each library is called.
16011
16012 Below is an example of a C program that uses the @code{mylib} library.
16013
16014 @smallexample
16015 #include "mylib_interface.h"
16016
16017 int
16018 main (void)
16019 @{
16020    /* First, elaborate the library before using it */
16021    mylibinit ();
16022
16023    /* Main program, using the library exported entities */
16024    do_something ();
16025    do_something_else ();
16026
16027    /* Library finalization at the end of the program */
16028    mylibfinal ();
16029    return 0;
16030 @}
16031 @end smallexample
16032
16033 @noindent
16034 Note that invoking any library finalization procedure generated by
16035 @code{gnatbind} shuts down the Ada run-time environment.
16036 Consequently, the
16037 finalization of all Ada libraries must be performed at the end of the program.
16038 No call to these libraries or to the Ada run-time library should be made
16039 after the finalization phase.
16040
16041 @node Restrictions in Stand-alone Libraries
16042 @subsection Restrictions in Stand-alone Libraries
16043
16044 @noindent
16045 The pragmas listed below should be used with caution inside libraries,
16046 as they can create incompatibilities with other Ada libraries:
16047 @itemize @bullet
16048 @item pragma @code{Locking_Policy}
16049 @item pragma @code{Queuing_Policy}
16050 @item pragma @code{Task_Dispatching_Policy}
16051 @item pragma @code{Unreserve_All_Interrupts}
16052 @end itemize
16053
16054 @noindent
16055 When using a library that contains such pragmas, the user must make sure
16056 that all libraries use the same pragmas with the same values. Otherwise,
16057 @code{Program_Error} will
16058 be raised during the elaboration of the conflicting
16059 libraries. The usage of these pragmas and its consequences for the user
16060 should therefore be well documented.
16061
16062 Similarly, the traceback in the exception occurrence mechanism should be
16063 enabled or disabled in a consistent manner across all libraries.
16064 Otherwise, Program_Error will be raised during the elaboration of the
16065 conflicting libraries.
16066
16067 If the @code{Version} or @code{Body_Version}
16068 attributes are used inside a library, then you need to
16069 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16070 libraries, so that version identifiers can be properly computed.
16071 In practice these attributes are rarely used, so this is unlikely
16072 to be a consideration.
16073
16074 @node  Rebuilding the GNAT Run-Time Library
16075 @section Rebuilding the GNAT Run-Time Library
16076 @cindex GNAT Run-Time Library, rebuilding
16077 @cindex Building the GNAT Run-Time Library
16078 @cindex Rebuilding the GNAT Run-Time Library
16079 @cindex Run-Time Library, rebuilding
16080
16081 @noindent
16082 It may be useful to recompile the GNAT library in various contexts, the
16083 most important one being the use of partition-wide configuration pragmas
16084 such as @code{Normalize_Scalars}. A special Makefile called
16085 @code{Makefile.adalib} is provided to that effect and can be found in
16086 the directory containing the GNAT library. The location of this
16087 directory depends on the way the GNAT environment has been installed and can
16088 be determined by means of the command:
16089
16090 @smallexample
16091 $ gnatls -v
16092 @end smallexample
16093
16094 @noindent
16095 The last entry in the object search path usually contains the
16096 gnat library. This Makefile contains its own documentation and in
16097 particular the set of instructions needed to rebuild a new library and
16098 to use it.
16099
16100 @node Using the GNU make Utility
16101 @chapter Using the GNU @code{make} Utility
16102 @findex make
16103
16104 @noindent
16105 This chapter offers some examples of makefiles that solve specific
16106 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16107 make, make, GNU @code{make}}), nor does it try to replace the
16108 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16109
16110 All the examples in this section are specific to the GNU version of
16111 make. Although @command{make} is a standard utility, and the basic language
16112 is the same, these examples use some advanced features found only in
16113 @code{GNU make}.
16114
16115 @menu
16116 * Using gnatmake in a Makefile::
16117 * Automatically Creating a List of Directories::
16118 * Generating the Command Line Switches::
16119 * Overcoming Command Line Length Limits::
16120 @end menu
16121
16122 @node Using gnatmake in a Makefile
16123 @section Using gnatmake in a Makefile
16124 @findex makefile
16125 @cindex GNU make
16126
16127 @noindent
16128 Complex project organizations can be handled in a very powerful way by
16129 using GNU make combined with gnatmake. For instance, here is a Makefile
16130 which allows you to build each subsystem of a big project into a separate
16131 shared library. Such a makefile allows you to significantly reduce the link
16132 time of very big applications while maintaining full coherence at
16133 each step of the build process.
16134
16135 The list of dependencies are handled automatically by
16136 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16137 the appropriate directories.
16138
16139 Note that you should also read the example on how to automatically
16140 create the list of directories
16141 (@pxref{Automatically Creating a List of Directories})
16142 which might help you in case your project has a lot of subdirectories.
16143
16144 @smallexample
16145 @iftex
16146 @leftskip=0cm
16147 @font@heightrm=cmr8
16148 @heightrm
16149 @end iftex
16150 ## This Makefile is intended to be used with the following directory
16151 ## configuration:
16152 ##  - The sources are split into a series of csc (computer software components)
16153 ##    Each of these csc is put in its own directory.
16154 ##    Their name are referenced by the directory names.
16155 ##    They will be compiled into shared library (although this would also work
16156 ##    with static libraries
16157 ##  - The main program (and possibly other packages that do not belong to any
16158 ##    csc is put in the top level directory (where the Makefile is).
16159 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16160 ##                    \_ second_csc (sources) __ lib (will contain the library)
16161 ##                    \_ @dots{}
16162 ## Although this Makefile is build for shared library, it is easy to modify
16163 ## to build partial link objects instead (modify the lines with -shared and
16164 ## gnatlink below)
16165 ##
16166 ## With this makefile, you can change any file in the system or add any new
16167 ## file, and everything will be recompiled correctly (only the relevant shared
16168 ## objects will be recompiled, and the main program will be re-linked).
16169
16170 # The list of computer software component for your project. This might be
16171 # generated automatically.
16172 CSC_LIST=aa bb cc
16173
16174 # Name of the main program (no extension)
16175 MAIN=main
16176
16177 # If we need to build objects with -fPIC, uncomment the following line
16178 #NEED_FPIC=-fPIC
16179
16180 # The following variable should give the directory containing libgnat.so
16181 # You can get this directory through 'gnatls -v'. This is usually the last
16182 # directory in the Object_Path.
16183 GLIB=@dots{}
16184
16185 # The directories for the libraries
16186 # (This macro expands the list of CSC to the list of shared libraries, you
16187 # could simply use the expanded form:
16188 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16189 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16190
16191 $@{MAIN@}: objects $@{LIB_DIR@}
16192     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16193     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16194
16195 objects::
16196     # recompile the sources
16197     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16198
16199 # Note: In a future version of GNAT, the following commands will be simplified
16200 # by a new tool, gnatmlib
16201 $@{LIB_DIR@}:
16202     mkdir -p $@{dir $@@ @}
16203     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16204     cd $@{dir $@@ @} && cp -f ../*.ali .
16205
16206 # The dependencies for the modules
16207 # Note that we have to force the expansion of *.o, since in some cases
16208 # make won't be able to do it itself.
16209 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16210 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16211 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16212
16213 # Make sure all of the shared libraries are in the path before starting the
16214 # program
16215 run::
16216     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16217
16218 clean::
16219     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16220     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16221     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16222     $@{RM@} *.o *.ali $@{MAIN@}
16223 @end smallexample
16224
16225 @node Automatically Creating a List of Directories
16226 @section Automatically Creating a List of Directories
16227
16228 @noindent
16229 In most makefiles, you will have to specify a list of directories, and
16230 store it in a variable. For small projects, it is often easier to
16231 specify each of them by hand, since you then have full control over what
16232 is the proper order for these directories, which ones should be
16233 included.
16234
16235 However, in larger projects, which might involve hundreds of
16236 subdirectories, it might be more convenient to generate this list
16237 automatically.
16238
16239 The example below presents two methods. The first one, although less
16240 general, gives you more control over the list. It involves wildcard
16241 characters, that are automatically expanded by @command{make}. Its
16242 shortcoming is that you need to explicitly specify some of the
16243 organization of your project, such as for instance the directory tree
16244 depth, whether some directories are found in a separate tree, @enddots{}
16245
16246 The second method is the most general one. It requires an external
16247 program, called @command{find}, which is standard on all Unix systems. All
16248 the directories found under a given root directory will be added to the
16249 list.
16250
16251 @smallexample
16252 @iftex
16253 @leftskip=0cm
16254 @font@heightrm=cmr8
16255 @heightrm
16256 @end iftex
16257 # The examples below are based on the following directory hierarchy:
16258 # All the directories can contain any number of files
16259 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16260 #                       ->  ab
16261 #                       ->  ac
16262 #                ->  b  ->  ba  ->  baa
16263 #                       ->  bb
16264 #                       ->  bc
16265 # This Makefile creates a variable called DIRS, that can be reused any time
16266 # you need this list (see the other examples in this section)
16267
16268 # The root of your project's directory hierarchy
16269 ROOT_DIRECTORY=.
16270
16271 ####
16272 # First method: specify explicitly the list of directories
16273 # This allows you to specify any subset of all the directories you need.
16274 ####
16275
16276 DIRS := a/aa/ a/ab/ b/ba/
16277
16278 ####
16279 # Second method: use wildcards
16280 # Note that the argument(s) to wildcard below should end with a '/'.
16281 # Since wildcards also return file names, we have to filter them out
16282 # to avoid duplicate directory names.
16283 # We thus use make's @code{dir} and @code{sort} functions.
16284 # It sets DIRs to the following value (note that the directories aaa and baa
16285 # are not given, unless you change the arguments to wildcard).
16286 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16287 ####
16288
16289 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16290                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16291
16292 ####
16293 # Third method: use an external program
16294 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16295 # This is the most complete command: it sets DIRs to the following value:
16296 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16297 ####
16298
16299 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16300
16301 @end smallexample
16302
16303 @node Generating the Command Line Switches
16304 @section Generating the Command Line Switches
16305
16306 @noindent
16307 Once you have created the list of directories as explained in the
16308 previous section (@pxref{Automatically Creating a List of Directories}),
16309 you can easily generate the command line arguments to pass to gnatmake.
16310
16311 For the sake of completeness, this example assumes that the source path
16312 is not the same as the object path, and that you have two separate lists
16313 of directories.
16314
16315 @smallexample
16316 # see "Automatically creating a list of directories" to create
16317 # these variables
16318 SOURCE_DIRS=
16319 OBJECT_DIRS=
16320
16321 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16322 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16323
16324 all:
16325         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16326 @end smallexample
16327
16328 @node Overcoming Command Line Length Limits
16329 @section Overcoming Command Line Length Limits
16330
16331 @noindent
16332 One problem that might be encountered on big projects is that many
16333 operating systems limit the length of the command line. It is thus hard to give
16334 gnatmake the list of source and object directories.
16335
16336 This example shows how you can set up environment variables, which will
16337 make @command{gnatmake} behave exactly as if the directories had been
16338 specified on the command line, but have a much higher length limit (or
16339 even none on most systems).
16340
16341 It assumes that you have created a list of directories in your Makefile,
16342 using one of the methods presented in
16343 @ref{Automatically Creating a List of Directories}.
16344 For the sake of completeness, we assume that the object
16345 path (where the ALI files are found) is different from the sources patch.
16346
16347 Note a small trick in the Makefile below: for efficiency reasons, we
16348 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16349 expanded immediately by @code{make}. This way we overcome the standard
16350 make behavior which is to expand the variables only when they are
16351 actually used.
16352
16353 On Windows, if you are using the standard Windows command shell, you must
16354 replace colons with semicolons in the assignments to these variables.
16355
16356 @smallexample
16357 @iftex
16358 @leftskip=0cm
16359 @font@heightrm=cmr8
16360 @heightrm
16361 @end iftex
16362 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16363 # This is the same thing as putting the -I arguments on the command line.
16364 # (the equivalent of using -aI on the command line would be to define
16365 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16366 # You can of course have different values for these variables.
16367 #
16368 # Note also that we need to keep the previous values of these variables, since
16369 # they might have been set before running 'make' to specify where the GNAT
16370 # library is installed.
16371
16372 # see "Automatically creating a list of directories" to create these
16373 # variables
16374 SOURCE_DIRS=
16375 OBJECT_DIRS=
16376
16377 empty:=
16378 space:=$@{empty@} $@{empty@}
16379 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16380 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16381 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16382 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16383 export ADA_INCLUDE_PATH
16384 export ADA_OBJECT_PATH
16385
16386 all:
16387         gnatmake main_unit
16388 @end smallexample
16389 @end ifclear
16390
16391 @node Memory Management Issues
16392 @chapter Memory Management Issues
16393
16394 @noindent
16395 This chapter describes some useful memory pools provided in the GNAT library
16396 and in particular the GNAT Debug Pool facility, which can be used to detect
16397 incorrect uses of access values (including ``dangling references'').
16398 @ifclear vms
16399 It also describes the @command{gnatmem} tool, which can be used to track down
16400 ``memory leaks''.
16401 @end ifclear
16402
16403 @menu
16404 * Some Useful Memory Pools::
16405 * The GNAT Debug Pool Facility::
16406 @ifclear vms
16407 * The gnatmem Tool::
16408 @end ifclear
16409 @end menu
16410
16411 @node Some Useful Memory Pools
16412 @section Some Useful Memory Pools
16413 @findex Memory Pool
16414 @cindex storage, pool
16415
16416 @noindent
16417 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16418 storage pool. Allocations use the standard system call @code{malloc} while
16419 deallocations use the standard system call @code{free}. No reclamation is
16420 performed when the pool goes out of scope. For performance reasons, the
16421 standard default Ada allocators/deallocators do not use any explicit storage
16422 pools but if they did, they could use this storage pool without any change in
16423 behavior. That is why this storage pool is used  when the user
16424 manages to make the default implicit allocator explicit as in this example:
16425 @smallexample @c ada
16426    type T1 is access Something;
16427     -- no Storage pool is defined for T2
16428    type T2 is access Something_Else;
16429    for T2'Storage_Pool use T1'Storage_Pool;
16430    -- the above is equivalent to
16431    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16432 @end smallexample
16433
16434 @noindent
16435 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16436 pool. The allocation strategy is similar to @code{Pool_Local}'s
16437 except that the all
16438 storage allocated with this pool is reclaimed when the pool object goes out of
16439 scope. This pool provides a explicit mechanism similar to the implicit one
16440 provided by several Ada 83 compilers for allocations performed through a local
16441 access type and whose purpose was to reclaim memory when exiting the
16442 scope of a given local access. As an example, the following program does not
16443 leak memory even though it does not perform explicit deallocation:
16444
16445 @smallexample @c ada
16446 with System.Pool_Local;
16447 procedure Pooloc1 is
16448    procedure Internal is
16449       type A is access Integer;
16450       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16451       for A'Storage_Pool use X;
16452       v : A;
16453    begin
16454       for I in  1 .. 50 loop
16455          v := new Integer;
16456       end loop;
16457    end Internal;
16458 begin
16459    for I in  1 .. 100 loop
16460       Internal;
16461    end loop;
16462 end Pooloc1;
16463 @end smallexample
16464
16465 @noindent
16466 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16467 @code{Storage_Size} is specified for an access type.
16468 The whole storage for the pool is
16469 allocated at once, usually on the stack at the point where the access type is
16470 elaborated. It is automatically reclaimed when exiting the scope where the
16471 access type is defined. This package is not intended to be used directly by the
16472 user and it is implicitly used for each such declaration:
16473
16474 @smallexample @c ada
16475    type T1 is access Something;
16476    for T1'Storage_Size use 10_000;
16477 @end smallexample
16478
16479 @node The GNAT Debug Pool Facility
16480 @section The GNAT Debug Pool Facility
16481 @findex Debug Pool
16482 @cindex storage, pool, memory corruption
16483
16484 @noindent
16485 The use of unchecked deallocation and unchecked conversion can easily
16486 lead to incorrect memory references. The problems generated by such
16487 references are usually difficult to tackle because the symptoms can be
16488 very remote from the origin of the problem. In such cases, it is
16489 very helpful to detect the problem as early as possible. This is the
16490 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16491
16492 In order to use the GNAT specific debugging pool, the user must
16493 associate a debug pool object with each of the access types that may be
16494 related to suspected memory problems. See Ada Reference Manual 13.11.
16495 @smallexample @c ada
16496 type Ptr is access Some_Type;
16497 Pool : GNAT.Debug_Pools.Debug_Pool;
16498 for Ptr'Storage_Pool use Pool;
16499 @end smallexample
16500
16501 @noindent
16502 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16503 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16504 allow the user to redefine allocation and deallocation strategies. They
16505 also provide a checkpoint for each dereference, through the use of
16506 the primitive operation @code{Dereference} which is implicitly called at
16507 each dereference of an access value.
16508
16509 Once an access type has been associated with a debug pool, operations on
16510 values of the type may raise four distinct exceptions,
16511 which correspond to four potential kinds of memory corruption:
16512 @itemize @bullet
16513 @item
16514 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16515 @item
16516 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16517 @item
16518 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16519 @item
16520 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16521 @end itemize
16522
16523 @noindent
16524 For types associated with a Debug_Pool, dynamic allocation is performed using
16525 the standard GNAT allocation routine. References to all allocated chunks of
16526 memory are kept in an internal dictionary. Several deallocation strategies are
16527 provided, whereupon the user can choose to release the memory to the system,
16528 keep it allocated for further invalid access checks, or fill it with an easily
16529 recognizable pattern for debug sessions. The memory pattern is the old IBM
16530 hexadecimal convention: @code{16#DEADBEEF#}.
16531
16532 See the documentation in the file g-debpoo.ads for more information on the
16533 various strategies.
16534
16535 Upon each dereference, a check is made that the access value denotes a
16536 properly allocated memory location. Here is a complete example of use of
16537 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16538 @smallexample @c ada
16539 @iftex
16540 @leftskip=0cm
16541 @end iftex
16542 with Gnat.Io; use Gnat.Io;
16543 with Unchecked_Deallocation;
16544 with Unchecked_Conversion;
16545 with GNAT.Debug_Pools;
16546 with System.Storage_Elements;
16547 with Ada.Exceptions; use Ada.Exceptions;
16548 procedure Debug_Pool_Test is
16549
16550    type T is access Integer;
16551    type U is access all T;
16552
16553    P : GNAT.Debug_Pools.Debug_Pool;
16554    for T'Storage_Pool use P;
16555
16556    procedure Free is new Unchecked_Deallocation (Integer, T);
16557    function UC is new Unchecked_Conversion (U, T);
16558    A, B : aliased T;
16559
16560    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16561
16562 begin
16563    Info (P);
16564    A := new Integer;
16565    B := new Integer;
16566    B := A;
16567    Info (P);
16568    Free (A);
16569    begin
16570       Put_Line (Integer'Image(B.all));
16571    exception
16572       when E : others => Put_Line ("raised: " & Exception_Name (E));
16573    end;
16574    begin
16575       Free (B);
16576    exception
16577       when E : others => Put_Line ("raised: " & Exception_Name (E));
16578    end;
16579    B := UC(A'Access);
16580    begin
16581       Put_Line (Integer'Image(B.all));
16582    exception
16583       when E : others => Put_Line ("raised: " & Exception_Name (E));
16584    end;
16585    begin
16586       Free (B);
16587    exception
16588       when E : others => Put_Line ("raised: " & Exception_Name (E));
16589    end;
16590    Info (P);
16591 end Debug_Pool_Test;
16592 @end smallexample
16593
16594 @noindent
16595 The debug pool mechanism provides the following precise diagnostics on the
16596 execution of this erroneous program:
16597 @smallexample
16598 Debug Pool info:
16599   Total allocated bytes :  0
16600   Total deallocated bytes :  0
16601   Current Water Mark:  0
16602   High Water Mark:  0
16603
16604 Debug Pool info:
16605   Total allocated bytes :  8
16606   Total deallocated bytes :  0
16607   Current Water Mark:  8
16608   High Water Mark:  8
16609
16610 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16611 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16612 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16613 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16614 Debug Pool info:
16615   Total allocated bytes :  8
16616   Total deallocated bytes :  4
16617   Current Water Mark:  4
16618   High Water Mark:  8
16619 @end smallexample
16620
16621 @ifclear vms
16622 @node The gnatmem Tool
16623 @section The @command{gnatmem} Tool
16624 @findex gnatmem
16625
16626 @noindent
16627 The @code{gnatmem} utility monitors dynamic allocation and
16628 deallocation activity in a program, and displays information about
16629 incorrect deallocations and possible sources of memory leaks.
16630 It is designed to work in association with a static runtime library
16631 only and in this context provides three types of information:
16632 @itemize @bullet
16633 @item
16634 General information concerning memory management, such as the total
16635 number of allocations and deallocations, the amount of allocated
16636 memory and the high water mark, i.e.@: the largest amount of allocated
16637 memory in the course of program execution.
16638
16639 @item
16640 Backtraces for all incorrect deallocations, that is to say deallocations
16641 which do not correspond to a valid allocation.
16642
16643 @item
16644 Information on each allocation that is potentially the origin of a memory
16645 leak.
16646 @end itemize
16647
16648 @menu
16649 * Running gnatmem::
16650 * Switches for gnatmem::
16651 * Example of gnatmem Usage::
16652 @end menu
16653
16654 @node Running gnatmem
16655 @subsection Running @code{gnatmem}
16656
16657 @noindent
16658 @code{gnatmem} makes use of the output created by the special version of
16659 allocation and deallocation routines that record call information. This
16660 allows to obtain accurate dynamic memory usage history at a minimal cost to
16661 the execution speed. Note however, that @code{gnatmem} is not supported on
16662 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16663 Solaris and Windows NT/2000/XP (x86).
16664
16665 @noindent
16666 The @code{gnatmem} command has the form
16667
16668 @smallexample
16669 @c    $ gnatmem @ovar{switches} user_program
16670 @c Expanding @ovar macro inline (explanation in macro def comments)
16671       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16672 @end smallexample
16673
16674 @noindent
16675 The program must have been linked with the instrumented version of the
16676 allocation and deallocation routines. This is done by linking with the
16677 @file{libgmem.a} library. For correct symbolic backtrace information,
16678 the user program should be compiled with debugging options
16679 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16680
16681 @smallexample
16682 $ gnatmake -g my_program -largs -lgmem
16683 @end smallexample
16684
16685 @noindent
16686 As library @file{libgmem.a} contains an alternate body for package
16687 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16688 when an executable is linked with library @file{libgmem.a}. It is then not
16689 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16690
16691 @noindent
16692 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16693 This file contains information about all allocations and deallocations
16694 performed by the program. It is produced by the instrumented allocations and
16695 deallocations routines and will be used by @code{gnatmem}.
16696
16697 In order to produce symbolic backtrace information for allocations and
16698 deallocations performed by the GNAT run-time library, you need to use a
16699 version of that library that has been compiled with the @option{-g} switch
16700 (see @ref{Rebuilding the GNAT Run-Time Library}).
16701
16702 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16703 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16704 @option{-i} switch, gnatmem will assume that this file can be found in the
16705 current directory. For example, after you have executed @file{my_program},
16706 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16707
16708 @smallexample
16709 $ gnatmem my_program
16710 @end smallexample
16711
16712 @noindent
16713 This will produce the output with the following format:
16714
16715 *************** debut cc
16716 @smallexample
16717 $ gnatmem my_program
16718
16719 Global information
16720 ------------------
16721    Total number of allocations        :  45
16722    Total number of deallocations      :   6
16723    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16724    High Water Mark                    :  11.40 Kilobytes
16725
16726 .
16727 .
16728 .
16729 Allocation Root # 2
16730 -------------------
16731  Number of non freed allocations    :  11
16732  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16733  High Water Mark                    :   1.27 Kilobytes
16734  Backtrace                          :
16735    my_program.adb:23 my_program.alloc
16736 .
16737 .
16738 .
16739 @end smallexample
16740
16741 The first block of output gives general information. In this case, the
16742 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16743 Unchecked_Deallocation routine occurred.
16744
16745 @noindent
16746 Subsequent paragraphs display  information on all allocation roots.
16747 An allocation root is a specific point in the execution of the program
16748 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16749 construct. This root is represented by an execution backtrace (or subprogram
16750 call stack). By default the backtrace depth for allocations roots is 1, so
16751 that a root corresponds exactly to a source location. The backtrace can
16752 be made deeper, to make the root more specific.
16753
16754 @node Switches for gnatmem
16755 @subsection Switches for @code{gnatmem}
16756
16757 @noindent
16758 @code{gnatmem} recognizes the following switches:
16759
16760 @table @option
16761
16762 @item -q
16763 @cindex @option{-q} (@code{gnatmem})
16764 Quiet. Gives the minimum output needed to identify the origin of the
16765 memory leaks. Omits statistical information.
16766
16767 @item @var{N}
16768 @cindex @var{N} (@code{gnatmem})
16769 N is an integer literal (usually between 1 and 10) which controls the
16770 depth of the backtraces defining allocation root. The default value for
16771 N is 1. The deeper the backtrace, the more precise the localization of
16772 the root. Note that the total number of roots can depend on this
16773 parameter. This parameter must be specified @emph{before} the name of the
16774 executable to be analyzed, to avoid ambiguity.
16775
16776 @item -b n
16777 @cindex @option{-b} (@code{gnatmem})
16778 This switch has the same effect as just depth parameter.
16779
16780 @item -i @var{file}
16781 @cindex @option{-i} (@code{gnatmem})
16782 Do the @code{gnatmem} processing starting from @file{file}, rather than
16783 @file{gmem.out} in the current directory.
16784
16785 @item -m n
16786 @cindex @option{-m} (@code{gnatmem})
16787 This switch causes @code{gnatmem} to mask the allocation roots that have less
16788 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16789 examine even the roots that didn't result in leaks.
16790
16791 @item -s order
16792 @cindex @option{-s} (@code{gnatmem})
16793 This switch causes @code{gnatmem} to sort the allocation roots according to the
16794 specified order of sort criteria, each identified by a single letter. The
16795 currently supported criteria are @code{n, h, w} standing respectively for
16796 number of unfreed allocations, high watermark, and final watermark
16797 corresponding to a specific root. The default order is @code{nwh}.
16798
16799 @end table
16800
16801 @node Example of gnatmem Usage
16802 @subsection Example of @code{gnatmem} Usage
16803
16804 @noindent
16805 The following example shows the use of @code{gnatmem}
16806 on a simple memory-leaking program.
16807 Suppose that we have the following Ada program:
16808
16809 @smallexample @c ada
16810 @group
16811 @cartouche
16812 with Unchecked_Deallocation;
16813 procedure Test_Gm is
16814
16815    type T is array (1..1000) of Integer;
16816    type Ptr is access T;
16817    procedure Free is new Unchecked_Deallocation (T, Ptr);
16818    A : Ptr;
16819
16820    procedure My_Alloc is
16821    begin
16822       A := new T;
16823    end My_Alloc;
16824
16825    procedure My_DeAlloc is
16826       B : Ptr := A;
16827    begin
16828       Free (B);
16829    end My_DeAlloc;
16830
16831 begin
16832    My_Alloc;
16833    for I in 1 .. 5 loop
16834       for J in I .. 5 loop
16835          My_Alloc;
16836       end loop;
16837       My_Dealloc;
16838    end loop;
16839 end;
16840 @end cartouche
16841 @end group
16842 @end smallexample
16843
16844 @noindent
16845 The program needs to be compiled with debugging option and linked with
16846 @code{gmem} library:
16847
16848 @smallexample
16849 $ gnatmake -g test_gm -largs -lgmem
16850 @end smallexample
16851
16852 @noindent
16853 Then we execute the program as usual:
16854
16855 @smallexample
16856 $ test_gm
16857 @end smallexample
16858
16859 @noindent
16860 Then @code{gnatmem} is invoked simply with
16861 @smallexample
16862 $ gnatmem test_gm
16863 @end smallexample
16864
16865 @noindent
16866 which produces the following output (result may vary on different platforms):
16867
16868 @smallexample
16869 Global information
16870 ------------------
16871    Total number of allocations        :  18
16872    Total number of deallocations      :   5
16873    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16874    High Water Mark                    :  56.90 Kilobytes
16875
16876 Allocation Root # 1
16877 -------------------
16878  Number of non freed allocations    :  11
16879  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16880  High Water Mark                    :  46.88 Kilobytes
16881  Backtrace                          :
16882    test_gm.adb:11 test_gm.my_alloc
16883
16884 Allocation Root # 2
16885 -------------------
16886  Number of non freed allocations    :   1
16887  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16888  High Water Mark                    :  10.02 Kilobytes
16889  Backtrace                          :
16890    s-secsta.adb:81 system.secondary_stack.ss_init
16891
16892 Allocation Root # 3
16893 -------------------
16894  Number of non freed allocations    :   1
16895  Final Water Mark (non freed mem)   :  12 Bytes
16896  High Water Mark                    :  12 Bytes
16897  Backtrace                          :
16898    s-secsta.adb:181 system.secondary_stack.ss_init
16899 @end smallexample
16900
16901 @noindent
16902 Note that the GNAT run time contains itself a certain number of
16903 allocations that have no  corresponding deallocation,
16904 as shown here for root #2 and root
16905 #3. This is a normal behavior when the number of non-freed allocations
16906 is one, it allocates dynamic data structures that the run time needs for
16907 the complete lifetime of the program. Note also that there is only one
16908 allocation root in the user program with a single line back trace:
16909 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16910 program shows that 'My_Alloc' is called at 2 different points in the
16911 source (line 21 and line 24). If those two allocation roots need to be
16912 distinguished, the backtrace depth parameter can be used:
16913
16914 @smallexample
16915 $ gnatmem 3 test_gm
16916 @end smallexample
16917
16918 @noindent
16919 which will give the following output:
16920
16921 @smallexample
16922 Global information
16923 ------------------
16924    Total number of allocations        :  18
16925    Total number of deallocations      :   5
16926    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16927    High Water Mark                    :  56.90 Kilobytes
16928
16929 Allocation Root # 1
16930 -------------------
16931  Number of non freed allocations    :  10
16932  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16933  High Water Mark                    :  42.97 Kilobytes
16934  Backtrace                          :
16935    test_gm.adb:11 test_gm.my_alloc
16936    test_gm.adb:24 test_gm
16937    b_test_gm.c:52 main
16938
16939 Allocation Root # 2
16940 -------------------
16941  Number of non freed allocations    :   1
16942  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16943  High Water Mark                    :  10.02 Kilobytes
16944  Backtrace                          :
16945    s-secsta.adb:81  system.secondary_stack.ss_init
16946    s-secsta.adb:283 <system__secondary_stack___elabb>
16947    b_test_gm.c:33   adainit
16948
16949 Allocation Root # 3
16950 -------------------
16951  Number of non freed allocations    :   1
16952  Final Water Mark (non freed mem)   :   3.91 Kilobytes
16953  High Water Mark                    :   3.91 Kilobytes
16954  Backtrace                          :
16955    test_gm.adb:11 test_gm.my_alloc
16956    test_gm.adb:21 test_gm
16957    b_test_gm.c:52 main
16958
16959 Allocation Root # 4
16960 -------------------
16961  Number of non freed allocations    :   1
16962  Final Water Mark (non freed mem)   :  12 Bytes
16963  High Water Mark                    :  12 Bytes
16964  Backtrace                          :
16965    s-secsta.adb:181 system.secondary_stack.ss_init
16966    s-secsta.adb:283 <system__secondary_stack___elabb>
16967    b_test_gm.c:33   adainit
16968 @end smallexample
16969
16970 @noindent
16971 The allocation root #1 of the first example has been split in 2 roots #1
16972 and #3 thanks to the more precise associated backtrace.
16973
16974 @end ifclear
16975
16976 @node Stack Related Facilities
16977 @chapter Stack Related Facilities
16978
16979 @noindent
16980 This chapter describes some useful tools associated with stack
16981 checking and analysis. In
16982 particular, it deals with dynamic and static stack usage measurements.
16983
16984 @menu
16985 * Stack Overflow Checking::
16986 * Static Stack Usage Analysis::
16987 * Dynamic Stack Usage Analysis::
16988 @end menu
16989
16990 @node Stack Overflow Checking
16991 @section Stack Overflow Checking
16992 @cindex Stack Overflow Checking
16993 @cindex -fstack-check
16994
16995 @noindent
16996 For most operating systems, @command{gcc} does not perform stack overflow
16997 checking by default. This means that if the main environment task or
16998 some other task exceeds the available stack space, then unpredictable
16999 behavior will occur. Most native systems offer some level of protection by
17000 adding a guard page at the end of each task stack. This mechanism is usually
17001 not enough for dealing properly with stack overflow situations because
17002 a large local variable could ``jump'' above the guard page.
17003 Furthermore, when the
17004 guard page is hit, there may not be any space left on the stack for executing
17005 the exception propagation code. Enabling stack checking avoids
17006 such situations.
17007
17008 To activate stack checking, compile all units with the gcc option
17009 @option{-fstack-check}. For example:
17010
17011 @smallexample
17012 gcc -c -fstack-check package1.adb
17013 @end smallexample
17014
17015 @noindent
17016 Units compiled with this option will generate extra instructions to check
17017 that any use of the stack (for procedure calls or for declaring local
17018 variables in declare blocks) does not exceed the available stack space.
17019 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17020
17021 For declared tasks, the stack size is controlled by the size
17022 given in an applicable @code{Storage_Size} pragma or by the value specified
17023 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17024 the default size as defined in the GNAT runtime otherwise.
17025
17026 For the environment task, the stack size depends on
17027 system defaults and is unknown to the compiler. Stack checking
17028 may still work correctly if a fixed
17029 size stack is allocated, but this cannot be guaranteed.
17030 @ifclear vms
17031 To ensure that a clean exception is signalled for stack
17032 overflow, set the environment variable
17033 @env{GNAT_STACK_LIMIT} to indicate the maximum
17034 stack area that can be used, as in:
17035 @cindex GNAT_STACK_LIMIT
17036
17037 @smallexample
17038 SET GNAT_STACK_LIMIT 1600
17039 @end smallexample
17040
17041 @noindent
17042 The limit is given in kilobytes, so the above declaration would
17043 set the stack limit of the environment task to 1.6 megabytes.
17044 Note that the only purpose of this usage is to limit the amount
17045 of stack used by the environment task. If it is necessary to
17046 increase the amount of stack for the environment task, then this
17047 is an operating systems issue, and must be addressed with the
17048 appropriate operating systems commands.
17049 @end ifclear
17050 @ifset vms
17051 To have a fixed size stack in the environment task, the stack must be put
17052 in the P0 address space and its size specified.  Use these switches to
17053 create a p0 image:
17054
17055 @smallexample
17056 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17057 @end smallexample
17058
17059 @noindent
17060 The quotes are required to keep case.  The number after @samp{STACK=} is the
17061 size of the environmental task stack in pagelets (512 bytes).  In this example
17062 the stack size is about 2 megabytes.
17063
17064 @noindent
17065 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17066 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17067 more details about the @option{/p0image} qualifier and the @option{stack}
17068 option.
17069 @end ifset
17070
17071 @node Static Stack Usage Analysis
17072 @section Static Stack Usage Analysis
17073 @cindex Static Stack Usage Analysis
17074 @cindex -fstack-usage
17075
17076 @noindent
17077 A unit compiled with @option{-fstack-usage} will generate an extra file
17078 that specifies
17079 the maximum amount of stack used, on a per-function basis.
17080 The file has the same
17081 basename as the target object file with a @file{.su} extension.
17082 Each line of this file is made up of three fields:
17083
17084 @itemize
17085 @item
17086 The name of the function.
17087 @item
17088 A number of bytes.
17089 @item
17090 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17091 @end itemize
17092
17093 The second field corresponds to the size of the known part of the function
17094 frame.
17095
17096 The qualifier @code{static} means that the function frame size
17097 is purely static.
17098 It usually means that all local variables have a static size.
17099 In this case, the second field is a reliable measure of the function stack
17100 utilization.
17101
17102 The qualifier @code{dynamic} means that the function frame size is not static.
17103 It happens mainly when some local variables have a dynamic size. When this
17104 qualifier appears alone, the second field is not a reliable measure
17105 of the function stack analysis. When it is qualified with  @code{bounded}, it
17106 means that the second field is a reliable maximum of the function stack
17107 utilization.
17108
17109 @node Dynamic Stack Usage Analysis
17110 @section Dynamic Stack Usage Analysis
17111
17112 @noindent
17113 It is possible to measure the maximum amount of stack used by a task, by
17114 adding a switch to @command{gnatbind}, as:
17115
17116 @smallexample
17117 $ gnatbind -u0 file
17118 @end smallexample
17119
17120 @noindent
17121 With this option, at each task termination, its stack usage is  output on
17122 @file{stderr}.
17123 It is not always convenient to output the stack usage when the program
17124 is still running. Hence, it is possible to delay this output until program
17125 termination. for a given number of tasks specified as the argument of the
17126 @option{-u} option. For instance:
17127
17128 @smallexample
17129 $ gnatbind -u100 file
17130 @end smallexample
17131
17132 @noindent
17133 will buffer the stack usage information of the first 100 tasks to terminate and
17134 output this info at program termination. Results are displayed in four
17135 columns:
17136
17137 @noindent
17138 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17139
17140 @noindent
17141 where:
17142
17143 @table @emph
17144 @item Index
17145 is a number associated with each task.
17146
17147 @item Task Name
17148 is the name of the task analyzed.
17149
17150 @item Stack Size
17151 is the maximum size for the stack.
17152
17153 @item Stack Usage
17154 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17155 is not entirely analyzed, and it's not possible to know exactly how
17156 much has actually been used. The report thus contains the theoretical stack usage
17157 (Value) and the possible variation (Variation) around this value.
17158
17159 @end table
17160
17161 @noindent
17162 The environment task stack, e.g., the stack that contains the main unit, is
17163 only processed when the environment variable GNAT_STACK_LIMIT is set.
17164
17165
17166 @c *********************************
17167 @c *            GNATCHECK          *
17168 @c *********************************
17169 @node Verifying Properties Using gnatcheck
17170 @chapter Verifying Properties Using @command{gnatcheck}
17171 @findex gnatcheck
17172 @cindex @command{gnatcheck}
17173
17174 @noindent
17175 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17176 of Ada source files according to a given set of semantic rules.
17177 @cindex ASIS
17178
17179 In order to check compliance with a given rule, @command{gnatcheck} has to
17180 semantically analyze the Ada sources.
17181 Therefore, checks can only be performed on
17182 legal Ada units. Moreover, when a unit depends semantically upon units located
17183 outside the current directory, the source search path has to be provided when
17184 calling @command{gnatcheck}, either through a specified project file or
17185 through @command{gnatcheck} switches as described below.
17186
17187 A number of rules are predefined in @command{gnatcheck} and are described
17188 later in this chapter.
17189 You can also add new rules, by modifying the @command{gnatcheck} code and
17190 rebuilding the tool. In order to add a simple rule making some local checks,
17191 a small amount of straightforward ASIS-based programming is usually needed.
17192
17193 Project support for @command{gnatcheck} is provided by the GNAT
17194 driver (see @ref{The GNAT Driver and Project Files}).
17195
17196 Invoking @command{gnatcheck} on the command line has the form:
17197
17198 @smallexample
17199 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
17200 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17201 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17202 @c Expanding @ovar macro inline (explanation in macro def comments)
17203 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
17204       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
17205       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
17206 @end smallexample
17207
17208 @noindent
17209 where
17210 @itemize @bullet
17211 @item
17212 @var{switches} specify the general tool options
17213
17214 @item
17215 Each @var{filename} is the name (including the extension) of a source
17216 file to process. ``Wildcards'' are allowed, and
17217 the file name may contain path information.
17218
17219 @item
17220 Each @var{arg_list_filename} is the name (including the extension) of a text
17221 file containing the names of the source files to process, separated by spaces
17222 or line breaks.
17223
17224 @item
17225 @var{gcc_switches} is a list of switches for
17226 @command{gcc}. They will be passed on to all compiler invocations made by
17227 @command{gnatcheck} to generate the ASIS trees. Here you can provide
17228 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17229 and use the @option{-gnatec} switch to set the configuration file,
17230 use the @option{-gnat05} switch if sources should be compiled in
17231 Ada 2005 mode etc.
17232
17233 @item
17234 @var{rule_options} is a list of options for controlling a set of
17235 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
17236 @end itemize
17237
17238 @noindent
17239 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
17240 supplied.
17241
17242 @menu
17243 * Format of the Report File::
17244 * General gnatcheck Switches::
17245 * gnatcheck Rule Options::
17246 * Adding the Results of Compiler Checks to gnatcheck Output::
17247 * Project-Wide Checks::
17248 * Rule exemption::
17249 * Predefined Rules::
17250 * Example of gnatcheck Usage::
17251 @end menu
17252
17253 @node Format of the Report File
17254 @section Format of the Report File
17255 @cindex Report file (for @code{gnatcheck})
17256
17257 @noindent
17258 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
17259 rule violations.
17260 It also creates a text file  that
17261 contains the complete report of the last gnatcheck run. By default this file
17262 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
17263 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
17264 name and/or location of the report file. This report contains:
17265 @itemize @bullet
17266 @item date and time of @command{gnatcheck} run, the version of
17267 the tool that has generated this report and the full parameters
17268 of the  @command{gnatcheck} invocation;
17269 @item list of enabled rules;
17270 @item total number of detected violations;
17271 @item list of source files where rule violations have been detected;
17272 @item list of source files where no violations have been detected.
17273 @end itemize
17274
17275 @node General gnatcheck Switches
17276 @section General @command{gnatcheck} Switches
17277
17278 @noindent
17279 The following switches control the general @command{gnatcheck} behavior
17280
17281 @table @option
17282 @c !sort!
17283 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
17284 @item ^-a^/ALL^
17285 Process all units including those with read-only ALI files such as
17286 those from the GNAT Run-Time library.
17287
17288 @ifclear vms
17289 @ignore
17290 @cindex @option{-d} (@command{gnatcheck})
17291 @item -d
17292 Debug mode
17293 @end ignore
17294
17295 @cindex @option{-dd} (@command{gnatcheck})
17296 @item -dd
17297 Progress indicator mode (for use in GPS).
17298 @end ifclear
17299
17300 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
17301 @item ^-h^/HELP^
17302 List the predefined and user-defined rules. For more details see
17303 @ref{Predefined Rules}.
17304
17305 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
17306 @item ^-l^/LOCS^
17307 Use full source locations references in the report file. For a construct from
17308 a generic instantiation a full source location is a chain from the location
17309 of this construct in the generic unit to the place where this unit is
17310 instantiated.
17311
17312 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
17313 @item ^-log^/LOG^
17314 Duplicate all the output sent to @file{stderr} into a log file. The log file
17315 is named @file{gnatcheck.log} and is located in the current directory.
17316
17317 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
17318 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
17319 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
17320 the range 0@dots{}1000;
17321 the default value is 500. Zero means that there is no limitation on
17322 the number of diagnostic messages to be output.
17323
17324 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
17325 @item ^-q^/QUIET^
17326 Quiet mode. All the diagnostics about rule violations are placed in the
17327 @command{gnatcheck} report file only, without duplication on @file{stdout}.
17328
17329 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
17330 @item ^-s^/SHORT^
17331 Short format of the report file (no version information, no list of applied
17332 rules, no list of checked sources is included)
17333
17334 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
17335 @item ^--include-file^/INCLUDE_FILE^
17336 Append the content of the specified text file to the report file
17337
17338 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
17339 @item ^-t^/TIME^
17340 Print out execution time.
17341
17342 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
17343 @item ^-v^/VERBOSE^
17344 Verbose mode; @command{gnatcheck} generates version information and then
17345 a trace of sources being processed.
17346
17347 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
17348 @item ^-o ^/OUTPUT=^@var{report_file}
17349 Set name of report file file to @var{report_file} .
17350
17351 @end table
17352
17353 @node gnatcheck Rule Options
17354 @section @command{gnatcheck} Rule Options
17355
17356 @noindent
17357 The following options control the processing performed by
17358 @command{gnatcheck}.
17359
17360 @table @option
17361 @cindex @option{+ALL} (@command{gnatcheck})
17362 @item +ALL
17363 Turn all the rule checks ON.
17364
17365 @cindex @option{-ALL} (@command{gnatcheck})
17366 @item -ALL
17367 Turn all the rule checks OFF.
17368
17369 @cindex @option{+R} (@command{gnatcheck})
17370 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
17371 Turn on the check for a specified rule with the specified parameter, if any.
17372 @var{rule_id} must be the identifier of one of the currently implemented rules
17373 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
17374 are not case-sensitive. The @var{param} item must
17375 be a string representing a valid parameter(s) for the specified rule.
17376 If it contains any space characters then this string must be enclosed in
17377 quotation marks.
17378
17379 @cindex @option{-R} (@command{gnatcheck})
17380 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
17381 Turn off the check for a specified rule with the specified parameter, if any.
17382
17383 @cindex @option{-from} (@command{gnatcheck})
17384 @item -from=@var{rule_option_filename}
17385 Read the rule options from the text file @var{rule_option_filename}, referred
17386 to as a ``coding standard file'' below.
17387
17388 @end table
17389
17390 @noindent
17391 The default behavior is that all the rule checks are disabled.
17392
17393 A coding standard file is a text file that contains a set of rule options
17394 described above.
17395 @cindex Coding standard file (for @code{gnatcheck})
17396 The file may contain empty lines and Ada-style comments (comment
17397 lines and end-of-line comments). There can be several rule options on a
17398 single line (separated by a space).
17399
17400 A coding standard file may reference other coding standard files by including
17401 more @option{-from=@var{rule_option_filename}}
17402 options, each such option being replaced with the content of the
17403 corresponding coding standard file during processing. In case a
17404 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
17405 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
17406 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
17407 processing fails with an error message.
17408
17409
17410 @node Adding the Results of Compiler Checks to gnatcheck Output
17411 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
17412
17413 @noindent
17414 The @command{gnatcheck} tool can include in the generated diagnostic messages
17415 and in
17416 the report file the results of the checks performed by the compiler. Though
17417 disabled by default, this effect may be obtained by using @option{+R} with
17418 the following rule identifiers and parameters:
17419
17420 @table @option
17421 @item Restrictions
17422 To record restrictions violations (which are performed by the compiler if the
17423 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
17424 use the @code{Restrictions} rule
17425 with the same parameters as pragma
17426 @code{Restrictions} or @code{Restriction_Warnings}.
17427
17428 @item Style_Checks
17429 To record compiler style checks (@pxref{Style Checking}), use the
17430 @code{Style_Checks} rule.
17431 This rule takes a parameter in one of the following forms:
17432 @itemize
17433 @item
17434 @code{All_Checks},
17435 which enables the standard style checks corresponding to the @option{-gnatyy}
17436 GNAT style check option, or
17437
17438 @item
17439 a string with the same
17440 structure and semantics as the @code{string_LITERAL} parameter of the
17441 GNAT pragma @code{Style_Checks}
17442 (for further information about this pragma,
17443 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
17444 @end itemize
17445
17446 @noindent
17447 For example, the
17448 @code{+RStyle_Checks:O} rule option activates
17449 the compiler style check that corresponds to
17450 @code{-gnatyO} style check option.
17451
17452 @item Warnings
17453 To record compiler warnings (@pxref{Warning Message Control}), use the
17454 @code{Warnings} rule with a parameter that is a valid
17455 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
17456 (for further information about this pragma,
17457 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
17458 Note that in case of gnatcheck
17459 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
17460 all the specific warnings, but not suppresses the warning mode,
17461 and 'e' parameter, corresponding to @option{-gnatwe} that means
17462 "treat warnings as errors", does not have any effect.
17463
17464 @end table
17465
17466 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
17467 option with the corresponding restriction name as a parameter. @code{-R} is
17468 not available for @code{Style_Checks} and @code{Warnings} options, to disable
17469 warnings and style checks, use the corresponding warning and style options.
17470
17471 @node Project-Wide Checks
17472 @section Project-Wide Checks
17473 @cindex Project-wide checks (for @command{gnatcheck})
17474
17475 @noindent
17476 In order to perform checks on all units of a given project, you can use
17477 the GNAT driver along with the @option{-P} option:
17478 @smallexample
17479    gnat check -Pproj -rules -from=my_rules
17480 @end smallexample
17481
17482 @noindent
17483 If the project @code{proj} depends upon other projects, you can perform
17484 checks on the project closure using the @option{-U} option:
17485 @smallexample
17486    gnat check -Pproj -U -rules -from=my_rules
17487 @end smallexample
17488
17489 @noindent
17490 Finally, if not all the units are relevant to a particular main
17491 program in the project closure, you can perform checks for the set
17492 of units needed to create a given main program (unit closure) using
17493 the @option{-U} option followed by the name of the main unit:
17494 @smallexample
17495    gnat check -Pproj -U main -rules -from=my_rules
17496 @end smallexample
17497
17498
17499 @node Rule exemption
17500 @section Rule exemption
17501 @cindex Rule exemption (for @command{gnatcheck})
17502
17503 @noindent
17504 One of the most useful applications of @command{gnatcheck} is to
17505 automate the enforcement of project-specific coding standards,
17506 for example in safety-critical systems where particular features
17507 must be restricted in order to simplify the certification effort.
17508 However, it may sometimes be appropriate to violate a coding standard rule,
17509 and in such cases the rationale for the violation should be provided
17510 in the source program itself so that the individuals
17511 reviewing or maintaining the program can immediately understand the intent.
17512
17513 The @command{gnatcheck} tool supports this practice with the notion of
17514 a ``rule exemption'' covering a specific source code section. Normally
17515 rule violation messages are issued both on @file{stderr}
17516 and in a report file. In contrast, exempted violations are not listed on
17517 @file{stderr}; thus users invoking @command{gnatcheck} interactively
17518 (e.g. in its GPS interface) do not need to pay attention to known and
17519 justified violations. However, exempted violations along with their
17520 justification are documented in a special section of the report file that
17521 @command{gnatcheck} generates.
17522
17523 @menu
17524 * Using pragma Annotate to Control Rule Exemption::
17525 * gnatcheck Annotations Rules::
17526 @end menu
17527
17528 @node Using pragma Annotate to Control Rule Exemption
17529 @subsection Using pragma @code{Annotate} to Control Rule Exemption
17530 @cindex Using pragma Annotate to control rule exemption
17531
17532 @noindent
17533 Rule exemption is controlled by pragma @code{Annotate} when its first
17534 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
17535 exemption control annotations is as follows:
17536
17537 @smallexample @c ada
17538 @group
17539 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
17540
17541 @i{exemption_control} ::= Exempt_On | Exempt_Off
17542
17543 @i{Rule_Name}         ::= string_literal
17544
17545 @i{justification}     ::= string_literal
17546 @end group
17547 @end smallexample
17548
17549 @noindent
17550 When a @command{gnatcheck} annotation has more then four arguments,
17551 @command{gnatcheck} issues a warning and ignores the additional arguments.
17552 If the additional arguments do not follow the syntax above,
17553 @command{gnatcheck} emits a warning and ignores the annotation.
17554
17555 The @i{@code{Rule_Name}} argument should be the name of some existing
17556 @command{gnatcheck} rule.
17557 Otherwise a warning message is generated and the pragma is
17558 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
17559 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
17560
17561 A source code section where an exemption is active for a given rule is
17562 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
17563
17564 @smallexample @c ada
17565 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
17566 -- source code section
17567 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
17568 @end smallexample
17569
17570
17571 @node gnatcheck Annotations Rules
17572 @subsection @command{gnatcheck} Annotations Rules
17573 @cindex @command{gnatcheck} annotations rules
17574
17575 @itemize @bullet
17576
17577 @item
17578 An ``Exempt_Off'' annotation can only appear after a corresponding
17579 ``Exempt_On'' annotation.
17580
17581 @item
17582 Exempted source code sections are only based on the source location of the
17583 annotations. Any source construct between the two
17584 annotations is part of the exempted source code section.
17585
17586 @item
17587 Exempted source code sections for different rules are independent. They can
17588 be nested or intersect with one another without limitation.
17589 Creating nested or intersecting source code sections for the same rule is
17590 not allowed.
17591
17592 @item
17593 Malformed exempted source code sections are reported by a warning, and
17594 the corresponding rule exemptions are ignored.
17595
17596 @item
17597 When an exempted source code section does not contain at least one violation
17598 of the exempted rule, a warning is emitted on @file{stderr}.
17599
17600 @item
17601 If an ``Exempt_On'' annotation pragma does not have a matching
17602 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
17603 exemption for the given rule is ignored and a warning is issued.
17604 @end itemize
17605
17606
17607 @node Predefined Rules
17608 @section Predefined Rules
17609 @cindex Predefined rules (for @command{gnatcheck})
17610
17611 @ignore
17612 @c (Jan 2007) Since the global rules are still under development and are not
17613 @c documented, there is no point in explaining the difference between
17614 @c global and local rules
17615 @noindent
17616 A rule in @command{gnatcheck} is either local or global.
17617 A @emph{local rule} is a rule that applies to a well-defined section
17618 of a program and that can be checked by analyzing only this section.
17619 A @emph{global rule} requires analysis of some global properties of the
17620 whole program (mostly related to the program call graph).
17621 As of @value{NOW}, the implementation of global rules should be
17622 considered to be at a preliminary stage. You can use the
17623 @option{+GLOBAL} option to enable all the global rules, and the
17624 @option{-GLOBAL} rule option to disable all the global rules.
17625
17626 All the global rules in the list below are
17627 so indicated by marking them ``GLOBAL''.
17628 This +GLOBAL and -GLOBAL options are not
17629 included in the list of gnatcheck options above, because at the moment they
17630 are considered as a temporary debug options.
17631
17632 @command{gnatcheck} performs rule checks for generic
17633 instances only for global rules.  This limitation may be relaxed in a later
17634 release.
17635 @end ignore
17636
17637 @noindent
17638 The predefined rules implemented in @command{gnatcheck}
17639 are described in a companion document,
17640 @cite{GNATcheck Reference Manual -- Predefined Rules}.
17641 The rule identifier is
17642 used as a parameter of @command{gnatcheck}'s @option{+R} or @option{-R}
17643 switches.
17644
17645
17646 @node Example of gnatcheck Usage
17647 @section Example of @command{gnatcheck} Usage
17648
17649 @noindent
17650 Here is a simple example. Suppose that in the current directory we have a
17651 project file named @file{gnatcheck_example.gpr} with the following content:
17652
17653 @smallexample @c projectfile
17654 project Gnatcheck_Example is
17655
17656    for Source_Dirs use ("src");
17657    for Object_Dir use "obj";
17658    for Main use ("main.adb");
17659
17660    package Check is
17661       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
17662    end Check;
17663
17664 end Gnatcheck_Example;
17665 @end smallexample
17666
17667 @noindent
17668 And the file named @file{coding_standard} is also located in the current
17669 directory and has the following content:
17670
17671 @smallexample
17672 -----------------------------------------------------
17673 -- This is a sample gnatcheck coding standard file --
17674 -----------------------------------------------------
17675
17676 --  First, turning on rules, that are directly implemented in gnatcheck
17677 +RAbstract_Type_Declarations
17678 +RAnonymous_Arrays
17679 +RLocal_Packages
17680 +RFloat_Equality_Checks
17681 +REXIT_Statements_With_No_Loop_Name
17682
17683 --  Then, activating compiler checks of interest:
17684 +RStyle_Checks:e
17685 --  This style check checks if a unit name is present on END keyword that
17686 --  is the end of the unit declaration
17687 @end smallexample
17688
17689 @noindent
17690 And the subdirectory @file{src} contains the following Ada sources:
17691
17692 @file{pack.ads}:
17693
17694 @smallexample @c ada
17695 package Pack is
17696    type T is abstract tagged private;
17697    procedure P (X : T) is abstract;
17698
17699    package Inner is
17700       type My_Float is digits 8;
17701       function Is_Equal (L, R : My_Float) return Boolean;
17702    end Inner;
17703 private
17704    type T is abstract tagged null record;
17705 end;
17706 @end smallexample
17707
17708 @noindent
17709 @file{pack.adb}:
17710
17711 @smallexample @c ada
17712 package body Pack is
17713    package body Inner is
17714       function Is_Equal (L, R : My_Float) return Boolean is
17715       begin
17716          return L = R;
17717       end;
17718    end Inner;
17719 end Pack;
17720 @end smallexample
17721
17722 @noindent
17723 and @file{main.adb}
17724
17725 @smallexample @c ada
17726 with Pack; use Pack;
17727 procedure Main is
17728
17729    pragma Annotate
17730      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
17731    Float_Array : array (1 .. 10) of Inner.My_Float;
17732    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
17733
17734    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
17735
17736    use Inner;
17737
17738    B : Boolean := False;
17739
17740 begin
17741    for J in Float_Array'Range loop
17742       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
17743          B := True;
17744          exit;
17745       end if;
17746    end loop;
17747 end Main;
17748 @end smallexample
17749
17750 @noindent
17751 And suppose we call @command{gnatcheck} from the current directory using
17752 the @command{gnat} driver:
17753
17754 @smallexample
17755    gnat check -Pgnatcheck_example.gpr
17756 @end smallexample
17757
17758 @noindent
17759 As a result, @command{gnatcheck} is called to check all the files from the
17760 project @file{gnatcheck_example.gpr} using the coding standard defined by
17761 the file @file{coding_standard}. As the result, the @command{gnatcheck}
17762 report file named @file{gnatcheck.out} will be created in the current
17763 directory, and it will have the following content:
17764
17765 @smallexample
17766 RULE CHECKING REPORT
17767
17768 1. OVERVIEW
17769
17770 Date and time of execution: 2009.10.28 14:17
17771 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
17772 Command line:
17773
17774 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
17775
17776 Coding standard (applied rules):
17777    Abstract_Type_Declarations
17778    Anonymous_Arrays
17779    EXIT_Statements_With_No_Loop_Name
17780    Float_Equality_Checks
17781    Local_Packages
17782
17783    Compiler style checks: -gnatye
17784
17785 Number of coding standard violations: 6
17786 Number of exempted coding standard violations: 1
17787
17788 2. DETECTED RULE VIOLATIONS
17789
17790 2.1. NON-EXEMPTED VIOLATIONS
17791
17792 Source files with non-exempted violations
17793    pack.ads
17794    pack.adb
17795    main.adb
17796
17797 List of violations grouped by files, and ordered by increasing source location:
17798
17799 pack.ads:2:4: declaration of abstract type
17800 pack.ads:5:4: declaration of local package
17801 pack.ads:10:30: declaration of abstract type
17802 pack.ads:11:1: (style) "end Pack" required
17803 pack.adb:5:19: use of equality operation for float values
17804 pack.adb:6:7: (style) "end Is_Equal" required
17805 main.adb:9:26: anonymous array type
17806 main.adb:19:10: exit statement with no loop name
17807
17808 2.2. EXEMPTED VIOLATIONS
17809
17810 Source files with exempted violations
17811    main.adb
17812
17813 List of violations grouped by files, and ordered by increasing source location:
17814
17815 main.adb:6:18: anonymous array type
17816    (this one is fine)
17817
17818 2.3. SOURCE FILES WITH NO VIOLATION
17819
17820    No files without violations
17821
17822 END OF REPORT
17823 @end smallexample
17824
17825
17826 @c *********************************
17827 @node Creating Sample Bodies Using gnatstub
17828 @chapter Creating Sample Bodies Using @command{gnatstub}
17829 @findex gnatstub
17830
17831 @noindent
17832 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17833 for library unit declarations.
17834
17835 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17836 driver (see @ref{The GNAT Driver and Project Files}).
17837
17838 To create a body stub, @command{gnatstub} has to compile the library
17839 unit declaration. Therefore, bodies can be created only for legal
17840 library units. Moreover, if a library unit depends semantically upon
17841 units located outside the current directory, you have to provide
17842 the source search path when calling @command{gnatstub}, see the description
17843 of @command{gnatstub} switches below.
17844
17845 By default, all the program unit body stubs generated by @code{gnatstub}
17846 raise the predefined @code{Program_Error} exception, which will catch
17847 accidental calls of generated stubs. This behavior can be changed with
17848 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17849
17850 @menu
17851 * Running gnatstub::
17852 * Switches for gnatstub::
17853 @end menu
17854
17855 @node Running gnatstub
17856 @section Running @command{gnatstub}
17857
17858 @noindent
17859 @command{gnatstub} has the command-line interface of the form
17860
17861 @smallexample
17862 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17863 @c Expanding @ovar macro inline (explanation in macro def comments)
17864 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17865 @end smallexample
17866
17867 @noindent
17868 where
17869 @table @var
17870 @item filename
17871 is the name of the source file that contains a library unit declaration
17872 for which a body must be created. The file name may contain the path
17873 information.
17874 The file name does not have to follow the GNAT file name conventions. If the
17875 name
17876 does not follow GNAT file naming conventions, the name of the body file must
17877 be provided
17878 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17879 If the file name follows the GNAT file naming
17880 conventions and the name of the body file is not provided,
17881 @command{gnatstub}
17882 creates the name
17883 of the body file from the argument file name by replacing the @file{.ads}
17884 suffix
17885 with the @file{.adb} suffix.
17886
17887 @item directory
17888 indicates the directory in which the body stub is to be placed (the default
17889 is the
17890 current directory)
17891
17892 @item @samp{@var{gcc_switches}} is a list of switches for
17893 @command{gcc}. They will be passed on to all compiler invocations made by
17894 @command{gnatelim} to generate the ASIS trees. Here you can provide
17895 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17896 use the @option{-gnatec} switch to set the configuration file,
17897 use the @option{-gnat05} switch if sources should be compiled in
17898 Ada 2005 mode etc.
17899
17900 @item switches
17901 is an optional sequence of switches as described in the next section
17902 @end table
17903
17904 @node Switches for gnatstub
17905 @section Switches for @command{gnatstub}
17906
17907 @table @option
17908 @c !sort!
17909
17910 @item ^-f^/FULL^
17911 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17912 If the destination directory already contains a file with the name of the
17913 body file
17914 for the argument spec file, replace it with the generated body stub.
17915
17916 @item ^-hs^/HEADER=SPEC^
17917 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17918 Put the comment header (i.e., all the comments preceding the
17919 compilation unit) from the source of the library unit declaration
17920 into the body stub.
17921
17922 @item ^-hg^/HEADER=GENERAL^
17923 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17924 Put a sample comment header into the body stub.
17925
17926 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17927 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17928 Use the content of the file as the comment header for a generated body stub.
17929
17930 @ifclear vms
17931 @item -IDIR
17932 @cindex @option{-IDIR} (@command{gnatstub})
17933 @itemx -I-
17934 @cindex @option{-I-} (@command{gnatstub})
17935 @end ifclear
17936 @ifset vms
17937 @item /NOCURRENT_DIRECTORY
17938 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17939 @end ifset
17940 ^These switches have ^This switch has^ the same meaning as in calls to
17941 @command{gcc}.
17942 ^They define ^It defines ^ the source search path in the call to
17943 @command{gcc} issued
17944 by @command{gnatstub} to compile an argument source file.
17945
17946 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17947 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17948 This switch has the same meaning as in calls to @command{gcc}.
17949 It defines the additional configuration file to be passed to the call to
17950 @command{gcc} issued
17951 by @command{gnatstub} to compile an argument source file.
17952
17953 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17954 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17955 (@var{n} is a non-negative integer). Set the maximum line length in the
17956 body stub to @var{n}; the default is 79. The maximum value that can be
17957 specified is 32767. Note that in the special case of configuration
17958 pragma files, the maximum is always 32767 regardless of whether or
17959 not this switch appears.
17960
17961 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17962 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17963 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17964 the generated body sample to @var{n}.
17965 The default indentation is 3.
17966
17967 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17968 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17969 Order local bodies alphabetically. (By default local bodies are ordered
17970 in the same way as the corresponding local specs in the argument spec file.)
17971
17972 @item ^-i^/INDENTATION=^@var{n}
17973 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17974 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17975
17976 @item ^-k^/TREE_FILE=SAVE^
17977 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17978 Do not remove the tree file (i.e., the snapshot of the compiler internal
17979 structures used by @command{gnatstub}) after creating the body stub.
17980
17981 @item ^-l^/LINE_LENGTH=^@var{n}
17982 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17983 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17984
17985 @item ^--no-exception^/NO_EXCEPTION^
17986 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17987 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17988 This is not always possible for function stubs.
17989
17990 @item ^--no-local-header^/NO_LOCAL_HEADER^
17991 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17992 Do not place local comment header with unit name before body stub for a
17993 unit.
17994
17995 @item ^-o ^/BODY=^@var{body-name}
17996 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17997 Body file name.  This should be set if the argument file name does not
17998 follow
17999 the GNAT file naming
18000 conventions. If this switch is omitted the default name for the body will be
18001 obtained
18002 from the argument file name according to the GNAT file naming conventions.
18003
18004 @item ^-q^/QUIET^
18005 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18006 Quiet mode: do not generate a confirmation when a body is
18007 successfully created, and do not generate a message when a body is not
18008 required for an
18009 argument unit.
18010
18011 @item ^-r^/TREE_FILE=REUSE^
18012 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18013 Reuse the tree file (if it exists) instead of creating it.  Instead of
18014 creating the tree file for the library unit declaration, @command{gnatstub}
18015 tries to find it in the current directory and use it for creating
18016 a body. If the tree file is not found, no body is created. This option
18017 also implies @option{^-k^/SAVE^}, whether or not
18018 the latter is set explicitly.
18019
18020 @item ^-t^/TREE_FILE=OVERWRITE^
18021 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18022 Overwrite the existing tree file.  If the current directory already
18023 contains the file which, according to the GNAT file naming rules should
18024 be considered as a tree file for the argument source file,
18025 @command{gnatstub}
18026 will refuse to create the tree file needed to create a sample body
18027 unless this option is set.
18028
18029 @item ^-v^/VERBOSE^
18030 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18031 Verbose mode: generate version information.
18032
18033 @end table
18034
18035 @c *********************************
18036 @node Generating Ada Bindings for C and C++ headers
18037 @chapter Generating Ada Bindings for C and C++ headers
18038 @findex binding
18039
18040 @noindent
18041 GNAT now comes with a binding generator for C and C++ headers which is
18042 intended to do 95% of the tedious work of generating Ada specs from C
18043 or C++ header files.
18044
18045 Note that this capability is not intended to generate 100% correct Ada specs,
18046 and will is some cases require manual adjustments, although it can often
18047 be used out of the box in practice.
18048
18049 Some of the known limitations include:
18050
18051 @itemize @bullet
18052 @item only very simple character constant macros are translated into Ada
18053 constants. Function macros (macros with arguments) are partially translated
18054 as comments, to be completed manually if needed.
18055 @item some extensions (e.g. vector types) are not supported
18056 @item pointers to pointers or complex structures are mapped to System.Address
18057 @end itemize
18058
18059 The code generated is using the Ada 2005 syntax, which makes it
18060 easier to interface with other languages than previous versions of Ada.
18061
18062 @menu
18063 * Running the binding generator::
18064 * Generating bindings for C++ headers::
18065 * Switches::
18066 @end menu
18067
18068 @node Running the binding generator
18069 @section Running the binding generator
18070
18071 @noindent
18072 The binding generator is part of the @command{gcc} compiler and can be
18073 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18074 spec files for the header files specified on the command line, and all
18075 header files needed by these files transitivitely. For example:
18076
18077 @smallexample
18078 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18079 $ gcc -c -gnat05 *.ads
18080 @end smallexample
18081
18082 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18083 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18084 correspond to the files @file{/usr/include/time.h},
18085 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18086 mode these Ada specs.
18087
18088 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18089 and will attempt to generate corresponding Ada comments.
18090
18091 If you want to generate a single Ada file and not the transitive closure, you
18092 can use instead the @option{-fdump-ada-spec-slim} switch.
18093
18094 Note that we recommend when possible to use the @command{g++} driver to
18095 generate bindings, even for most C headers, since this will in general
18096 generate better Ada specs. For generating bindings for C++ headers, it is
18097 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18098 is equivalent in this case. If @command{g++} cannot work on your C headers
18099 because of incompatibilities between C and C++, then you can fallback to
18100 @command{gcc} instead.
18101
18102 For an example of better bindings generated from the C++ front-end,
18103 the name of the parameters (when available) are actually ignored by the C
18104 front-end. Consider the following C header:
18105
18106 @smallexample
18107 extern void foo (int variable);
18108 @end smallexample
18109
18110 with the C front-end, @code{variable} is ignored, and the above is handled as:
18111
18112 @smallexample
18113 extern void foo (int);
18114 @end smallexample
18115
18116 generating a generic:
18117
18118 @smallexample
18119 procedure foo (param1 : int);
18120 @end smallexample
18121
18122 with the C++ front-end, the name is available, and we generate:
18123
18124 @smallexample
18125 procedure foo (variable : int);
18126 @end smallexample
18127
18128 In some cases, the generated bindings will be more complete or more meaningful
18129 when defining some macros, which you can do via the @option{-D} switch. This
18130 is for example the case with @file{Xlib.h} under GNU/Linux:
18131
18132 @smallexample
18133 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18134 @end smallexample
18135
18136 The above will generate more complete bindings than a straight call without
18137 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18138
18139 In other cases, it is not possible to parse a header file in a stand alone
18140 manner, because other include files need to be included first. In this
18141 case, the solution is to create a small header file including the needed
18142 @code{#include} and possible @code{#define} directives. For example, to
18143 generate Ada bindings for @file{readline/readline.h}, you need to first
18144 include @file{stdio.h}, so you can create a file with the following two
18145 lines in e.g. @file{readline1.h}:
18146
18147 @smallexample
18148 #include <stdio.h>
18149 #include <readline/readline.h>
18150 @end smallexample
18151
18152 and then generate Ada bindings from this file:
18153
18154 @smallexample
18155 $ g++ -c -fdump-ada-spec readline1.h
18156 @end smallexample
18157
18158 @node Generating bindings for C++ headers
18159 @section Generating bindings for C++ headers
18160
18161 @noindent
18162 Generating bindings for C++ headers is done using the same options, always
18163 with the @command{g++} compiler.
18164
18165 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18166 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18167 multiple inheritance of abstract classes will be mapped to Ada interfaces
18168 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18169 information on interfacing to C++).
18170
18171 For example, given the following C++ header file:
18172
18173 @smallexample
18174 @group
18175 @cartouche
18176 class Carnivore @{
18177 public:
18178    virtual int Number_Of_Teeth () = 0;
18179 @};
18180
18181 class Domestic @{
18182 public:
18183    virtual void Set_Owner (char* Name) = 0;
18184 @};
18185
18186 class Animal @{
18187 public:
18188   int Age_Count;
18189   virtual void Set_Age (int New_Age);
18190 @};
18191
18192 class Dog : Animal, Carnivore, Domestic @{
18193  public:
18194   int  Tooth_Count;
18195   char *Owner;
18196
18197   virtual int  Number_Of_Teeth ();
18198   virtual void Set_Owner (char* Name);
18199
18200   Dog();
18201 @};
18202 @end cartouche
18203 @end group
18204 @end smallexample
18205
18206 The corresponding Ada code is generated:
18207
18208 @smallexample @c ada
18209 @group
18210 @cartouche
18211   package Class_Carnivore is
18212     type Carnivore is limited interface;
18213     pragma Import (CPP, Carnivore);
18214
18215     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18216   end;
18217   use Class_Carnivore;
18218
18219   package Class_Domestic is
18220     type Domestic is limited interface;
18221     pragma Import (CPP, Domestic);
18222
18223     procedure Set_Owner
18224       (this : access Domestic;
18225        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18226   end;
18227   use Class_Domestic;
18228
18229   package Class_Animal is
18230     type Animal is tagged limited record
18231       Age_Count : aliased int;
18232     end record;
18233     pragma Import (CPP, Animal);
18234
18235     procedure Set_Age (this : access Animal; New_Age : int);
18236     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18237   end;
18238   use Class_Animal;
18239
18240   package Class_Dog is
18241     type Dog is new Animal and Carnivore and Domestic with record
18242       Tooth_Count : aliased int;
18243       Owner : Interfaces.C.Strings.chars_ptr;
18244     end record;
18245     pragma Import (CPP, Dog);
18246
18247     function Number_Of_Teeth (this : access Dog) return int;
18248     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18249
18250     procedure Set_Owner
18251       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18252     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18253
18254     function New_Dog return Dog;
18255     pragma CPP_Constructor (New_Dog);
18256     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18257   end;
18258   use Class_Dog;
18259 @end cartouche
18260 @end group
18261 @end smallexample
18262
18263 @node Switches
18264 @section Switches
18265
18266 @table @option
18267 @item -fdump-ada-spec
18268 @cindex @option{-fdump-ada-spec} (@command{gcc})
18269 Generate Ada spec files for the given header files transitively (including
18270 all header files that these headers depend upon).
18271
18272 @item -fdump-ada-spec-slim
18273 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18274 Generate Ada spec files for the header files specified on the command line
18275 only.
18276
18277 @item -C
18278 @cindex @option{-C} (@command{gcc})
18279 Extract comments from headers and generate Ada comments in the Ada spec files.
18280 @end table
18281
18282 @node Other Utility Programs
18283 @chapter Other Utility Programs
18284
18285 @noindent
18286 This chapter discusses some other utility programs available in the Ada
18287 environment.
18288
18289 @menu
18290 * Using Other Utility Programs with GNAT::
18291 * The External Symbol Naming Scheme of GNAT::
18292 * Converting Ada Files to html with gnathtml::
18293 * Installing gnathtml::
18294 @ifset vms
18295 * LSE::
18296 * Profiling::
18297 @end ifset
18298 @end menu
18299
18300 @node Using Other Utility Programs with GNAT
18301 @section Using Other Utility Programs with GNAT
18302
18303 @noindent
18304 The object files generated by GNAT are in standard system format and in
18305 particular the debugging information uses this format. This means
18306 programs generated by GNAT can be used with existing utilities that
18307 depend on these formats.
18308
18309 @ifclear vms
18310 In general, any utility program that works with C will also often work with
18311 Ada programs generated by GNAT. This includes software utilities such as
18312 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18313 as Purify.
18314 @end ifclear
18315
18316 @node The External Symbol Naming Scheme of GNAT
18317 @section The External Symbol Naming Scheme of GNAT
18318
18319 @noindent
18320 In order to interpret the output from GNAT, when using tools that are
18321 originally intended for use with other languages, it is useful to
18322 understand the conventions used to generate link names from the Ada
18323 entity names.
18324
18325 All link names are in all lowercase letters. With the exception of library
18326 procedure names, the mechanism used is simply to use the full expanded
18327 Ada name with dots replaced by double underscores. For example, suppose
18328 we have the following package spec:
18329
18330 @smallexample @c ada
18331 @group
18332 @cartouche
18333 package QRS is
18334    MN : Integer;
18335 end QRS;
18336 @end cartouche
18337 @end group
18338 @end smallexample
18339
18340 @noindent
18341 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18342 the corresponding link name is @code{qrs__mn}.
18343 @findex Export
18344 Of course if a @code{pragma Export} is used this may be overridden:
18345
18346 @smallexample @c ada
18347 @group
18348 @cartouche
18349 package Exports is
18350    Var1 : Integer;
18351    pragma Export (Var1, C, External_Name => "var1_name");
18352    Var2 : Integer;
18353    pragma Export (Var2, C, Link_Name => "var2_link_name");
18354 end Exports;
18355 @end cartouche
18356 @end group
18357 @end smallexample
18358
18359 @noindent
18360 In this case, the link name for @var{Var1} is whatever link name the
18361 C compiler would assign for the C function @var{var1_name}. This typically
18362 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18363 system conventions, but other possibilities exist. The link name for
18364 @var{Var2} is @var{var2_link_name}, and this is not operating system
18365 dependent.
18366
18367 @findex _main
18368 One exception occurs for library level procedures. A potential ambiguity
18369 arises between the required name @code{_main} for the C main program,
18370 and the name we would otherwise assign to an Ada library level procedure
18371 called @code{Main} (which might well not be the main program).
18372
18373 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18374 names. So if we have a library level procedure such as
18375
18376 @smallexample @c ada
18377 @group
18378 @cartouche
18379 procedure Hello (S : String);
18380 @end cartouche
18381 @end group
18382 @end smallexample
18383
18384 @noindent
18385 the external name of this procedure will be @var{_ada_hello}.
18386
18387
18388 @node Converting Ada Files to html with gnathtml
18389 @section Converting Ada Files to HTML with @code{gnathtml}
18390
18391 @noindent
18392 This @code{Perl} script allows Ada source files to be browsed using
18393 standard Web browsers. For installation procedure, see the section
18394 @xref{Installing gnathtml}.
18395
18396 Ada reserved keywords are highlighted in a bold font and Ada comments in
18397 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18398 switch to suppress the generation of cross-referencing information, user
18399 defined variables and types will appear in a different color; you will
18400 be able to click on any identifier and go to its declaration.
18401
18402 The command line is as follow:
18403 @smallexample
18404 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18405 @c Expanding @ovar macro inline (explanation in macro def comments)
18406 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18407 @end smallexample
18408
18409 @noindent
18410 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18411 an html file for every ada file, and a global file called @file{index.htm}.
18412 This file is an index of every identifier defined in the files.
18413
18414 The available ^switches^options^ are the following ones:
18415
18416 @table @option
18417 @item -83
18418 @cindex @option{-83} (@code{gnathtml})
18419 Only the Ada 83 subset of keywords will be highlighted.
18420
18421 @item -cc @var{color}
18422 @cindex @option{-cc} (@code{gnathtml})
18423 This option allows you to change the color used for comments. The default
18424 value is green. The color argument can be any name accepted by html.
18425
18426 @item -d
18427 @cindex @option{-d} (@code{gnathtml})
18428 If the Ada files depend on some other files (for instance through
18429 @code{with} clauses, the latter files will also be converted to html.
18430 Only the files in the user project will be converted to html, not the files
18431 in the run-time library itself.
18432
18433 @item -D
18434 @cindex @option{-D} (@code{gnathtml})
18435 This command is the same as @option{-d} above, but @command{gnathtml} will
18436 also look for files in the run-time library, and generate html files for them.
18437
18438 @item -ext @var{extension}
18439 @cindex @option{-ext} (@code{gnathtml})
18440 This option allows you to change the extension of the generated HTML files.
18441 If you do not specify an extension, it will default to @file{htm}.
18442
18443 @item -f
18444 @cindex @option{-f} (@code{gnathtml})
18445 By default, gnathtml will generate html links only for global entities
18446 ('with'ed units, global variables and types,@dots{}).  If you specify
18447 @option{-f} on the command line, then links will be generated for local
18448 entities too.
18449
18450 @item -l @var{number}
18451 @cindex @option{-l} (@code{gnathtml})
18452 If this ^switch^option^ is provided and @var{number} is not 0, then
18453 @code{gnathtml} will number the html files every @var{number} line.
18454
18455 @item -I @var{dir}
18456 @cindex @option{-I} (@code{gnathtml})
18457 Specify a directory to search for library files (@file{.ALI} files) and
18458 source files. You can provide several -I switches on the command line,
18459 and the directories will be parsed in the order of the command line.
18460
18461 @item -o @var{dir}
18462 @cindex @option{-o} (@code{gnathtml})
18463 Specify the output directory for html files. By default, gnathtml will
18464 saved the generated html files in a subdirectory named @file{html/}.
18465
18466 @item -p @var{file}
18467 @cindex @option{-p} (@code{gnathtml})
18468 If you are using Emacs and the most recent Emacs Ada mode, which provides
18469 a full Integrated Development Environment for compiling, checking,
18470 running and debugging applications, you may use @file{.gpr} files
18471 to give the directories where Emacs can find sources and object files.
18472
18473 Using this ^switch^option^, you can tell gnathtml to use these files.
18474 This allows you to get an html version of your application, even if it
18475 is spread over multiple directories.
18476
18477 @item -sc @var{color}
18478 @cindex @option{-sc} (@code{gnathtml})
18479 This ^switch^option^ allows you to change the color used for symbol
18480 definitions.
18481 The default value is red. The color argument can be any name accepted by html.
18482
18483 @item -t @var{file}
18484 @cindex @option{-t} (@code{gnathtml})
18485 This ^switch^option^ provides the name of a file. This file contains a list of
18486 file names to be converted, and the effect is exactly as though they had
18487 appeared explicitly on the command line. This
18488 is the recommended way to work around the command line length limit on some
18489 systems.
18490
18491 @end table
18492
18493 @node Installing gnathtml
18494 @section Installing @code{gnathtml}
18495
18496 @noindent
18497 @code{Perl} needs to be installed on your machine to run this script.
18498 @code{Perl} is freely available for almost every architecture and
18499 Operating System via the Internet.
18500
18501 On Unix systems, you  may want to modify  the  first line of  the script
18502 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18503 is. The syntax of this line is:
18504 @smallexample
18505 #!full_path_name_to_perl
18506 @end smallexample
18507
18508 @noindent
18509 Alternatively, you may run the script using the following command line:
18510
18511 @smallexample
18512 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18513 @c Expanding @ovar macro inline (explanation in macro def comments)
18514 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18515 @end smallexample
18516
18517 @ifset vms
18518 @node LSE
18519 @section LSE
18520 @findex LSE
18521
18522 @noindent
18523 The GNAT distribution provides an Ada 95 template for the HP Language
18524 Sensitive Editor (LSE), a component of DECset. In order to
18525 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18526
18527 @node Profiling
18528 @section Profiling
18529 @findex PCA
18530
18531 @noindent
18532 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18533 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18534 the collection phase with the /DEBUG qualifier.
18535
18536 @smallexample
18537 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18538 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18539 $ RUN/DEBUG <PROGRAM_NAME>
18540 @end smallexample
18541 @noindent
18542 @end ifset
18543
18544 @ifclear vms
18545 @c ******************************
18546 @node Code Coverage and Profiling
18547 @chapter Code Coverage and Profiling
18548 @cindex Code Coverage
18549 @cindex Profiling
18550
18551 @noindent
18552 This chapter describes how to use @code{gcov} - coverage testing tool - and
18553 @code{gprof} - profiler tool - on your Ada programs.
18554
18555 @menu
18556 * Code Coverage of Ada Programs using gcov::
18557 * Profiling an Ada Program using gprof::
18558 @end menu
18559
18560 @node Code Coverage of Ada Programs using gcov
18561 @section Code Coverage of Ada Programs using gcov
18562 @cindex gcov
18563 @cindex -fprofile-arcs
18564 @cindex -ftest-coverage
18565 @cindex -coverage
18566 @cindex Code Coverage
18567
18568 @noindent
18569 @code{gcov} is a test coverage program: it analyzes the execution of a given
18570 program on selected tests, to help you determine the portions of the program
18571 that are still untested.
18572
18573 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18574 User's Guide. You can refer to this documentation for a more complete
18575 description.
18576
18577 This chapter provides a quick startup guide, and
18578 details some Gnat-specific features.
18579
18580 @menu
18581 * Quick startup guide::
18582 * Gnat specifics::
18583 @end menu
18584
18585 @node Quick startup guide
18586 @subsection Quick startup guide
18587
18588 In order to perform coverage analysis of a program using @code{gcov}, 3
18589 steps are needed:
18590
18591 @itemize @bullet
18592 @item
18593 Code instrumentation during the compilation process
18594 @item
18595 Execution of the instrumented program
18596 @item
18597 Execution of the @code{gcov} tool to generate the result.
18598 @end itemize
18599
18600 The code instrumentation needed by gcov is created at the object level:
18601 The source code is not modified in any way, because the instrumentation code is
18602 inserted by gcc during the compilation process. To compile your code with code
18603 coverage activated, you need to recompile your whole project using the
18604 switches
18605 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18606 @code{-fprofile-arcs}.
18607
18608 @smallexample
18609 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18610    -largs -fprofile-arcs
18611 @end smallexample
18612
18613 This compilation process will create @file{.gcno} files together with
18614 the usual object files.
18615
18616 Once the program is compiled with coverage instrumentation, you can
18617 run it as many times as needed - on portions of a test suite for
18618 example. The first execution will produce @file{.gcda} files at the
18619 same location as the @file{.gcno} files.  The following executions
18620 will update those files, so that a cumulative result of the covered
18621 portions of the program is generated.
18622
18623 Finally, you need to call the @code{gcov} tool. The different options of
18624 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18625
18626 This will create annotated source files with a @file{.gcov} extension:
18627 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18628
18629 @node Gnat specifics
18630 @subsection Gnat specifics
18631
18632 Because Ada semantics, portions of the source code may be shared among
18633 several object files. This is the case for example when generics are
18634 involved, when inlining is active  or when declarations generate  initialisation
18635 calls. In order to take
18636 into account this shared code, you need to call @code{gcov} on all
18637 source files of the tested program at once.
18638
18639 The list of source files might exceed the system's maximum command line
18640 length. In order to bypass this limitation, a new mechanism has been
18641 implemented in @code{gcov}: you can now list all your project's files into a
18642 text file, and provide this file to gcov as a parameter,  preceded by a @@
18643 (e.g. @samp{gcov @@mysrclist.txt}).
18644
18645 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18646 not supported as there can be unresolved symbols during the final link.
18647
18648 @node Profiling an Ada Program using gprof
18649 @section Profiling an Ada Program using gprof
18650 @cindex gprof
18651 @cindex -pg
18652 @cindex Profiling
18653
18654 @noindent
18655 This section is not meant to be an exhaustive documentation of @code{gprof}.
18656 Full documentation for it can be found in the GNU Profiler User's Guide
18657 documentation that is part of this GNAT distribution.
18658
18659 Profiling a program helps determine the parts of a program that are executed
18660 most often, and are therefore the most time-consuming.
18661
18662 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18663 better handle Ada programs and multitasking.
18664 It is currently supported on the following platforms
18665 @itemize @bullet
18666 @item
18667 linux x86/x86_64
18668 @item
18669 solaris sparc/sparc64/x86
18670 @item
18671 windows x86
18672 @end itemize
18673
18674 @noindent
18675 In order to profile a program using @code{gprof}, 3 steps are needed:
18676
18677 @itemize @bullet
18678 @item
18679 Code instrumentation, requiring a full recompilation of the project with the
18680 proper switches.
18681 @item
18682 Execution of the program under the analysis conditions, i.e. with the desired
18683 input.
18684 @item
18685 Analysis of the results using the @code{gprof} tool.
18686 @end itemize
18687
18688 @noindent
18689 The following sections detail the different steps, and indicate how
18690 to interpret the results:
18691 @menu
18692 * Compilation for profiling::
18693 * Program execution::
18694 * Running gprof::
18695 * Interpretation of profiling results::
18696 @end menu
18697
18698 @node Compilation for profiling
18699 @subsection Compilation for profiling
18700 @cindex -pg
18701 @cindex Profiling
18702
18703 In order to profile a program the first step is to tell the compiler
18704 to generate the necessary profiling information. The compiler switch to be used
18705 is @code{-pg}, which must be added to other compilation switches. This
18706 switch needs to be specified both during compilation and link stages, and can
18707 be specified once when using gnatmake:
18708
18709 @smallexample
18710 gnatmake -f -pg -P my_project
18711 @end smallexample
18712
18713 @noindent
18714 Note that only the objects that were compiled with the @samp{-pg} switch will
18715 be profiled; if you need to profile your whole project, use the @samp{-f}
18716 gnatmake switch to force full recompilation.
18717
18718 @node Program execution
18719 @subsection Program execution
18720
18721 @noindent
18722 Once the program has been compiled for profiling, you can run it as usual.
18723
18724 The only constraint imposed by profiling is that the program must terminate
18725 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18726 properly analyzed.
18727
18728 Once the program completes execution, a data file called @file{gmon.out} is
18729 generated in the directory where the program was launched from. If this file
18730 already exists, it will be overwritten.
18731
18732 @node Running gprof
18733 @subsection Running gprof
18734
18735 @noindent
18736 The @code{gprof} tool is called as follow:
18737
18738 @smallexample
18739 gprof my_prog gmon.out
18740 @end smallexample
18741
18742 @noindent
18743 or simpler:
18744
18745 @smallexample
18746 gprof my_prog
18747 @end smallexample
18748
18749 @noindent
18750 The complete form of the gprof command line is the following:
18751
18752 @smallexample
18753 gprof [^switches^options^] [executable [data-file]]
18754 @end smallexample
18755
18756 @noindent
18757 @code{gprof} supports numerous ^switch^options^. The order of these
18758 ^switch^options^ does not matter. The full list of options can be found in
18759 the GNU Profiler User's Guide documentation that comes with this documentation.
18760
18761 The following is the subset of those switches that is most relevant:
18762
18763 @table @option
18764
18765 @item --demangle[=@var{style}]
18766 @itemx --no-demangle
18767 @cindex @option{--demangle} (@code{gprof})
18768 These options control whether symbol names should be demangled when
18769 printing output.  The default is to demangle C++ symbols.  The
18770 @code{--no-demangle} option may be used to turn off demangling. Different
18771 compilers have different mangling styles.  The optional demangling style
18772 argument can be used to choose an appropriate demangling style for your
18773 compiler, in particular Ada symbols generated by GNAT can be demangled using
18774 @code{--demangle=gnat}.
18775
18776 @item -e @var{function_name}
18777 @cindex @option{-e} (@code{gprof})
18778 The @samp{-e @var{function}} option tells @code{gprof} not to print
18779 information about the function @var{function_name} (and its
18780 children@dots{}) in the call graph.  The function will still be listed
18781 as a child of any functions that call it, but its index number will be
18782 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18783 given; only one @var{function_name} may be indicated with each @samp{-e}
18784 option.
18785
18786 @item -E @var{function_name}
18787 @cindex @option{-E} (@code{gprof})
18788 The @code{-E @var{function}} option works like the @code{-e} option, but
18789 execution time spent in the function (and children who were not called from
18790 anywhere else), will not be used to compute the percentages-of-time for
18791 the call graph.  More than one @samp{-E} option may be given; only one
18792 @var{function_name} may be indicated with each @samp{-E} option.
18793
18794 @item -f @var{function_name}
18795 @cindex @option{-f} (@code{gprof})
18796 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18797 call graph to the function @var{function_name} and its children (and
18798 their children@dots{}).  More than one @samp{-f} option may be given;
18799 only one @var{function_name} may be indicated with each @samp{-f}
18800 option.
18801
18802 @item -F @var{function_name}
18803 @cindex @option{-F} (@code{gprof})
18804 The @samp{-F @var{function}} option works like the @code{-f} option, but
18805 only time spent in the function and its children (and their
18806 children@dots{}) will be used to determine total-time and
18807 percentages-of-time for the call graph.  More than one @samp{-F} option
18808 may be given; only one @var{function_name} may be indicated with each
18809 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18810
18811 @end table
18812
18813 @node Interpretation of profiling results
18814 @subsection Interpretation of profiling results
18815
18816 @noindent
18817
18818 The results of the profiling analysis are represented by two arrays: the
18819 'flat profile' and the 'call graph'. Full documentation of those outputs
18820 can be found in the GNU Profiler User's Guide.
18821
18822 The flat profile shows the time spent in each function of the program, and how
18823 many time it has been called. This allows you to locate easily the most
18824 time-consuming functions.
18825
18826 The call graph shows, for each subprogram, the subprograms that call it,
18827 and the subprograms that it calls. It also provides an estimate of the time
18828 spent in each of those callers/called subprograms.
18829 @end ifclear
18830
18831 @c ******************************
18832 @node Running and Debugging Ada Programs
18833 @chapter Running and Debugging Ada Programs
18834 @cindex Debugging
18835
18836 @noindent
18837 This chapter discusses how to debug Ada programs.
18838 @ifset vms
18839 It applies to GNAT on the Alpha OpenVMS platform;
18840 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18841 since HP has implemented Ada support in the OpenVMS debugger on I64.
18842 @end ifset
18843
18844 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18845
18846 @enumerate
18847 @item
18848 The illegality may be a violation of the static semantics of Ada. In
18849 that case GNAT diagnoses the constructs in the program that are illegal.
18850 It is then a straightforward matter for the user to modify those parts of
18851 the program.
18852
18853 @item
18854 The illegality may be a violation of the dynamic semantics of Ada. In
18855 that case the program compiles and executes, but may generate incorrect
18856 results, or may terminate abnormally with some exception.
18857
18858 @item
18859 When presented with a program that contains convoluted errors, GNAT
18860 itself may terminate abnormally without providing full diagnostics on
18861 the incorrect user program.
18862 @end enumerate
18863
18864 @menu
18865 * The GNAT Debugger GDB::
18866 * Running GDB::
18867 * Introduction to GDB Commands::
18868 * Using Ada Expressions::
18869 * Calling User-Defined Subprograms::
18870 * Using the Next Command in a Function::
18871 * Ada Exceptions::
18872 * Ada Tasks::
18873 * Debugging Generic Units::
18874 * Remote Debugging using gdbserver::
18875 * GNAT Abnormal Termination or Failure to Terminate::
18876 * Naming Conventions for GNAT Source Files::
18877 * Getting Internal Debugging Information::
18878 * Stack Traceback::
18879 @end menu
18880
18881 @cindex Debugger
18882 @findex gdb
18883
18884 @node The GNAT Debugger GDB
18885 @section The GNAT Debugger GDB
18886
18887 @noindent
18888 @code{GDB} is a general purpose, platform-independent debugger that
18889 can be used to debug mixed-language programs compiled with @command{gcc},
18890 and in particular is capable of debugging Ada programs compiled with
18891 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18892 complex Ada data structures.
18893
18894 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18895 @ifset vms
18896 located in the GNU:[DOCS] directory,
18897 @end ifset
18898 for full details on the usage of @code{GDB}, including a section on
18899 its usage on programs. This manual should be consulted for full
18900 details. The section that follows is a brief introduction to the
18901 philosophy and use of @code{GDB}.
18902
18903 When GNAT programs are compiled, the compiler optionally writes debugging
18904 information into the generated object file, including information on
18905 line numbers, and on declared types and variables. This information is
18906 separate from the generated code. It makes the object files considerably
18907 larger, but it does not add to the size of the actual executable that
18908 will be loaded into memory, and has no impact on run-time performance. The
18909 generation of debug information is triggered by the use of the
18910 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18911 used to carry out the compilations. It is important to emphasize that
18912 the use of these options does not change the generated code.
18913
18914 The debugging information is written in standard system formats that
18915 are used by many tools, including debuggers and profilers. The format
18916 of the information is typically designed to describe C types and
18917 semantics, but GNAT implements a translation scheme which allows full
18918 details about Ada types and variables to be encoded into these
18919 standard C formats. Details of this encoding scheme may be found in
18920 the file exp_dbug.ads in the GNAT source distribution. However, the
18921 details of this encoding are, in general, of no interest to a user,
18922 since @code{GDB} automatically performs the necessary decoding.
18923
18924 When a program is bound and linked, the debugging information is
18925 collected from the object files, and stored in the executable image of
18926 the program. Again, this process significantly increases the size of
18927 the generated executable file, but it does not increase the size of
18928 the executable program itself. Furthermore, if this program is run in
18929 the normal manner, it runs exactly as if the debug information were
18930 not present, and takes no more actual memory.
18931
18932 However, if the program is run under control of @code{GDB}, the
18933 debugger is activated.  The image of the program is loaded, at which
18934 point it is ready to run.  If a run command is given, then the program
18935 will run exactly as it would have if @code{GDB} were not present. This
18936 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18937 entirely non-intrusive until a breakpoint is encountered.  If no
18938 breakpoint is ever hit, the program will run exactly as it would if no
18939 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18940 the debugging information and can respond to user commands to inspect
18941 variables, and more generally to report on the state of execution.
18942
18943 @c **************
18944 @node Running GDB
18945 @section Running GDB
18946
18947 @noindent
18948 This section describes how to initiate the debugger.
18949 @c The above sentence is really just filler, but it was otherwise
18950 @c clumsy to get the first paragraph nonindented given the conditional
18951 @c nature of the description
18952
18953 @ifclear vms
18954 The debugger can be launched from a @code{GPS} menu or
18955 directly from the command line. The description below covers the latter use.
18956 All the commands shown can be used in the @code{GPS} debug console window,
18957 but there are usually more GUI-based ways to achieve the same effect.
18958 @end ifclear
18959
18960 The command to run @code{GDB} is
18961
18962 @smallexample
18963 $ ^gdb program^GDB PROGRAM^
18964 @end smallexample
18965
18966 @noindent
18967 where @code{^program^PROGRAM^} is the name of the executable file. This
18968 activates the debugger and results in a prompt for debugger commands.
18969 The simplest command is simply @code{run}, which causes the program to run
18970 exactly as if the debugger were not present. The following section
18971 describes some of the additional commands that can be given to @code{GDB}.
18972
18973 @c *******************************
18974 @node Introduction to GDB Commands
18975 @section Introduction to GDB Commands
18976
18977 @noindent
18978 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18979 Debugging with GDB, gdb, Debugging with GDB},
18980 @ifset vms
18981 located in the GNU:[DOCS] directory,
18982 @end ifset
18983 for extensive documentation on the use
18984 of these commands, together with examples of their use. Furthermore,
18985 the command @command{help} invoked from within GDB activates a simple help
18986 facility which summarizes the available commands and their options.
18987 In this section we summarize a few of the most commonly
18988 used commands to give an idea of what @code{GDB} is about. You should create
18989 a simple program with debugging information and experiment with the use of
18990 these @code{GDB} commands on the program as you read through the
18991 following section.
18992
18993 @table @code
18994 @item set args @var{arguments}
18995 The @var{arguments} list above is a list of arguments to be passed to
18996 the program on a subsequent run command, just as though the arguments
18997 had been entered on a normal invocation of the program. The @code{set args}
18998 command is not needed if the program does not require arguments.
18999
19000 @item run
19001 The @code{run} command causes execution of the program to start from
19002 the beginning. If the program is already running, that is to say if
19003 you are currently positioned at a breakpoint, then a prompt will ask
19004 for confirmation that you want to abandon the current execution and
19005 restart.
19006
19007 @item breakpoint @var{location}
19008 The breakpoint command sets a breakpoint, that is to say a point at which
19009 execution will halt and @code{GDB} will await further
19010 commands. @var{location} is
19011 either a line number within a file, given in the format @code{file:linenumber},
19012 or it is the name of a subprogram. If you request that a breakpoint be set on
19013 a subprogram that is overloaded, a prompt will ask you to specify on which of
19014 those subprograms you want to breakpoint. You can also
19015 specify that all of them should be breakpointed. If the program is run
19016 and execution encounters the breakpoint, then the program
19017 stops and @code{GDB} signals that the breakpoint was encountered by
19018 printing the line of code before which the program is halted.
19019
19020 @item catch exception @var{name}
19021 This command causes the program execution to stop whenever exception
19022 @var{name} is raised.  If @var{name} is omitted, then the execution is
19023 suspended when any exception is raised.
19024
19025 @item print @var{expression}
19026 This will print the value of the given expression. Most simple
19027 Ada expression formats are properly handled by @code{GDB}, so the expression
19028 can contain function calls, variables, operators, and attribute references.
19029
19030 @item continue
19031 Continues execution following a breakpoint, until the next breakpoint or the
19032 termination of the program.
19033
19034 @item step
19035 Executes a single line after a breakpoint. If the next statement
19036 is a subprogram call, execution continues into (the first statement of)
19037 the called subprogram.
19038
19039 @item next
19040 Executes a single line. If this line is a subprogram call, executes and
19041 returns from the call.
19042
19043 @item list
19044 Lists a few lines around the current source location. In practice, it
19045 is usually more convenient to have a separate edit window open with the
19046 relevant source file displayed. Successive applications of this command
19047 print subsequent lines. The command can be given an argument which is a
19048 line number, in which case it displays a few lines around the specified one.
19049
19050 @item backtrace
19051 Displays a backtrace of the call chain. This command is typically
19052 used after a breakpoint has occurred, to examine the sequence of calls that
19053 leads to the current breakpoint. The display includes one line for each
19054 activation record (frame) corresponding to an active subprogram.
19055
19056 @item up
19057 At a breakpoint, @code{GDB} can display the values of variables local
19058 to the current frame. The command @code{up} can be used to
19059 examine the contents of other active frames, by moving the focus up
19060 the stack, that is to say from callee to caller, one frame at a time.
19061
19062 @item down
19063 Moves the focus of @code{GDB} down from the frame currently being
19064 examined to the frame of its callee (the reverse of the previous command),
19065
19066 @item frame @var{n}
19067 Inspect the frame with the given number. The value 0 denotes the frame
19068 of the current breakpoint, that is to say the top of the call stack.
19069
19070 @end table
19071
19072 @noindent
19073 The above list is a very short introduction to the commands that
19074 @code{GDB} provides. Important additional capabilities, including conditional
19075 breakpoints, the ability to execute command sequences on a breakpoint,
19076 the ability to debug at the machine instruction level and many other
19077 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19078 Debugging with GDB}.  Note that most commands can be abbreviated
19079 (for example, c for continue, bt for backtrace).
19080
19081 @node Using Ada Expressions
19082 @section Using Ada Expressions
19083 @cindex Ada expressions
19084
19085 @noindent
19086 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19087 extensions. The philosophy behind the design of this subset is
19088
19089 @itemize @bullet
19090 @item
19091 That @code{GDB} should provide basic literals and access to operations for
19092 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19093 leaving more sophisticated computations to subprograms written into the
19094 program (which therefore may be called from @code{GDB}).
19095
19096 @item
19097 That type safety and strict adherence to Ada language restrictions
19098 are not particularly important to the @code{GDB} user.
19099
19100 @item
19101 That brevity is important to the @code{GDB} user.
19102 @end itemize
19103
19104 @noindent
19105 Thus, for brevity, the debugger acts as if there were
19106 implicit @code{with} and @code{use} clauses in effect for all user-written
19107 packages, thus making it unnecessary to fully qualify most names with
19108 their packages, regardless of context. Where this causes ambiguity,
19109 @code{GDB} asks the user's intent.
19110
19111 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19112 GDB, gdb, Debugging with GDB}.
19113
19114 @node Calling User-Defined Subprograms
19115 @section Calling User-Defined Subprograms
19116
19117 @noindent
19118 An important capability of @code{GDB} is the ability to call user-defined
19119 subprograms while debugging. This is achieved simply by entering
19120 a subprogram call statement in the form:
19121
19122 @smallexample
19123 call subprogram-name (parameters)
19124 @end smallexample
19125
19126 @noindent
19127 The keyword @code{call} can be omitted in the normal case where the
19128 @code{subprogram-name} does not coincide with any of the predefined
19129 @code{GDB} commands.
19130
19131 The effect is to invoke the given subprogram, passing it the
19132 list of parameters that is supplied. The parameters can be expressions and
19133 can include variables from the program being debugged. The
19134 subprogram must be defined
19135 at the library level within your program, and @code{GDB} will call the
19136 subprogram within the environment of your program execution (which
19137 means that the subprogram is free to access or even modify variables
19138 within your program).
19139
19140 The most important use of this facility is in allowing the inclusion of
19141 debugging routines that are tailored to particular data structures
19142 in your program. Such debugging routines can be written to provide a suitably
19143 high-level description of an abstract type, rather than a low-level dump
19144 of its physical layout. After all, the standard
19145 @code{GDB print} command only knows the physical layout of your
19146 types, not their abstract meaning. Debugging routines can provide information
19147 at the desired semantic level and are thus enormously useful.
19148
19149 For example, when debugging GNAT itself, it is crucial to have access to
19150 the contents of the tree nodes used to represent the program internally.
19151 But tree nodes are represented simply by an integer value (which in turn
19152 is an index into a table of nodes).
19153 Using the @code{print} command on a tree node would simply print this integer
19154 value, which is not very useful. But the PN routine (defined in file
19155 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19156 a useful high level representation of the tree node, which includes the
19157 syntactic category of the node, its position in the source, the integers
19158 that denote descendant nodes and parent node, as well as varied
19159 semantic information. To study this example in more detail, you might want to
19160 look at the body of the PN procedure in the stated file.
19161
19162 @node Using the Next Command in a Function
19163 @section Using the Next Command in a Function
19164
19165 @noindent
19166 When you use the @code{next} command in a function, the current source
19167 location will advance to the next statement as usual. A special case
19168 arises in the case of a @code{return} statement.
19169
19170 Part of the code for a return statement is the ``epilog'' of the function.
19171 This is the code that returns to the caller. There is only one copy of
19172 this epilog code, and it is typically associated with the last return
19173 statement in the function if there is more than one return. In some
19174 implementations, this epilog is associated with the first statement
19175 of the function.
19176
19177 The result is that if you use the @code{next} command from a return
19178 statement that is not the last return statement of the function you
19179 may see a strange apparent jump to the last return statement or to
19180 the start of the function. You should simply ignore this odd jump.
19181 The value returned is always that from the first return statement
19182 that was stepped through.
19183
19184 @node Ada Exceptions
19185 @section Stopping when Ada Exceptions are Raised
19186 @cindex Exceptions
19187
19188 @noindent
19189 You can set catchpoints that stop the program execution when your program
19190 raises selected exceptions.
19191
19192 @table @code
19193 @item catch exception
19194 Set a catchpoint that stops execution whenever (any task in the) program
19195 raises any exception.
19196
19197 @item catch exception @var{name}
19198 Set a catchpoint that stops execution whenever (any task in the) program
19199 raises the exception @var{name}.
19200
19201 @item catch exception unhandled
19202 Set a catchpoint that stops executino whenever (any task in the) program
19203 raises an exception for which there is no handler.
19204
19205 @item info exceptions
19206 @itemx info exceptions @var{regexp}
19207 The @code{info exceptions} command permits the user to examine all defined
19208 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19209 argument, prints out only those exceptions whose name matches @var{regexp}.
19210 @end table
19211
19212 @node Ada Tasks
19213 @section Ada Tasks
19214 @cindex Tasks
19215
19216 @noindent
19217 @code{GDB} allows the following task-related commands:
19218
19219 @table @code
19220 @item info tasks
19221 This command shows a list of current Ada tasks, as in the following example:
19222
19223 @smallexample
19224 @iftex
19225 @leftskip=0cm
19226 @end iftex
19227 (gdb) info tasks
19228   ID       TID P-ID   Thread Pri State                 Name
19229    1   8088000   0   807e000  15 Child Activation Wait main_task
19230    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19231    3   809a800   1   80a4800  15 Child Activation Wait a
19232 *  4   80ae800   3   80b8000  15 Running               c
19233 @end smallexample
19234
19235 @noindent
19236 In this listing, the asterisk before the first task indicates it to be the
19237 currently running task. The first column lists the task ID that is used
19238 to refer to tasks in the following commands.
19239
19240 @item break @var{linespec} task @var{taskid}
19241 @itemx break @var{linespec} task @var{taskid} if @dots{}
19242 @cindex Breakpoints and tasks
19243 These commands are like the @code{break @dots{} thread @dots{}}.
19244 @var{linespec} specifies source lines.
19245
19246 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19247 to specify that you only want @code{GDB} to stop the program when a
19248 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19249 numeric task identifiers assigned by @code{GDB}, shown in the first
19250 column of the @samp{info tasks} display.
19251
19252 If you do not specify @samp{task @var{taskid}} when you set a
19253 breakpoint, the breakpoint applies to @emph{all} tasks of your
19254 program.
19255
19256 You can use the @code{task} qualifier on conditional breakpoints as
19257 well; in this case, place @samp{task @var{taskid}} before the
19258 breakpoint condition (before the @code{if}).
19259
19260 @item task @var{taskno}
19261 @cindex Task switching
19262
19263 This command allows to switch to the task referred by @var{taskno}. In
19264 particular, This allows to browse the backtrace of the specified
19265 task. It is advised to switch back to the original task before
19266 continuing execution otherwise the scheduling of the program may be
19267 perturbed.
19268 @end table
19269
19270 @noindent
19271 For more detailed information on the tasking support,
19272 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19273
19274 @node Debugging Generic Units
19275 @section Debugging Generic Units
19276 @cindex Debugging Generic Units
19277 @cindex Generics
19278
19279 @noindent
19280 GNAT always uses code expansion for generic instantiation. This means that
19281 each time an instantiation occurs, a complete copy of the original code is
19282 made, with appropriate substitutions of formals by actuals.
19283
19284 It is not possible to refer to the original generic entities in
19285 @code{GDB}, but it is always possible to debug a particular instance of
19286 a generic, by using the appropriate expanded names. For example, if we have
19287
19288 @smallexample @c ada
19289 @group
19290 @cartouche
19291 procedure g is
19292
19293    generic package k is
19294       procedure kp (v1 : in out integer);
19295    end k;
19296
19297    package body k is
19298       procedure kp (v1 : in out integer) is
19299       begin
19300          v1 := v1 + 1;
19301       end kp;
19302    end k;
19303
19304    package k1 is new k;
19305    package k2 is new k;
19306
19307    var : integer := 1;
19308
19309 begin
19310    k1.kp (var);
19311    k2.kp (var);
19312    k1.kp (var);
19313    k2.kp (var);
19314 end;
19315 @end cartouche
19316 @end group
19317 @end smallexample
19318
19319 @noindent
19320 Then to break on a call to procedure kp in the k2 instance, simply
19321 use the command:
19322
19323 @smallexample
19324 (gdb) break g.k2.kp
19325 @end smallexample
19326
19327 @noindent
19328 When the breakpoint occurs, you can step through the code of the
19329 instance in the normal manner and examine the values of local variables, as for
19330 other units.
19331
19332 @node Remote Debugging using gdbserver
19333 @section Remote Debugging using gdbserver
19334 @cindex Remote Debugging using gdbserver
19335
19336 @noindent
19337 On platforms where gdbserver is supported, it is possible to use this tool
19338 to debug your application remotely.  This can be useful in situations
19339 where the program needs to be run on a target host that is different
19340 from the host used for development, particularly when the target has
19341 a limited amount of resources (either CPU and/or memory).
19342
19343 To do so, start your program using gdbserver on the target machine.
19344 gdbserver then automatically suspends the execution of your program
19345 at its entry point, waiting for a debugger to connect to it.  The
19346 following commands starts an application and tells gdbserver to
19347 wait for a connection with the debugger on localhost port 4444.
19348
19349 @smallexample
19350 $ gdbserver localhost:4444 program
19351 Process program created; pid = 5685
19352 Listening on port 4444
19353 @end smallexample
19354
19355 Once gdbserver has started listening, we can tell the debugger to establish
19356 a connection with this gdbserver, and then start the same debugging session
19357 as if the program was being debugged on the same host, directly under
19358 the control of GDB.
19359
19360 @smallexample
19361 $ gdb program
19362 (gdb) target remote targethost:4444
19363 Remote debugging using targethost:4444
19364 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19365 (gdb) b foo.adb:3
19366 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19367 (gdb) continue
19368 Continuing.
19369
19370 Breakpoint 1, foo () at foo.adb:4
19371 4       end foo;
19372 @end smallexample
19373
19374 It is also possible to use gdbserver to attach to an already running
19375 program, in which case the execution of that program is simply suspended
19376 until the connection between the debugger and gdbserver is established.
19377
19378 For more information on how to use gdbserver, @ref{Top, Server, Using
19379 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
19380 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19381
19382 @node GNAT Abnormal Termination or Failure to Terminate
19383 @section GNAT Abnormal Termination or Failure to Terminate
19384 @cindex GNAT Abnormal Termination or Failure to Terminate
19385
19386 @noindent
19387 When presented with programs that contain serious errors in syntax
19388 or semantics,
19389 GNAT may on rare occasions  experience problems in operation, such
19390 as aborting with a
19391 segmentation fault or illegal memory access, raising an internal
19392 exception, terminating abnormally, or failing to terminate at all.
19393 In such cases, you can activate
19394 various features of GNAT that can help you pinpoint the construct in your
19395 program that is the likely source of the problem.
19396
19397 The following strategies are presented in increasing order of
19398 difficulty, corresponding to your experience in using GNAT and your
19399 familiarity with compiler internals.
19400
19401 @enumerate
19402 @item
19403 Run @command{gcc} with the @option{-gnatf}. This first
19404 switch causes all errors on a given line to be reported. In its absence,
19405 only the first error on a line is displayed.
19406
19407 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19408 are encountered, rather than after compilation is terminated. If GNAT
19409 terminates prematurely or goes into an infinite loop, the last error
19410 message displayed may help to pinpoint the culprit.
19411
19412 @item
19413 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19414 mode, @command{gcc} produces ongoing information about the progress of the
19415 compilation and provides the name of each procedure as code is
19416 generated. This switch allows you to find which Ada procedure was being
19417 compiled when it encountered a code generation problem.
19418
19419 @item
19420 @cindex @option{-gnatdc} switch
19421 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19422 switch that does for the front-end what @option{^-v^VERBOSE^} does
19423 for the back end. The system prints the name of each unit,
19424 either a compilation unit or nested unit, as it is being analyzed.
19425 @item
19426 Finally, you can start
19427 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19428 front-end of GNAT, and can be run independently (normally it is just
19429 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19430 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19431 @code{where} command is the first line of attack; the variable
19432 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19433 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19434 which the execution stopped, and @code{input_file name} indicates the name of
19435 the source file.
19436 @end enumerate
19437
19438 @node Naming Conventions for GNAT Source Files
19439 @section Naming Conventions for GNAT Source Files
19440
19441 @noindent
19442 In order to examine the workings of the GNAT system, the following
19443 brief description of its organization may be helpful:
19444
19445 @itemize @bullet
19446 @item
19447 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19448
19449 @item
19450 All files prefixed with @file{^par^PAR^} are components of the parser. The
19451 numbers correspond to chapters of the Ada Reference Manual. For example,
19452 parsing of select statements can be found in @file{par-ch9.adb}.
19453
19454 @item
19455 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19456 numbers correspond to chapters of the Ada standard. For example, all
19457 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19458 addition, some features of the language require sufficient special processing
19459 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19460 dynamic dispatching, etc.
19461
19462 @item
19463 All files prefixed with @file{^exp^EXP^} perform normalization and
19464 expansion of the intermediate representation (abstract syntax tree, or AST).
19465 these files use the same numbering scheme as the parser and semantics files.
19466 For example, the construction of record initialization procedures is done in
19467 @file{exp_ch3.adb}.
19468
19469 @item
19470 The files prefixed with @file{^bind^BIND^} implement the binder, which
19471 verifies the consistency of the compilation, determines an order of
19472 elaboration, and generates the bind file.
19473
19474 @item
19475 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19476 data structures used by the front-end.
19477
19478 @item
19479 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19480 the abstract syntax tree as produced by the parser.
19481
19482 @item
19483 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19484 all entities, computed during semantic analysis.
19485
19486 @item
19487 Library management issues are dealt with in files with prefix
19488 @file{^lib^LIB^}.
19489
19490 @item
19491 @findex Ada
19492 @cindex Annex A
19493 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19494 defined in Annex A.
19495
19496 @item
19497 @findex Interfaces
19498 @cindex Annex B
19499 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19500 defined in Annex B.
19501
19502 @item
19503 @findex System
19504 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19505 both language-defined children and GNAT run-time routines.
19506
19507 @item
19508 @findex GNAT
19509 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19510 general-purpose packages, fully documented in their specs. All
19511 the other @file{.c} files are modifications of common @command{gcc} files.
19512 @end itemize
19513
19514 @node Getting Internal Debugging Information
19515 @section Getting Internal Debugging Information
19516
19517 @noindent
19518 Most compilers have internal debugging switches and modes. GNAT
19519 does also, except GNAT internal debugging switches and modes are not
19520 secret. A summary and full description of all the compiler and binder
19521 debug flags are in the file @file{debug.adb}. You must obtain the
19522 sources of the compiler to see the full detailed effects of these flags.
19523
19524 The switches that print the source of the program (reconstructed from
19525 the internal tree) are of general interest for user programs, as are the
19526 options to print
19527 the full internal tree, and the entity table (the symbol table
19528 information). The reconstructed source provides a readable version of the
19529 program after the front-end has completed analysis and  expansion,
19530 and is useful when studying the performance of specific constructs.
19531 For example, constraint checks are indicated, complex aggregates
19532 are replaced with loops and assignments, and tasking primitives
19533 are replaced with run-time calls.
19534
19535 @node Stack Traceback
19536 @section Stack Traceback
19537 @cindex traceback
19538 @cindex stack traceback
19539 @cindex stack unwinding
19540
19541 @noindent
19542 Traceback is a mechanism to display the sequence of subprogram calls that
19543 leads to a specified execution point in a program. Often (but not always)
19544 the execution point is an instruction at which an exception has been raised.
19545 This mechanism is also known as @i{stack unwinding} because it obtains
19546 its information by scanning the run-time stack and recovering the activation
19547 records of all active subprograms. Stack unwinding is one of the most
19548 important tools for program debugging.
19549
19550 The first entry stored in traceback corresponds to the deepest calling level,
19551 that is to say the subprogram currently executing the instruction
19552 from which we want to obtain the traceback.
19553
19554 Note that there is no runtime performance penalty when stack traceback
19555 is enabled, and no exception is raised during program execution.
19556
19557 @menu
19558 * Non-Symbolic Traceback::
19559 * Symbolic Traceback::
19560 @end menu
19561
19562 @node Non-Symbolic Traceback
19563 @subsection Non-Symbolic Traceback
19564 @cindex traceback, non-symbolic
19565
19566 @noindent
19567 Note: this feature is not supported on all platforms. See
19568 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19569 platforms.
19570
19571 @menu
19572 * Tracebacks From an Unhandled Exception::
19573 * Tracebacks From Exception Occurrences (non-symbolic)::
19574 * Tracebacks From Anywhere in a Program (non-symbolic)::
19575 @end menu
19576
19577 @node Tracebacks From an Unhandled Exception
19578 @subsubsection Tracebacks From an Unhandled Exception
19579
19580 @noindent
19581 A runtime non-symbolic traceback is a list of addresses of call instructions.
19582 To enable this feature you must use the @option{-E}
19583 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19584 of exception information. You can retrieve this information using the
19585 @code{addr2line} tool.
19586
19587 Here is a simple example:
19588
19589 @smallexample @c ada
19590 @cartouche
19591 procedure STB is
19592
19593    procedure P1 is
19594    begin
19595       raise Constraint_Error;
19596    end P1;
19597
19598    procedure P2 is
19599    begin
19600       P1;
19601    end P2;
19602
19603 begin
19604    P2;
19605 end STB;
19606 @end cartouche
19607 @end smallexample
19608
19609 @smallexample
19610 $ gnatmake stb -bargs -E
19611 $ stb
19612
19613 Execution terminated by unhandled exception
19614 Exception name: CONSTRAINT_ERROR
19615 Message: stb.adb:5
19616 Call stack traceback locations:
19617 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19618 @end smallexample
19619
19620 @noindent
19621 As we see the traceback lists a sequence of addresses for the unhandled
19622 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19623 guess that this exception come from procedure P1. To translate these
19624 addresses into the source lines where the calls appear, the
19625 @code{addr2line} tool, described below, is invaluable. The use of this tool
19626 requires the program to be compiled with debug information.
19627
19628 @smallexample
19629 $ gnatmake -g stb -bargs -E
19630 $ stb
19631
19632 Execution terminated by unhandled exception
19633 Exception name: CONSTRAINT_ERROR
19634 Message: stb.adb:5
19635 Call stack traceback locations:
19636 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19637
19638 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19639    0x4011f1 0x77e892a4
19640
19641 00401373 at d:/stb/stb.adb:5
19642 0040138B at d:/stb/stb.adb:10
19643 0040139C at d:/stb/stb.adb:14
19644 00401335 at d:/stb/b~stb.adb:104
19645 004011C4 at /build/@dots{}/crt1.c:200
19646 004011F1 at /build/@dots{}/crt1.c:222
19647 77E892A4 in ?? at ??:0
19648 @end smallexample
19649
19650 @noindent
19651 The @code{addr2line} tool has several other useful options:
19652
19653 @table @code
19654 @item --functions
19655 to get the function name corresponding to any location
19656
19657 @item --demangle=gnat
19658 to use the gnat decoding mode for the function names. Note that
19659 for binutils version 2.9.x the option is simply @option{--demangle}.
19660 @end table
19661
19662 @smallexample
19663 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19664    0x40139c 0x401335 0x4011c4 0x4011f1
19665
19666 00401373 in stb.p1 at d:/stb/stb.adb:5
19667 0040138B in stb.p2 at d:/stb/stb.adb:10
19668 0040139C in stb at d:/stb/stb.adb:14
19669 00401335 in main at d:/stb/b~stb.adb:104
19670 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19671 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19672 @end smallexample
19673
19674 @noindent
19675 From this traceback we can see that the exception was raised in
19676 @file{stb.adb} at line 5, which was reached from a procedure call in
19677 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19678 which contains the call to the main program.
19679 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19680 and the output will vary from platform to platform.
19681
19682 It is also possible to use @code{GDB} with these traceback addresses to debug
19683 the program. For example, we can break at a given code location, as reported
19684 in the stack traceback:
19685
19686 @smallexample
19687 $ gdb -nw stb
19688 @ifclear vms
19689 @noindent
19690 Furthermore, this feature is not implemented inside Windows DLL. Only
19691 the non-symbolic traceback is reported in this case.
19692 @end ifclear
19693
19694 (gdb) break *0x401373
19695 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19696 @end smallexample
19697
19698 @noindent
19699 It is important to note that the stack traceback addresses
19700 do not change when debug information is included. This is particularly useful
19701 because it makes it possible to release software without debug information (to
19702 minimize object size), get a field report that includes a stack traceback
19703 whenever an internal bug occurs, and then be able to retrieve the sequence
19704 of calls with the same program compiled with debug information.
19705
19706 @node Tracebacks From Exception Occurrences (non-symbolic)
19707 @subsubsection Tracebacks From Exception Occurrences
19708
19709 @noindent
19710 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19711 The stack traceback is attached to the exception information string, and can
19712 be retrieved in an exception handler within the Ada program, by means of the
19713 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19714
19715 @smallexample @c ada
19716 with Ada.Text_IO;
19717 with Ada.Exceptions;
19718
19719 procedure STB is
19720
19721    use Ada;
19722    use Ada.Exceptions;
19723
19724    procedure P1 is
19725       K : Positive := 1;
19726    begin
19727       K := K - 1;
19728    exception
19729       when E : others =>
19730          Text_IO.Put_Line (Exception_Information (E));
19731    end P1;
19732
19733    procedure P2 is
19734    begin
19735       P1;
19736    end P2;
19737
19738 begin
19739    P2;
19740 end STB;
19741 @end smallexample
19742
19743 @noindent
19744 This program will output:
19745
19746 @smallexample
19747 $ stb
19748
19749 Exception name: CONSTRAINT_ERROR
19750 Message: stb.adb:12
19751 Call stack traceback locations:
19752 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19753 @end smallexample
19754
19755 @node Tracebacks From Anywhere in a Program (non-symbolic)
19756 @subsubsection Tracebacks From Anywhere in a Program
19757
19758 @noindent
19759 It is also possible to retrieve a stack traceback from anywhere in a
19760 program. For this you need to
19761 use the @code{GNAT.Traceback} API. This package includes a procedure called
19762 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19763 display procedures described below. It is not necessary to use the
19764 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19765 is invoked explicitly.
19766
19767 @noindent
19768 In the following example we compute a traceback at a specific location in
19769 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19770 convert addresses to strings:
19771
19772 @smallexample @c ada
19773 with Ada.Text_IO;
19774 with GNAT.Traceback;
19775 with GNAT.Debug_Utilities;
19776
19777 procedure STB is
19778
19779    use Ada;
19780    use GNAT;
19781    use GNAT.Traceback;
19782
19783    procedure P1 is
19784       TB  : Tracebacks_Array (1 .. 10);
19785       --  We are asking for a maximum of 10 stack frames.
19786       Len : Natural;
19787       --  Len will receive the actual number of stack frames returned.
19788    begin
19789       Call_Chain (TB, Len);
19790
19791       Text_IO.Put ("In STB.P1 : ");
19792
19793       for K in 1 .. Len loop
19794          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19795          Text_IO.Put (' ');
19796       end loop;
19797
19798       Text_IO.New_Line;
19799    end P1;
19800
19801    procedure P2 is
19802    begin
19803       P1;
19804    end P2;
19805
19806 begin
19807    P2;
19808 end STB;
19809 @end smallexample
19810
19811 @smallexample
19812 $ gnatmake -g stb
19813 $ stb
19814
19815 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19816 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19817 @end smallexample
19818
19819 @noindent
19820 You can then get further information by invoking the @code{addr2line}
19821 tool as described earlier (note that the hexadecimal addresses
19822 need to be specified in C format, with a leading ``0x'').
19823
19824 @node Symbolic Traceback
19825 @subsection Symbolic Traceback
19826 @cindex traceback, symbolic
19827
19828 @noindent
19829 A symbolic traceback is a stack traceback in which procedure names are
19830 associated with each code location.
19831
19832 @noindent
19833 Note that this feature is not supported on all platforms. See
19834 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19835 list of currently supported platforms.
19836
19837 @noindent
19838 Note that the symbolic traceback requires that the program be compiled
19839 with debug information. If it is not compiled with debug information
19840 only the non-symbolic information will be valid.
19841
19842 @menu
19843 * Tracebacks From Exception Occurrences (symbolic)::
19844 * Tracebacks From Anywhere in a Program (symbolic)::
19845 @end menu
19846
19847 @node Tracebacks From Exception Occurrences (symbolic)
19848 @subsubsection Tracebacks From Exception Occurrences
19849
19850 @smallexample @c ada
19851 with Ada.Text_IO;
19852 with GNAT.Traceback.Symbolic;
19853
19854 procedure STB is
19855
19856    procedure P1 is
19857    begin
19858       raise Constraint_Error;
19859    end P1;
19860
19861    procedure P2 is
19862    begin
19863       P1;
19864    end P2;
19865
19866    procedure P3 is
19867    begin
19868       P2;
19869    end P3;
19870
19871 begin
19872    P3;
19873 exception
19874    when E : others =>
19875       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19876 end STB;
19877 @end smallexample
19878
19879 @smallexample
19880 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19881 $ stb
19882
19883 0040149F in stb.p1 at stb.adb:8
19884 004014B7 in stb.p2 at stb.adb:13
19885 004014CF in stb.p3 at stb.adb:18
19886 004015DD in ada.stb at stb.adb:22
19887 00401461 in main at b~stb.adb:168
19888 004011C4 in __mingw_CRTStartup at crt1.c:200
19889 004011F1 in mainCRTStartup at crt1.c:222
19890 77E892A4 in ?? at ??:0
19891 @end smallexample
19892
19893 @noindent
19894 In the above example the ``.\'' syntax in the @command{gnatmake} command
19895 is currently required by @command{addr2line} for files that are in
19896 the current working directory.
19897 Moreover, the exact sequence of linker options may vary from platform
19898 to platform.
19899 The above @option{-largs} section is for Windows platforms. By contrast,
19900 under Unix there is no need for the @option{-largs} section.
19901 Differences across platforms are due to details of linker implementation.
19902
19903 @node Tracebacks From Anywhere in a Program (symbolic)
19904 @subsubsection Tracebacks From Anywhere in a Program
19905
19906 @noindent
19907 It is possible to get a symbolic stack traceback
19908 from anywhere in a program, just as for non-symbolic tracebacks.
19909 The first step is to obtain a non-symbolic
19910 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19911 information. Here is an example:
19912
19913 @smallexample @c ada
19914 with Ada.Text_IO;
19915 with GNAT.Traceback;
19916 with GNAT.Traceback.Symbolic;
19917
19918 procedure STB is
19919
19920    use Ada;
19921    use GNAT.Traceback;
19922    use GNAT.Traceback.Symbolic;
19923
19924    procedure P1 is
19925       TB  : Tracebacks_Array (1 .. 10);
19926       --  We are asking for a maximum of 10 stack frames.
19927       Len : Natural;
19928       --  Len will receive the actual number of stack frames returned.
19929    begin
19930       Call_Chain (TB, Len);
19931       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19932    end P1;
19933
19934    procedure P2 is
19935    begin
19936       P1;
19937    end P2;
19938
19939 begin
19940    P2;
19941 end STB;
19942 @end smallexample
19943
19944 @c ******************************
19945 @ifset vms
19946 @node Compatibility with HP Ada
19947 @chapter Compatibility with HP Ada
19948 @cindex Compatibility
19949
19950 @noindent
19951 @cindex DEC Ada
19952 @cindex HP Ada
19953 @cindex Compatibility between GNAT and HP Ada
19954 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19955 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19956 GNAT is highly compatible
19957 with HP Ada, and it should generally be straightforward to port code
19958 from the HP Ada environment to GNAT. However, there are a few language
19959 and implementation differences of which the user must be aware. These
19960 differences are discussed in this chapter. In
19961 addition, the operating environment and command structure for the
19962 compiler are different, and these differences are also discussed.
19963
19964 For further details on these and other compatibility issues,
19965 see Appendix E of the HP publication
19966 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19967
19968 Except where otherwise indicated, the description of GNAT for OpenVMS
19969 applies to both the Alpha and I64 platforms.
19970
19971 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19972 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19973
19974 The discussion in this chapter addresses specifically the implementation
19975 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19976 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19977 GNAT always follows the Alpha implementation.
19978
19979 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19980 attributes are recognized, although only a subset of them can sensibly
19981 be implemented.  The description of pragmas in
19982 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19983 indicates whether or not they are applicable to non-VMS systems.
19984
19985 @menu
19986 * Ada Language Compatibility::
19987 * Differences in the Definition of Package System::
19988 * Language-Related Features::
19989 * The Package STANDARD::
19990 * The Package SYSTEM::
19991 * Tasking and Task-Related Features::
19992 * Pragmas and Pragma-Related Features::
19993 * Library of Predefined Units::
19994 * Bindings::
19995 * Main Program Definition::
19996 * Implementation-Defined Attributes::
19997 * Compiler and Run-Time Interfacing::
19998 * Program Compilation and Library Management::
19999 * Input-Output::
20000 * Implementation Limits::
20001 * Tools and Utilities::
20002 @end menu
20003
20004 @node Ada Language Compatibility
20005 @section Ada Language Compatibility
20006
20007 @noindent
20008 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20009 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20010 with Ada 83, and therefore Ada 83 programs will compile
20011 and run under GNAT with
20012 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20013 provides details on specific incompatibilities.
20014
20015 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20016 as well as the pragma @code{ADA_83}, to force the compiler to
20017 operate in Ada 83 mode. This mode does not guarantee complete
20018 conformance to Ada 83, but in practice is sufficient to
20019 eliminate most sources of incompatibilities.
20020 In particular, it eliminates the recognition of the
20021 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20022 in Ada 83 programs is legal, and handles the cases of packages
20023 with optional bodies, and generics that instantiate unconstrained
20024 types without the use of @code{(<>)}.
20025
20026 @node Differences in the Definition of Package System
20027 @section Differences in the Definition of Package @code{System}
20028
20029 @noindent
20030 An Ada compiler is allowed to add
20031 implementation-dependent declarations to package @code{System}.
20032 In normal mode,
20033 GNAT does not take advantage of this permission, and the version of
20034 @code{System} provided by GNAT exactly matches that defined in the Ada
20035 Reference Manual.
20036
20037 However, HP Ada adds an extensive set of declarations to package
20038 @code{System},
20039 as fully documented in the HP Ada manuals. To minimize changes required
20040 for programs that make use of these extensions, GNAT provides the pragma
20041 @code{Extend_System} for extending the definition of package System. By using:
20042 @cindex pragma @code{Extend_System}
20043 @cindex @code{Extend_System} pragma
20044
20045 @smallexample @c ada
20046 @group
20047 @cartouche
20048 pragma Extend_System (Aux_DEC);
20049 @end cartouche
20050 @end group
20051 @end smallexample
20052
20053 @noindent
20054 the set of definitions in @code{System} is extended to include those in
20055 package @code{System.Aux_DEC}.
20056 @cindex @code{System.Aux_DEC} package
20057 @cindex @code{Aux_DEC} package (child of @code{System})
20058 These definitions are incorporated directly into package @code{System},
20059 as though they had been declared there. For a
20060 list of the declarations added, see the spec of this package,
20061 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20062 @cindex @file{s-auxdec.ads} file
20063 The pragma @code{Extend_System} is a configuration pragma, which means that
20064 it can be placed in the file @file{gnat.adc}, so that it will automatically
20065 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20066 for further details.
20067
20068 An alternative approach that avoids the use of the non-standard
20069 @code{Extend_System} pragma is to add a context clause to the unit that
20070 references these facilities:
20071
20072 @smallexample @c ada
20073 @cartouche
20074 with System.Aux_DEC;
20075 use  System.Aux_DEC;
20076 @end cartouche
20077 @end smallexample
20078
20079 @noindent
20080 The effect is not quite semantically identical to incorporating
20081 the declarations directly into package @code{System},
20082 but most programs will not notice a difference
20083 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20084 to reference the entities directly in package @code{System}.
20085 For units containing such references,
20086 the prefixes must either be removed, or the pragma @code{Extend_System}
20087 must be used.
20088
20089 @node Language-Related Features
20090 @section Language-Related Features
20091
20092 @noindent
20093 The following sections highlight differences in types,
20094 representations of types, operations, alignment, and
20095 related topics.
20096
20097 @menu
20098 * Integer Types and Representations::
20099 * Floating-Point Types and Representations::
20100 * Pragmas Float_Representation and Long_Float::
20101 * Fixed-Point Types and Representations::
20102 * Record and Array Component Alignment::
20103 * Address Clauses::
20104 * Other Representation Clauses::
20105 @end menu
20106
20107 @node Integer Types and Representations
20108 @subsection Integer Types and Representations
20109
20110 @noindent
20111 The set of predefined integer types is identical in HP Ada and GNAT.
20112 Furthermore the representation of these integer types is also identical,
20113 including the capability of size clauses forcing biased representation.
20114
20115 In addition,
20116 HP Ada for OpenVMS Alpha systems has defined the
20117 following additional integer types in package @code{System}:
20118
20119 @itemize @bullet
20120
20121 @item
20122 @code{INTEGER_8}
20123
20124 @item
20125 @code{INTEGER_16}
20126
20127 @item
20128 @code{INTEGER_32}
20129
20130 @item
20131 @code{INTEGER_64}
20132
20133 @item
20134 @code{LARGEST_INTEGER}
20135 @end itemize
20136
20137 @noindent
20138 In GNAT, the first four of these types may be obtained from the
20139 standard Ada package @code{Interfaces}.
20140 Alternatively, by use of the pragma @code{Extend_System}, identical
20141 declarations can be referenced directly in package @code{System}.
20142 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20143
20144 @node Floating-Point Types and Representations
20145 @subsection Floating-Point Types and Representations
20146 @cindex Floating-Point types
20147
20148 @noindent
20149 The set of predefined floating-point types is identical in HP Ada and GNAT.
20150 Furthermore the representation of these floating-point
20151 types is also identical. One important difference is that the default
20152 representation for HP Ada is @code{VAX_Float}, but the default representation
20153 for GNAT is IEEE.
20154
20155 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20156 pragma @code{Float_Representation} as described in the HP Ada
20157 documentation.
20158 For example, the declarations:
20159
20160 @smallexample @c ada
20161 @cartouche
20162 type F_Float is digits 6;
20163 pragma Float_Representation (VAX_Float, F_Float);
20164 @end cartouche
20165 @end smallexample
20166
20167 @noindent
20168 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20169 format.
20170 This set of declarations actually appears in @code{System.Aux_DEC},
20171 which contains
20172 the full set of additional floating-point declarations provided in
20173 the HP Ada version of package @code{System}.
20174 This and similar declarations may be accessed in a user program
20175 by using pragma @code{Extend_System}. The use of this
20176 pragma, and the related pragma @code{Long_Float} is described in further
20177 detail in the following section.
20178
20179 @node Pragmas Float_Representation and Long_Float
20180 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20181
20182 @noindent
20183 HP Ada provides the pragma @code{Float_Representation}, which
20184 acts as a program library switch to allow control over
20185 the internal representation chosen for the predefined
20186 floating-point types declared in the package @code{Standard}.
20187 The format of this pragma is as follows:
20188
20189 @smallexample @c ada
20190 @cartouche
20191 pragma Float_Representation(VAX_Float | IEEE_Float);
20192 @end cartouche
20193 @end smallexample
20194
20195 @noindent
20196 This pragma controls the representation of floating-point
20197 types as follows:
20198
20199 @itemize @bullet
20200 @item
20201 @code{VAX_Float} specifies that floating-point
20202 types are represented by default with the VAX system hardware types
20203 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20204 Note that the @code{H-floating}
20205 type was available only on VAX systems, and is not available
20206 in either HP Ada or GNAT.
20207
20208 @item
20209 @code{IEEE_Float} specifies that floating-point
20210 types are represented by default with the IEEE single and
20211 double floating-point types.
20212 @end itemize
20213
20214 @noindent
20215 GNAT provides an identical implementation of the pragma
20216 @code{Float_Representation}, except that it functions as a
20217 configuration pragma. Note that the
20218 notion of configuration pragma corresponds closely to the
20219 HP Ada notion of a program library switch.
20220
20221 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20222 which is different
20223 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20224 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20225 advisable to change the format of numbers passed to standard library
20226 routines, and if necessary explicit type conversions may be needed.
20227
20228 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20229 efficient, and (given that it conforms to an international standard)
20230 potentially more portable.
20231 The situation in which @code{VAX_Float} may be useful is in interfacing
20232 to existing code and data that expect the use of @code{VAX_Float}.
20233 In such a situation use the predefined @code{VAX_Float}
20234 types in package @code{System}, as extended by
20235 @code{Extend_System}. For example, use @code{System.F_Float}
20236 to specify the 32-bit @code{F-Float} format.
20237
20238 @noindent
20239 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20240 to allow control over the internal representation chosen
20241 for the predefined type @code{Long_Float} and for floating-point
20242 type declarations with digits specified in the range 7 .. 15.
20243 The format of this pragma is as follows:
20244
20245 @smallexample @c ada
20246 @cartouche
20247 pragma Long_Float (D_FLOAT | G_FLOAT);
20248 @end cartouche
20249 @end smallexample
20250
20251 @node Fixed-Point Types and Representations
20252 @subsection Fixed-Point Types and Representations
20253
20254 @noindent
20255 On HP Ada for OpenVMS Alpha systems, rounding is
20256 away from zero for both positive and negative numbers.
20257 Therefore, @code{+0.5} rounds to @code{1},
20258 and @code{-0.5} rounds to @code{-1}.
20259
20260 On GNAT the results of operations
20261 on fixed-point types are in accordance with the Ada
20262 rules. In particular, results of operations on decimal
20263 fixed-point types are truncated.
20264
20265 @node Record and Array Component Alignment
20266 @subsection Record and Array Component Alignment
20267
20268 @noindent
20269 On HP Ada for OpenVMS Alpha, all non-composite components
20270 are aligned on natural boundaries. For example, 1-byte
20271 components are aligned on byte boundaries, 2-byte
20272 components on 2-byte boundaries, 4-byte components on 4-byte
20273 byte boundaries, and so on. The OpenVMS Alpha hardware
20274 runs more efficiently with naturally aligned data.
20275
20276 On GNAT, alignment rules are compatible
20277 with HP Ada for OpenVMS Alpha.
20278
20279 @node Address Clauses
20280 @subsection Address Clauses
20281
20282 @noindent
20283 In HP Ada and GNAT, address clauses are supported for
20284 objects and imported subprograms.
20285 The predefined type @code{System.Address} is a private type
20286 in both compilers on Alpha OpenVMS, with the same representation
20287 (it is simply a machine pointer). Addition, subtraction, and comparison
20288 operations are available in the standard Ada package
20289 @code{System.Storage_Elements}, or in package @code{System}
20290 if it is extended to include @code{System.Aux_DEC} using a
20291 pragma @code{Extend_System} as previously described.
20292
20293 Note that code that @code{with}'s both this extended package @code{System}
20294 and the package @code{System.Storage_Elements} should not @code{use}
20295 both packages, or ambiguities will result. In general it is better
20296 not to mix these two sets of facilities. The Ada package was
20297 designed specifically to provide the kind of features that HP Ada
20298 adds directly to package @code{System}.
20299
20300 The type @code{System.Address} is a 64-bit integer type in GNAT for
20301 I64 OpenVMS.  For more information,
20302 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20303
20304 GNAT is compatible with HP Ada in its handling of address
20305 clauses, except for some limitations in
20306 the form of address clauses for composite objects with
20307 initialization. Such address clauses are easily replaced
20308 by the use of an explicitly-defined constant as described
20309 in the Ada Reference Manual (13.1(22)). For example, the sequence
20310 of declarations:
20311
20312 @smallexample @c ada
20313 @cartouche
20314 X, Y : Integer := Init_Func;
20315 Q : String (X .. Y) := "abc";
20316 @dots{}
20317 for Q'Address use Compute_Address;
20318 @end cartouche
20319 @end smallexample
20320
20321 @noindent
20322 will be rejected by GNAT, since the address cannot be computed at the time
20323 that @code{Q} is declared. To achieve the intended effect, write instead:
20324
20325 @smallexample @c ada
20326 @group
20327 @cartouche
20328 X, Y : Integer := Init_Func;
20329 Q_Address : constant Address := Compute_Address;
20330 Q : String (X .. Y) := "abc";
20331 @dots{}
20332 for Q'Address use Q_Address;
20333 @end cartouche
20334 @end group
20335 @end smallexample
20336
20337 @noindent
20338 which will be accepted by GNAT (and other Ada compilers), and is also
20339 compatible with Ada 83. A fuller description of the restrictions
20340 on address specifications is found in @ref{Top, GNAT Reference Manual,
20341 About This Guide, gnat_rm, GNAT Reference Manual}.
20342
20343 @node Other Representation Clauses
20344 @subsection Other Representation Clauses
20345
20346 @noindent
20347 GNAT implements in a compatible manner all the representation
20348 clauses supported by HP Ada. In addition, GNAT
20349 implements the representation clause forms that were introduced in Ada 95,
20350 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20351
20352 @node The Package STANDARD
20353 @section The Package @code{STANDARD}
20354
20355 @noindent
20356 The package @code{STANDARD}, as implemented by HP Ada, is fully
20357 described in the @cite{Ada Reference Manual} and in the
20358 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20359 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20360
20361 In addition, HP Ada supports the Latin-1 character set in
20362 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20363 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20364 the type @code{WIDE_CHARACTER}.
20365
20366 The floating-point types supported by GNAT are those
20367 supported by HP Ada, but the defaults are different, and are controlled by
20368 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20369
20370 @node The Package SYSTEM
20371 @section The Package @code{SYSTEM}
20372
20373 @noindent
20374 HP Ada provides a specific version of the package
20375 @code{SYSTEM} for each platform on which the language is implemented.
20376 For the complete spec of the package @code{SYSTEM}, see
20377 Appendix F of the @cite{HP Ada Language Reference Manual}.
20378
20379 On HP Ada, the package @code{SYSTEM} includes the following conversion
20380 functions:
20381 @itemize @bullet
20382 @item @code{TO_ADDRESS(INTEGER)}
20383
20384 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20385
20386 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20387
20388 @item @code{TO_INTEGER(ADDRESS)}
20389
20390 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20391
20392 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20393 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20394 @end itemize
20395
20396 @noindent
20397 By default, GNAT supplies a version of @code{SYSTEM} that matches
20398 the definition given in the @cite{Ada Reference Manual}.
20399 This
20400 is a subset of the HP system definitions, which is as
20401 close as possible to the original definitions. The only difference
20402 is that the definition of @code{SYSTEM_NAME} is different:
20403
20404 @smallexample @c ada
20405 @cartouche
20406 type Name is (SYSTEM_NAME_GNAT);
20407 System_Name : constant Name := SYSTEM_NAME_GNAT;
20408 @end cartouche
20409 @end smallexample
20410
20411 @noindent
20412 Also, GNAT adds the Ada declarations for
20413 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20414
20415 However, the use of the following pragma causes GNAT
20416 to extend the definition of package @code{SYSTEM} so that it
20417 encompasses the full set of HP-specific extensions,
20418 including the functions listed above:
20419
20420 @smallexample @c ada
20421 @cartouche
20422 pragma Extend_System (Aux_DEC);
20423 @end cartouche
20424 @end smallexample
20425
20426 @noindent
20427 The pragma @code{Extend_System} is a configuration pragma that
20428 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20429 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20430
20431 HP Ada does not allow the recompilation of the package
20432 @code{SYSTEM}. Instead HP Ada provides several pragmas
20433 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20434 to modify values in the package @code{SYSTEM}.
20435 On OpenVMS Alpha systems, the pragma
20436 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20437 its single argument.
20438
20439 GNAT does permit the recompilation of package @code{SYSTEM} using
20440 the special switch @option{-gnatg}, and this switch can be used if
20441 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20442 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20443 or @code{MEMORY_SIZE} by any other means.
20444
20445 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20446 enumeration literal @code{SYSTEM_NAME_GNAT}.
20447
20448 The definitions provided by the use of
20449
20450 @smallexample @c ada
20451 pragma Extend_System (AUX_Dec);
20452 @end smallexample
20453
20454 @noindent
20455 are virtually identical to those provided by the HP Ada 83 package
20456 @code{SYSTEM}. One important difference is that the name of the
20457 @code{TO_ADDRESS}
20458 function for type @code{UNSIGNED_LONGWORD} is changed to
20459 @code{TO_ADDRESS_LONG}.
20460 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20461 discussion of why this change was necessary.
20462
20463 @noindent
20464 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20465 is in fact
20466 an extension to Ada 83 not strictly compatible with the reference manual.
20467 GNAT, in order to be exactly compatible with the standard,
20468 does not provide this capability. In HP Ada 83, the
20469 point of this definition is to deal with a call like:
20470
20471 @smallexample @c ada
20472 TO_ADDRESS (16#12777#);
20473 @end smallexample
20474
20475 @noindent
20476 Normally, according to Ada 83 semantics, one would expect this to be
20477 ambiguous, since it matches both the @code{INTEGER} and
20478 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20479 However, in HP Ada 83, there is no ambiguity, since the
20480 definition using @i{universal_integer} takes precedence.
20481
20482 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20483 it is
20484 not possible to be 100% compatible. Since there are many programs using
20485 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20486 GNAT was
20487 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20488 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20489
20490 @smallexample @c ada
20491 function To_Address (X : Integer) return Address;
20492 pragma Pure_Function (To_Address);
20493
20494 function To_Address_Long (X : Unsigned_Longword) return Address;
20495 pragma Pure_Function (To_Address_Long);
20496 @end smallexample
20497
20498 @noindent
20499 This means that programs using @code{TO_ADDRESS} for
20500 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20501
20502 @node Tasking and Task-Related Features
20503 @section Tasking and Task-Related Features
20504
20505 @noindent
20506 This section compares the treatment of tasking in GNAT
20507 and in HP Ada for OpenVMS Alpha.
20508 The GNAT description applies to both Alpha and I64 OpenVMS.
20509 For detailed information on tasking in
20510 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20511 relevant run-time reference manual.
20512
20513 @menu
20514 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20515 * Assigning Task IDs::
20516 * Task IDs and Delays::
20517 * Task-Related Pragmas::
20518 * Scheduling and Task Priority::
20519 * The Task Stack::
20520 * External Interrupts::
20521 @end menu
20522
20523 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20524 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20525
20526 @noindent
20527 On OpenVMS Alpha systems, each Ada task (except a passive
20528 task) is implemented as a single stream of execution
20529 that is created and managed by the kernel. On these
20530 systems, HP Ada tasking support is based on DECthreads,
20531 an implementation of the POSIX standard for threads.
20532
20533 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20534 code that calls DECthreads routines can be used together.
20535 The interaction between Ada tasks and DECthreads routines
20536 can have some benefits. For example when on OpenVMS Alpha,
20537 HP Ada can call C code that is already threaded.
20538
20539 GNAT uses the facilities of DECthreads,
20540 and Ada tasks are mapped to threads.
20541
20542 @node Assigning Task IDs
20543 @subsection Assigning Task IDs
20544
20545 @noindent
20546 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20547 the environment task that executes the main program. On
20548 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20549 that have been created but are not yet activated.
20550
20551 On OpenVMS Alpha systems, task IDs are assigned at
20552 activation. On GNAT systems, task IDs are also assigned at
20553 task creation but do not have the same form or values as
20554 task ID values in HP Ada. There is no null task, and the
20555 environment task does not have a specific task ID value.
20556
20557 @node Task IDs and Delays
20558 @subsection Task IDs and Delays
20559
20560 @noindent
20561 On OpenVMS Alpha systems, tasking delays are implemented
20562 using Timer System Services. The Task ID is used for the
20563 identification of the timer request (the @code{REQIDT} parameter).
20564 If Timers are used in the application take care not to use
20565 @code{0} for the identification, because cancelling such a timer
20566 will cancel all timers and may lead to unpredictable results.
20567
20568 @node Task-Related Pragmas
20569 @subsection Task-Related Pragmas
20570
20571 @noindent
20572 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20573 specification of the size of the guard area for a task
20574 stack. (The guard area forms an area of memory that has no
20575 read or write access and thus helps in the detection of
20576 stack overflow.) On OpenVMS Alpha systems, if the pragma
20577 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20578 area is created. In the absence of a pragma @code{TASK_STORAGE},
20579 a default guard area is created.
20580
20581 GNAT supplies the following task-related pragmas:
20582
20583 @itemize @bullet
20584 @item  @code{TASK_INFO}
20585
20586 This pragma appears within a task definition and
20587 applies to the task in which it appears. The argument
20588 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20589
20590 @item  @code{TASK_STORAGE}
20591
20592 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20593 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20594 @code{SUPPRESS}, and @code{VOLATILE}.
20595 @end itemize
20596 @node Scheduling and Task Priority
20597 @subsection Scheduling and Task Priority
20598
20599 @noindent
20600 HP Ada implements the Ada language requirement that
20601 when two tasks are eligible for execution and they have
20602 different priorities, the lower priority task does not
20603 execute while the higher priority task is waiting. The HP
20604 Ada Run-Time Library keeps a task running until either the
20605 task is suspended or a higher priority task becomes ready.
20606
20607 On OpenVMS Alpha systems, the default strategy is round-
20608 robin with preemption. Tasks of equal priority take turns
20609 at the processor. A task is run for a certain period of
20610 time and then placed at the tail of the ready queue for
20611 its priority level.
20612
20613 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20614 which can be used to enable or disable round-robin
20615 scheduling of tasks with the same priority.
20616 See the relevant HP Ada run-time reference manual for
20617 information on using the pragmas to control HP Ada task
20618 scheduling.
20619
20620 GNAT follows the scheduling rules of Annex D (Real-Time
20621 Annex) of the @cite{Ada Reference Manual}. In general, this
20622 scheduling strategy is fully compatible with HP Ada
20623 although it provides some additional constraints (as
20624 fully documented in Annex D).
20625 GNAT implements time slicing control in a manner compatible with
20626 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20627 are identical to the HP Ada 83 pragma of the same name.
20628 Note that it is not possible to mix GNAT tasking and
20629 HP Ada 83 tasking in the same program, since the two run-time
20630 libraries are not compatible.
20631
20632 @node The Task Stack
20633 @subsection The Task Stack
20634
20635 @noindent
20636 In HP Ada, a task stack is allocated each time a
20637 non-passive task is activated. As soon as the task is
20638 terminated, the storage for the task stack is deallocated.
20639 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20640 a default stack size is used. Also, regardless of the size
20641 specified, some additional space is allocated for task
20642 management purposes. On OpenVMS Alpha systems, at least
20643 one page is allocated.
20644
20645 GNAT handles task stacks in a similar manner. In accordance with
20646 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20647 an alternative method for controlling the task stack size.
20648 The specification of the attribute @code{T'STORAGE_SIZE} is also
20649 supported in a manner compatible with HP Ada.
20650
20651 @node External Interrupts
20652 @subsection External Interrupts
20653
20654 @noindent
20655 On HP Ada, external interrupts can be associated with task entries.
20656 GNAT is compatible with HP Ada in its handling of external interrupts.
20657
20658 @node Pragmas and Pragma-Related Features
20659 @section Pragmas and Pragma-Related Features
20660
20661 @noindent
20662 Both HP Ada and GNAT supply all language-defined pragmas
20663 as specified by the Ada 83 standard. GNAT also supplies all
20664 language-defined pragmas introduced by Ada 95 and Ada 2005.
20665 In addition, GNAT implements the implementation-defined pragmas
20666 from HP Ada 83.
20667
20668 @itemize @bullet
20669 @item  @code{AST_ENTRY}
20670
20671 @item  @code{COMMON_OBJECT}
20672
20673 @item  @code{COMPONENT_ALIGNMENT}
20674
20675 @item  @code{EXPORT_EXCEPTION}
20676
20677 @item  @code{EXPORT_FUNCTION}
20678
20679 @item  @code{EXPORT_OBJECT}
20680
20681 @item  @code{EXPORT_PROCEDURE}
20682
20683 @item  @code{EXPORT_VALUED_PROCEDURE}
20684
20685 @item  @code{FLOAT_REPRESENTATION}
20686
20687 @item  @code{IDENT}
20688
20689 @item  @code{IMPORT_EXCEPTION}
20690
20691 @item  @code{IMPORT_FUNCTION}
20692
20693 @item  @code{IMPORT_OBJECT}
20694
20695 @item  @code{IMPORT_PROCEDURE}
20696
20697 @item  @code{IMPORT_VALUED_PROCEDURE}
20698
20699 @item  @code{INLINE_GENERIC}
20700
20701 @item  @code{INTERFACE_NAME}
20702
20703 @item  @code{LONG_FLOAT}
20704
20705 @item  @code{MAIN_STORAGE}
20706
20707 @item  @code{PASSIVE}
20708
20709 @item  @code{PSECT_OBJECT}
20710
20711 @item  @code{SHARE_GENERIC}
20712
20713 @item  @code{SUPPRESS_ALL}
20714
20715 @item  @code{TASK_STORAGE}
20716
20717 @item  @code{TIME_SLICE}
20718
20719 @item  @code{TITLE}
20720 @end itemize
20721
20722 @noindent
20723 These pragmas are all fully implemented, with the exception of @code{TITLE},
20724 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20725 recognized, but which have no
20726 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20727 use of Ada protected objects. In GNAT, all generics are inlined.
20728
20729 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20730 a separate subprogram specification which must appear before the
20731 subprogram body.
20732
20733 GNAT also supplies a number of implementation-defined pragmas including the
20734 following:
20735
20736 @itemize @bullet
20737 @item  @code{ABORT_DEFER}
20738
20739 @item  @code{ADA_83}
20740
20741 @item  @code{ADA_95}
20742
20743 @item  @code{ADA_05}
20744
20745 @item  @code{Ada_2005}
20746
20747 @item  @code{Ada_12}
20748
20749 @item  @code{Ada_2012}
20750
20751 @item  @code{ANNOTATE}
20752
20753 @item  @code{ASSERT}
20754
20755 @item  @code{C_PASS_BY_COPY}
20756
20757 @item  @code{CPP_CLASS}
20758
20759 @item  @code{CPP_CONSTRUCTOR}
20760
20761 @item  @code{CPP_DESTRUCTOR}
20762
20763 @item  @code{DEBUG}
20764
20765 @item  @code{EXTEND_SYSTEM}
20766
20767 @item  @code{LINKER_ALIAS}
20768
20769 @item  @code{LINKER_SECTION}
20770
20771 @item  @code{MACHINE_ATTRIBUTE}
20772
20773 @item  @code{NO_RETURN}
20774
20775 @item  @code{PURE_FUNCTION}
20776
20777 @item  @code{SOURCE_FILE_NAME}
20778
20779 @item  @code{SOURCE_REFERENCE}
20780
20781 @item  @code{TASK_INFO}
20782
20783 @item  @code{UNCHECKED_UNION}
20784
20785 @item  @code{UNIMPLEMENTED_UNIT}
20786
20787 @item  @code{UNIVERSAL_DATA}
20788
20789 @item  @code{UNSUPPRESS}
20790
20791 @item  @code{WARNINGS}
20792
20793 @item  @code{WEAK_EXTERNAL}
20794 @end itemize
20795
20796 @noindent
20797 For full details on these and other GNAT implementation-defined pragmas,
20798 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20799 Manual}.
20800
20801 @menu
20802 * Restrictions on the Pragma INLINE::
20803 * Restrictions on the Pragma INTERFACE::
20804 * Restrictions on the Pragma SYSTEM_NAME::
20805 @end menu
20806
20807 @node Restrictions on the Pragma INLINE
20808 @subsection Restrictions on Pragma @code{INLINE}
20809
20810 @noindent
20811 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20812 @itemize @bullet
20813 @item  Parameters cannot have a task type.
20814
20815 @item  Function results cannot be task types, unconstrained
20816 array types, or unconstrained types with discriminants.
20817
20818 @item  Bodies cannot declare the following:
20819 @itemize @bullet
20820 @item  Subprogram body or stub (imported subprogram is allowed)
20821
20822 @item  Tasks
20823
20824 @item  Generic declarations
20825
20826 @item  Instantiations
20827
20828 @item  Exceptions
20829
20830 @item  Access types (types derived from access types allowed)
20831
20832 @item  Array or record types
20833
20834 @item  Dependent tasks
20835
20836 @item  Direct recursive calls of subprogram or containing
20837 subprogram, directly or via a renaming
20838
20839 @end itemize
20840 @end itemize
20841
20842 @noindent
20843 In GNAT, the only restriction on pragma @code{INLINE} is that the
20844 body must occur before the call if both are in the same
20845 unit, and the size must be appropriately small. There are
20846 no other specific restrictions which cause subprograms to
20847 be incapable of being inlined.
20848
20849 @node  Restrictions on the Pragma INTERFACE
20850 @subsection  Restrictions on Pragma @code{INTERFACE}
20851
20852 @noindent
20853 The following restrictions on pragma @code{INTERFACE}
20854 are enforced by both HP Ada and GNAT:
20855 @itemize @bullet
20856 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20857 Default is the default on OpenVMS Alpha systems.
20858
20859 @item  Parameter passing: Language specifies default
20860 mechanisms but can be overridden with an @code{EXPORT} pragma.
20861
20862 @itemize @bullet
20863 @item  Ada: Use internal Ada rules.
20864
20865 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20866 record or task type. Result cannot be a string, an
20867 array, or a record.
20868
20869 @item  Fortran: Parameters cannot have a task type. Result cannot
20870 be a string, an array, or a record.
20871 @end itemize
20872 @end itemize
20873
20874 @noindent
20875 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20876 record parameters for all languages.
20877
20878 @node  Restrictions on the Pragma SYSTEM_NAME
20879 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20880
20881 @noindent
20882 For HP Ada for OpenVMS Alpha, the enumeration literal
20883 for the type @code{NAME} is @code{OPENVMS_AXP}.
20884 In GNAT, the enumeration
20885 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20886
20887 @node  Library of Predefined Units
20888 @section  Library of Predefined Units
20889
20890 @noindent
20891 A library of predefined units is provided as part of the
20892 HP Ada and GNAT implementations. HP Ada does not provide
20893 the package @code{MACHINE_CODE} but instead recommends importing
20894 assembler code.
20895
20896 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20897 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20898 version.
20899 The HP Ada Predefined Library units are modified to remove post-Ada 83
20900 incompatibilities and to make them interoperable with GNAT
20901 (@pxref{Changes to DECLIB}, for details).
20902 The units are located in the @file{DECLIB} directory.
20903
20904 The GNAT RTL is contained in
20905 the @file{ADALIB} directory, and
20906 the default search path is set up to find @code{DECLIB} units in preference
20907 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20908 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20909
20910 @menu
20911 * Changes to DECLIB::
20912 @end menu
20913
20914 @node Changes to DECLIB
20915 @subsection Changes to @code{DECLIB}
20916
20917 @noindent
20918 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20919 compatibility are minor and include the following:
20920
20921 @itemize @bullet
20922 @item  Adjusting the location of pragmas and record representation
20923 clauses to obey Ada 95 (and thus Ada 2005) rules
20924
20925 @item  Adding the proper notation to generic formal parameters
20926 that take unconstrained types in instantiation
20927
20928 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20929 that have package bodies not otherwise allowed
20930
20931 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20932 ``@code{PROTECTD}''.
20933 Currently these are found only in the @code{STARLET} package spec.
20934
20935 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20936 where the address size is constrained to 32 bits.
20937 @end itemize
20938
20939 @noindent
20940 None of the above changes is visible to users.
20941
20942 @node Bindings
20943 @section Bindings
20944
20945 @noindent
20946 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20947 @itemize @bullet
20948
20949 @item  Command Language Interpreter (CLI interface)
20950
20951 @item  DECtalk Run-Time Library (DTK interface)
20952
20953 @item  Librarian utility routines (LBR interface)
20954
20955 @item  General Purpose Run-Time Library (LIB interface)
20956
20957 @item  Math Run-Time Library (MTH interface)
20958
20959 @item  National Character Set Run-Time Library (NCS interface)
20960
20961 @item  Compiled Code Support Run-Time Library (OTS interface)
20962
20963 @item  Parallel Processing Run-Time Library (PPL interface)
20964
20965 @item  Screen Management Run-Time Library (SMG interface)
20966
20967 @item  Sort Run-Time Library (SOR interface)
20968
20969 @item  String Run-Time Library (STR interface)
20970
20971 @item STARLET System Library
20972 @findex Starlet
20973
20974 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20975
20976 @item  X Windows Toolkit (XT interface)
20977
20978 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20979 @end itemize
20980
20981 @noindent
20982 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20983 directory, on both the Alpha and I64 OpenVMS platforms.
20984
20985 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20986 in the
20987 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20988 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20989 @code{Xt}, and @code{X_Lib}
20990 causing the default X/Motif sharable image libraries to be linked in. This
20991 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20992 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20993
20994 It may be necessary to edit these options files to update or correct the
20995 library names if, for example, the newer X/Motif bindings from
20996 @file{ADA$EXAMPLES}
20997 had been (previous to installing GNAT) copied and renamed to supersede the
20998 default @file{ADA$PREDEFINED} versions.
20999
21000 @menu
21001 * Shared Libraries and Options Files::
21002 * Interfaces to C::
21003 @end menu
21004
21005 @node Shared Libraries and Options Files
21006 @subsection Shared Libraries and Options Files
21007
21008 @noindent
21009 When using the HP Ada
21010 predefined X and Motif bindings, the linking with their sharable images is
21011 done automatically by @command{GNAT LINK}.
21012 When using other X and Motif bindings, you need
21013 to add the corresponding sharable images to the command line for
21014 @code{GNAT LINK}. When linking with shared libraries, or with
21015 @file{.OPT} files, you must
21016 also add them to the command line for @command{GNAT LINK}.
21017
21018 A shared library to be used with GNAT is built in the same way as other
21019 libraries under VMS. The VMS Link command can be used in standard fashion.
21020
21021 @node Interfaces to C
21022 @subsection Interfaces to C
21023
21024 @noindent
21025 HP Ada
21026 provides the following Ada types and operations:
21027
21028 @itemize @bullet
21029 @item C types package (@code{C_TYPES})
21030
21031 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21032
21033 @item Other_types (@code{SHORT_INT})
21034 @end itemize
21035
21036 @noindent
21037 Interfacing to C with GNAT, you can use the above approach
21038 described for HP Ada or the facilities of Annex B of
21039 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21040 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21041 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21042
21043 The @option{-gnatF} qualifier forces default and explicit
21044 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21045 to be uppercased for compatibility with the default behavior
21046 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21047
21048 @node Main Program Definition
21049 @section Main Program Definition
21050
21051 @noindent
21052 The following section discusses differences in the
21053 definition of main programs on HP Ada and GNAT.
21054 On HP Ada, main programs are defined to meet the
21055 following conditions:
21056 @itemize @bullet
21057 @item  Procedure with no formal parameters (returns @code{0} upon
21058 normal completion)
21059
21060 @item  Procedure with no formal parameters (returns @code{42} when
21061 an unhandled exception is raised)
21062
21063 @item  Function with no formal parameters whose returned value
21064 is of a discrete type
21065
21066 @item  Procedure with one @code{out} formal of a discrete type for
21067 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21068
21069 @end itemize
21070
21071 @noindent
21072 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21073 a main function or main procedure returns a discrete
21074 value whose size is less than 64 bits (32 on VAX systems),
21075 the value is zero- or sign-extended as appropriate.
21076 On GNAT, main programs are defined as follows:
21077 @itemize @bullet
21078 @item  Must be a non-generic, parameterless subprogram that
21079 is either a procedure or function returning an Ada
21080 @code{STANDARD.INTEGER} (the predefined type)
21081
21082 @item  Cannot be a generic subprogram or an instantiation of a
21083 generic subprogram
21084 @end itemize
21085
21086 @node Implementation-Defined Attributes
21087 @section Implementation-Defined Attributes
21088
21089 @noindent
21090 GNAT provides all HP Ada implementation-defined
21091 attributes.
21092
21093 @node Compiler and Run-Time Interfacing
21094 @section Compiler and Run-Time Interfacing
21095
21096 @noindent
21097 HP Ada provides the following qualifiers to pass options to the linker
21098 (ACS LINK):
21099 @itemize @bullet
21100 @item  @option{/WAIT} and @option{/SUBMIT}
21101
21102 @item  @option{/COMMAND}
21103
21104 @item  @option{/@r{[}NO@r{]}MAP}
21105
21106 @item  @option{/OUTPUT=@var{file-spec}}
21107
21108 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21109 @end itemize
21110
21111 @noindent
21112 To pass options to the linker, GNAT provides the following
21113 switches:
21114
21115 @itemize @bullet
21116 @item   @option{/EXECUTABLE=@var{exec-name}}
21117
21118 @item   @option{/VERBOSE}
21119
21120 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21121 @end itemize
21122
21123 @noindent
21124 For more information on these switches, see
21125 @ref{Switches for gnatlink}.
21126 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21127 to control optimization. HP Ada also supplies the
21128 following pragmas:
21129 @itemize @bullet
21130 @item  @code{OPTIMIZE}
21131
21132 @item  @code{INLINE}
21133
21134 @item  @code{INLINE_GENERIC}
21135
21136 @item  @code{SUPPRESS_ALL}
21137
21138 @item  @code{PASSIVE}
21139 @end itemize
21140
21141 @noindent
21142 In GNAT, optimization is controlled strictly by command
21143 line parameters, as described in the corresponding section of this guide.
21144 The HP pragmas for control of optimization are
21145 recognized but ignored.
21146
21147 Note that in GNAT, the default is optimization off, whereas in HP Ada
21148 the default is that optimization is turned on.
21149
21150 @node Program Compilation and Library Management
21151 @section Program Compilation and Library Management
21152
21153 @noindent
21154 HP Ada and GNAT provide a comparable set of commands to
21155 build programs. HP Ada also provides a program library,
21156 which is a concept that does not exist on GNAT. Instead,
21157 GNAT provides directories of sources that are compiled as
21158 needed.
21159
21160 The following table summarizes
21161 the HP Ada commands and provides
21162 equivalent GNAT commands. In this table, some GNAT
21163 equivalents reflect the fact that GNAT does not use the
21164 concept of a program library. Instead, it uses a model
21165 in which collections of source and object files are used
21166 in a manner consistent with other languages like C and
21167 Fortran. Therefore, standard system file commands are used
21168 to manipulate these elements. Those GNAT commands are marked with
21169 an asterisk.
21170 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21171
21172 @need 1500
21173 @multitable @columnfractions .35 .65
21174
21175 @item @emph{HP Ada Command}
21176 @tab @emph{GNAT Equivalent / Description}
21177
21178 @item @command{ADA}
21179 @tab @command{GNAT COMPILE}@*
21180 Invokes the compiler to compile one or more Ada source files.
21181
21182 @item @command{ACS ATTACH}@*
21183 @tab [No equivalent]@*
21184 Switches control of terminal from current process running the program
21185 library manager.
21186
21187 @item @command{ACS CHECK}
21188 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21189 Forms the execution closure of one
21190 or more compiled units and checks completeness and currency.
21191
21192 @item @command{ACS COMPILE}
21193 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21194 Forms the execution closure of one or
21195 more specified units, checks completeness and currency,
21196 identifies units that have revised source files, compiles same,
21197 and recompiles units that are or will become obsolete.
21198 Also completes incomplete generic instantiations.
21199
21200 @item @command{ACS COPY FOREIGN}
21201 @tab Copy (*)@*
21202 Copies a foreign object file into the program library as a
21203 library unit body.
21204
21205 @item @command{ACS COPY UNIT}
21206 @tab Copy (*)@*
21207 Copies a compiled unit from one program library to another.
21208
21209 @item @command{ACS CREATE LIBRARY}
21210 @tab Create /directory (*)@*
21211 Creates a program library.
21212
21213 @item @command{ACS CREATE SUBLIBRARY}
21214 @tab Create /directory (*)@*
21215 Creates a program sublibrary.
21216
21217 @item @command{ACS DELETE LIBRARY}
21218 @tab @*
21219 Deletes a program library and its contents.
21220
21221 @item @command{ACS DELETE SUBLIBRARY}
21222 @tab @*
21223 Deletes a program sublibrary and its contents.
21224
21225 @item @command{ACS DELETE UNIT}
21226 @tab Delete file (*)@*
21227 On OpenVMS systems, deletes one or more compiled units from
21228 the current program library.
21229
21230 @item @command{ACS DIRECTORY}
21231 @tab Directory (*)@*
21232 On OpenVMS systems, lists units contained in the current
21233 program library.
21234
21235 @item @command{ACS ENTER FOREIGN}
21236 @tab Copy (*)@*
21237 Allows the import of a foreign body as an Ada library
21238 spec and enters a reference to a pointer.
21239
21240 @item @command{ACS ENTER UNIT}
21241 @tab Copy (*)@*
21242 Enters a reference (pointer) from the current program library to
21243 a unit compiled into another program library.
21244
21245 @item @command{ACS EXIT}
21246 @tab [No equivalent]@*
21247 Exits from the program library manager.
21248
21249 @item @command{ACS EXPORT}
21250 @tab Copy (*)@*
21251 Creates an object file that contains system-specific object code
21252 for one or more units. With GNAT, object files can simply be copied
21253 into the desired directory.
21254
21255 @item @command{ACS EXTRACT SOURCE}
21256 @tab Copy (*)@*
21257 Allows access to the copied source file for each Ada compilation unit
21258
21259 @item @command{ACS HELP}
21260 @tab @command{HELP GNAT}@*
21261 Provides online help.
21262
21263 @item @command{ACS LINK}
21264 @tab @command{GNAT LINK}@*
21265 Links an object file containing Ada units into an executable file.
21266
21267 @item @command{ACS LOAD}
21268 @tab Copy (*)@*
21269 Loads (partially compiles) Ada units into the program library.
21270 Allows loading a program from a collection of files into a library
21271 without knowing the relationship among units.
21272
21273 @item @command{ACS MERGE}
21274 @tab Copy (*)@*
21275 Merges into the current program library, one or more units from
21276 another library where they were modified.
21277
21278 @item @command{ACS RECOMPILE}
21279 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21280 Recompiles from   external or copied source files any obsolete
21281 unit in the closure. Also, completes any incomplete generic
21282 instantiations.
21283
21284 @item @command{ACS REENTER}
21285 @tab @command{GNAT MAKE}@*
21286 Reenters current references to units compiled after last entered
21287 with the @command{ACS ENTER UNIT} command.
21288
21289 @item @command{ACS SET LIBRARY}
21290 @tab Set default (*)@*
21291 Defines a program library to be the compilation context as well
21292 as the target library for compiler output and commands in general.
21293
21294 @item @command{ACS SET PRAGMA}
21295 @tab Edit @file{gnat.adc} (*)@*
21296 Redefines specified  values of the library characteristics
21297 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21298 and @code{Float_Representation}.
21299
21300 @item @command{ACS SET SOURCE}
21301 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21302 Defines the source file search list for the @command{ACS COMPILE} command.
21303
21304 @item @command{ACS SHOW LIBRARY}
21305 @tab Directory (*)@*
21306 Lists information about one or more program libraries.
21307
21308 @item @command{ACS SHOW PROGRAM}
21309 @tab [No equivalent]@*
21310 Lists information about the execution closure of one or
21311 more units in the program library.
21312
21313 @item @command{ACS SHOW SOURCE}
21314 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21315 Shows the source file search used when compiling units.
21316
21317 @item @command{ACS SHOW VERSION}
21318 @tab Compile with @option{VERBOSE} option
21319 Displays the version number of the compiler and program library
21320 manager used.
21321
21322 @item @command{ACS SPAWN}
21323 @tab [No equivalent]@*
21324 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21325 command).
21326
21327 @item @command{ACS VERIFY}
21328 @tab [No equivalent]@*
21329 Performs a series of consistency checks on a program library to
21330 determine whether the library structure and library files are in
21331 valid form.
21332 @end multitable
21333
21334 @noindent
21335
21336 @node Input-Output
21337 @section Input-Output
21338
21339 @noindent
21340 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21341 Management Services (RMS) to perform operations on
21342 external files.
21343
21344 @noindent
21345 HP Ada and GNAT predefine an identical set of input-
21346 output packages. To make the use of the
21347 generic @code{TEXT_IO} operations more convenient, HP Ada
21348 provides predefined library packages that instantiate the
21349 integer and floating-point operations for the predefined
21350 integer and floating-point types as shown in the following table.
21351
21352 @multitable @columnfractions .45 .55
21353 @item @emph{Package Name} @tab Instantiation
21354
21355 @item @code{INTEGER_TEXT_IO}
21356 @tab @code{INTEGER_IO(INTEGER)}
21357
21358 @item @code{SHORT_INTEGER_TEXT_IO}
21359 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21360
21361 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21362 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21363
21364 @item @code{FLOAT_TEXT_IO}
21365 @tab @code{FLOAT_IO(FLOAT)}
21366
21367 @item @code{LONG_FLOAT_TEXT_IO}
21368 @tab @code{FLOAT_IO(LONG_FLOAT)}
21369 @end multitable
21370
21371 @noindent
21372 The HP Ada predefined packages and their operations
21373 are implemented using OpenVMS Alpha files and input-output
21374 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21375 Familiarity with the following is recommended:
21376 @itemize @bullet
21377 @item  RMS file organizations and access methods
21378
21379 @item  OpenVMS file specifications and directories
21380
21381 @item  OpenVMS File Definition Language (FDL)
21382 @end itemize
21383
21384 @noindent
21385 GNAT provides I/O facilities that are completely
21386 compatible with HP Ada. The distribution includes the
21387 standard HP Ada versions of all I/O packages, operating
21388 in a manner compatible with HP Ada. In particular, the
21389 following packages are by default the HP Ada (Ada 83)
21390 versions of these packages rather than the renamings
21391 suggested in Annex J of the Ada Reference Manual:
21392 @itemize @bullet
21393 @item  @code{TEXT_IO}
21394
21395 @item  @code{SEQUENTIAL_IO}
21396
21397 @item  @code{DIRECT_IO}
21398 @end itemize
21399
21400 @noindent
21401 The use of the standard child package syntax (for
21402 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21403 packages.
21404 GNAT provides HP-compatible predefined instantiations
21405 of the @code{TEXT_IO} packages, and also
21406 provides the standard predefined instantiations required
21407 by the @cite{Ada Reference Manual}.
21408
21409 For further information on how GNAT interfaces to the file
21410 system or how I/O is implemented in programs written in
21411 mixed languages, see @ref{Implementation of the Standard I/O,,,
21412 gnat_rm, GNAT Reference Manual}.
21413 This chapter covers the following:
21414 @itemize @bullet
21415 @item  Standard I/O packages
21416
21417 @item  @code{FORM} strings
21418
21419 @item  @code{ADA.DIRECT_IO}
21420
21421 @item  @code{ADA.SEQUENTIAL_IO}
21422
21423 @item  @code{ADA.TEXT_IO}
21424
21425 @item  Stream pointer positioning
21426
21427 @item  Reading and writing non-regular files
21428
21429 @item  @code{GET_IMMEDIATE}
21430
21431 @item  Treating @code{TEXT_IO} files as streams
21432
21433 @item  Shared files
21434
21435 @item  Open modes
21436 @end itemize
21437
21438 @node Implementation Limits
21439 @section Implementation Limits
21440
21441 @noindent
21442 The following table lists implementation limits for HP Ada
21443 and GNAT systems.
21444 @multitable @columnfractions .60 .20 .20
21445 @sp 1
21446 @item  @emph{Compilation Parameter}
21447 @tab   @emph{HP Ada}
21448 @tab   @emph{GNAT}
21449 @sp 1
21450
21451 @item  In a subprogram or entry  declaration, maximum number of
21452 formal parameters that are of an unconstrained record type
21453 @tab   32
21454 @tab   No set limit
21455 @sp 1
21456
21457 @item  Maximum identifier length (number of characters)
21458 @tab   255
21459 @tab   32766
21460 @sp 1
21461
21462 @item  Maximum number of characters in a source line
21463 @tab   255
21464 @tab   32766
21465 @sp 1
21466
21467 @item  Maximum collection size   (number of bytes)
21468 @tab   2**31-1
21469 @tab   2**31-1
21470 @sp 1
21471
21472 @item  Maximum number of discriminants for a record type
21473 @tab   245
21474 @tab   No set limit
21475 @sp 1
21476
21477 @item  Maximum number of formal parameters in an entry or
21478 subprogram declaration
21479 @tab   246
21480 @tab    No set limit
21481 @sp 1
21482
21483 @item  Maximum number of dimensions in an array type
21484 @tab   255
21485 @tab   No set limit
21486 @sp 1
21487
21488 @item  Maximum number of library  units and subunits in a compilation.
21489 @tab   4095
21490 @tab   No set limit
21491 @sp 1
21492
21493 @item  Maximum number of library units and subunits in an execution.
21494 @tab   16383
21495 @tab   No set limit
21496 @sp 1
21497
21498 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21499 or @code{PSECT_OBJECT}
21500 @tab   32757
21501 @tab   No set limit
21502 @sp 1
21503
21504 @item  Maximum number of enumeration literals in an enumeration type
21505 definition
21506 @tab   65535
21507 @tab   No set limit
21508 @sp 1
21509
21510 @item  Maximum number of lines in a source file
21511 @tab   65534
21512 @tab   No set limit
21513 @sp 1
21514
21515 @item  Maximum number of bits in any object
21516 @tab   2**31-1
21517 @tab   2**31-1
21518 @sp 1
21519
21520 @item  Maximum size of the static portion of a stack frame (approximate)
21521 @tab   2**31-1
21522 @tab   2**31-1
21523 @end multitable
21524
21525 @node Tools and Utilities
21526 @section Tools and Utilities
21527
21528 @noindent
21529 The following table lists some of the OpenVMS development tools
21530 available for HP Ada, and the corresponding tools for
21531 use with @value{EDITION} on Alpha and I64 platforms.
21532 Aside from the debugger, all the OpenVMS tools identified are part
21533 of the DECset package.
21534
21535 @iftex
21536 @c Specify table in TeX since Texinfo does a poor job
21537 @tex
21538 \smallskip
21539 \smallskip
21540 \settabs\+Language-Sensitive Editor\quad
21541    &Product with HP Ada\quad
21542    &\cr
21543 \+\it Tool
21544    &\it Product with HP Ada
21545    & \it Product with GNAT Pro\cr
21546 \smallskip
21547 \+Code Management System
21548    &HP CMS
21549    & HP CMS\cr
21550 \smallskip
21551 \+Language-Sensitive Editor
21552    &HP LSE
21553    & emacs or HP LSE (Alpha)\cr
21554 \+
21555    &
21556    & HP LSE (I64)\cr
21557 \smallskip
21558 \+Debugger
21559    &OpenVMS Debug
21560    & gdb (Alpha),\cr
21561 \+
21562    &
21563    & OpenVMS Debug (I64)\cr
21564 \smallskip
21565 \+Source Code Analyzer /
21566    &HP SCA
21567    & GNAT XREF\cr
21568 \+Cross Referencer
21569    &
21570    &\cr
21571 \smallskip
21572 \+Test Manager
21573    &HP Digital Test
21574    & HP DTM\cr
21575 \+
21576    &Manager (DTM)
21577    &\cr
21578 \smallskip
21579 \+Performance and
21580    & HP PCA
21581    & HP PCA\cr
21582 \+Coverage Analyzer
21583    &
21584    &\cr
21585 \smallskip
21586 \+Module Management
21587    & HP MMS
21588    & Not applicable\cr
21589 \+ System
21590    &
21591    &\cr
21592 \smallskip
21593 \smallskip
21594 @end tex
21595 @end iftex
21596
21597 @ifnottex
21598 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21599 @c the TeX version above for the printed version
21600 @flushleft
21601 @c @multitable @columnfractions .3 .4 .4
21602 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21603 @item @i{Tool}
21604 @tab @i{Tool with HP Ada}
21605 @tab @i{Tool with @value{EDITION}}
21606 @item Code Management@*System
21607 @tab HP CMS
21608 @tab HP CMS
21609 @item Language-Sensitive@*Editor
21610 @tab HP LSE
21611 @tab emacs or HP LSE (Alpha)
21612 @item
21613 @tab
21614 @tab HP LSE (I64)
21615 @item Debugger
21616 @tab OpenVMS Debug
21617 @tab gdb (Alpha),
21618 @item
21619 @tab
21620 @tab OpenVMS Debug (I64)
21621 @item Source Code Analyzer /@*Cross Referencer
21622 @tab HP SCA
21623 @tab GNAT XREF
21624 @item Test Manager
21625 @tab HP Digital Test@*Manager (DTM)
21626 @tab HP DTM
21627 @item Performance and@*Coverage Analyzer
21628 @tab HP PCA
21629 @tab HP PCA
21630 @item Module Management@*System
21631 @tab HP MMS
21632 @tab Not applicable
21633 @end multitable
21634 @end flushleft
21635 @end ifnottex
21636
21637 @end ifset
21638
21639 @c **************************************
21640 @node Platform-Specific Information for the Run-Time Libraries
21641 @appendix Platform-Specific Information for the Run-Time Libraries
21642 @cindex Tasking and threads libraries
21643 @cindex Threads libraries and tasking
21644 @cindex Run-time libraries (platform-specific information)
21645
21646 @noindent
21647 The GNAT run-time implementation may vary with respect to both the
21648 underlying threads library and the exception handling scheme.
21649 For threads support, one or more of the following are supplied:
21650 @itemize @bullet
21651 @item @b{native threads library}, a binding to the thread package from
21652 the underlying operating system
21653
21654 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21655 POSIX thread package
21656 @end itemize
21657
21658 @noindent
21659 For exception handling, either or both of two models are supplied:
21660 @itemize @bullet
21661 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21662 Most programs should experience a substantial speed improvement by
21663 being compiled with a ZCX run-time.
21664 This is especially true for
21665 tasking applications or applications with many exception handlers.}
21666 @cindex Zero-Cost Exceptions
21667 @cindex ZCX (Zero-Cost Exceptions)
21668 which uses binder-generated tables that
21669 are interrogated at run time to locate a handler
21670
21671 @item @b{setjmp / longjmp} (``SJLJ''),
21672 @cindex setjmp/longjmp Exception Model
21673 @cindex SJLJ (setjmp/longjmp Exception Model)
21674 which uses dynamically-set data to establish
21675 the set of handlers
21676 @end itemize
21677
21678 @noindent
21679 This appendix summarizes which combinations of threads and exception support
21680 are supplied on various GNAT platforms.
21681 It then shows how to select a particular library either
21682 permanently or temporarily,
21683 explains the properties of (and tradeoffs among) the various threads
21684 libraries, and provides some additional
21685 information about several specific platforms.
21686
21687 @menu
21688 * Summary of Run-Time Configurations::
21689 * Specifying a Run-Time Library::
21690 * Choosing the Scheduling Policy::
21691 * Solaris-Specific Considerations::
21692 * Linux-Specific Considerations::
21693 * AIX-Specific Considerations::
21694 * Irix-Specific Considerations::
21695 * RTX-Specific Considerations::
21696 * HP-UX-Specific Considerations::
21697 @end menu
21698
21699 @node Summary of Run-Time Configurations
21700 @section Summary of Run-Time Configurations
21701
21702 @multitable @columnfractions .30 .70
21703 @item @b{alpha-openvms}
21704 @item @code{@ @ }@i{rts-native (default)}
21705 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21706 @item @code{@ @ @ @ }Exceptions @tab ZCX
21707 @*
21708 @item @b{alpha-tru64}
21709 @item @code{@ @ }@i{rts-native (default)}
21710 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21711 @item @code{@ @ @ @ }Exceptions @tab ZCX
21712 @*
21713 @item @code{@ @ }@i{rts-sjlj}
21714 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21716 @*
21717 @item @b{ia64-hp_linux}
21718 @item @code{@ @ }@i{rts-native (default)}
21719 @item @code{@ @ @ @ }Tasking    @tab pthread library
21720 @item @code{@ @ @ @ }Exceptions @tab ZCX
21721 @*
21722 @item @b{ia64-hpux}
21723 @item @code{@ @ }@i{rts-native (default)}
21724 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21725 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21726 @*
21727 @item @b{ia64-openvms}
21728 @item @code{@ @ }@i{rts-native (default)}
21729 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21730 @item @code{@ @ @ @ }Exceptions @tab ZCX
21731 @*
21732 @item @b{ia64-sgi_linux}
21733 @item @code{@ @ }@i{rts-native (default)}
21734 @item @code{@ @ @ @ }Tasking    @tab pthread library
21735 @item @code{@ @ @ @ }Exceptions @tab ZCX
21736 @*
21737 @item @b{mips-irix}
21738 @item @code{@ @ }@i{rts-native (default)}
21739 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21740 @item @code{@ @ @ @ }Exceptions @tab ZCX
21741 @*
21742 @item @b{pa-hpux}
21743 @item @code{@ @ }@i{rts-native (default)}
21744 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21745 @item @code{@ @ @ @ }Exceptions @tab ZCX
21746 @*
21747 @item @code{@ @ }@i{rts-sjlj}
21748 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21750 @*
21751 @item @b{ppc-aix}
21752 @item @code{@ @ }@i{rts-native (default)}
21753 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21754 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21755 @*
21756 @item @b{ppc-darwin}
21757 @item @code{@ @ }@i{rts-native (default)}
21758 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21759 @item @code{@ @ @ @ }Exceptions @tab ZCX
21760 @*
21761 @item @b{sparc-solaris}  @tab
21762 @item @code{@ @ }@i{rts-native (default)}
21763 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21764 @item @code{@ @ @ @ }Exceptions @tab ZCX
21765 @*
21766 @item @code{@ @ }@i{rts-pthread}
21767 @item @code{@ @ @ @ }Tasking    @tab pthread library
21768 @item @code{@ @ @ @ }Exceptions @tab ZCX
21769 @*
21770 @item @code{@ @ }@i{rts-sjlj}
21771 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21772 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21773 @*
21774 @item @b{sparc64-solaris}  @tab
21775 @item @code{@ @ }@i{rts-native (default)}
21776 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21777 @item @code{@ @ @ @ }Exceptions @tab ZCX
21778 @*
21779 @item @b{x86-linux}
21780 @item @code{@ @ }@i{rts-native (default)}
21781 @item @code{@ @ @ @ }Tasking    @tab pthread library
21782 @item @code{@ @ @ @ }Exceptions @tab ZCX
21783 @*
21784 @item @code{@ @ }@i{rts-sjlj}
21785 @item @code{@ @ @ @ }Tasking    @tab pthread library
21786 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21787 @*
21788 @item @b{x86-lynx}
21789 @item @code{@ @ }@i{rts-native (default)}
21790 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21791 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21792 @*
21793 @item @b{x86-solaris}
21794 @item @code{@ @ }@i{rts-native (default)}
21795 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21796 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21797 @*
21798 @item @b{x86-windows}
21799 @item @code{@ @ }@i{rts-native (default)}
21800 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21801 @item @code{@ @ @ @ }Exceptions @tab ZCX
21802 @*
21803 @item @code{@ @ }@i{rts-sjlj (default)}
21804 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21805 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21806 @*
21807 @item @b{x86-windows-rtx}
21808 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21809 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21810 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21811 @*
21812 @item @code{@ @ }@i{rts-rtx-w32}
21813 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21814 @item @code{@ @ @ @ }Exceptions @tab ZCX
21815 @*
21816 @item @b{x86_64-linux}
21817 @item @code{@ @ }@i{rts-native (default)}
21818 @item @code{@ @ @ @ }Tasking    @tab pthread library
21819 @item @code{@ @ @ @ }Exceptions @tab ZCX
21820 @*
21821 @item @code{@ @ }@i{rts-sjlj}
21822 @item @code{@ @ @ @ }Tasking    @tab pthread library
21823 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21824 @*
21825 @end multitable
21826
21827 @node Specifying a Run-Time Library
21828 @section Specifying a Run-Time Library
21829
21830 @noindent
21831 The @file{adainclude} subdirectory containing the sources of the GNAT
21832 run-time library, and the @file{adalib} subdirectory containing the
21833 @file{ALI} files and the static and/or shared GNAT library, are located
21834 in the gcc target-dependent area:
21835
21836 @smallexample
21837 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21838 @end smallexample
21839
21840 @noindent
21841 As indicated above, on some platforms several run-time libraries are supplied.
21842 These libraries are installed in the target dependent area and
21843 contain a complete source and binary subdirectory. The detailed description
21844 below explains the differences between the different libraries in terms of
21845 their thread support.
21846
21847 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21848 This default run time is selected by the means of soft links.
21849 For example on x86-linux:
21850
21851 @smallexample
21852 @group
21853  $(target-dir)
21854      |
21855      +--- adainclude----------+
21856      |                        |
21857      +--- adalib-----------+  |
21858      |                     |  |
21859      +--- rts-native       |  |
21860      |    |                |  |
21861      |    +--- adainclude <---+
21862      |    |                |
21863      |    +--- adalib <----+
21864      |
21865      +--- rts-sjlj
21866           |
21867           +--- adainclude
21868           |
21869           +--- adalib
21870 @end group
21871 @end smallexample
21872
21873 @noindent
21874 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21875 these soft links can be modified with the following commands:
21876
21877 @smallexample
21878 $ cd $target
21879 $ rm -f adainclude adalib
21880 $ ln -s rts-sjlj/adainclude adainclude
21881 $ ln -s rts-sjlj/adalib adalib
21882 @end smallexample
21883
21884 @noindent
21885 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21886 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21887 @file{$target/ada_object_path}.
21888
21889 Selecting another run-time library temporarily can be
21890 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21891 @cindex @option{--RTS} option
21892
21893 @node Choosing the Scheduling Policy
21894 @section Choosing the Scheduling Policy
21895
21896 @noindent
21897 When using a POSIX threads implementation, you have a choice of several
21898 scheduling policies: @code{SCHED_FIFO},
21899 @cindex @code{SCHED_FIFO} scheduling policy
21900 @code{SCHED_RR}
21901 @cindex @code{SCHED_RR} scheduling policy
21902 and @code{SCHED_OTHER}.
21903 @cindex @code{SCHED_OTHER} scheduling policy
21904 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21905 or @code{SCHED_RR} requires special (e.g., root) privileges.
21906
21907 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21908 @code{SCHED_FIFO},
21909 @cindex @code{SCHED_FIFO} scheduling policy
21910 you can use one of the following:
21911
21912 @itemize @bullet
21913 @item
21914 @code{pragma Time_Slice (0.0)}
21915 @cindex pragma Time_Slice
21916 @item
21917 the corresponding binder option @option{-T0}
21918 @cindex @option{-T0} option
21919 @item
21920 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21921 @cindex pragma Task_Dispatching_Policy
21922 @end itemize
21923
21924 @noindent
21925 To specify @code{SCHED_RR},
21926 @cindex @code{SCHED_RR} scheduling policy
21927 you should use @code{pragma Time_Slice} with a
21928 value greater than @code{0.0}, or else use the corresponding @option{-T}
21929 binder option.
21930
21931 @node Solaris-Specific Considerations
21932 @section Solaris-Specific Considerations
21933 @cindex Solaris Sparc threads libraries
21934
21935 @noindent
21936 This section addresses some topics related to the various threads libraries
21937 on Sparc Solaris.
21938
21939 @menu
21940 * Solaris Threads Issues::
21941 @end menu
21942
21943 @node Solaris Threads Issues
21944 @subsection Solaris Threads Issues
21945
21946 @noindent
21947 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21948 library based on POSIX threads --- @emph{rts-pthread}.
21949 @cindex rts-pthread threads library
21950 This run-time library has the advantage of being mostly shared across all
21951 POSIX-compliant thread implementations, and it also provides under
21952 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21953 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21954 and @code{PTHREAD_PRIO_PROTECT}
21955 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21956 semantics that can be selected using the predefined pragma
21957 @code{Locking_Policy}
21958 @cindex pragma Locking_Policy (under rts-pthread)
21959 with respectively
21960 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21961 @cindex @code{Inheritance_Locking} (under rts-pthread)
21962 @cindex @code{Ceiling_Locking} (under rts-pthread)
21963
21964 As explained above, the native run-time library is based on the Solaris thread
21965 library (@code{libthread}) and is the default library.
21966
21967 When the Solaris threads library is used (this is the default), programs
21968 compiled with GNAT can automatically take advantage of
21969 and can thus execute on multiple processors.
21970 The user can alternatively specify a processor on which the program should run
21971 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21972 is made by
21973 setting the environment variable @env{GNAT_PROCESSOR}
21974 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21975 to one of the following:
21976
21977 @table @code
21978 @item -2
21979 Use the default configuration (run the program on all
21980 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21981 unset
21982
21983 @item -1
21984 Let the run-time implementation choose one processor and run the program on
21985 that processor
21986
21987 @item 0 .. Last_Proc
21988 Run the program on the specified processor.
21989 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21990 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21991 @end table
21992
21993 @node Linux-Specific Considerations
21994 @section Linux-Specific Considerations
21995 @cindex Linux threads libraries
21996
21997 @noindent
21998 On GNU/Linux without NPTL support (usually system with GNU C Library
21999 older than 2.3), the signal model is not POSIX compliant, which means
22000 that to send a signal to the process, you need to send the signal to all
22001 threads, e.g.@: by using @code{killpg()}.
22002
22003 @node AIX-Specific Considerations
22004 @section AIX-Specific Considerations
22005 @cindex AIX resolver library
22006
22007 @noindent
22008 On AIX, the resolver library initializes some internal structure on
22009 the first call to @code{get*by*} functions, which are used to implement
22010 @code{GNAT.Sockets.Get_Host_By_Name} and
22011 @code{GNAT.Sockets.Get_Host_By_Address}.
22012 If such initialization occurs within an Ada task, and the stack size for
22013 the task is the default size, a stack overflow may occur.
22014
22015 To avoid this overflow, the user should either ensure that the first call
22016 to @code{GNAT.Sockets.Get_Host_By_Name} or
22017 @code{GNAT.Sockets.Get_Host_By_Addrss}
22018 occurs in the environment task, or use @code{pragma Storage_Size} to
22019 specify a sufficiently large size for the stack of the task that contains
22020 this call.
22021
22022 @node Irix-Specific Considerations
22023 @section Irix-Specific Considerations
22024 @cindex Irix libraries
22025
22026 @noindent
22027 The GCC support libraries coming with the Irix compiler have moved to
22028 their canonical place with respect to the general Irix ABI related
22029 conventions. Running applications built with the default shared GNAT
22030 run-time now requires the LD_LIBRARY_PATH environment variable to
22031 include this location. A possible way to achieve this is to issue the
22032 following command line on a bash prompt:
22033
22034 @smallexample
22035 @group
22036 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22037 @end group
22038 @end smallexample
22039
22040 @node RTX-Specific Considerations
22041 @section RTX-Specific Considerations
22042 @cindex RTX libraries
22043
22044 @noindent
22045 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22046 API. Applications can be built to work in two different modes:
22047
22048 @itemize @bullet
22049 @item
22050 Windows executables that run in Ring 3 to utilize memory protection
22051 (@emph{rts-rtx-w32}).
22052
22053 @item
22054 Real-time subsystem (RTSS) executables that run in Ring 0, where
22055 performance can be optimized with RTSS applications taking precedent
22056 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22057 the Microsoft linker to handle RTSS libraries.
22058
22059 @end itemize
22060
22061 @node HP-UX-Specific Considerations
22062 @section HP-UX-Specific Considerations
22063 @cindex HP-UX Scheduling
22064
22065 @noindent
22066 On HP-UX, appropriate privileges are required to change the scheduling
22067 parameters of a task. The calling process must have appropriate
22068 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22069 successfully change the scheduling parameters.
22070
22071 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22072 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22073 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22074
22075 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22076 one of the following:
22077
22078 @itemize @bullet
22079 @item
22080 @code{pragma Time_Slice (0.0)}
22081 @cindex pragma Time_Slice
22082 @item
22083 the corresponding binder option @option{-T0}
22084 @cindex @option{-T0} option
22085 @item
22086 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22087 @cindex pragma Task_Dispatching_Policy
22088 @end itemize
22089
22090 @noindent
22091 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22092 you should use @code{pragma Time_Slice} with a
22093 value greater than @code{0.0}, or use the corresponding @option{-T}
22094 binder option, or set the @code{pragma Task_Dispatching_Policy
22095 (Round_Robin_Within_Priorities)}.
22096
22097 @c *******************************
22098 @node Example of Binder Output File
22099 @appendix Example of Binder Output File
22100
22101 @noindent
22102 This Appendix displays the source code for @command{gnatbind}'s output
22103 file generated for a simple ``Hello World'' program.
22104 Comments have been added for clarification purposes.
22105
22106 @smallexample @c adanocomment
22107 @iftex
22108 @leftskip=0cm
22109 @end iftex
22110 --  The package is called Ada_Main unless this name is actually used
22111 --  as a unit name in the partition, in which case some other unique
22112 --  name is used.
22113
22114 with System;
22115 package ada_main is
22116
22117    Elab_Final_Code : Integer;
22118    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22119
22120    --  The main program saves the parameters (argument count,
22121    --  argument values, environment pointer) in global variables
22122    --  for later access by other units including
22123    --  Ada.Command_Line.
22124
22125    gnat_argc : Integer;
22126    gnat_argv : System.Address;
22127    gnat_envp : System.Address;
22128
22129    --  The actual variables are stored in a library routine. This
22130    --  is useful for some shared library situations, where there
22131    --  are problems if variables are not in the library.
22132
22133    pragma Import (C, gnat_argc);
22134    pragma Import (C, gnat_argv);
22135    pragma Import (C, gnat_envp);
22136
22137    --  The exit status is similarly an external location
22138
22139    gnat_exit_status : Integer;
22140    pragma Import (C, gnat_exit_status);
22141
22142    GNAT_Version : constant String :=
22143                     "GNAT Version: 6.0.0w (20061115)";
22144    pragma Export (C, GNAT_Version, "__gnat_version");
22145
22146    --  This is the generated adafinal routine that performs
22147    --  finalization at the end of execution. In the case where
22148    --  Ada is the main program, this main program makes a call
22149    --  to adafinal at program termination.
22150
22151    procedure adafinal;
22152    pragma Export (C, adafinal, "adafinal");
22153
22154    --  This is the generated adainit routine that performs
22155    --  initialization at the start of execution. In the case
22156    --  where Ada is the main program, this main program makes
22157    --  a call to adainit at program startup.
22158
22159    procedure adainit;
22160    pragma Export (C, adainit, "adainit");
22161
22162    --  This routine is called at the start of execution. It is
22163    --  a dummy routine that is used by the debugger to breakpoint
22164    --  at the start of execution.
22165
22166    procedure Break_Start;
22167    pragma Import (C, Break_Start, "__gnat_break_start");
22168
22169    --  This is the actual generated main program (it would be
22170    --  suppressed if the no main program switch were used). As
22171    --  required by standard system conventions, this program has
22172    --  the external name main.
22173
22174    function main
22175      (argc : Integer;
22176       argv : System.Address;
22177       envp : System.Address)
22178       return Integer;
22179    pragma Export (C, main, "main");
22180
22181    --  The following set of constants give the version
22182    --  identification values for every unit in the bound
22183    --  partition. This identification is computed from all
22184    --  dependent semantic units, and corresponds to the
22185    --  string that would be returned by use of the
22186    --  Body_Version or Version attributes.
22187
22188    type Version_32 is mod 2 ** 32;
22189    u00001 : constant Version_32 := 16#7880BEB3#;
22190    u00002 : constant Version_32 := 16#0D24CBD0#;
22191    u00003 : constant Version_32 := 16#3283DBEB#;
22192    u00004 : constant Version_32 := 16#2359F9ED#;
22193    u00005 : constant Version_32 := 16#664FB847#;
22194    u00006 : constant Version_32 := 16#68E803DF#;
22195    u00007 : constant Version_32 := 16#5572E604#;
22196    u00008 : constant Version_32 := 16#46B173D8#;
22197    u00009 : constant Version_32 := 16#156A40CF#;
22198    u00010 : constant Version_32 := 16#033DABE0#;
22199    u00011 : constant Version_32 := 16#6AB38FEA#;
22200    u00012 : constant Version_32 := 16#22B6217D#;
22201    u00013 : constant Version_32 := 16#68A22947#;
22202    u00014 : constant Version_32 := 16#18CC4A56#;
22203    u00015 : constant Version_32 := 16#08258E1B#;
22204    u00016 : constant Version_32 := 16#367D5222#;
22205    u00017 : constant Version_32 := 16#20C9ECA4#;
22206    u00018 : constant Version_32 := 16#50D32CB6#;
22207    u00019 : constant Version_32 := 16#39A8BB77#;
22208    u00020 : constant Version_32 := 16#5CF8FA2B#;
22209    u00021 : constant Version_32 := 16#2F1EB794#;
22210    u00022 : constant Version_32 := 16#31AB6444#;
22211    u00023 : constant Version_32 := 16#1574B6E9#;
22212    u00024 : constant Version_32 := 16#5109C189#;
22213    u00025 : constant Version_32 := 16#56D770CD#;
22214    u00026 : constant Version_32 := 16#02F9DE3D#;
22215    u00027 : constant Version_32 := 16#08AB6B2C#;
22216    u00028 : constant Version_32 := 16#3FA37670#;
22217    u00029 : constant Version_32 := 16#476457A0#;
22218    u00030 : constant Version_32 := 16#731E1B6E#;
22219    u00031 : constant Version_32 := 16#23C2E789#;
22220    u00032 : constant Version_32 := 16#0F1BD6A1#;
22221    u00033 : constant Version_32 := 16#7C25DE96#;
22222    u00034 : constant Version_32 := 16#39ADFFA2#;
22223    u00035 : constant Version_32 := 16#571DE3E7#;
22224    u00036 : constant Version_32 := 16#5EB646AB#;
22225    u00037 : constant Version_32 := 16#4249379B#;
22226    u00038 : constant Version_32 := 16#0357E00A#;
22227    u00039 : constant Version_32 := 16#3784FB72#;
22228    u00040 : constant Version_32 := 16#2E723019#;
22229    u00041 : constant Version_32 := 16#623358EA#;
22230    u00042 : constant Version_32 := 16#107F9465#;
22231    u00043 : constant Version_32 := 16#6843F68A#;
22232    u00044 : constant Version_32 := 16#63305874#;
22233    u00045 : constant Version_32 := 16#31E56CE1#;
22234    u00046 : constant Version_32 := 16#02917970#;
22235    u00047 : constant Version_32 := 16#6CCBA70E#;
22236    u00048 : constant Version_32 := 16#41CD4204#;
22237    u00049 : constant Version_32 := 16#572E3F58#;
22238    u00050 : constant Version_32 := 16#20729FF5#;
22239    u00051 : constant Version_32 := 16#1D4F93E8#;
22240    u00052 : constant Version_32 := 16#30B2EC3D#;
22241    u00053 : constant Version_32 := 16#34054F96#;
22242    u00054 : constant Version_32 := 16#5A199860#;
22243    u00055 : constant Version_32 := 16#0E7F912B#;
22244    u00056 : constant Version_32 := 16#5760634A#;
22245    u00057 : constant Version_32 := 16#5D851835#;
22246
22247    --  The following Export pragmas export the version numbers
22248    --  with symbolic names ending in B (for body) or S
22249    --  (for spec) so that they can be located in a link. The
22250    --  information provided here is sufficient to track down
22251    --  the exact versions of units used in a given build.
22252
22253    pragma Export (C, u00001, "helloB");
22254    pragma Export (C, u00002, "system__standard_libraryB");
22255    pragma Export (C, u00003, "system__standard_libraryS");
22256    pragma Export (C, u00004, "adaS");
22257    pragma Export (C, u00005, "ada__text_ioB");
22258    pragma Export (C, u00006, "ada__text_ioS");
22259    pragma Export (C, u00007, "ada__exceptionsB");
22260    pragma Export (C, u00008, "ada__exceptionsS");
22261    pragma Export (C, u00009, "gnatS");
22262    pragma Export (C, u00010, "gnat__heap_sort_aB");
22263    pragma Export (C, u00011, "gnat__heap_sort_aS");
22264    pragma Export (C, u00012, "systemS");
22265    pragma Export (C, u00013, "system__exception_tableB");
22266    pragma Export (C, u00014, "system__exception_tableS");
22267    pragma Export (C, u00015, "gnat__htableB");
22268    pragma Export (C, u00016, "gnat__htableS");
22269    pragma Export (C, u00017, "system__exceptionsS");
22270    pragma Export (C, u00018, "system__machine_state_operationsB");
22271    pragma Export (C, u00019, "system__machine_state_operationsS");
22272    pragma Export (C, u00020, "system__machine_codeS");
22273    pragma Export (C, u00021, "system__storage_elementsB");
22274    pragma Export (C, u00022, "system__storage_elementsS");
22275    pragma Export (C, u00023, "system__secondary_stackB");
22276    pragma Export (C, u00024, "system__secondary_stackS");
22277    pragma Export (C, u00025, "system__parametersB");
22278    pragma Export (C, u00026, "system__parametersS");
22279    pragma Export (C, u00027, "system__soft_linksB");
22280    pragma Export (C, u00028, "system__soft_linksS");
22281    pragma Export (C, u00029, "system__stack_checkingB");
22282    pragma Export (C, u00030, "system__stack_checkingS");
22283    pragma Export (C, u00031, "system__tracebackB");
22284    pragma Export (C, u00032, "system__tracebackS");
22285    pragma Export (C, u00033, "ada__streamsS");
22286    pragma Export (C, u00034, "ada__tagsB");
22287    pragma Export (C, u00035, "ada__tagsS");
22288    pragma Export (C, u00036, "system__string_opsB");
22289    pragma Export (C, u00037, "system__string_opsS");
22290    pragma Export (C, u00038, "interfacesS");
22291    pragma Export (C, u00039, "interfaces__c_streamsB");
22292    pragma Export (C, u00040, "interfaces__c_streamsS");
22293    pragma Export (C, u00041, "system__file_ioB");
22294    pragma Export (C, u00042, "system__file_ioS");
22295    pragma Export (C, u00043, "ada__finalizationB");
22296    pragma Export (C, u00044, "ada__finalizationS");
22297    pragma Export (C, u00045, "system__finalization_rootB");
22298    pragma Export (C, u00046, "system__finalization_rootS");
22299    pragma Export (C, u00047, "system__finalization_implementationB");
22300    pragma Export (C, u00048, "system__finalization_implementationS");
22301    pragma Export (C, u00049, "system__string_ops_concat_3B");
22302    pragma Export (C, u00050, "system__string_ops_concat_3S");
22303    pragma Export (C, u00051, "system__stream_attributesB");
22304    pragma Export (C, u00052, "system__stream_attributesS");
22305    pragma Export (C, u00053, "ada__io_exceptionsS");
22306    pragma Export (C, u00054, "system__unsigned_typesS");
22307    pragma Export (C, u00055, "system__file_control_blockS");
22308    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22309    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22310
22311    -- BEGIN ELABORATION ORDER
22312    -- ada (spec)
22313    -- gnat (spec)
22314    -- gnat.heap_sort_a (spec)
22315    -- gnat.heap_sort_a (body)
22316    -- gnat.htable (spec)
22317    -- gnat.htable (body)
22318    -- interfaces (spec)
22319    -- system (spec)
22320    -- system.machine_code (spec)
22321    -- system.parameters (spec)
22322    -- system.parameters (body)
22323    -- interfaces.c_streams (spec)
22324    -- interfaces.c_streams (body)
22325    -- system.standard_library (spec)
22326    -- ada.exceptions (spec)
22327    -- system.exception_table (spec)
22328    -- system.exception_table (body)
22329    -- ada.io_exceptions (spec)
22330    -- system.exceptions (spec)
22331    -- system.storage_elements (spec)
22332    -- system.storage_elements (body)
22333    -- system.machine_state_operations (spec)
22334    -- system.machine_state_operations (body)
22335    -- system.secondary_stack (spec)
22336    -- system.stack_checking (spec)
22337    -- system.soft_links (spec)
22338    -- system.soft_links (body)
22339    -- system.stack_checking (body)
22340    -- system.secondary_stack (body)
22341    -- system.standard_library (body)
22342    -- system.string_ops (spec)
22343    -- system.string_ops (body)
22344    -- ada.tags (spec)
22345    -- ada.tags (body)
22346    -- ada.streams (spec)
22347    -- system.finalization_root (spec)
22348    -- system.finalization_root (body)
22349    -- system.string_ops_concat_3 (spec)
22350    -- system.string_ops_concat_3 (body)
22351    -- system.traceback (spec)
22352    -- system.traceback (body)
22353    -- ada.exceptions (body)
22354    -- system.unsigned_types (spec)
22355    -- system.stream_attributes (spec)
22356    -- system.stream_attributes (body)
22357    -- system.finalization_implementation (spec)
22358    -- system.finalization_implementation (body)
22359    -- ada.finalization (spec)
22360    -- ada.finalization (body)
22361    -- ada.finalization.list_controller (spec)
22362    -- ada.finalization.list_controller (body)
22363    -- system.file_control_block (spec)
22364    -- system.file_io (spec)
22365    -- system.file_io (body)
22366    -- ada.text_io (spec)
22367    -- ada.text_io (body)
22368    -- hello (body)
22369    -- END ELABORATION ORDER
22370
22371 end ada_main;
22372
22373 --  The following source file name pragmas allow the generated file
22374 --  names to be unique for different main programs. They are needed
22375 --  since the package name will always be Ada_Main.
22376
22377 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22378 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22379
22380 --  Generated package body for Ada_Main starts here
22381
22382 package body ada_main is
22383
22384    --  The actual finalization is performed by calling the
22385    --  library routine in System.Standard_Library.Adafinal
22386
22387    procedure Do_Finalize;
22388    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22389
22390    -------------
22391    -- adainit --
22392    -------------
22393
22394 @findex adainit
22395    procedure adainit is
22396
22397       --  These booleans are set to True once the associated unit has
22398       --  been elaborated. It is also used to avoid elaborating the
22399       --  same unit twice.
22400
22401       E040 : Boolean;
22402       pragma Import (Ada, E040, "interfaces__c_streams_E");
22403
22404       E008 : Boolean;
22405       pragma Import (Ada, E008, "ada__exceptions_E");
22406
22407       E014 : Boolean;
22408       pragma Import (Ada, E014, "system__exception_table_E");
22409
22410       E053 : Boolean;
22411       pragma Import (Ada, E053, "ada__io_exceptions_E");
22412
22413       E017 : Boolean;
22414       pragma Import (Ada, E017, "system__exceptions_E");
22415
22416       E024 : Boolean;
22417       pragma Import (Ada, E024, "system__secondary_stack_E");
22418
22419       E030 : Boolean;
22420       pragma Import (Ada, E030, "system__stack_checking_E");
22421
22422       E028 : Boolean;
22423       pragma Import (Ada, E028, "system__soft_links_E");
22424
22425       E035 : Boolean;
22426       pragma Import (Ada, E035, "ada__tags_E");
22427
22428       E033 : Boolean;
22429       pragma Import (Ada, E033, "ada__streams_E");
22430
22431       E046 : Boolean;
22432       pragma Import (Ada, E046, "system__finalization_root_E");
22433
22434       E048 : Boolean;
22435       pragma Import (Ada, E048, "system__finalization_implementation_E");
22436
22437       E044 : Boolean;
22438       pragma Import (Ada, E044, "ada__finalization_E");
22439
22440       E057 : Boolean;
22441       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22442
22443       E055 : Boolean;
22444       pragma Import (Ada, E055, "system__file_control_block_E");
22445
22446       E042 : Boolean;
22447       pragma Import (Ada, E042, "system__file_io_E");
22448
22449       E006 : Boolean;
22450       pragma Import (Ada, E006, "ada__text_io_E");
22451
22452       --  Set_Globals is a library routine that stores away the
22453       --  value of the indicated set of global values in global
22454       --  variables within the library.
22455
22456       procedure Set_Globals
22457         (Main_Priority            : Integer;
22458          Time_Slice_Value         : Integer;
22459          WC_Encoding              : Character;
22460          Locking_Policy           : Character;
22461          Queuing_Policy           : Character;
22462          Task_Dispatching_Policy  : Character;
22463          Adafinal                 : System.Address;
22464          Unreserve_All_Interrupts : Integer;
22465          Exception_Tracebacks     : Integer);
22466 @findex __gnat_set_globals
22467       pragma Import (C, Set_Globals, "__gnat_set_globals");
22468
22469       --  SDP_Table_Build is a library routine used to build the
22470       --  exception tables. See unit Ada.Exceptions in files
22471       --  a-except.ads/adb for full details of how zero cost
22472       --  exception handling works. This procedure, the call to
22473       --  it, and the two following tables are all omitted if the
22474       --  build is in longjmp/setjmp exception mode.
22475
22476 @findex SDP_Table_Build
22477 @findex Zero Cost Exceptions
22478       procedure SDP_Table_Build
22479         (SDP_Addresses   : System.Address;
22480          SDP_Count       : Natural;
22481          Elab_Addresses  : System.Address;
22482          Elab_Addr_Count : Natural);
22483       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22484
22485       --  Table of Unit_Exception_Table addresses. Used for zero
22486       --  cost exception handling to build the top level table.
22487
22488       ST : aliased constant array (1 .. 23) of System.Address := (
22489         Hello'UET_Address,
22490         Ada.Text_Io'UET_Address,
22491         Ada.Exceptions'UET_Address,
22492         Gnat.Heap_Sort_A'UET_Address,
22493         System.Exception_Table'UET_Address,
22494         System.Machine_State_Operations'UET_Address,
22495         System.Secondary_Stack'UET_Address,
22496         System.Parameters'UET_Address,
22497         System.Soft_Links'UET_Address,
22498         System.Stack_Checking'UET_Address,
22499         System.Traceback'UET_Address,
22500         Ada.Streams'UET_Address,
22501         Ada.Tags'UET_Address,
22502         System.String_Ops'UET_Address,
22503         Interfaces.C_Streams'UET_Address,
22504         System.File_Io'UET_Address,
22505         Ada.Finalization'UET_Address,
22506         System.Finalization_Root'UET_Address,
22507         System.Finalization_Implementation'UET_Address,
22508         System.String_Ops_Concat_3'UET_Address,
22509         System.Stream_Attributes'UET_Address,
22510         System.File_Control_Block'UET_Address,
22511         Ada.Finalization.List_Controller'UET_Address);
22512
22513       --  Table of addresses of elaboration routines. Used for
22514       --  zero cost exception handling to make sure these
22515       --  addresses are included in the top level procedure
22516       --  address table.
22517
22518       EA : aliased constant array (1 .. 23) of System.Address := (
22519         adainit'Code_Address,
22520         Do_Finalize'Code_Address,
22521         Ada.Exceptions'Elab_Spec'Address,
22522         System.Exceptions'Elab_Spec'Address,
22523         Interfaces.C_Streams'Elab_Spec'Address,
22524         System.Exception_Table'Elab_Body'Address,
22525         Ada.Io_Exceptions'Elab_Spec'Address,
22526         System.Stack_Checking'Elab_Spec'Address,
22527         System.Soft_Links'Elab_Body'Address,
22528         System.Secondary_Stack'Elab_Body'Address,
22529         Ada.Tags'Elab_Spec'Address,
22530         Ada.Tags'Elab_Body'Address,
22531         Ada.Streams'Elab_Spec'Address,
22532         System.Finalization_Root'Elab_Spec'Address,
22533         Ada.Exceptions'Elab_Body'Address,
22534         System.Finalization_Implementation'Elab_Spec'Address,
22535         System.Finalization_Implementation'Elab_Body'Address,
22536         Ada.Finalization'Elab_Spec'Address,
22537         Ada.Finalization.List_Controller'Elab_Spec'Address,
22538         System.File_Control_Block'Elab_Spec'Address,
22539         System.File_Io'Elab_Body'Address,
22540         Ada.Text_Io'Elab_Spec'Address,
22541         Ada.Text_Io'Elab_Body'Address);
22542
22543    --  Start of processing for adainit
22544
22545    begin
22546
22547       --  Call SDP_Table_Build to build the top level procedure
22548       --  table for zero cost exception handling (omitted in
22549       --  longjmp/setjmp mode).
22550
22551       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22552
22553       --  Call Set_Globals to record various information for
22554       --  this partition.  The values are derived by the binder
22555       --  from information stored in the ali files by the compiler.
22556
22557 @findex __gnat_set_globals
22558       Set_Globals
22559         (Main_Priority            => -1,
22560          --  Priority of main program, -1 if no pragma Priority used
22561
22562          Time_Slice_Value         => -1,
22563          --  Time slice from Time_Slice pragma, -1 if none used
22564
22565          WC_Encoding              => 'b',
22566          --  Wide_Character encoding used, default is brackets
22567
22568          Locking_Policy           => ' ',
22569          --  Locking_Policy used, default of space means not
22570          --  specified, otherwise it is the first character of
22571          --  the policy name.
22572
22573          Queuing_Policy           => ' ',
22574          --  Queuing_Policy used, default of space means not
22575          --  specified, otherwise it is the first character of
22576          --  the policy name.
22577
22578          Task_Dispatching_Policy  => ' ',
22579          --  Task_Dispatching_Policy used, default of space means
22580          --  not specified, otherwise first character of the
22581          --  policy name.
22582
22583          Adafinal                 => System.Null_Address,
22584          --  Address of Adafinal routine, not used anymore
22585
22586          Unreserve_All_Interrupts => 0,
22587          --  Set true if pragma Unreserve_All_Interrupts was used
22588
22589          Exception_Tracebacks     => 0);
22590          --  Indicates if exception tracebacks are enabled
22591
22592       Elab_Final_Code := 1;
22593
22594       --  Now we have the elaboration calls for all units in the partition.
22595       --  The Elab_Spec and Elab_Body attributes generate references to the
22596       --  implicit elaboration procedures generated by the compiler for
22597       --  each unit that requires elaboration.
22598
22599       if not E040 then
22600          Interfaces.C_Streams'Elab_Spec;
22601       end if;
22602       E040 := True;
22603       if not E008 then
22604          Ada.Exceptions'Elab_Spec;
22605       end if;
22606       if not E014 then
22607          System.Exception_Table'Elab_Body;
22608          E014 := True;
22609       end if;
22610       if not E053 then
22611          Ada.Io_Exceptions'Elab_Spec;
22612          E053 := True;
22613       end if;
22614       if not E017 then
22615          System.Exceptions'Elab_Spec;
22616          E017 := True;
22617       end if;
22618       if not E030 then
22619          System.Stack_Checking'Elab_Spec;
22620       end if;
22621       if not E028 then
22622          System.Soft_Links'Elab_Body;
22623          E028 := True;
22624       end if;
22625       E030 := True;
22626       if not E024 then
22627          System.Secondary_Stack'Elab_Body;
22628          E024 := True;
22629       end if;
22630       if not E035 then
22631          Ada.Tags'Elab_Spec;
22632       end if;
22633       if not E035 then
22634          Ada.Tags'Elab_Body;
22635          E035 := True;
22636       end if;
22637       if not E033 then
22638          Ada.Streams'Elab_Spec;
22639          E033 := True;
22640       end if;
22641       if not E046 then
22642          System.Finalization_Root'Elab_Spec;
22643       end if;
22644       E046 := True;
22645       if not E008 then
22646          Ada.Exceptions'Elab_Body;
22647          E008 := True;
22648       end if;
22649       if not E048 then
22650          System.Finalization_Implementation'Elab_Spec;
22651       end if;
22652       if not E048 then
22653          System.Finalization_Implementation'Elab_Body;
22654          E048 := True;
22655       end if;
22656       if not E044 then
22657          Ada.Finalization'Elab_Spec;
22658       end if;
22659       E044 := True;
22660       if not E057 then
22661          Ada.Finalization.List_Controller'Elab_Spec;
22662       end if;
22663       E057 := True;
22664       if not E055 then
22665          System.File_Control_Block'Elab_Spec;
22666          E055 := True;
22667       end if;
22668       if not E042 then
22669          System.File_Io'Elab_Body;
22670          E042 := True;
22671       end if;
22672       if not E006 then
22673          Ada.Text_Io'Elab_Spec;
22674       end if;
22675       if not E006 then
22676          Ada.Text_Io'Elab_Body;
22677          E006 := True;
22678       end if;
22679
22680       Elab_Final_Code := 0;
22681    end adainit;
22682
22683    --------------
22684    -- adafinal --
22685    --------------
22686
22687 @findex adafinal
22688    procedure adafinal is
22689    begin
22690       Do_Finalize;
22691    end adafinal;
22692
22693    ----------
22694    -- main --
22695    ----------
22696
22697    --  main is actually a function, as in the ANSI C standard,
22698    --  defined to return the exit status. The three parameters
22699    --  are the argument count, argument values and environment
22700    --  pointer.
22701
22702 @findex Main Program
22703    function main
22704      (argc : Integer;
22705       argv : System.Address;
22706       envp : System.Address)
22707       return Integer
22708    is
22709       --  The initialize routine performs low level system
22710       --  initialization using a standard library routine which
22711       --  sets up signal handling and performs any other
22712       --  required setup. The routine can be found in file
22713       --  a-init.c.
22714
22715 @findex __gnat_initialize
22716       procedure initialize;
22717       pragma Import (C, initialize, "__gnat_initialize");
22718
22719       --  The finalize routine performs low level system
22720       --  finalization using a standard library routine. The
22721       --  routine is found in file a-final.c and in the standard
22722       --  distribution is a dummy routine that does nothing, so
22723       --  really this is a hook for special user finalization.
22724
22725 @findex __gnat_finalize
22726       procedure finalize;
22727       pragma Import (C, finalize, "__gnat_finalize");
22728
22729       --  We get to the main program of the partition by using
22730       --  pragma Import because if we try to with the unit and
22731       --  call it Ada style, then not only do we waste time
22732       --  recompiling it, but also, we don't really know the right
22733       --  switches (e.g.@: identifier character set) to be used
22734       --  to compile it.
22735
22736       procedure Ada_Main_Program;
22737       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22738
22739    --  Start of processing for main
22740
22741    begin
22742       --  Save global variables
22743
22744       gnat_argc := argc;
22745       gnat_argv := argv;
22746       gnat_envp := envp;
22747
22748       --  Call low level system initialization
22749
22750       Initialize;
22751
22752       --  Call our generated Ada initialization routine
22753
22754       adainit;
22755
22756       --  This is the point at which we want the debugger to get
22757       --  control
22758
22759       Break_Start;
22760
22761       --  Now we call the main program of the partition
22762
22763       Ada_Main_Program;
22764
22765       --  Perform Ada finalization
22766
22767       adafinal;
22768
22769       --  Perform low level system finalization
22770
22771       Finalize;
22772
22773       --  Return the proper exit status
22774       return (gnat_exit_status);
22775    end;
22776
22777 --  This section is entirely comments, so it has no effect on the
22778 --  compilation of the Ada_Main package. It provides the list of
22779 --  object files and linker options, as well as some standard
22780 --  libraries needed for the link. The gnatlink utility parses
22781 --  this b~hello.adb file to read these comment lines to generate
22782 --  the appropriate command line arguments for the call to the
22783 --  system linker. The BEGIN/END lines are used for sentinels for
22784 --  this parsing operation.
22785
22786 --  The exact file names will of course depend on the environment,
22787 --  host/target and location of files on the host system.
22788
22789 @findex Object file list
22790 -- BEGIN Object file/option list
22791    --   ./hello.o
22792    --   -L./
22793    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22794    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22795 -- END Object file/option list
22796
22797 end ada_main;
22798 @end smallexample
22799
22800 @noindent
22801 The Ada code in the above example is exactly what is generated by the
22802 binder. We have added comments to more clearly indicate the function
22803 of each part of the generated @code{Ada_Main} package.
22804
22805 The code is standard Ada in all respects, and can be processed by any
22806 tools that handle Ada. In particular, it is possible to use the debugger
22807 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22808 suppose that for reasons that you do not understand, your program is crashing
22809 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22810 you can place a breakpoint on the call:
22811
22812 @smallexample @c ada
22813 Ada.Text_Io'Elab_Body;
22814 @end smallexample
22815
22816 @noindent
22817 and trace the elaboration routine for this package to find out where
22818 the problem might be (more usually of course you would be debugging
22819 elaboration code in your own application).
22820
22821 @node Elaboration Order Handling in GNAT
22822 @appendix Elaboration Order Handling in GNAT
22823 @cindex Order of elaboration
22824 @cindex Elaboration control
22825
22826 @menu
22827 * Elaboration Code::
22828 * Checking the Elaboration Order::
22829 * Controlling the Elaboration Order::
22830 * Controlling Elaboration in GNAT - Internal Calls::
22831 * Controlling Elaboration in GNAT - External Calls::
22832 * Default Behavior in GNAT - Ensuring Safety::
22833 * Treatment of Pragma Elaborate::
22834 * Elaboration Issues for Library Tasks::
22835 * Mixing Elaboration Models::
22836 * What to Do If the Default Elaboration Behavior Fails::
22837 * Elaboration for Access-to-Subprogram Values::
22838 * Summary of Procedures for Elaboration Control::
22839 * Other Elaboration Order Considerations::
22840 @end menu
22841
22842 @noindent
22843 This chapter describes the handling of elaboration code in Ada and
22844 in GNAT, and discusses how the order of elaboration of program units can
22845 be controlled in GNAT, either automatically or with explicit programming
22846 features.
22847
22848 @node Elaboration Code
22849 @section Elaboration Code
22850
22851 @noindent
22852 Ada provides rather general mechanisms for executing code at elaboration
22853 time, that is to say before the main program starts executing. Such code arises
22854 in three contexts:
22855
22856 @table @asis
22857 @item Initializers for variables.
22858 Variables declared at the library level, in package specs or bodies, can
22859 require initialization that is performed at elaboration time, as in:
22860 @smallexample @c ada
22861 @cartouche
22862 Sqrt_Half : Float := Sqrt (0.5);
22863 @end cartouche
22864 @end smallexample
22865
22866 @item Package initialization code
22867 Code in a @code{BEGIN-END} section at the outer level of a package body is
22868 executed as part of the package body elaboration code.
22869
22870 @item Library level task allocators
22871 Tasks that are declared using task allocators at the library level
22872 start executing immediately and hence can execute at elaboration time.
22873 @end table
22874
22875 @noindent
22876 Subprogram calls are possible in any of these contexts, which means that
22877 any arbitrary part of the program may be executed as part of the elaboration
22878 code. It is even possible to write a program which does all its work at
22879 elaboration time, with a null main program, although stylistically this
22880 would usually be considered an inappropriate way to structure
22881 a program.
22882
22883 An important concern arises in the context of elaboration code:
22884 we have to be sure that it is executed in an appropriate order. What we
22885 have is a series of elaboration code sections, potentially one section
22886 for each unit in the program. It is important that these execute
22887 in the correct order. Correctness here means that, taking the above
22888 example of the declaration of @code{Sqrt_Half},
22889 if some other piece of
22890 elaboration code references @code{Sqrt_Half},
22891 then it must run after the
22892 section of elaboration code that contains the declaration of
22893 @code{Sqrt_Half}.
22894
22895 There would never be any order of elaboration problem if we made a rule
22896 that whenever you @code{with} a unit, you must elaborate both the spec and body
22897 of that unit before elaborating the unit doing the @code{with}'ing:
22898
22899 @smallexample @c ada
22900 @group
22901 @cartouche
22902 with Unit_1;
22903 package Unit_2 is @dots{}
22904 @end cartouche
22905 @end group
22906 @end smallexample
22907
22908 @noindent
22909 would require that both the body and spec of @code{Unit_1} be elaborated
22910 before the spec of @code{Unit_2}. However, a rule like that would be far too
22911 restrictive. In particular, it would make it impossible to have routines
22912 in separate packages that were mutually recursive.
22913
22914 You might think that a clever enough compiler could look at the actual
22915 elaboration code and determine an appropriate correct order of elaboration,
22916 but in the general case, this is not possible. Consider the following
22917 example.
22918
22919 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22920 that references
22921 the variable @code{Sqrt_1}, which is declared in the elaboration code
22922 of the body of @code{Unit_1}:
22923
22924 @smallexample @c ada
22925 @cartouche
22926 Sqrt_1 : Float := Sqrt (0.1);
22927 @end cartouche
22928 @end smallexample
22929
22930 @noindent
22931 The elaboration code of the body of @code{Unit_1} also contains:
22932
22933 @smallexample @c ada
22934 @group
22935 @cartouche
22936 if expression_1 = 1 then
22937    Q := Unit_2.Func_2;
22938 end if;
22939 @end cartouche
22940 @end group
22941 @end smallexample
22942
22943 @noindent
22944 @code{Unit_2} is exactly parallel,
22945 it has a procedure @code{Func_2} that references
22946 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22947 the body @code{Unit_2}:
22948
22949 @smallexample @c ada
22950 @cartouche
22951 Sqrt_2 : Float := Sqrt (0.1);
22952 @end cartouche
22953 @end smallexample
22954
22955 @noindent
22956 The elaboration code of the body of @code{Unit_2} also contains:
22957
22958 @smallexample @c ada
22959 @group
22960 @cartouche
22961 if expression_2 = 2 then
22962    Q := Unit_1.Func_1;
22963 end if;
22964 @end cartouche
22965 @end group
22966 @end smallexample
22967
22968 @noindent
22969 Now the question is, which of the following orders of elaboration is
22970 acceptable:
22971
22972 @smallexample
22973 @group
22974 Spec of Unit_1
22975 Spec of Unit_2
22976 Body of Unit_1
22977 Body of Unit_2
22978 @end group
22979 @end smallexample
22980
22981 @noindent
22982 or
22983
22984 @smallexample
22985 @group
22986 Spec of Unit_2
22987 Spec of Unit_1
22988 Body of Unit_2
22989 Body of Unit_1
22990 @end group
22991 @end smallexample
22992
22993 @noindent
22994 If you carefully analyze the flow here, you will see that you cannot tell
22995 at compile time the answer to this question.
22996 If @code{expression_1} is not equal to 1,
22997 and @code{expression_2} is not equal to 2,
22998 then either order is acceptable, because neither of the function calls is
22999 executed. If both tests evaluate to true, then neither order is acceptable
23000 and in fact there is no correct order.
23001
23002 If one of the two expressions is true, and the other is false, then one
23003 of the above orders is correct, and the other is incorrect. For example,
23004 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23005 then the call to @code{Func_1}
23006 will occur, but not the call to @code{Func_2.}
23007 This means that it is essential
23008 to elaborate the body of @code{Unit_1} before
23009 the body of @code{Unit_2}, so the first
23010 order of elaboration is correct and the second is wrong.
23011
23012 By making @code{expression_1} and @code{expression_2}
23013 depend on input data, or perhaps
23014 the time of day, we can make it impossible for the compiler or binder
23015 to figure out which of these expressions will be true, and hence it
23016 is impossible to guarantee a safe order of elaboration at run time.
23017
23018 @node Checking the Elaboration Order
23019 @section Checking the Elaboration Order
23020
23021 @noindent
23022 In some languages that involve the same kind of elaboration problems,
23023 e.g.@: Java and C++, the programmer is expected to worry about these
23024 ordering problems himself, and it is common to
23025 write a program in which an incorrect elaboration order  gives
23026 surprising results, because it references variables before they
23027 are initialized.
23028 Ada is designed to be a safe language, and a programmer-beware approach is
23029 clearly not sufficient. Consequently, the language provides three lines
23030 of defense:
23031
23032 @table @asis
23033 @item Standard rules
23034 Some standard rules restrict the possible choice of elaboration
23035 order. In particular, if you @code{with} a unit, then its spec is always
23036 elaborated before the unit doing the @code{with}. Similarly, a parent
23037 spec is always elaborated before the child spec, and finally
23038 a spec is always elaborated before its corresponding body.
23039
23040 @item Dynamic elaboration checks
23041 @cindex Elaboration checks
23042 @cindex Checks, elaboration
23043 Dynamic checks are made at run time, so that if some entity is accessed
23044 before it is elaborated (typically  by means of a subprogram call)
23045 then the exception (@code{Program_Error}) is raised.
23046
23047 @item Elaboration control
23048 Facilities are provided for the programmer to specify the desired order
23049 of elaboration.
23050 @end table
23051
23052 Let's look at these facilities in more detail. First, the rules for
23053 dynamic checking. One possible rule would be simply to say that the
23054 exception is raised if you access a variable which has not yet been
23055 elaborated. The trouble with this approach is that it could require
23056 expensive checks on every variable reference. Instead Ada has two
23057 rules which are a little more restrictive, but easier to check, and
23058 easier to state:
23059
23060 @table @asis
23061 @item Restrictions on calls
23062 A subprogram can only be called at elaboration time if its body
23063 has been elaborated. The rules for elaboration given above guarantee
23064 that the spec of the subprogram has been elaborated before the
23065 call, but not the body. If this rule is violated, then the
23066 exception @code{Program_Error} is raised.
23067
23068 @item Restrictions on instantiations
23069 A generic unit can only be instantiated if the body of the generic
23070 unit has been elaborated. Again, the rules for elaboration given above
23071 guarantee that the spec of the generic unit has been elaborated
23072 before the instantiation, but not the body. If this rule is
23073 violated, then the exception @code{Program_Error} is raised.
23074 @end table
23075
23076 @noindent
23077 The idea is that if the body has been elaborated, then any variables
23078 it references must have been elaborated; by checking for the body being
23079 elaborated we guarantee that none of its references causes any
23080 trouble. As we noted above, this is a little too restrictive, because a
23081 subprogram that has no non-local references in its body may in fact be safe
23082 to call. However, it really would be unsafe to rely on this, because
23083 it would mean that the caller was aware of details of the implementation
23084 in the body. This goes against the basic tenets of Ada.
23085
23086 A plausible implementation can be described as follows.
23087 A Boolean variable is associated with each subprogram
23088 and each generic unit. This variable is initialized to False, and is set to
23089 True at the point body is elaborated. Every call or instantiation checks the
23090 variable, and raises @code{Program_Error} if the variable is False.
23091
23092 Note that one might think that it would be good enough to have one Boolean
23093 variable for each package, but that would not deal with cases of trying
23094 to call a body in the same package as the call
23095 that has not been elaborated yet.
23096 Of course a compiler may be able to do enough analysis to optimize away
23097 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23098 does such optimizations, but still the easiest conceptual model is to
23099 think of there being one variable per subprogram.
23100
23101 @node Controlling the Elaboration Order
23102 @section Controlling the Elaboration Order
23103
23104 @noindent
23105 In the previous section we discussed the rules in Ada which ensure
23106 that @code{Program_Error} is raised if an incorrect elaboration order is
23107 chosen. This prevents erroneous executions, but we need mechanisms to
23108 specify a correct execution and avoid the exception altogether.
23109 To achieve this, Ada provides a number of features for controlling
23110 the order of elaboration. We discuss these features in this section.
23111
23112 First, there are several ways of indicating to the compiler that a given
23113 unit has no elaboration problems:
23114
23115 @table @asis
23116 @item packages that do not require a body
23117 A library package that does not require a body does not permit
23118 a body (this rule was introduced in Ada 95).
23119 Thus if we have a such a package, as in:
23120
23121 @smallexample @c ada
23122 @group
23123 @cartouche
23124 package Definitions is
23125    generic
23126       type m is new integer;
23127    package Subp is
23128       type a is array (1 .. 10) of m;
23129       type b is array (1 .. 20) of m;
23130    end Subp;
23131 end Definitions;
23132 @end cartouche
23133 @end group
23134 @end smallexample
23135
23136 @noindent
23137 A package that @code{with}'s @code{Definitions} may safely instantiate
23138 @code{Definitions.Subp} because the compiler can determine that there
23139 definitely is no package body to worry about in this case
23140
23141 @item pragma Pure
23142 @cindex pragma Pure
23143 @findex Pure
23144 Places sufficient restrictions on a unit to guarantee that
23145 no call to any subprogram in the unit can result in an
23146 elaboration problem. This means that the compiler does not need
23147 to worry about the point of elaboration of such units, and in
23148 particular, does not need to check any calls to any subprograms
23149 in this unit.
23150
23151 @item pragma Preelaborate
23152 @findex Preelaborate
23153 @cindex pragma Preelaborate
23154 This pragma places slightly less stringent restrictions on a unit than
23155 does pragma Pure,
23156 but these restrictions are still sufficient to ensure that there
23157 are no elaboration problems with any calls to the unit.
23158
23159 @item pragma Elaborate_Body
23160 @findex Elaborate_Body
23161 @cindex pragma Elaborate_Body
23162 This pragma requires that the body of a unit be elaborated immediately
23163 after its spec. Suppose a unit @code{A} has such a pragma,
23164 and unit @code{B} does
23165 a @code{with} of unit @code{A}. Recall that the standard rules require
23166 the spec of unit @code{A}
23167 to be elaborated before the @code{with}'ing unit; given the pragma in
23168 @code{A}, we also know that the body of @code{A}
23169 will be elaborated before @code{B}, so
23170 that calls to @code{A} are safe and do not need a check.
23171 @end table
23172
23173 @noindent
23174 Note that,
23175 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23176 the use of
23177 @code{Elaborate_Body} does not guarantee that the program is
23178 free of elaboration problems, because it may not be possible
23179 to satisfy the requested elaboration order.
23180 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23181 If a programmer
23182 marks @code{Unit_1} as @code{Elaborate_Body},
23183 and not @code{Unit_2,} then the order of
23184 elaboration will be:
23185
23186 @smallexample
23187 @group
23188 Spec of Unit_2
23189 Spec of Unit_1
23190 Body of Unit_1
23191 Body of Unit_2
23192 @end group
23193 @end smallexample
23194
23195 @noindent
23196 Now that means that the call to @code{Func_1} in @code{Unit_2}
23197 need not be checked,
23198 it must be safe. But the call to @code{Func_2} in
23199 @code{Unit_1} may still fail if
23200 @code{Expression_1} is equal to 1,
23201 and the programmer must still take
23202 responsibility for this not being the case.
23203
23204 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23205 eliminated, except for calls entirely within a body, which are
23206 in any case fully under programmer control. However, using the pragma
23207 everywhere is not always possible.
23208 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23209 we marked both of them as having pragma @code{Elaborate_Body}, then
23210 clearly there would be no possible elaboration order.
23211
23212 The above pragmas allow a server to guarantee safe use by clients, and
23213 clearly this is the preferable approach. Consequently a good rule
23214 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23215 and if this is not possible,
23216 mark them as @code{Elaborate_Body} if possible.
23217 As we have seen, there are situations where neither of these
23218 three pragmas can be used.
23219 So we also provide methods for clients to control the
23220 order of elaboration of the servers on which they depend:
23221
23222 @table @asis
23223 @item pragma Elaborate (unit)
23224 @findex Elaborate
23225 @cindex pragma Elaborate
23226 This pragma is placed in the context clause, after a @code{with} clause,
23227 and it requires that the body of the named unit be elaborated before
23228 the unit in which the pragma occurs. The idea is to use this pragma
23229 if the current unit calls at elaboration time, directly or indirectly,
23230 some subprogram in the named unit.
23231
23232 @item pragma Elaborate_All (unit)
23233 @findex Elaborate_All
23234 @cindex pragma Elaborate_All
23235 This is a stronger version of the Elaborate pragma. Consider the
23236 following example:
23237
23238 @smallexample
23239 Unit A @code{with}'s unit B and calls B.Func in elab code
23240 Unit B @code{with}'s unit C, and B.Func calls C.Func
23241 @end smallexample
23242
23243 @noindent
23244 Now if we put a pragma @code{Elaborate (B)}
23245 in unit @code{A}, this ensures that the
23246 body of @code{B} is elaborated before the call, but not the
23247 body of @code{C}, so
23248 the call to @code{C.Func} could still cause @code{Program_Error} to
23249 be raised.
23250
23251 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23252 not only that the body of the named unit be elaborated before the
23253 unit doing the @code{with}, but also the bodies of all units that the
23254 named unit uses, following @code{with} links transitively. For example,
23255 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23256 then it requires
23257 not only that the body of @code{B} be elaborated before @code{A},
23258 but also the
23259 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23260 @end table
23261
23262 @noindent
23263 We are now in a position to give a usage rule in Ada for avoiding
23264 elaboration problems, at least if dynamic dispatching and access to
23265 subprogram values are not used. We will handle these cases separately
23266 later.
23267
23268 The rule is simple. If a unit has elaboration code that can directly or
23269 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23270 a generic package in a @code{with}'ed unit,
23271 then if the @code{with}'ed unit does not have
23272 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23273 a pragma @code{Elaborate_All}
23274 for the @code{with}'ed unit. By following this rule a client is
23275 assured that calls can be made without risk of an exception.
23276
23277 For generic subprogram instantiations, the rule can be relaxed to
23278 require only a pragma @code{Elaborate} since elaborating the body
23279 of a subprogram cannot cause any transitive elaboration (we are
23280 not calling the subprogram in this case, just elaborating its
23281 declaration).
23282
23283 If this rule is not followed, then a program may be in one of four
23284 states:
23285
23286 @table @asis
23287 @item No order exists
23288 No order of elaboration exists which follows the rules, taking into
23289 account any @code{Elaborate}, @code{Elaborate_All},
23290 or @code{Elaborate_Body} pragmas. In
23291 this case, an Ada compiler must diagnose the situation at bind
23292 time, and refuse to build an executable program.
23293
23294 @item One or more orders exist, all incorrect
23295 One or more acceptable elaboration orders exist, and all of them
23296 generate an elaboration order problem. In this case, the binder
23297 can build an executable program, but @code{Program_Error} will be raised
23298 when the program is run.
23299
23300 @item Several orders exist, some right, some incorrect
23301 One or more acceptable elaboration orders exists, and some of them
23302 work, and some do not. The programmer has not controlled
23303 the order of elaboration, so the binder may or may not pick one of
23304 the correct orders, and the program may or may not raise an
23305 exception when it is run. This is the worst case, because it means
23306 that the program may fail when moved to another compiler, or even
23307 another version of the same compiler.
23308
23309 @item One or more orders exists, all correct
23310 One ore more acceptable elaboration orders exist, and all of them
23311 work. In this case the program runs successfully. This state of
23312 affairs can be guaranteed by following the rule we gave above, but
23313 may be true even if the rule is not followed.
23314 @end table
23315
23316 @noindent
23317 Note that one additional advantage of following our rules on the use
23318 of @code{Elaborate} and @code{Elaborate_All}
23319 is that the program continues to stay in the ideal (all orders OK) state
23320 even if maintenance
23321 changes some bodies of some units. Conversely, if a program that does
23322 not follow this rule happens to be safe at some point, this state of affairs
23323 may deteriorate silently as a result of maintenance changes.
23324
23325 You may have noticed that the above discussion did not mention
23326 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23327 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23328 code in the body makes calls to some other unit, so it is still necessary
23329 to use @code{Elaborate_All} on such units.
23330
23331 @node Controlling Elaboration in GNAT - Internal Calls
23332 @section Controlling Elaboration in GNAT - Internal Calls
23333
23334 @noindent
23335 In the case of internal calls, i.e., calls within a single package, the
23336 programmer has full control over the order of elaboration, and it is up
23337 to the programmer to elaborate declarations in an appropriate order. For
23338 example writing:
23339
23340 @smallexample @c ada
23341 @group
23342 @cartouche
23343 function One return Float;
23344
23345 Q : Float := One;
23346
23347 function One return Float is
23348 begin
23349      return 1.0;
23350 end One;
23351 @end cartouche
23352 @end group
23353 @end smallexample
23354
23355 @noindent
23356 will obviously raise @code{Program_Error} at run time, because function
23357 One will be called before its body is elaborated. In this case GNAT will
23358 generate a warning that the call will raise @code{Program_Error}:
23359
23360 @smallexample
23361 @group
23362 @cartouche
23363  1. procedure y is
23364  2.    function One return Float;
23365  3.
23366  4.    Q : Float := One;
23367                     |
23368     >>> warning: cannot call "One" before body is elaborated
23369     >>> warning: Program_Error will be raised at run time
23370
23371  5.
23372  6.    function One return Float is
23373  7.    begin
23374  8.         return 1.0;
23375  9.    end One;
23376 10.
23377 11. begin
23378 12.    null;
23379 13. end;
23380 @end cartouche
23381 @end group
23382 @end smallexample
23383
23384 @noindent
23385 Note that in this particular case, it is likely that the call is safe, because
23386 the function @code{One} does not access any global variables.
23387 Nevertheless in Ada, we do not want the validity of the check to depend on
23388 the contents of the body (think about the separate compilation case), so this
23389 is still wrong, as we discussed in the previous sections.
23390
23391 The error is easily corrected by rearranging the declarations so that the
23392 body of @code{One} appears before the declaration containing the call
23393 (note that in Ada 95 and Ada 2005,
23394 declarations can appear in any order, so there is no restriction that
23395 would prevent this reordering, and if we write:
23396
23397 @smallexample @c ada
23398 @group
23399 @cartouche
23400 function One return Float;
23401
23402 function One return Float is
23403 begin
23404      return 1.0;
23405 end One;
23406
23407 Q : Float := One;
23408 @end cartouche
23409 @end group
23410 @end smallexample
23411
23412 @noindent
23413 then all is well, no warning is generated, and no
23414 @code{Program_Error} exception
23415 will be raised.
23416 Things are more complicated when a chain of subprograms is executed:
23417
23418 @smallexample @c ada
23419 @group
23420 @cartouche
23421 function A return Integer;
23422 function B return Integer;
23423 function C return Integer;
23424
23425 function B return Integer is begin return A; end;
23426 function C return Integer is begin return B; end;
23427
23428 X : Integer := C;
23429
23430 function A return Integer is begin return 1; end;
23431 @end cartouche
23432 @end group
23433 @end smallexample
23434
23435 @noindent
23436 Now the call to @code{C}
23437 at elaboration time in the declaration of @code{X} is correct, because
23438 the body of @code{C} is already elaborated,
23439 and the call to @code{B} within the body of
23440 @code{C} is correct, but the call
23441 to @code{A} within the body of @code{B} is incorrect, because the body
23442 of @code{A} has not been elaborated, so @code{Program_Error}
23443 will be raised on the call to @code{A}.
23444 In this case GNAT will generate a
23445 warning that @code{Program_Error} may be
23446 raised at the point of the call. Let's look at the warning:
23447
23448 @smallexample
23449 @group
23450 @cartouche
23451  1. procedure x is
23452  2.    function A return Integer;
23453  3.    function B return Integer;
23454  4.    function C return Integer;
23455  5.
23456  6.    function B return Integer is begin return A; end;
23457                                                     |
23458     >>> warning: call to "A" before body is elaborated may
23459                  raise Program_Error
23460     >>> warning: "B" called at line 7
23461     >>> warning: "C" called at line 9
23462
23463  7.    function C return Integer is begin return B; end;
23464  8.
23465  9.    X : Integer := C;
23466 10.
23467 11.    function A return Integer is begin return 1; end;
23468 12.
23469 13. begin
23470 14.    null;
23471 15. end;
23472 @end cartouche
23473 @end group
23474 @end smallexample
23475
23476 @noindent
23477 Note that the message here says ``may raise'', instead of the direct case,
23478 where the message says ``will be raised''. That's because whether
23479 @code{A} is
23480 actually called depends in general on run-time flow of control.
23481 For example, if the body of @code{B} said
23482
23483 @smallexample @c ada
23484 @group
23485 @cartouche
23486 function B return Integer is
23487 begin
23488    if some-condition-depending-on-input-data then
23489       return A;
23490    else
23491       return 1;
23492    end if;
23493 end B;
23494 @end cartouche
23495 @end group
23496 @end smallexample
23497
23498 @noindent
23499 then we could not know until run time whether the incorrect call to A would
23500 actually occur, so @code{Program_Error} might
23501 or might not be raised. It is possible for a compiler to
23502 do a better job of analyzing bodies, to
23503 determine whether or not @code{Program_Error}
23504 might be raised, but it certainly
23505 couldn't do a perfect job (that would require solving the halting problem
23506 and is provably impossible), and because this is a warning anyway, it does
23507 not seem worth the effort to do the analysis. Cases in which it
23508 would be relevant are rare.
23509
23510 In practice, warnings of either of the forms given
23511 above will usually correspond to
23512 real errors, and should be examined carefully and eliminated.
23513 In the rare case where a warning is bogus, it can be suppressed by any of
23514 the following methods:
23515
23516 @itemize @bullet
23517 @item
23518 Compile with the @option{-gnatws} switch set
23519
23520 @item
23521 Suppress @code{Elaboration_Check} for the called subprogram
23522
23523 @item
23524 Use pragma @code{Warnings_Off} to turn warnings off for the call
23525 @end itemize
23526
23527 @noindent
23528 For the internal elaboration check case,
23529 GNAT by default generates the
23530 necessary run-time checks to ensure
23531 that @code{Program_Error} is raised if any
23532 call fails an elaboration check. Of course this can only happen if a
23533 warning has been issued as described above. The use of pragma
23534 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23535 some of these checks, meaning that it may be possible (but is not
23536 guaranteed) for a program to be able to call a subprogram whose body
23537 is not yet elaborated, without raising a @code{Program_Error} exception.
23538
23539 @node Controlling Elaboration in GNAT - External Calls
23540 @section Controlling Elaboration in GNAT - External Calls
23541
23542 @noindent
23543 The previous section discussed the case in which the execution of a
23544 particular thread of elaboration code occurred entirely within a
23545 single unit. This is the easy case to handle, because a programmer
23546 has direct and total control over the order of elaboration, and
23547 furthermore, checks need only be generated in cases which are rare
23548 and which the compiler can easily detect.
23549 The situation is more complex when separate compilation is taken into account.
23550 Consider the following:
23551
23552 @smallexample @c ada
23553 @cartouche
23554 @group
23555 package Math is
23556    function Sqrt (Arg : Float) return Float;
23557 end Math;
23558
23559 package body Math is
23560    function Sqrt (Arg : Float) return Float is
23561    begin
23562          @dots{}
23563    end Sqrt;
23564 end Math;
23565 @end group
23566 @group
23567 with Math;
23568 package Stuff is
23569    X : Float := Math.Sqrt (0.5);
23570 end Stuff;
23571
23572 with Stuff;
23573 procedure Main is
23574 begin
23575    @dots{}
23576 end Main;
23577 @end group
23578 @end cartouche
23579 @end smallexample
23580
23581 @noindent
23582 where @code{Main} is the main program. When this program is executed, the
23583 elaboration code must first be executed, and one of the jobs of the
23584 binder is to determine the order in which the units of a program are
23585 to be elaborated. In this case we have four units: the spec and body
23586 of @code{Math},
23587 the spec of @code{Stuff} and the body of @code{Main}).
23588 In what order should the four separate sections of elaboration code
23589 be executed?
23590
23591 There are some restrictions in the order of elaboration that the binder
23592 can choose. In particular, if unit U has a @code{with}
23593 for a package @code{X}, then you
23594 are assured that the spec of @code{X}
23595 is elaborated before U , but you are
23596 not assured that the body of @code{X}
23597 is elaborated before U.
23598 This means that in the above case, the binder is allowed to choose the
23599 order:
23600
23601 @smallexample
23602 spec of Math
23603 spec of Stuff
23604 body of Math
23605 body of Main
23606 @end smallexample
23607
23608 @noindent
23609 but that's not good, because now the call to @code{Math.Sqrt}
23610 that happens during
23611 the elaboration of the @code{Stuff}
23612 spec happens before the body of @code{Math.Sqrt} is
23613 elaborated, and hence causes @code{Program_Error} exception to be raised.
23614 At first glance, one might say that the binder is misbehaving, because
23615 obviously you want to elaborate the body of something you @code{with}
23616 first, but
23617 that is not a general rule that can be followed in all cases. Consider
23618
23619 @smallexample @c ada
23620 @group
23621 @cartouche
23622 package X is @dots{}
23623
23624 package Y is @dots{}
23625
23626 with X;
23627 package body Y is @dots{}
23628
23629 with Y;
23630 package body X is @dots{}
23631 @end cartouche
23632 @end group
23633 @end smallexample
23634
23635 @noindent
23636 This is a common arrangement, and, apart from the order of elaboration
23637 problems that might arise in connection with elaboration code, this works fine.
23638 A rule that says that you must first elaborate the body of anything you
23639 @code{with} cannot work in this case:
23640 the body of @code{X} @code{with}'s @code{Y},
23641 which means you would have to
23642 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23643 which means
23644 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23645 loop that cannot be broken.
23646
23647 It is true that the binder can in many cases guess an order of elaboration
23648 that is unlikely to cause a @code{Program_Error}
23649 exception to be raised, and it tries to do so (in the
23650 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23651 by default
23652 elaborate the body of @code{Math} right after its spec, so all will be well).
23653
23654 However, a program that blindly relies on the binder to be helpful can
23655 get into trouble, as we discussed in the previous sections, so
23656 GNAT
23657 provides a number of facilities for assisting the programmer in
23658 developing programs that are robust with respect to elaboration order.
23659
23660 @node Default Behavior in GNAT - Ensuring Safety
23661 @section Default Behavior in GNAT - Ensuring Safety
23662
23663 @noindent
23664 The default behavior in GNAT ensures elaboration safety. In its
23665 default mode GNAT implements the
23666 rule we previously described as the right approach. Let's restate it:
23667
23668 @itemize
23669 @item
23670 @emph{If a unit has elaboration code that can directly or indirectly make a
23671 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23672 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23673 does not have pragma @code{Pure} or
23674 @code{Preelaborate}, then the client should have an
23675 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23676
23677 @emph{In the case of instantiating a generic subprogram, it is always
23678 sufficient to have only an @code{Elaborate} pragma for the
23679 @code{with}'ed unit.}
23680 @end itemize
23681
23682 @noindent
23683 By following this rule a client is assured that calls and instantiations
23684 can be made without risk of an exception.
23685
23686 In this mode GNAT traces all calls that are potentially made from
23687 elaboration code, and puts in any missing implicit @code{Elaborate}
23688 and @code{Elaborate_All} pragmas.
23689 The advantage of this approach is that no elaboration problems
23690 are possible if the binder can find an elaboration order that is
23691 consistent with these implicit @code{Elaborate} and
23692 @code{Elaborate_All} pragmas. The
23693 disadvantage of this approach is that no such order may exist.
23694
23695 If the binder does not generate any diagnostics, then it means that it has
23696 found an elaboration order that is guaranteed to be safe. However, the binder
23697 may still be relying on implicitly generated @code{Elaborate} and
23698 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23699 guaranteed.
23700
23701 If it is important to guarantee portability, then the compilations should
23702 use the
23703 @option{-gnatwl}
23704 (warn on elaboration problems) switch. This will cause warning messages
23705 to be generated indicating the missing @code{Elaborate} and
23706 @code{Elaborate_All} pragmas.
23707 Consider the following source program:
23708
23709 @smallexample @c ada
23710 @group
23711 @cartouche
23712 with k;
23713 package j is
23714   m : integer := k.r;
23715 end;
23716 @end cartouche
23717 @end group
23718 @end smallexample
23719
23720 @noindent
23721 where it is clear that there
23722 should be a pragma @code{Elaborate_All}
23723 for unit @code{k}. An implicit pragma will be generated, and it is
23724 likely that the binder will be able to honor it. However, if you want
23725 to port this program to some other Ada compiler than GNAT.
23726 it is safer to include the pragma explicitly in the source. If this
23727 unit is compiled with the
23728 @option{-gnatwl}
23729 switch, then the compiler outputs a warning:
23730
23731 @smallexample
23732 @group
23733 @cartouche
23734 1. with k;
23735 2. package j is
23736 3.   m : integer := k.r;
23737                      |
23738    >>> warning: call to "r" may raise Program_Error
23739    >>> warning: missing pragma Elaborate_All for "k"
23740
23741 4. end;
23742 @end cartouche
23743 @end group
23744 @end smallexample
23745
23746 @noindent
23747 and these warnings can be used as a guide for supplying manually
23748 the missing pragmas. It is usually a bad idea to use this warning
23749 option during development. That's because it will warn you when
23750 you need to put in a pragma, but cannot warn you when it is time
23751 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23752 unnecessary dependencies and even false circularities.
23753
23754 This default mode is more restrictive than the Ada Reference
23755 Manual, and it is possible to construct programs which will compile
23756 using the dynamic model described there, but will run into a
23757 circularity using the safer static model we have described.
23758
23759 Of course any Ada compiler must be able to operate in a mode
23760 consistent with the requirements of the Ada Reference Manual,
23761 and in particular must have the capability of implementing the
23762 standard dynamic model of elaboration with run-time checks.
23763
23764 In GNAT, this standard mode can be achieved either by the use of
23765 the @option{-gnatE} switch on the compiler (@command{gcc} or
23766 @command{gnatmake}) command, or by the use of the configuration pragma:
23767
23768 @smallexample @c ada
23769 pragma Elaboration_Checks (DYNAMIC);
23770 @end smallexample
23771
23772 @noindent
23773 Either approach will cause the unit affected to be compiled using the
23774 standard dynamic run-time elaboration checks described in the Ada
23775 Reference Manual. The static model is generally preferable, since it
23776 is clearly safer to rely on compile and link time checks rather than
23777 run-time checks. However, in the case of legacy code, it may be
23778 difficult to meet the requirements of the static model. This
23779 issue is further discussed in
23780 @ref{What to Do If the Default Elaboration Behavior Fails}.
23781
23782 Note that the static model provides a strict subset of the allowed
23783 behavior and programs of the Ada Reference Manual, so if you do
23784 adhere to the static model and no circularities exist,
23785 then you are assured that your program will
23786 work using the dynamic model, providing that you remove any
23787 pragma Elaborate statements from the source.
23788
23789 @node Treatment of Pragma Elaborate
23790 @section Treatment of Pragma Elaborate
23791 @cindex Pragma Elaborate
23792
23793 @noindent
23794 The use of @code{pragma Elaborate}
23795 should generally be avoided in Ada 95 and Ada 2005 programs,
23796 since there is no guarantee that transitive calls
23797 will be properly handled. Indeed at one point, this pragma was placed
23798 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23799
23800 Now that's a bit restrictive. In practice, the case in which
23801 @code{pragma Elaborate} is useful is when the caller knows that there
23802 are no transitive calls, or that the called unit contains all necessary
23803 transitive @code{pragma Elaborate} statements, and legacy code often
23804 contains such uses.
23805
23806 Strictly speaking the static mode in GNAT should ignore such pragmas,
23807 since there is no assurance at compile time that the necessary safety
23808 conditions are met. In practice, this would cause GNAT to be incompatible
23809 with correctly written Ada 83 code that had all necessary
23810 @code{pragma Elaborate} statements in place. Consequently, we made the
23811 decision that GNAT in its default mode will believe that if it encounters
23812 a @code{pragma Elaborate} then the programmer knows what they are doing,
23813 and it will trust that no elaboration errors can occur.
23814
23815 The result of this decision is two-fold. First to be safe using the
23816 static mode, you should remove all @code{pragma Elaborate} statements.
23817 Second, when fixing circularities in existing code, you can selectively
23818 use @code{pragma Elaborate} statements to convince the static mode of
23819 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23820 statement.
23821
23822 When using the static mode with @option{-gnatwl}, any use of
23823 @code{pragma Elaborate} will generate a warning about possible
23824 problems.
23825
23826 @node Elaboration Issues for Library Tasks
23827 @section Elaboration Issues for Library Tasks
23828 @cindex Library tasks, elaboration issues
23829 @cindex Elaboration of library tasks
23830
23831 @noindent
23832 In this section we examine special elaboration issues that arise for
23833 programs that declare library level tasks.
23834
23835 Generally the model of execution of an Ada program is that all units are
23836 elaborated, and then execution of the program starts. However, the
23837 declaration of library tasks definitely does not fit this model. The
23838 reason for this is that library tasks start as soon as they are declared
23839 (more precisely, as soon as the statement part of the enclosing package
23840 body is reached), that is to say before elaboration
23841 of the program is complete. This means that if such a task calls a
23842 subprogram, or an entry in another task, the callee may or may not be
23843 elaborated yet, and in the standard
23844 Reference Manual model of dynamic elaboration checks, you can even
23845 get timing dependent Program_Error exceptions, since there can be
23846 a race between the elaboration code and the task code.
23847
23848 The static model of elaboration in GNAT seeks to avoid all such
23849 dynamic behavior, by being conservative, and the conservative
23850 approach in this particular case is to assume that all the code
23851 in a task body is potentially executed at elaboration time if
23852 a task is declared at the library level.
23853
23854 This can definitely result in unexpected circularities. Consider
23855 the following example
23856
23857 @smallexample @c ada
23858 package Decls is
23859   task Lib_Task is
23860      entry Start;
23861   end Lib_Task;
23862
23863   type My_Int is new Integer;
23864
23865   function Ident (M : My_Int) return My_Int;
23866 end Decls;
23867
23868 with Utils;
23869 package body Decls is
23870   task body Lib_Task is
23871   begin
23872      accept Start;
23873      Utils.Put_Val (2);
23874   end Lib_Task;
23875
23876   function Ident (M : My_Int) return My_Int is
23877   begin
23878      return M;
23879   end Ident;
23880 end Decls;
23881
23882 with Decls;
23883 package Utils is
23884   procedure Put_Val (Arg : Decls.My_Int);
23885 end Utils;
23886
23887 with Text_IO;
23888 package body Utils is
23889   procedure Put_Val (Arg : Decls.My_Int) is
23890   begin
23891      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23892   end Put_Val;
23893 end Utils;
23894
23895 with Decls;
23896 procedure Main is
23897 begin
23898    Decls.Lib_Task.Start;
23899 end;
23900 @end smallexample
23901
23902 @noindent
23903 If the above example is compiled in the default static elaboration
23904 mode, then a circularity occurs. The circularity comes from the call
23905 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23906 this call occurs in elaboration code, we need an implicit pragma
23907 @code{Elaborate_All} for @code{Utils}. This means that not only must
23908 the spec and body of @code{Utils} be elaborated before the body
23909 of @code{Decls}, but also the spec and body of any unit that is
23910 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23911 the body of @code{Decls}. This is the transitive implication of
23912 pragma @code{Elaborate_All} and it makes sense, because in general
23913 the body of @code{Put_Val} might have a call to something in a
23914 @code{with'ed} unit.
23915
23916 In this case, the body of Utils (actually its spec) @code{with's}
23917 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23918 must be elaborated before itself, in case there is a call from the
23919 body of @code{Utils}.
23920
23921 Here is the exact chain of events we are worrying about:
23922
23923 @enumerate
23924 @item
23925 In the body of @code{Decls} a call is made from within the body of a library
23926 task to a subprogram in the package @code{Utils}. Since this call may
23927 occur at elaboration time (given that the task is activated at elaboration
23928 time), we have to assume the worst, i.e., that the
23929 call does happen at elaboration time.
23930
23931 @item
23932 This means that the body and spec of @code{Util} must be elaborated before
23933 the body of @code{Decls} so that this call does not cause an access before
23934 elaboration.
23935
23936 @item
23937 Within the body of @code{Util}, specifically within the body of
23938 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23939 by this package.
23940
23941 @item
23942 One such @code{with}'ed package is package @code{Decls}, so there
23943 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23944 In fact there is such a call in this example, but we would have to
23945 assume that there was such a call even if it were not there, since
23946 we are not supposed to write the body of @code{Decls} knowing what
23947 is in the body of @code{Utils}; certainly in the case of the
23948 static elaboration model, the compiler does not know what is in
23949 other bodies and must assume the worst.
23950
23951 @item
23952 This means that the spec and body of @code{Decls} must also be
23953 elaborated before we elaborate the unit containing the call, but
23954 that unit is @code{Decls}! This means that the body of @code{Decls}
23955 must be elaborated before itself, and that's a circularity.
23956 @end enumerate
23957
23958 @noindent
23959 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23960 the body of @code{Decls} you will get a true Ada Reference Manual
23961 circularity that makes the program illegal.
23962
23963 In practice, we have found that problems with the static model of
23964 elaboration in existing code often arise from library tasks, so
23965 we must address this particular situation.
23966
23967 Note that if we compile and run the program above, using the dynamic model of
23968 elaboration (that is to say use the @option{-gnatE} switch),
23969 then it compiles, binds,
23970 links, and runs, printing the expected result of 2. Therefore in some sense
23971 the circularity here is only apparent, and we need to capture
23972 the properties of this program that  distinguish it from other library-level
23973 tasks that have real elaboration problems.
23974
23975 We have four possible answers to this question:
23976
23977 @itemize @bullet
23978
23979 @item
23980 Use the dynamic model of elaboration.
23981
23982 If we use the @option{-gnatE} switch, then as noted above, the program works.
23983 Why is this? If we examine the task body, it is apparent that the task cannot
23984 proceed past the
23985 @code{accept} statement until after elaboration has been completed, because
23986 the corresponding entry call comes from the main program, not earlier.
23987 This is why the dynamic model works here. But that's really giving
23988 up on a precise analysis, and we prefer to take this approach only if we cannot
23989 solve the
23990 problem in any other manner. So let us examine two ways to reorganize
23991 the program to avoid the potential elaboration problem.
23992
23993 @item
23994 Split library tasks into separate packages.
23995
23996 Write separate packages, so that library tasks are isolated from
23997 other declarations as much as possible. Let us look at a variation on
23998 the above program.
23999
24000 @smallexample @c ada
24001 package Decls1 is
24002   task Lib_Task is
24003      entry Start;
24004   end Lib_Task;
24005 end Decls1;
24006
24007 with Utils;
24008 package body Decls1 is
24009   task body Lib_Task is
24010   begin
24011      accept Start;
24012      Utils.Put_Val (2);
24013   end Lib_Task;
24014 end Decls1;
24015
24016 package Decls2 is
24017   type My_Int is new Integer;
24018   function Ident (M : My_Int) return My_Int;
24019 end Decls2;
24020
24021 with Utils;
24022 package body Decls2 is
24023   function Ident (M : My_Int) return My_Int is
24024   begin
24025      return M;
24026   end Ident;
24027 end Decls2;
24028
24029 with Decls2;
24030 package Utils is
24031   procedure Put_Val (Arg : Decls2.My_Int);
24032 end Utils;
24033
24034 with Text_IO;
24035 package body Utils is
24036   procedure Put_Val (Arg : Decls2.My_Int) is
24037   begin
24038      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24039   end Put_Val;
24040 end Utils;
24041
24042 with Decls1;
24043 procedure Main is
24044 begin
24045    Decls1.Lib_Task.Start;
24046 end;
24047 @end smallexample
24048
24049 @noindent
24050 All we have done is to split @code{Decls} into two packages, one
24051 containing the library task, and one containing everything else. Now
24052 there is no cycle, and the program compiles, binds, links and executes
24053 using the default static model of elaboration.
24054
24055 @item
24056 Declare separate task types.
24057
24058 A significant part of the problem arises because of the use of the
24059 single task declaration form. This means that the elaboration of
24060 the task type, and the elaboration of the task itself (i.e.@: the
24061 creation of the task) happen at the same time. A good rule
24062 of style in Ada is to always create explicit task types. By
24063 following the additional step of placing task objects in separate
24064 packages from the task type declaration, many elaboration problems
24065 are avoided. Here is another modified example of the example program:
24066
24067 @smallexample @c ada
24068 package Decls is
24069   task type Lib_Task_Type is
24070      entry Start;
24071   end Lib_Task_Type;
24072
24073   type My_Int is new Integer;
24074
24075   function Ident (M : My_Int) return My_Int;
24076 end Decls;
24077
24078 with Utils;
24079 package body Decls is
24080   task body Lib_Task_Type is
24081   begin
24082      accept Start;
24083      Utils.Put_Val (2);
24084   end Lib_Task_Type;
24085
24086   function Ident (M : My_Int) return My_Int is
24087   begin
24088      return M;
24089   end Ident;
24090 end Decls;
24091
24092 with Decls;
24093 package Utils is
24094   procedure Put_Val (Arg : Decls.My_Int);
24095 end Utils;
24096
24097 with Text_IO;
24098 package body Utils is
24099   procedure Put_Val (Arg : Decls.My_Int) is
24100   begin
24101      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24102   end Put_Val;
24103 end Utils;
24104
24105 with Decls;
24106 package Declst is
24107    Lib_Task : Decls.Lib_Task_Type;
24108 end Declst;
24109
24110 with Declst;
24111 procedure Main is
24112 begin
24113    Declst.Lib_Task.Start;
24114 end;
24115 @end smallexample
24116
24117 @noindent
24118 What we have done here is to replace the @code{task} declaration in
24119 package @code{Decls} with a @code{task type} declaration. Then we
24120 introduce a separate package @code{Declst} to contain the actual
24121 task object. This separates the elaboration issues for
24122 the @code{task type}
24123 declaration, which causes no trouble, from the elaboration issues
24124 of the task object, which is also unproblematic, since it is now independent
24125 of the elaboration of  @code{Utils}.
24126 This separation of concerns also corresponds to
24127 a generally sound engineering principle of separating declarations
24128 from instances. This version of the program also compiles, binds, links,
24129 and executes, generating the expected output.
24130
24131 @item
24132 Use No_Entry_Calls_In_Elaboration_Code restriction.
24133 @cindex No_Entry_Calls_In_Elaboration_Code
24134
24135 The previous two approaches described how a program can be restructured
24136 to avoid the special problems caused by library task bodies. in practice,
24137 however, such restructuring may be difficult to apply to existing legacy code,
24138 so we must consider solutions that do not require massive rewriting.
24139
24140 Let us consider more carefully why our original sample program works
24141 under the dynamic model of elaboration. The reason is that the code
24142 in the task body blocks immediately on the @code{accept}
24143 statement. Now of course there is nothing to prohibit elaboration
24144 code from making entry calls (for example from another library level task),
24145 so we cannot tell in isolation that
24146 the task will not execute the accept statement  during elaboration.
24147
24148 However, in practice it is very unusual to see elaboration code
24149 make any entry calls, and the pattern of tasks starting
24150 at elaboration time and then immediately blocking on @code{accept} or
24151 @code{select} statements is very common. What this means is that
24152 the compiler is being too pessimistic when it analyzes the
24153 whole package body as though it might be executed at elaboration
24154 time.
24155
24156 If we know that the elaboration code contains no entry calls, (a very safe
24157 assumption most of the time, that could almost be made the default
24158 behavior), then we can compile all units of the program under control
24159 of the following configuration pragma:
24160
24161 @smallexample
24162 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24163 @end smallexample
24164
24165 @noindent
24166 This pragma can be placed in the @file{gnat.adc} file in the usual
24167 manner. If we take our original unmodified program and compile it
24168 in the presence of a @file{gnat.adc} containing the above pragma,
24169 then once again, we can compile, bind, link, and execute, obtaining
24170 the expected result. In the presence of this pragma, the compiler does
24171 not trace calls in a task body, that appear after the first @code{accept}
24172 or @code{select} statement, and therefore does not report a potential
24173 circularity in the original program.
24174
24175 The compiler will check to the extent it can that the above
24176 restriction is not violated, but it is not always possible to do a
24177 complete check at compile time, so it is important to use this
24178 pragma only if the stated restriction is in fact met, that is to say
24179 no task receives an entry call before elaboration of all units is completed.
24180
24181 @end itemize
24182
24183 @node Mixing Elaboration Models
24184 @section Mixing Elaboration Models
24185 @noindent
24186 So far, we have assumed that the entire program is either compiled
24187 using the dynamic model or static model, ensuring consistency. It
24188 is possible to mix the two models, but rules have to be followed
24189 if this mixing is done to ensure that elaboration checks are not
24190 omitted.
24191
24192 The basic rule is that @emph{a unit compiled with the static model cannot
24193 be @code{with'ed} by a unit compiled with the dynamic model}. The
24194 reason for this is that in the static model, a unit assumes that
24195 its clients guarantee to use (the equivalent of) pragma
24196 @code{Elaborate_All} so that no elaboration checks are required
24197 in inner subprograms, and this assumption is violated if the
24198 client is compiled with dynamic checks.
24199
24200 The precise rule is as follows. A unit that is compiled with dynamic
24201 checks can only @code{with} a unit that meets at least one of the
24202 following criteria:
24203
24204 @itemize @bullet
24205
24206 @item
24207 The @code{with'ed} unit is itself compiled with dynamic elaboration
24208 checks (that is with the @option{-gnatE} switch.
24209
24210 @item
24211 The @code{with'ed} unit is an internal GNAT implementation unit from
24212 the System, Interfaces, Ada, or GNAT hierarchies.
24213
24214 @item
24215 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24216
24217 @item
24218 The @code{with'ing} unit (that is the client) has an explicit pragma
24219 @code{Elaborate_All} for the @code{with'ed} unit.
24220
24221 @end itemize
24222
24223 @noindent
24224 If this rule is violated, that is if a unit with dynamic elaboration
24225 checks @code{with's} a unit that does not meet one of the above four
24226 criteria, then the binder (@code{gnatbind}) will issue a warning
24227 similar to that in the following example:
24228
24229 @smallexample
24230 warning: "x.ads" has dynamic elaboration checks and with's
24231 warning:   "y.ads" which has static elaboration checks
24232 @end smallexample
24233
24234 @noindent
24235 These warnings indicate that the rule has been violated, and that as a result
24236 elaboration checks may be missed in the resulting executable file.
24237 This warning may be suppressed using the @option{-ws} binder switch
24238 in the usual manner.
24239
24240 One useful application of this mixing rule is in the case of a subsystem
24241 which does not itself @code{with} units from the remainder of the
24242 application. In this case, the entire subsystem can be compiled with
24243 dynamic checks to resolve a circularity in the subsystem, while
24244 allowing the main application that uses this subsystem to be compiled
24245 using the more reliable default static model.
24246
24247 @node What to Do If the Default Elaboration Behavior Fails
24248 @section What to Do If the Default Elaboration Behavior Fails
24249
24250 @noindent
24251 If the binder cannot find an acceptable order, it outputs detailed
24252 diagnostics. For example:
24253 @smallexample
24254 @group
24255 @iftex
24256 @leftskip=0cm
24257 @end iftex
24258 error: elaboration circularity detected
24259 info:   "proc (body)" must be elaborated before "pack (body)"
24260 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24261 info:     recompile "pack (body)" with -gnatwl
24262 info:                             for full details
24263 info:       "proc (body)"
24264 info:         is needed by its spec:
24265 info:       "proc (spec)"
24266 info:         which is withed by:
24267 info:       "pack (body)"
24268 info:  "pack (body)" must be elaborated before "proc (body)"
24269 info:     reason: pragma Elaborate in unit "proc (body)"
24270 @end group
24271
24272 @end smallexample
24273
24274 @noindent
24275 In this case we have a cycle that the binder cannot break. On the one
24276 hand, there is an explicit pragma Elaborate in @code{proc} for
24277 @code{pack}. This means that the body of @code{pack} must be elaborated
24278 before the body of @code{proc}. On the other hand, there is elaboration
24279 code in @code{pack} that calls a subprogram in @code{proc}. This means
24280 that for maximum safety, there should really be a pragma
24281 Elaborate_All in @code{pack} for @code{proc} which would require that
24282 the body of @code{proc} be elaborated before the body of
24283 @code{pack}. Clearly both requirements cannot be satisfied.
24284 Faced with a circularity of this kind, you have three different options.
24285
24286 @table @asis
24287 @item Fix the program
24288 The most desirable option from the point of view of long-term maintenance
24289 is to rearrange the program so that the elaboration problems are avoided.
24290 One useful technique is to place the elaboration code into separate
24291 child packages. Another is to move some of the initialization code to
24292 explicitly called subprograms, where the program controls the order
24293 of initialization explicitly. Although this is the most desirable option,
24294 it may be impractical and involve too much modification, especially in
24295 the case of complex legacy code.
24296
24297 @item Perform dynamic checks
24298 If the compilations are done using the
24299 @option{-gnatE}
24300 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24301 manner. Dynamic checks are generated for all calls that could possibly result
24302 in raising an exception. With this switch, the compiler does not generate
24303 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24304 exactly as specified in the @cite{Ada Reference Manual}.
24305 The binder will generate
24306 an executable program that may or may not raise @code{Program_Error}, and then
24307 it is the programmer's job to ensure that it does not raise an exception. Note
24308 that it is important to compile all units with the switch, it cannot be used
24309 selectively.
24310
24311 @item Suppress checks
24312 The drawback of dynamic checks is that they generate a
24313 significant overhead at run time, both in space and time. If you
24314 are absolutely sure that your program cannot raise any elaboration
24315 exceptions, and you still want to use the dynamic elaboration model,
24316 then you can use the configuration pragma
24317 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24318 example this pragma could be placed in the @file{gnat.adc} file.
24319
24320 @item Suppress checks selectively
24321 When you know that certain calls or instantiations in elaboration code cannot
24322 possibly lead to an elaboration error, and the binder nevertheless complains
24323 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24324 elaboration circularities, it is possible to remove those warnings locally and
24325 obtain a program that will bind. Clearly this can be unsafe, and it is the
24326 responsibility of the programmer to make sure that the resulting program has no
24327 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24328 used with different granularity to suppress warnings and break elaboration
24329 circularities:
24330
24331 @itemize @bullet
24332 @item
24333 Place the pragma that names the called subprogram in the declarative part
24334 that contains the call.
24335
24336 @item
24337 Place the pragma in the declarative part, without naming an entity. This
24338 disables warnings on all calls in the corresponding  declarative region.
24339
24340 @item
24341 Place the pragma in the package spec that declares the called subprogram,
24342 and name the subprogram. This disables warnings on all elaboration calls to
24343 that subprogram.
24344
24345 @item
24346 Place the pragma in the package spec that declares the called subprogram,
24347 without naming any entity. This disables warnings on all elaboration calls to
24348 all subprograms declared in this spec.
24349
24350 @item Use Pragma Elaborate
24351 As previously described in section @xref{Treatment of Pragma Elaborate},
24352 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24353 that no elaboration checks are required on calls to the designated unit.
24354 There may be cases in which the caller knows that no transitive calls
24355 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24356 case where @code{pragma Elaborate_All} would cause a circularity.
24357 @end itemize
24358
24359 @noindent
24360 These five cases are listed in order of decreasing safety, and therefore
24361 require increasing programmer care in their application. Consider the
24362 following program:
24363
24364 @smallexample @c adanocomment
24365 package Pack1 is
24366   function F1 return Integer;
24367   X1 : Integer;
24368 end Pack1;
24369
24370 package Pack2 is
24371   function F2 return Integer;
24372   function Pure (x : integer) return integer;
24373   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24374   --  pragma Suppress (Elaboration_Check);              -- (4)
24375 end Pack2;
24376
24377 with Pack2;
24378 package body Pack1 is
24379   function F1 return Integer is
24380   begin
24381     return 100;
24382   end F1;
24383   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24384 begin
24385   declare
24386     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24387     --  pragma Suppress(Elaboration_Check);             -- (2)
24388   begin
24389     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24390   end;
24391 end Pack1;
24392
24393 with Pack1;
24394 package body Pack2 is
24395   function F2 return Integer is
24396   begin
24397      return Pack1.F1;
24398   end F2;
24399   function Pure (x : integer) return integer is
24400   begin
24401      return x ** 3 - 3 * x;
24402   end;
24403 end Pack2;
24404
24405 with Pack1, Ada.Text_IO;
24406 procedure Proc3 is
24407 begin
24408   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24409 end Proc3;
24410 @end smallexample
24411 In the absence of any pragmas, an attempt to bind this program produces
24412 the following diagnostics:
24413 @smallexample
24414 @group
24415 @iftex
24416 @leftskip=.5cm
24417 @end iftex
24418 error: elaboration circularity detected
24419 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24420 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24421 info:       recompile "pack1 (body)" with -gnatwl for full details
24422 info:          "pack1 (body)"
24423 info:             must be elaborated along with its spec:
24424 info:          "pack1 (spec)"
24425 info:             which is withed by:
24426 info:          "pack2 (body)"
24427 info:             which must be elaborated along with its spec:
24428 info:          "pack2 (spec)"
24429 info:             which is withed by:
24430 info:          "pack1 (body)"
24431 @end group
24432 @end smallexample
24433 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24434 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24435 F2 is safe, even though F2 calls F1, because the call appears after the
24436 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24437 remove the warning on the call. It is also possible to use pragma (2)
24438 because there are no other potentially unsafe calls in the block.
24439
24440 @noindent
24441 The call to @code{Pure} is safe because this function does not depend on the
24442 state of @code{Pack2}. Therefore any call to this function is safe, and it
24443 is correct to place pragma (3) in the corresponding package spec.
24444
24445 @noindent
24446 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24447 warnings on all calls to functions declared therein. Note that this is not
24448 necessarily safe, and requires more detailed examination of the subprogram
24449 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24450 be already elaborated.
24451 @end table
24452
24453 @noindent
24454 It is hard to generalize on which of these four approaches should be
24455 taken. Obviously if it is possible to fix the program so that the default
24456 treatment works, this is preferable, but this may not always be practical.
24457 It is certainly simple enough to use
24458 @option{-gnatE}
24459 but the danger in this case is that, even if the GNAT binder
24460 finds a correct elaboration order, it may not always do so,
24461 and certainly a binder from another Ada compiler might not. A
24462 combination of testing and analysis (for which the warnings generated
24463 with the
24464 @option{-gnatwl}
24465 switch can be useful) must be used to ensure that the program is free
24466 of errors. One switch that is useful in this testing is the
24467 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24468 switch for
24469 @code{gnatbind}.
24470 Normally the binder tries to find an order that has the best chance
24471 of avoiding elaboration problems. However, if this switch is used, the binder
24472 plays a devil's advocate role, and tries to choose the order that
24473 has the best chance of failing. If your program works even with this
24474 switch, then it has a better chance of being error free, but this is still
24475 not a guarantee.
24476
24477 For an example of this approach in action, consider the C-tests (executable
24478 tests) from the ACVC suite. If these are compiled and run with the default
24479 treatment, then all but one of them succeed without generating any error
24480 diagnostics from the binder. However, there is one test that fails, and
24481 this is not surprising, because the whole point of this test is to ensure
24482 that the compiler can handle cases where it is impossible to determine
24483 a correct order statically, and it checks that an exception is indeed
24484 raised at run time.
24485
24486 This one test must be compiled and run using the
24487 @option{-gnatE}
24488 switch, and then it passes. Alternatively, the entire suite can
24489 be run using this switch. It is never wrong to run with the dynamic
24490 elaboration switch if your code is correct, and we assume that the
24491 C-tests are indeed correct (it is less efficient, but efficiency is
24492 not a factor in running the ACVC tests.)
24493
24494 @node Elaboration for Access-to-Subprogram Values
24495 @section Elaboration for Access-to-Subprogram Values
24496 @cindex Access-to-subprogram
24497
24498 @noindent
24499 Access-to-subprogram types (introduced in Ada 95) complicate
24500 the handling of elaboration. The trouble is that it becomes
24501 impossible to tell at compile time which procedure
24502 is being called. This means that it is not possible for the binder
24503 to analyze the elaboration requirements in this case.
24504
24505 If at the point at which the access value is created
24506 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24507 the body of the subprogram is
24508 known to have been elaborated, then the access value is safe, and its use
24509 does not require a check. This may be achieved by appropriate arrangement
24510 of the order of declarations if the subprogram is in the current unit,
24511 or, if the subprogram is in another unit, by using pragma
24512 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24513 on the referenced unit.
24514
24515 If the referenced body is not known to have been elaborated at the point
24516 the access value is created, then any use of the access value must do a
24517 dynamic check, and this dynamic check will fail and raise a
24518 @code{Program_Error} exception if the body has not been elaborated yet.
24519 GNAT will generate the necessary checks, and in addition, if the
24520 @option{-gnatwl}
24521 switch is set, will generate warnings that such checks are required.
24522
24523 The use of dynamic dispatching for tagged types similarly generates
24524 a requirement for dynamic checks, and premature calls to any primitive
24525 operation of a tagged type before the body of the operation has been
24526 elaborated, will result in the raising of @code{Program_Error}.
24527
24528 @node Summary of Procedures for Elaboration Control
24529 @section Summary of Procedures for Elaboration Control
24530 @cindex Elaboration control
24531
24532 @noindent
24533 First, compile your program with the default options, using none of
24534 the special elaboration control switches. If the binder successfully
24535 binds your program, then you can be confident that, apart from issues
24536 raised by the use of access-to-subprogram types and dynamic dispatching,
24537 the program is free of elaboration errors. If it is important that the
24538 program be portable, then use the
24539 @option{-gnatwl}
24540 switch to generate warnings about missing @code{Elaborate} or
24541 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24542
24543 If the program fails to bind using the default static elaboration
24544 handling, then you can fix the program to eliminate the binder
24545 message, or recompile the entire program with the
24546 @option{-gnatE} switch to generate dynamic elaboration checks,
24547 and, if you are sure there really are no elaboration problems,
24548 use a global pragma @code{Suppress (Elaboration_Check)}.
24549
24550 @node Other Elaboration Order Considerations
24551 @section Other Elaboration Order Considerations
24552 @noindent
24553 This section has been entirely concerned with the issue of finding a valid
24554 elaboration order, as defined by the Ada Reference Manual. In a case
24555 where several elaboration orders are valid, the task is to find one
24556 of the possible valid elaboration orders (and the static model in GNAT
24557 will ensure that this is achieved).
24558
24559 The purpose of the elaboration rules in the Ada Reference Manual is to
24560 make sure that no entity is accessed before it has been elaborated. For
24561 a subprogram, this means that the spec and body must have been elaborated
24562 before the subprogram is called. For an object, this means that the object
24563 must have been elaborated before its value is read or written. A violation
24564 of either of these two requirements is an access before elaboration order,
24565 and this section has been all about avoiding such errors.
24566
24567 In the case where more than one order of elaboration is possible, in the
24568 sense that access before elaboration errors are avoided, then any one of
24569 the orders is ``correct'' in the sense that it meets the requirements of
24570 the Ada Reference Manual, and no such error occurs.
24571
24572 However, it may be the case for a given program, that there are
24573 constraints on the order of elaboration that come not from consideration
24574 of avoiding elaboration errors, but rather from extra-lingual logic
24575 requirements. Consider this example:
24576
24577 @smallexample @c ada
24578 with Init_Constants;
24579 package Constants is
24580    X : Integer := 0;
24581    Y : Integer := 0;
24582 end Constants;
24583
24584 package Init_Constants is
24585    procedure P; -- require a body
24586 end Init_Constants;
24587
24588 with Constants;
24589 package body Init_Constants is
24590    procedure P is begin null; end;
24591 begin
24592    Constants.X := 3;
24593    Constants.Y := 4;
24594 end Init_Constants;
24595
24596 with Constants;
24597 package Calc is
24598    Z : Integer := Constants.X + Constants.Y;
24599 end Calc;
24600
24601 with Calc;
24602 with Text_IO; use Text_IO;
24603 procedure Main is
24604 begin
24605    Put_Line (Calc.Z'Img);
24606 end Main;
24607 @end smallexample
24608
24609 @noindent
24610 In this example, there is more than one valid order of elaboration. For
24611 example both the following are correct orders:
24612
24613 @smallexample
24614 Init_Constants spec
24615 Constants spec
24616 Calc spec
24617 Init_Constants body
24618 Main body
24619
24620   and
24621
24622 Init_Constants spec
24623 Init_Constants body
24624 Constants spec
24625 Calc spec
24626 Main body
24627 @end smallexample
24628
24629 @noindent
24630 There is no language rule to prefer one or the other, both are correct
24631 from an order of elaboration point of view. But the programmatic effects
24632 of the two orders are very different. In the first, the elaboration routine
24633 of @code{Calc} initializes @code{Z} to zero, and then the main program
24634 runs with this value of zero. But in the second order, the elaboration
24635 routine of @code{Calc} runs after the body of Init_Constants has set
24636 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24637 runs.
24638
24639 One could perhaps by applying pretty clever non-artificial intelligence
24640 to the situation guess that it is more likely that the second order of
24641 elaboration is the one desired, but there is no formal linguistic reason
24642 to prefer one over the other. In fact in this particular case, GNAT will
24643 prefer the second order, because of the rule that bodies are elaborated
24644 as soon as possible, but it's just luck that this is what was wanted
24645 (if indeed the second order was preferred).
24646
24647 If the program cares about the order of elaboration routines in a case like
24648 this, it is important to specify the order required. In this particular
24649 case, that could have been achieved by adding to the spec of Calc:
24650
24651 @smallexample @c ada
24652 pragma Elaborate_All (Constants);
24653 @end smallexample
24654
24655 @noindent
24656 which requires that the body (if any) and spec of @code{Constants},
24657 as well as the body and spec of any unit @code{with}'ed by
24658 @code{Constants} be elaborated before @code{Calc} is elaborated.
24659
24660 Clearly no automatic method can always guess which alternative you require,
24661 and if you are working with legacy code that had constraints of this kind
24662 which were not properly specified by adding @code{Elaborate} or
24663 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24664 compilers can choose different orders.
24665
24666 However, GNAT does attempt to diagnose the common situation where there
24667 are uninitialized variables in the visible part of a package spec, and the
24668 corresponding package body has an elaboration block that directly or
24669 indirectly initialized one or more of these variables. This is the situation
24670 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24671 a warning that suggests this addition if it detects this situation.
24672
24673 The @code{gnatbind}
24674 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24675 out problems. This switch causes bodies to be elaborated as late as possible
24676 instead of as early as possible. In the example above, it would have forced
24677 the choice of the first elaboration order. If you get different results
24678 when using this switch, and particularly if one set of results is right,
24679 and one is wrong as far as you are concerned, it shows that you have some
24680 missing @code{Elaborate} pragmas. For the example above, we have the
24681 following output:
24682
24683 @smallexample
24684 gnatmake -f -q main
24685 main
24686  7
24687 gnatmake -f -q main -bargs -p
24688 main
24689  0
24690 @end smallexample
24691
24692 @noindent
24693 It is of course quite unlikely that both these results are correct, so
24694 it is up to you in a case like this to investigate the source of the
24695 difference, by looking at the two elaboration orders that are chosen,
24696 and figuring out which is correct, and then adding the necessary
24697 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24698
24699
24700
24701 @c *******************************
24702 @node Conditional Compilation
24703 @appendix Conditional Compilation
24704 @c *******************************
24705 @cindex Conditional compilation
24706
24707 @noindent
24708 It is often necessary to arrange for a single source program
24709 to serve multiple purposes, where it is compiled in different
24710 ways to achieve these different goals. Some examples of the
24711 need for this feature are
24712
24713 @itemize @bullet
24714 @item  Adapting a program to a different hardware environment
24715 @item  Adapting a program to a different target architecture
24716 @item  Turning debugging features on and off
24717 @item  Arranging for a program to compile with different compilers
24718 @end itemize
24719
24720 @noindent
24721 In C, or C++, the typical approach would be to use the preprocessor
24722 that is defined as part of the language. The Ada language does not
24723 contain such a feature. This is not an oversight, but rather a very
24724 deliberate design decision, based on the experience that overuse of
24725 the preprocessing features in C and C++ can result in programs that
24726 are extremely difficult to maintain. For example, if we have ten
24727 switches that can be on or off, this means that there are a thousand
24728 separate programs, any one of which might not even be syntactically
24729 correct, and even if syntactically correct, the resulting program
24730 might not work correctly. Testing all combinations can quickly become
24731 impossible.
24732
24733 Nevertheless, the need to tailor programs certainly exists, and in
24734 this Appendix we will discuss how this can
24735 be achieved using Ada in general, and GNAT in particular.
24736
24737 @menu
24738 * Use of Boolean Constants::
24739 * Debugging - A Special Case::
24740 * Conditionalizing Declarations::
24741 * Use of Alternative Implementations::
24742 * Preprocessing::
24743 @end menu
24744
24745 @node Use of Boolean Constants
24746 @section Use of Boolean Constants
24747
24748 @noindent
24749 In the case where the difference is simply which code
24750 sequence is executed, the cleanest solution is to use Boolean
24751 constants to control which code is executed.
24752
24753 @smallexample @c ada
24754 @group
24755 FP_Initialize_Required : constant Boolean := True;
24756 @dots{}
24757 if FP_Initialize_Required then
24758 @dots{}
24759 end if;
24760 @end group
24761 @end smallexample
24762
24763 @noindent
24764 Not only will the code inside the @code{if} statement not be executed if
24765 the constant Boolean is @code{False}, but it will also be completely
24766 deleted from the program.
24767 However, the code is only deleted after the @code{if} statement
24768 has been checked for syntactic and semantic correctness.
24769 (In contrast, with preprocessors the code is deleted before the
24770 compiler ever gets to see it, so it is not checked until the switch
24771 is turned on.)
24772 @cindex Preprocessors (contrasted with conditional compilation)
24773
24774 Typically the Boolean constants will be in a separate package,
24775 something like:
24776
24777 @smallexample @c ada
24778 @group
24779 package Config is
24780    FP_Initialize_Required : constant Boolean := True;
24781    Reset_Available        : constant Boolean := False;
24782    @dots{}
24783 end Config;
24784 @end group
24785 @end smallexample
24786
24787 @noindent
24788 The @code{Config} package exists in multiple forms for the various targets,
24789 with an appropriate script selecting the version of @code{Config} needed.
24790 Then any other unit requiring conditional compilation can do a @code{with}
24791 of @code{Config} to make the constants visible.
24792
24793
24794 @node Debugging - A Special Case
24795 @section Debugging - A Special Case
24796
24797 @noindent
24798 A common use of conditional code is to execute statements (for example
24799 dynamic checks, or output of intermediate results) under control of a
24800 debug switch, so that the debugging behavior can be turned on and off.
24801 This can be done using a Boolean constant to control whether the code
24802 is active:
24803
24804 @smallexample @c ada
24805 @group
24806 if Debugging then
24807    Put_Line ("got to the first stage!");
24808 end if;
24809 @end group
24810 @end smallexample
24811
24812 @noindent
24813 or
24814
24815 @smallexample @c ada
24816 @group
24817 if Debugging and then Temperature > 999.0 then
24818    raise Temperature_Crazy;
24819 end if;
24820 @end group
24821 @end smallexample
24822
24823 @noindent
24824 Since this is a common case, there are special features to deal with
24825 this in a convenient manner. For the case of tests, Ada 2005 has added
24826 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24827 @cindex pragma @code{Assert}
24828 on the @code{Assert} pragma that has always been available in GNAT, so this
24829 feature may be used with GNAT even if you are not using Ada 2005 features.
24830 The use of pragma @code{Assert} is described in
24831 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24832 example, the last test could be written:
24833
24834 @smallexample @c ada
24835 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24836 @end smallexample
24837
24838 @noindent
24839 or simply
24840
24841 @smallexample @c ada
24842 pragma Assert (Temperature <= 999.0);
24843 @end smallexample
24844
24845 @noindent
24846 In both cases, if assertions are active and the temperature is excessive,
24847 the exception @code{Assert_Failure} will be raised, with the given string in
24848 the first case or a string indicating the location of the pragma in the second
24849 case used as the exception message.
24850
24851 You can turn assertions on and off by using the @code{Assertion_Policy}
24852 pragma.
24853 @cindex pragma @code{Assertion_Policy}
24854 This is an Ada 2005 pragma which is implemented in all modes by
24855 GNAT, but only in the latest versions of GNAT which include Ada 2005
24856 capability. Alternatively, you can use the @option{-gnata} switch
24857 @cindex @option{-gnata} switch
24858 to enable assertions from the command line (this is recognized by all versions
24859 of GNAT).
24860
24861 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24862 @code{Debug} can be used:
24863 @cindex pragma @code{Debug}
24864
24865 @smallexample @c ada
24866 pragma Debug (Put_Line ("got to the first stage!"));
24867 @end smallexample
24868
24869 @noindent
24870 If debug pragmas are enabled, the argument, which must be of the form of
24871 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24872 Only one call can be present, but of course a special debugging procedure
24873 containing any code you like can be included in the program and then
24874 called in a pragma @code{Debug} argument as needed.
24875
24876 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24877 construct is that pragma @code{Debug} can appear in declarative contexts,
24878 such as at the very beginning of a procedure, before local declarations have
24879 been elaborated.
24880
24881 Debug pragmas are enabled using either the @option{-gnata} switch that also
24882 controls assertions, or with a separate Debug_Policy pragma.
24883 @cindex pragma @code{Debug_Policy}
24884 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24885 in Ada 95 and Ada 83 programs as well), and is analogous to
24886 pragma @code{Assertion_Policy} to control assertions.
24887
24888 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24889 and thus they can appear in @file{gnat.adc} if you are not using a
24890 project file, or in the file designated to contain configuration pragmas
24891 in a project file.
24892 They then apply to all subsequent compilations. In practice the use of
24893 the @option{-gnata} switch is often the most convenient method of controlling
24894 the status of these pragmas.
24895
24896 Note that a pragma is not a statement, so in contexts where a statement
24897 sequence is required, you can't just write a pragma on its own. You have
24898 to add a @code{null} statement.
24899
24900 @smallexample @c ada
24901 @group
24902 if @dots{} then
24903    @dots{} -- some statements
24904 else
24905    pragma Assert (Num_Cases < 10);
24906    null;
24907 end if;
24908 @end group
24909 @end smallexample
24910
24911
24912 @node Conditionalizing Declarations
24913 @section Conditionalizing Declarations
24914
24915 @noindent
24916 In some cases, it may be necessary to conditionalize declarations to meet
24917 different requirements. For example we might want a bit string whose length
24918 is set to meet some hardware message requirement.
24919
24920 In some cases, it may be possible to do this using declare blocks controlled
24921 by conditional constants:
24922
24923 @smallexample @c ada
24924 @group
24925 if Small_Machine then
24926    declare
24927       X : Bit_String (1 .. 10);
24928    begin
24929       @dots{}
24930    end;
24931 else
24932    declare
24933       X : Large_Bit_String (1 .. 1000);
24934    begin
24935       @dots{}
24936    end;
24937 end if;
24938 @end group
24939 @end smallexample
24940
24941 @noindent
24942 Note that in this approach, both declarations are analyzed by the
24943 compiler so this can only be used where both declarations are legal,
24944 even though one of them will not be used.
24945
24946 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24947 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24948 that are parameterized by these constants. For example
24949
24950 @smallexample @c ada
24951 @group
24952 for Rec use
24953   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24954 end record;
24955 @end group
24956 @end smallexample
24957
24958 @noindent
24959 If @code{Bits_Per_Word} is set to 32, this generates either
24960
24961 @smallexample @c ada
24962 @group
24963 for Rec use
24964   Field1 at 0 range 0 .. 32;
24965 end record;
24966 @end group
24967 @end smallexample
24968
24969 @noindent
24970 for the big endian case, or
24971
24972 @smallexample @c ada
24973 @group
24974 for Rec use record
24975   Field1 at 0 range 10 .. 32;
24976 end record;
24977 @end group
24978 @end smallexample
24979
24980 @noindent
24981 for the little endian case. Since a powerful subset of Ada expression
24982 notation is usable for creating static constants, clever use of this
24983 feature can often solve quite difficult problems in conditionalizing
24984 compilation (note incidentally that in Ada 95, the little endian
24985 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24986 need to define this one yourself).
24987
24988
24989 @node Use of Alternative Implementations
24990 @section Use of Alternative Implementations
24991
24992 @noindent
24993 In some cases, none of the approaches described above are adequate. This
24994 can occur for example if the set of declarations required is radically
24995 different for two different configurations.
24996
24997 In this situation, the official Ada way of dealing with conditionalizing
24998 such code is to write separate units for the different cases. As long as
24999 this does not result in excessive duplication of code, this can be done
25000 without creating maintenance problems. The approach is to share common
25001 code as far as possible, and then isolate the code and declarations
25002 that are different. Subunits are often a convenient method for breaking
25003 out a piece of a unit that is to be conditionalized, with separate files
25004 for different versions of the subunit for different targets, where the
25005 build script selects the right one to give to the compiler.
25006 @cindex Subunits (and conditional compilation)
25007
25008 As an example, consider a situation where a new feature in Ada 2005
25009 allows something to be done in a really nice way. But your code must be able
25010 to compile with an Ada 95 compiler. Conceptually you want to say:
25011
25012 @smallexample @c ada
25013 @group
25014 if Ada_2005 then
25015    @dots{} neat Ada 2005 code
25016 else
25017    @dots{} not quite as neat Ada 95 code
25018 end if;
25019 @end group
25020 @end smallexample
25021
25022 @noindent
25023 where @code{Ada_2005} is a Boolean constant.
25024
25025 But this won't work when @code{Ada_2005} is set to @code{False},
25026 since the @code{then} clause will be illegal for an Ada 95 compiler.
25027 (Recall that although such unreachable code would eventually be deleted
25028 by the compiler, it still needs to be legal.  If it uses features
25029 introduced in Ada 2005, it will be illegal in Ada 95.)
25030
25031 So instead we write
25032
25033 @smallexample @c ada
25034 procedure Insert is separate;
25035 @end smallexample
25036
25037 @noindent
25038 Then we have two files for the subunit @code{Insert}, with the two sets of
25039 code.
25040 If the package containing this is called @code{File_Queries}, then we might
25041 have two files
25042
25043 @itemize @bullet
25044 @item    @file{file_queries-insert-2005.adb}
25045 @item    @file{file_queries-insert-95.adb}
25046 @end itemize
25047
25048 @noindent
25049 and the build script renames the appropriate file to
25050
25051 @smallexample
25052 file_queries-insert.adb
25053 @end smallexample
25054
25055 @noindent
25056 and then carries out the compilation.
25057
25058 This can also be done with project files' naming schemes. For example:
25059
25060 @smallexample @c project
25061 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25062 @end smallexample
25063
25064 @noindent
25065 Note also that with project files it is desirable to use a different extension
25066 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25067 conflict may arise through another commonly used feature: to declare as part
25068 of the project a set of directories containing all the sources obeying the
25069 default naming scheme.
25070
25071 The use of alternative units is certainly feasible in all situations,
25072 and for example the Ada part of the GNAT run-time is conditionalized
25073 based on the target architecture using this approach. As a specific example,
25074 consider the implementation of the AST feature in VMS. There is one
25075 spec:
25076
25077 @smallexample
25078 s-asthan.ads
25079 @end smallexample
25080
25081 @noindent
25082 which is the same for all architectures, and three bodies:
25083
25084 @table @file
25085 @item    s-asthan.adb
25086 used for all non-VMS operating systems
25087 @item    s-asthan-vms-alpha.adb
25088 used for VMS on the Alpha
25089 @item    s-asthan-vms-ia64.adb
25090 used for VMS on the ia64
25091 @end table
25092
25093 @noindent
25094 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25095 this operating system feature is not available, and the two remaining
25096 versions interface with the corresponding versions of VMS to provide
25097 VMS-compatible AST handling. The GNAT build script knows the architecture
25098 and operating system, and automatically selects the right version,
25099 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25100
25101 Another style for arranging alternative implementations is through Ada's
25102 access-to-subprogram facility.
25103 In case some functionality is to be conditionally included,
25104 you can declare an access-to-procedure variable @code{Ref} that is initialized
25105 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25106 when appropriate.
25107 In some library package, set @code{Ref} to @code{Proc'Access} for some
25108 procedure @code{Proc} that performs the relevant processing.
25109 The initialization only occurs if the library package is included in the
25110 program.
25111 The same idea can also be implemented using tagged types and dispatching
25112 calls.
25113
25114
25115 @node Preprocessing
25116 @section Preprocessing
25117 @cindex Preprocessing
25118
25119 @noindent
25120 Although it is quite possible to conditionalize code without the use of
25121 C-style preprocessing, as described earlier in this section, it is
25122 nevertheless convenient in some cases to use the C approach. Moreover,
25123 older Ada compilers have often provided some preprocessing capability,
25124 so legacy code may depend on this approach, even though it is not
25125 standard.
25126
25127 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25128 extent on the various preprocessors that have been used
25129 with legacy code on other compilers, to enable easier transition).
25130
25131 The preprocessor may be used in two separate modes. It can be used quite
25132 separately from the compiler, to generate a separate output source file
25133 that is then fed to the compiler as a separate step. This is the
25134 @code{gnatprep} utility, whose use is fully described in
25135 @ref{Preprocessing Using gnatprep}.
25136 @cindex @code{gnatprep}
25137
25138 The preprocessing language allows such constructs as
25139
25140 @smallexample
25141 @group
25142 #if DEBUG or PRIORITY > 4 then
25143    bunch of declarations
25144 #else
25145    completely different bunch of declarations
25146 #end if;
25147 @end group
25148 @end smallexample
25149
25150 @noindent
25151 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25152 defined either on the command line or in a separate file.
25153
25154 The other way of running the preprocessor is even closer to the C style and
25155 often more convenient. In this approach the preprocessing is integrated into
25156 the compilation process. The compiler is fed the preprocessor input which
25157 includes @code{#if} lines etc, and then the compiler carries out the
25158 preprocessing internally and processes the resulting output.
25159 For more details on this approach, see @ref{Integrated Preprocessing}.
25160
25161
25162 @c *******************************
25163 @node Inline Assembler
25164 @appendix Inline Assembler
25165 @c *******************************
25166
25167 @noindent
25168 If you need to write low-level software that interacts directly
25169 with the hardware, Ada provides two ways to incorporate assembly
25170 language code into your program.  First, you can import and invoke
25171 external routines written in assembly language, an Ada feature fully
25172 supported by GNAT@.  However, for small sections of code it may be simpler
25173 or more efficient to include assembly language statements directly
25174 in your Ada source program, using the facilities of the implementation-defined
25175 package @code{System.Machine_Code}, which incorporates the gcc
25176 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25177 including the following:
25178
25179 @itemize @bullet
25180 @item No need to use non-Ada tools
25181 @item Consistent interface over different targets
25182 @item Automatic usage of the proper calling conventions
25183 @item Access to Ada constants and variables
25184 @item Definition of intrinsic routines
25185 @item Possibility of inlining a subprogram comprising assembler code
25186 @item Code optimizer can take Inline Assembler code into account
25187 @end itemize
25188
25189 This chapter presents a series of examples to show you how to use
25190 the Inline Assembler.  Although it focuses on the Intel x86,
25191 the general approach applies also to other processors.
25192 It is assumed that you are familiar with Ada
25193 and with assembly language programming.
25194
25195 @menu
25196 * Basic Assembler Syntax::
25197 * A Simple Example of Inline Assembler::
25198 * Output Variables in Inline Assembler::
25199 * Input Variables in Inline Assembler::
25200 * Inlining Inline Assembler Code::
25201 * Other Asm Functionality::
25202 @end menu
25203
25204 @c ---------------------------------------------------------------------------
25205 @node Basic Assembler Syntax
25206 @section Basic Assembler Syntax
25207
25208 @noindent
25209 The assembler used by GNAT and gcc is based not on the Intel assembly
25210 language, but rather on a language that descends from the AT&T Unix
25211 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25212 The following table summarizes the main features of @emph{as} syntax
25213 and points out the differences from the Intel conventions.
25214 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25215 pre-processor) documentation for further information.
25216
25217 @table @asis
25218 @item Register names
25219 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25220 @*
25221 Intel: No extra punctuation; for example @code{eax}
25222
25223 @item Immediate operand
25224 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25225 @*
25226 Intel: No extra punctuation; for example @code{4}
25227
25228 @item Address
25229 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25230 @*
25231 Intel: No extra punctuation; for example @code{loc}
25232
25233 @item Memory contents
25234 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25235 @*
25236 Intel: Square brackets; for example @code{[loc]}
25237
25238 @item Register contents
25239 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25240 @*
25241 Intel: Square brackets; for example @code{[eax]}
25242
25243 @item Hexadecimal numbers
25244 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25245 @*
25246 Intel: Trailing ``h''; for example @code{A0h}
25247
25248 @item Operand size
25249 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25250 a 16-bit word
25251 @*
25252 Intel: Implicit, deduced by assembler; for example @code{mov}
25253
25254 @item Instruction repetition
25255 gcc / @emph{as}: Split into two lines; for example
25256 @*
25257 @code{rep}
25258 @*
25259 @code{stosl}
25260 @*
25261 Intel: Keep on one line; for example @code{rep stosl}
25262
25263 @item Order of operands
25264 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25265 @*
25266 Intel: Destination first; for example @code{mov eax, 4}
25267 @end table
25268
25269 @c ---------------------------------------------------------------------------
25270 @node A Simple Example of Inline Assembler
25271 @section A Simple Example of Inline Assembler
25272
25273 @noindent
25274 The following example will generate a single assembly language statement,
25275 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25276 the example will be useful in illustrating the basics of
25277 the Inline Assembler facility.
25278
25279 @smallexample @c ada
25280 @group
25281 with System.Machine_Code; use System.Machine_Code;
25282 procedure Nothing is
25283 begin
25284    Asm ("nop");
25285 end Nothing;
25286 @end group
25287 @end smallexample
25288
25289 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25290 here it takes one parameter, a @emph{template string} that must be a static
25291 expression and that will form the generated instruction.
25292 @code{Asm} may be regarded as a compile-time procedure that parses
25293 the template string and additional parameters (none here),
25294 from which it generates a sequence of assembly language instructions.
25295
25296 The examples in this chapter will illustrate several of the forms
25297 for invoking @code{Asm}; a complete specification of the syntax
25298 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25299 Manual}.
25300
25301 Under the standard GNAT conventions, the @code{Nothing} procedure
25302 should be in a file named @file{nothing.adb}.
25303 You can build the executable in the usual way:
25304 @smallexample
25305 gnatmake nothing
25306 @end smallexample
25307 However, the interesting aspect of this example is not its run-time behavior
25308 but rather the generated assembly code.
25309 To see this output, invoke the compiler as follows:
25310 @smallexample
25311    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25312 @end smallexample
25313 where the options are:
25314
25315 @table @code
25316 @item -c
25317 compile only (no bind or link)
25318 @item -S
25319 generate assembler listing
25320 @item -fomit-frame-pointer
25321 do not set up separate stack frames
25322 @item -gnatp
25323 do not add runtime checks
25324 @end table
25325
25326 This gives a human-readable assembler version of the code. The resulting
25327 file will have the same name as the Ada source file, but with a @code{.s}
25328 extension. In our example, the file @file{nothing.s} has the following
25329 contents:
25330
25331 @smallexample
25332 @group
25333 .file "nothing.adb"
25334 gcc2_compiled.:
25335 ___gnu_compiled_ada:
25336 .text
25337    .align 4
25338 .globl __ada_nothing
25339 __ada_nothing:
25340 #APP
25341    nop
25342 #NO_APP
25343    jmp L1
25344    .align 2,0x90
25345 L1:
25346    ret
25347 @end group
25348 @end smallexample
25349
25350 The assembly code you included is clearly indicated by
25351 the compiler, between the @code{#APP} and @code{#NO_APP}
25352 delimiters. The character before the 'APP' and 'NOAPP'
25353 can differ on different targets. For example, GNU/Linux uses '#APP' while
25354 on NT you will see '/APP'.
25355
25356 If you make a mistake in your assembler code (such as using the
25357 wrong size modifier, or using a wrong operand for the instruction) GNAT
25358 will report this error in a temporary file, which will be deleted when
25359 the compilation is finished.  Generating an assembler file will help
25360 in such cases, since you can assemble this file separately using the
25361 @emph{as} assembler that comes with gcc.
25362
25363 Assembling the file using the command
25364
25365 @smallexample
25366 as @file{nothing.s}
25367 @end smallexample
25368 @noindent
25369 will give you error messages whose lines correspond to the assembler
25370 input file, so you can easily find and correct any mistakes you made.
25371 If there are no errors, @emph{as} will generate an object file
25372 @file{nothing.out}.
25373
25374 @c ---------------------------------------------------------------------------
25375 @node Output Variables in Inline Assembler
25376 @section Output Variables in Inline Assembler
25377
25378 @noindent
25379 The examples in this section, showing how to access the processor flags,
25380 illustrate how to specify the destination operands for assembly language
25381 statements.
25382
25383 @smallexample @c ada
25384 @group
25385 with Interfaces; use Interfaces;
25386 with Ada.Text_IO; use Ada.Text_IO;
25387 with System.Machine_Code; use System.Machine_Code;
25388 procedure Get_Flags is
25389    Flags : Unsigned_32;
25390    use ASCII;
25391 begin
25392    Asm ("pushfl"          & LF & HT & -- push flags on stack
25393         "popl %%eax"      & LF & HT & -- load eax with flags
25394         "movl %%eax, %0",             -- store flags in variable
25395         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25396    Put_Line ("Flags register:" & Flags'Img);
25397 end Get_Flags;
25398 @end group
25399 @end smallexample
25400
25401 In order to have a nicely aligned assembly listing, we have separated
25402 multiple assembler statements in the Asm template string with linefeed
25403 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25404 The resulting section of the assembly output file is:
25405
25406 @smallexample
25407 @group
25408 #APP
25409    pushfl
25410    popl %eax
25411    movl %eax, -40(%ebp)
25412 #NO_APP
25413 @end group
25414 @end smallexample
25415
25416 It would have been legal to write the Asm invocation as:
25417
25418 @smallexample
25419 Asm ("pushfl popl %%eax movl %%eax, %0")
25420 @end smallexample
25421
25422 but in the generated assembler file, this would come out as:
25423
25424 @smallexample
25425 #APP
25426    pushfl popl %eax movl %eax, -40(%ebp)
25427 #NO_APP
25428 @end smallexample
25429
25430 which is not so convenient for the human reader.
25431
25432 We use Ada comments
25433 at the end of each line to explain what the assembler instructions
25434 actually do.  This is a useful convention.
25435
25436 When writing Inline Assembler instructions, you need to precede each register
25437 and variable name with a percent sign.  Since the assembler already requires
25438 a percent sign at the beginning of a register name, you need two consecutive
25439 percent signs for such names in the Asm template string, thus @code{%%eax}.
25440 In the generated assembly code, one of the percent signs will be stripped off.
25441
25442 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25443 variables: operands you later define using @code{Input} or @code{Output}
25444 parameters to @code{Asm}.
25445 An output variable is illustrated in
25446 the third statement in the Asm template string:
25447 @smallexample
25448 movl %%eax, %0
25449 @end smallexample
25450 The intent is to store the contents of the eax register in a variable that can
25451 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25452 necessarily work, since the compiler might optimize by using a register
25453 to hold Flags, and the expansion of the @code{movl} instruction would not be
25454 aware of this optimization.  The solution is not to store the result directly
25455 but rather to advise the compiler to choose the correct operand form;
25456 that is the purpose of the @code{%0} output variable.
25457
25458 Information about the output variable is supplied in the @code{Outputs}
25459 parameter to @code{Asm}:
25460 @smallexample
25461 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25462 @end smallexample
25463
25464 The output is defined by the @code{Asm_Output} attribute of the target type;
25465 the general format is
25466 @smallexample
25467 Type'Asm_Output (constraint_string, variable_name)
25468 @end smallexample
25469
25470 The constraint string directs the compiler how
25471 to store/access the associated variable.  In the example
25472 @smallexample
25473 Unsigned_32'Asm_Output ("=m", Flags);
25474 @end smallexample
25475 the @code{"m"} (memory) constraint tells the compiler that the variable
25476 @code{Flags} should be stored in a memory variable, thus preventing
25477 the optimizer from keeping it in a register.  In contrast,
25478 @smallexample
25479 Unsigned_32'Asm_Output ("=r", Flags);
25480 @end smallexample
25481 uses the @code{"r"} (register) constraint, telling the compiler to
25482 store the variable in a register.
25483
25484 If the constraint is preceded by the equal character (@strong{=}), it tells
25485 the compiler that the variable will be used to store data into it.
25486
25487 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25488 allowing the optimizer to choose whatever it deems best.
25489
25490 There are a fairly large number of constraints, but the ones that are
25491 most useful (for the Intel x86 processor) are the following:
25492
25493 @table @code
25494 @item =
25495 output constraint
25496 @item g
25497 global (i.e.@: can be stored anywhere)
25498 @item m
25499 in memory
25500 @item I
25501 a constant
25502 @item a
25503 use eax
25504 @item b
25505 use ebx
25506 @item c
25507 use ecx
25508 @item d
25509 use edx
25510 @item S
25511 use esi
25512 @item D
25513 use edi
25514 @item r
25515 use one of eax, ebx, ecx or edx
25516 @item q
25517 use one of eax, ebx, ecx, edx, esi or edi
25518 @end table
25519
25520 The full set of constraints is described in the gcc and @emph{as}
25521 documentation; note that it is possible to combine certain constraints
25522 in one constraint string.
25523
25524 You specify the association of an output variable with an assembler operand
25525 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25526 integer.  Thus in
25527 @smallexample @c ada
25528 @group
25529 Asm ("pushfl"          & LF & HT & -- push flags on stack
25530      "popl %%eax"      & LF & HT & -- load eax with flags
25531      "movl %%eax, %0",             -- store flags in variable
25532      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25533 @end group
25534 @end smallexample
25535 @noindent
25536 @code{%0} will be replaced in the expanded code by the appropriate operand,
25537 whatever
25538 the compiler decided for the @code{Flags} variable.
25539
25540 In general, you may have any number of output variables:
25541 @itemize @bullet
25542 @item
25543 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25544 @item
25545 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25546 of @code{Asm_Output} attributes
25547 @end itemize
25548
25549 For example:
25550 @smallexample @c ada
25551 @group
25552 Asm ("movl %%eax, %0" & LF & HT &
25553      "movl %%ebx, %1" & LF & HT &
25554      "movl %%ecx, %2",
25555      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25556                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25557                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25558 @end group
25559 @end smallexample
25560 @noindent
25561 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25562 in the Ada program.
25563
25564 As a variation on the @code{Get_Flags} example, we can use the constraints
25565 string to direct the compiler to store the eax register into the @code{Flags}
25566 variable, instead of including the store instruction explicitly in the
25567 @code{Asm} template string:
25568
25569 @smallexample @c ada
25570 @group
25571 with Interfaces; use Interfaces;
25572 with Ada.Text_IO; use Ada.Text_IO;
25573 with System.Machine_Code; use System.Machine_Code;
25574 procedure Get_Flags_2 is
25575    Flags : Unsigned_32;
25576    use ASCII;
25577 begin
25578    Asm ("pushfl"      & LF & HT & -- push flags on stack
25579         "popl %%eax",             -- save flags in eax
25580         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25581    Put_Line ("Flags register:" & Flags'Img);
25582 end Get_Flags_2;
25583 @end group
25584 @end smallexample
25585
25586 @noindent
25587 The @code{"a"} constraint tells the compiler that the @code{Flags}
25588 variable will come from the eax register. Here is the resulting code:
25589
25590 @smallexample
25591 @group
25592 #APP
25593    pushfl
25594    popl %eax
25595 #NO_APP
25596    movl %eax,-40(%ebp)
25597 @end group
25598 @end smallexample
25599
25600 @noindent
25601 The compiler generated the store of eax into Flags after
25602 expanding the assembler code.
25603
25604 Actually, there was no need to pop the flags into the eax register;
25605 more simply, we could just pop the flags directly into the program variable:
25606
25607 @smallexample @c ada
25608 @group
25609 with Interfaces; use Interfaces;
25610 with Ada.Text_IO; use Ada.Text_IO;
25611 with System.Machine_Code; use System.Machine_Code;
25612 procedure Get_Flags_3 is
25613    Flags : Unsigned_32;
25614    use ASCII;
25615 begin
25616    Asm ("pushfl"  & LF & HT & -- push flags on stack
25617         "pop %0",             -- save flags in Flags
25618         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25619    Put_Line ("Flags register:" & Flags'Img);
25620 end Get_Flags_3;
25621 @end group
25622 @end smallexample
25623
25624 @c ---------------------------------------------------------------------------
25625 @node Input Variables in Inline Assembler
25626 @section Input Variables in Inline Assembler
25627
25628 @noindent
25629 The example in this section illustrates how to specify the source operands
25630 for assembly language statements.
25631 The program simply increments its input value by 1:
25632
25633 @smallexample @c ada
25634 @group
25635 with Interfaces; use Interfaces;
25636 with Ada.Text_IO; use Ada.Text_IO;
25637 with System.Machine_Code; use System.Machine_Code;
25638 procedure Increment is
25639
25640    function Incr (Value : Unsigned_32) return Unsigned_32 is
25641       Result : Unsigned_32;
25642    begin
25643       Asm ("incl %0",
25644            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25645            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25646       return Result;
25647    end Incr;
25648
25649    Value : Unsigned_32;
25650
25651 begin
25652    Value := 5;
25653    Put_Line ("Value before is" & Value'Img);
25654    Value := Incr (Value);
25655    Put_Line ("Value after is" & Value'Img);
25656 end Increment;
25657 @end group
25658 @end smallexample
25659
25660 The @code{Outputs} parameter to @code{Asm} specifies
25661 that the result will be in the eax register and that it is to be stored
25662 in the @code{Result} variable.
25663
25664 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25665 but with an @code{Asm_Input} attribute.
25666 The @code{"="} constraint, indicating an output value, is not present.
25667
25668 You can have multiple input variables, in the same way that you can have more
25669 than one output variable.
25670
25671 The parameter count (%0, %1) etc, now starts at the first input
25672 statement, and continues with the output statements.
25673 When both parameters use the same variable, the
25674 compiler will treat them as the same %n operand, which is the case here.
25675
25676 Just as the @code{Outputs} parameter causes the register to be stored into the
25677 target variable after execution of the assembler statements, so does the
25678 @code{Inputs} parameter cause its variable to be loaded into the register
25679 before execution of the assembler statements.
25680
25681 Thus the effect of the @code{Asm} invocation is:
25682 @enumerate
25683 @item load the 32-bit value of @code{Value} into eax
25684 @item execute the @code{incl %eax} instruction
25685 @item store the contents of eax into the @code{Result} variable
25686 @end enumerate
25687
25688 The resulting assembler file (with @option{-O2} optimization) contains:
25689 @smallexample
25690 @group
25691 _increment__incr.1:
25692    subl $4,%esp
25693    movl 8(%esp),%eax
25694 #APP
25695    incl %eax
25696 #NO_APP
25697    movl %eax,%edx
25698    movl %ecx,(%esp)
25699    addl $4,%esp
25700    ret
25701 @end group
25702 @end smallexample
25703
25704 @c ---------------------------------------------------------------------------
25705 @node Inlining Inline Assembler Code
25706 @section Inlining Inline Assembler Code
25707
25708 @noindent
25709 For a short subprogram such as the @code{Incr} function in the previous
25710 section, the overhead of the call and return (creating / deleting the stack
25711 frame) can be significant, compared to the amount of code in the subprogram
25712 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25713 which directs the compiler to expand invocations of the subprogram at the
25714 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25715 Here is the resulting program:
25716
25717 @smallexample @c ada
25718 @group
25719 with Interfaces; use Interfaces;
25720 with Ada.Text_IO; use Ada.Text_IO;
25721 with System.Machine_Code; use System.Machine_Code;
25722 procedure Increment_2 is
25723
25724    function Incr (Value : Unsigned_32) return Unsigned_32 is
25725       Result : Unsigned_32;
25726    begin
25727       Asm ("incl %0",
25728            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25729            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25730       return Result;
25731    end Incr;
25732    pragma Inline (Increment);
25733
25734    Value : Unsigned_32;
25735
25736 begin
25737    Value := 5;
25738    Put_Line ("Value before is" & Value'Img);
25739    Value := Increment (Value);
25740    Put_Line ("Value after is" & Value'Img);
25741 end Increment_2;
25742 @end group
25743 @end smallexample
25744
25745 Compile the program with both optimization (@option{-O2}) and inlining
25746 (@option{-gnatn}) enabled.
25747
25748 The @code{Incr} function is still compiled as usual, but at the
25749 point in @code{Increment} where our function used to be called:
25750
25751 @smallexample
25752 @group
25753 pushl %edi
25754 call _increment__incr.1
25755 @end group
25756 @end smallexample
25757
25758 @noindent
25759 the code for the function body directly appears:
25760
25761 @smallexample
25762 @group
25763 movl %esi,%eax
25764 #APP
25765    incl %eax
25766 #NO_APP
25767    movl %eax,%edx
25768 @end group
25769 @end smallexample
25770
25771 @noindent
25772 thus saving the overhead of stack frame setup and an out-of-line call.
25773
25774 @c ---------------------------------------------------------------------------
25775 @node Other Asm Functionality
25776 @section Other @code{Asm} Functionality
25777
25778 @noindent
25779 This section describes two important parameters to the @code{Asm}
25780 procedure: @code{Clobber}, which identifies register usage;
25781 and @code{Volatile}, which inhibits unwanted optimizations.
25782
25783 @menu
25784 * The Clobber Parameter::
25785 * The Volatile Parameter::
25786 @end menu
25787
25788 @c ---------------------------------------------------------------------------
25789 @node The Clobber Parameter
25790 @subsection The @code{Clobber} Parameter
25791
25792 @noindent
25793 One of the dangers of intermixing assembly language and a compiled language
25794 such as Ada is that the compiler needs to be aware of which registers are
25795 being used by the assembly code.  In some cases, such as the earlier examples,
25796 the constraint string is sufficient to indicate register usage (e.g.,
25797 @code{"a"} for
25798 the eax register).  But more generally, the compiler needs an explicit
25799 identification of the registers that are used by the Inline Assembly
25800 statements.
25801
25802 Using a register that the compiler doesn't know about
25803 could be a side effect of an instruction (like @code{mull}
25804 storing its result in both eax and edx).
25805 It can also arise from explicit register usage in your
25806 assembly code; for example:
25807 @smallexample
25808 @group
25809 Asm ("movl %0, %%ebx" & LF & HT &
25810      "movl %%ebx, %1",
25811      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25812      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25813 @end group
25814 @end smallexample
25815 @noindent
25816 where the compiler (since it does not analyze the @code{Asm} template string)
25817 does not know you are using the ebx register.
25818
25819 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25820 to identify the registers that will be used by your assembly code:
25821
25822 @smallexample
25823 @group
25824 Asm ("movl %0, %%ebx" & LF & HT &
25825      "movl %%ebx, %1",
25826      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25827      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25828      Clobber => "ebx");
25829 @end group
25830 @end smallexample
25831
25832 The Clobber parameter is a static string expression specifying the
25833 register(s) you are using.  Note that register names are @emph{not} prefixed
25834 by a percent sign. Also, if more than one register is used then their names
25835 are separated by commas; e.g., @code{"eax, ebx"}
25836
25837 The @code{Clobber} parameter has several additional uses:
25838 @enumerate
25839 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25840 @item Use ``register'' name @code{memory} if you changed a memory location
25841 @end enumerate
25842
25843 @c ---------------------------------------------------------------------------
25844 @node The Volatile Parameter
25845 @subsection The @code{Volatile} Parameter
25846 @cindex Volatile parameter
25847
25848 @noindent
25849 Compiler optimizations in the presence of Inline Assembler may sometimes have
25850 unwanted effects.  For example, when an @code{Asm} invocation with an input
25851 variable is inside a loop, the compiler might move the loading of the input
25852 variable outside the loop, regarding it as a one-time initialization.
25853
25854 If this effect is not desired, you can disable such optimizations by setting
25855 the @code{Volatile} parameter to @code{True}; for example:
25856
25857 @smallexample @c ada
25858 @group
25859 Asm ("movl %0, %%ebx" & LF & HT &
25860      "movl %%ebx, %1",
25861      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25862      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25863      Clobber  => "ebx",
25864      Volatile => True);
25865 @end group
25866 @end smallexample
25867
25868 By default, @code{Volatile} is set to @code{False} unless there is no
25869 @code{Outputs} parameter.
25870
25871 Although setting @code{Volatile} to @code{True} prevents unwanted
25872 optimizations, it will also disable other optimizations that might be
25873 important for efficiency. In general, you should set @code{Volatile}
25874 to @code{True} only if the compiler's optimizations have created
25875 problems.
25876 @c END OF INLINE ASSEMBLER CHAPTER
25877 @c ===============================
25878
25879 @c ***********************************
25880 @c * Compatibility and Porting Guide *
25881 @c ***********************************
25882 @node Compatibility and Porting Guide
25883 @appendix Compatibility and Porting Guide
25884
25885 @noindent
25886 This chapter describes the compatibility issues that may arise between
25887 GNAT and other Ada compilation systems (including those for Ada 83),
25888 and shows how GNAT can expedite porting
25889 applications developed in other Ada environments.
25890
25891 @menu
25892 * Compatibility with Ada 83::
25893 * Compatibility between Ada 95 and Ada 2005::
25894 * Implementation-dependent characteristics::
25895 * Compatibility with Other Ada Systems::
25896 * Representation Clauses::
25897 @ifclear vms
25898 @c Brief section is only in non-VMS version
25899 @c Full chapter is in VMS version
25900 * Compatibility with HP Ada 83::
25901 @end ifclear
25902 @ifset vms
25903 * Transitioning to 64-Bit GNAT for OpenVMS::
25904 @end ifset
25905 @end menu
25906
25907 @node Compatibility with Ada 83
25908 @section Compatibility with Ada 83
25909 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25910
25911 @noindent
25912 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25913 particular, the design intention was that the difficulties associated
25914 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25915 that occur when moving from one Ada 83 system to another.
25916
25917 However, there are a number of points at which there are minor
25918 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25919 full details of these issues,
25920 and should be consulted for a complete treatment.
25921 In practice the
25922 following subsections treat the most likely issues to be encountered.
25923
25924 @menu
25925 * Legal Ada 83 programs that are illegal in Ada 95::
25926 * More deterministic semantics::
25927 * Changed semantics::
25928 * Other language compatibility issues::
25929 @end menu
25930
25931 @node Legal Ada 83 programs that are illegal in Ada 95
25932 @subsection Legal Ada 83 programs that are illegal in Ada 95
25933
25934 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25935 Ada 95 and thus also in Ada 2005:
25936
25937 @table @emph
25938 @item Character literals
25939 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25940 @code{Wide_Character} as a new predefined character type, some uses of
25941 character literals that were legal in Ada 83 are illegal in Ada 95.
25942 For example:
25943 @smallexample @c ada
25944    for Char in 'A' .. 'Z' loop @dots{} end loop;
25945 @end smallexample
25946
25947 @noindent
25948 The problem is that @code{'A'} and @code{'Z'} could be from either
25949 @code{Character} or @code{Wide_Character}.  The simplest correction
25950 is to make the type explicit; e.g.:
25951 @smallexample @c ada
25952    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25953 @end smallexample
25954
25955 @item New reserved words
25956 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25957 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25958 Existing Ada 83 code using any of these identifiers must be edited to
25959 use some alternative name.
25960
25961 @item Freezing rules
25962 The rules in Ada 95 are slightly different with regard to the point at
25963 which entities are frozen, and representation pragmas and clauses are
25964 not permitted past the freeze point.  This shows up most typically in
25965 the form of an error message complaining that a representation item
25966 appears too late, and the appropriate corrective action is to move
25967 the item nearer to the declaration of the entity to which it refers.
25968
25969 A particular case is that representation pragmas
25970 @ifset vms
25971 (including the
25972 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25973 @end ifset
25974 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25975 declaration must be introduced to which the pragma can be applied.
25976
25977 @item Optional bodies for library packages
25978 In Ada 83, a package that did not require a package body was nevertheless
25979 allowed to have one.  This lead to certain surprises in compiling large
25980 systems (situations in which the body could be unexpectedly ignored by the
25981 binder).  In Ada 95, if a package does not require a body then it is not
25982 permitted to have a body.  To fix this problem, simply remove a redundant
25983 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25984 into the spec that makes the body required.  One approach is to add a private
25985 part to the package declaration (if necessary), and define a parameterless
25986 procedure called @code{Requires_Body}, which must then be given a dummy
25987 procedure body in the package body, which then becomes required.
25988 Another approach (assuming that this does not introduce elaboration
25989 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25990 since one effect of this pragma is to require the presence of a package body.
25991
25992 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25993 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25994 @code{Constraint_Error}.
25995 This means that it is illegal to have separate exception handlers for
25996 the two exceptions.  The fix is simply to remove the handler for the
25997 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25998 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25999
26000 @item Indefinite subtypes in generics
26001 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26002 as the actual for a generic formal private type, but then the instantiation
26003 would be illegal if there were any instances of declarations of variables
26004 of this type in the generic body.  In Ada 95, to avoid this clear violation
26005 of the methodological principle known as the ``contract model'',
26006 the generic declaration explicitly indicates whether
26007 or not such instantiations are permitted.  If a generic formal parameter
26008 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26009 type name, then it can be instantiated with indefinite types, but no
26010 stand-alone variables can be declared of this type.  Any attempt to declare
26011 such a variable will result in an illegality at the time the generic is
26012 declared.  If the @code{(<>)} notation is not used, then it is illegal
26013 to instantiate the generic with an indefinite type.
26014 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26015 It will show up as a compile time error, and
26016 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26017 @end table
26018
26019 @node More deterministic semantics
26020 @subsection More deterministic semantics
26021
26022 @table @emph
26023 @item Conversions
26024 Conversions from real types to integer types round away from 0.  In Ada 83
26025 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26026 implementation freedom was intended to support unbiased rounding in
26027 statistical applications, but in practice it interfered with portability.
26028 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26029 is required.  Numeric code may be affected by this change in semantics.
26030 Note, though, that this issue is no worse than already existed in Ada 83
26031 when porting code from one vendor to another.
26032
26033 @item Tasking
26034 The Real-Time Annex introduces a set of policies that define the behavior of
26035 features that were implementation dependent in Ada 83, such as the order in
26036 which open select branches are executed.
26037 @end table
26038
26039 @node Changed semantics
26040 @subsection Changed semantics
26041
26042 @noindent
26043 The worst kind of incompatibility is one where a program that is legal in
26044 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26045 possible in Ada 83.  Fortunately this is extremely rare, but the one
26046 situation that you should be alert to is the change in the predefined type
26047 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26048
26049 @table @emph
26050 @item Range of type @code{Character}
26051 The range of @code{Standard.Character} is now the full 256 characters
26052 of Latin-1, whereas in most Ada 83 implementations it was restricted
26053 to 128 characters. Although some of the effects of
26054 this change will be manifest in compile-time rejection of legal
26055 Ada 83 programs it is possible for a working Ada 83 program to have
26056 a different effect in Ada 95, one that was not permitted in Ada 83.
26057 As an example, the expression
26058 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26059 delivers @code{255} as its value.
26060 In general, you should look at the logic of any
26061 character-processing Ada 83 program and see whether it needs to be adapted
26062 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26063 character handling package that may be relevant if code needs to be adapted
26064 to account for the additional Latin-1 elements.
26065 The desirable fix is to
26066 modify the program to accommodate the full character set, but in some cases
26067 it may be convenient to define a subtype or derived type of Character that
26068 covers only the restricted range.
26069 @cindex Latin-1
26070 @end table
26071
26072 @node Other language compatibility issues
26073 @subsection Other language compatibility issues
26074
26075 @table @emph
26076 @item @option{-gnat83} switch
26077 All implementations of GNAT provide a switch that causes GNAT to operate
26078 in Ada 83 mode.  In this mode, some but not all compatibility problems
26079 of the type described above are handled automatically.  For example, the
26080 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26081 as identifiers as in Ada 83.
26082 However,
26083 in practice, it is usually advisable to make the necessary modifications
26084 to the program to remove the need for using this switch.
26085 See @ref{Compiling Different Versions of Ada}.
26086
26087 @item Support for removed Ada 83 pragmas and attributes
26088 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26089 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26090 compilers are allowed, but not required, to implement these missing
26091 elements.  In contrast with some other compilers, GNAT implements all
26092 such pragmas and attributes, eliminating this compatibility concern.  These
26093 include @code{pragma Interface} and the floating point type attributes
26094 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26095 @end table
26096
26097
26098 @node Compatibility between Ada 95 and Ada 2005
26099 @section Compatibility between Ada 95 and Ada 2005
26100 @cindex Compatibility between Ada 95 and Ada 2005
26101
26102 @noindent
26103 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26104 a number of incompatibilities. Several are enumerated below;
26105 for a complete description please see the
26106 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26107 @cite{Rationale for Ada 2005}.
26108
26109 @table @emph
26110 @item New reserved words.
26111 The words @code{interface}, @code{overriding} and @code{synchronized} are
26112 reserved in Ada 2005.
26113 A pre-Ada 2005 program that uses any of these as an identifier will be
26114 illegal.
26115
26116 @item New declarations in predefined packages.
26117 A number of packages in the predefined environment contain new declarations:
26118 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26119 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26120 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26121 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26122 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26123 If an Ada 95 program does a @code{with} and @code{use} of any of these
26124 packages, the new declarations may cause name clashes.
26125
26126 @item Access parameters.
26127 A nondispatching subprogram with an access parameter cannot be renamed
26128 as a dispatching operation.  This was permitted in Ada 95.
26129
26130 @item Access types, discriminants, and constraints.
26131 Rule changes in this area have led to some incompatibilities; for example,
26132 constrained subtypes of some access types are not permitted in Ada 2005.
26133
26134 @item Aggregates for limited types.
26135 The allowance of aggregates for limited types in Ada 2005 raises the
26136 possibility of ambiguities in legal Ada 95 programs, since additional types
26137 now need to be considered in expression resolution.
26138
26139 @item Fixed-point multiplication and division.
26140 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26141 were legal in Ada 95 and invoked the predefined versions of these operations,
26142 are now ambiguous.
26143 The ambiguity may be resolved either by applying a type conversion to the
26144 expression, or by explicitly invoking the operation from package
26145 @code{Standard}.
26146
26147 @item Return-by-reference types.
26148 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26149 can declare a function returning a value from an anonymous access type.
26150 @end table
26151
26152
26153 @node Implementation-dependent characteristics
26154 @section Implementation-dependent characteristics
26155 @noindent
26156 Although the Ada language defines the semantics of each construct as
26157 precisely as practical, in some situations (for example for reasons of
26158 efficiency, or where the effect is heavily dependent on the host or target
26159 platform) the implementation is allowed some freedom.  In porting Ada 83
26160 code to GNAT, you need to be aware of whether / how the existing code
26161 exercised such implementation dependencies.  Such characteristics fall into
26162 several categories, and GNAT offers specific support in assisting the
26163 transition from certain Ada 83 compilers.
26164
26165 @menu
26166 * Implementation-defined pragmas::
26167 * Implementation-defined attributes::
26168 * Libraries::
26169 * Elaboration order::
26170 * Target-specific aspects::
26171 @end menu
26172
26173 @node Implementation-defined pragmas
26174 @subsection Implementation-defined pragmas
26175
26176 @noindent
26177 Ada compilers are allowed to supplement the language-defined pragmas, and
26178 these are a potential source of non-portability.  All GNAT-defined pragmas
26179 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26180 Reference Manual}, and these include several that are specifically
26181 intended to correspond to other vendors' Ada 83 pragmas.
26182 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26183 For compatibility with HP Ada 83, GNAT supplies the pragmas
26184 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26185 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26186 and @code{Volatile}.
26187 Other relevant pragmas include @code{External} and @code{Link_With}.
26188 Some vendor-specific
26189 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26190 recognized, thus
26191 avoiding compiler rejection of units that contain such pragmas; they are not
26192 relevant in a GNAT context and hence are not otherwise implemented.
26193
26194 @node Implementation-defined attributes
26195 @subsection Implementation-defined attributes
26196
26197 Analogous to pragmas, the set of attributes may be extended by an
26198 implementation.  All GNAT-defined attributes are described in
26199 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26200 Manual}, and these include several that are specifically intended
26201 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26202 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26203 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26204 @code{Type_Class}.
26205
26206 @node Libraries
26207 @subsection Libraries
26208 @noindent
26209 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26210 code uses vendor-specific libraries then there are several ways to manage
26211 this in Ada 95 or Ada 2005:
26212 @enumerate
26213 @item
26214 If the source code for the libraries (specs and bodies) are
26215 available, then the libraries can be migrated in the same way as the
26216 application.
26217 @item
26218 If the source code for the specs but not the bodies are
26219 available, then you can reimplement the bodies.
26220 @item
26221 Some features introduced by Ada 95 obviate the need for library support.  For
26222 example most Ada 83 vendors supplied a package for unsigned integers.  The
26223 Ada 95 modular type feature is the preferred way to handle this need, so
26224 instead of migrating or reimplementing the unsigned integer package it may
26225 be preferable to retrofit the application using modular types.
26226 @end enumerate
26227
26228 @node Elaboration order
26229 @subsection Elaboration order
26230 @noindent
26231 The implementation can choose any elaboration order consistent with the unit
26232 dependency relationship.  This freedom means that some orders can result in
26233 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26234 to invoke a subprogram its body has been elaborated, or to instantiate a
26235 generic before the generic body has been elaborated.  By default GNAT
26236 attempts to choose a safe order (one that will not encounter access before
26237 elaboration problems) by implicitly inserting @code{Elaborate} or
26238 @code{Elaborate_All} pragmas where
26239 needed.  However, this can lead to the creation of elaboration circularities
26240 and a resulting rejection of the program by gnatbind.  This issue is
26241 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26242 In brief, there are several
26243 ways to deal with this situation:
26244
26245 @itemize @bullet
26246 @item
26247 Modify the program to eliminate the circularities, e.g.@: by moving
26248 elaboration-time code into explicitly-invoked procedures
26249 @item
26250 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26251 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26252 @code{Elaborate_All}
26253 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26254 (by selectively suppressing elaboration checks via pragma
26255 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26256 @end itemize
26257
26258 @node Target-specific aspects
26259 @subsection Target-specific aspects
26260 @noindent
26261 Low-level applications need to deal with machine addresses, data
26262 representations, interfacing with assembler code, and similar issues.  If
26263 such an Ada 83 application is being ported to different target hardware (for
26264 example where the byte endianness has changed) then you will need to
26265 carefully examine the program logic; the porting effort will heavily depend
26266 on the robustness of the original design.  Moreover, Ada 95 (and thus
26267 Ada 2005) are sometimes
26268 incompatible with typical Ada 83 compiler practices regarding implicit
26269 packing, the meaning of the Size attribute, and the size of access values.
26270 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26271
26272 @node Compatibility with Other Ada Systems
26273 @section Compatibility with Other Ada Systems
26274
26275 @noindent
26276 If programs avoid the use of implementation dependent and
26277 implementation defined features, as documented in the @cite{Ada
26278 Reference Manual}, there should be a high degree of portability between
26279 GNAT and other Ada systems.  The following are specific items which
26280 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26281 compilers, but do not affect porting code to GNAT@.
26282 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26283 the following issues may or may not arise for Ada 2005 programs
26284 when other compilers appear.)
26285
26286 @table @emph
26287 @item Ada 83 Pragmas and Attributes
26288 Ada 95 compilers are allowed, but not required, to implement the missing
26289 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26290 GNAT implements all such pragmas and attributes, eliminating this as
26291 a compatibility concern, but some other Ada 95 compilers reject these
26292 pragmas and attributes.
26293
26294 @item Specialized Needs Annexes
26295 GNAT implements the full set of special needs annexes.  At the
26296 current time, it is the only Ada 95 compiler to do so.  This means that
26297 programs making use of these features may not be portable to other Ada
26298 95 compilation systems.
26299
26300 @item Representation Clauses
26301 Some other Ada 95 compilers implement only the minimal set of
26302 representation clauses required by the Ada 95 reference manual.  GNAT goes
26303 far beyond this minimal set, as described in the next section.
26304 @end table
26305
26306 @node Representation Clauses
26307 @section Representation Clauses
26308
26309 @noindent
26310 The Ada 83 reference manual was quite vague in describing both the minimal
26311 required implementation of representation clauses, and also their precise
26312 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26313 minimal set of capabilities required is still quite limited.
26314
26315 GNAT implements the full required set of capabilities in
26316 Ada 95 and Ada 2005, but also goes much further, and in particular
26317 an effort has been made to be compatible with existing Ada 83 usage to the
26318 greatest extent possible.
26319
26320 A few cases exist in which Ada 83 compiler behavior is incompatible with
26321 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26322 intentional or accidental dependence on specific implementation dependent
26323 characteristics of these Ada 83 compilers.  The following is a list of
26324 the cases most likely to arise in existing Ada 83 code.
26325
26326 @table @emph
26327 @item Implicit Packing
26328 Some Ada 83 compilers allowed a Size specification to cause implicit
26329 packing of an array or record.  This could cause expensive implicit
26330 conversions for change of representation in the presence of derived
26331 types, and the Ada design intends to avoid this possibility.
26332 Subsequent AI's were issued to make it clear that such implicit
26333 change of representation in response to a Size clause is inadvisable,
26334 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26335 Reference Manuals as implementation advice that is followed by GNAT@.
26336 The problem will show up as an error
26337 message rejecting the size clause.  The fix is simply to provide
26338 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26339 a Component_Size clause.
26340
26341 @item Meaning of Size Attribute
26342 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26343 the minimal number of bits required to hold values of the type.  For example,
26344 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26345 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26346 some 32 in this situation.  This problem will usually show up as a compile
26347 time error, but not always.  It is a good idea to check all uses of the
26348 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26349 Object_Size can provide a useful way of duplicating the behavior of
26350 some Ada 83 compiler systems.
26351
26352 @item Size of Access Types
26353 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26354 and that therefore it will be the same size as a System.Address value.  This
26355 assumption is true for GNAT in most cases with one exception.  For the case of
26356 a pointer to an unconstrained array type (where the bounds may vary from one
26357 value of the access type to another), the default is to use a ``fat pointer'',
26358 which is represented as two separate pointers, one to the bounds, and one to
26359 the array.  This representation has a number of advantages, including improved
26360 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26361 code which makes the assumption that, for example, pointers fit in 32 bits on
26362 a machine with 32-bit addressing.
26363
26364 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26365 access types in this case (where the designated type is an unconstrained array
26366 type).  These thin pointers are indeed the same size as a System.Address value.
26367 To specify a thin pointer, use a size clause for the type, for example:
26368
26369 @smallexample @c ada
26370 type X is access all String;
26371 for X'Size use Standard'Address_Size;
26372 @end smallexample
26373
26374 @noindent
26375 which will cause the type X to be represented using a single pointer.
26376 When using this representation, the bounds are right behind the array.
26377 This representation is slightly less efficient, and does not allow quite
26378 such flexibility in the use of foreign pointers or in using the
26379 Unrestricted_Access attribute to create pointers to non-aliased objects.
26380 But for any standard portable use of the access type it will work in
26381 a functionally correct manner and allow porting of existing code.
26382 Note that another way of forcing a thin pointer representation
26383 is to use a component size clause for the element size in an array,
26384 or a record representation clause for an access field in a record.
26385 @end table
26386
26387 @ifclear vms
26388 @c This brief section is only in the non-VMS version
26389 @c The complete chapter on HP Ada is in the VMS version
26390 @node Compatibility with HP Ada 83
26391 @section Compatibility with HP Ada 83
26392
26393 @noindent
26394 The VMS version of GNAT fully implements all the pragmas and attributes
26395 provided by HP Ada 83, as well as providing the standard HP Ada 83
26396 libraries, including Starlet.  In addition, data layouts and parameter
26397 passing conventions are highly compatible.  This means that porting
26398 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26399 most other porting efforts.  The following are some of the most
26400 significant differences between GNAT and HP Ada 83.
26401
26402 @table @emph
26403 @item Default floating-point representation
26404 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26405 it is VMS format.  GNAT does implement the necessary pragmas
26406 (Long_Float, Float_Representation) for changing this default.
26407
26408 @item System
26409 The package System in GNAT exactly corresponds to the definition in the
26410 Ada 95 reference manual, which means that it excludes many of the
26411 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26412 that contains the additional definitions, and a special pragma,
26413 Extend_System allows this package to be treated transparently as an
26414 extension of package System.
26415
26416 @item To_Address
26417 The definitions provided by Aux_DEC are exactly compatible with those
26418 in the HP Ada 83 version of System, with one exception.
26419 HP Ada provides the following declarations:
26420
26421 @smallexample @c ada
26422 TO_ADDRESS (INTEGER)
26423 TO_ADDRESS (UNSIGNED_LONGWORD)
26424 TO_ADDRESS (@i{universal_integer})
26425 @end smallexample
26426
26427 @noindent
26428 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26429 an extension to Ada 83 not strictly compatible with the reference manual.
26430 In GNAT, we are constrained to be exactly compatible with the standard,
26431 and this means we cannot provide this capability.  In HP Ada 83, the
26432 point of this definition is to deal with a call like:
26433
26434 @smallexample @c ada
26435 TO_ADDRESS (16#12777#);
26436 @end smallexample
26437
26438 @noindent
26439 Normally, according to the Ada 83 standard, one would expect this to be
26440 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26441 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26442 definition using @i{universal_integer} takes precedence.
26443
26444 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26445 is not possible to be 100% compatible.  Since there are many programs using
26446 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26447 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26448 declarations provided in the GNAT version of AUX_Dec are:
26449
26450 @smallexample @c ada
26451 function To_Address (X : Integer) return Address;
26452 pragma Pure_Function (To_Address);
26453
26454 function To_Address_Long (X : Unsigned_Longword)
26455  return Address;
26456 pragma Pure_Function (To_Address_Long);
26457 @end smallexample
26458
26459 @noindent
26460 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26461 change the name to TO_ADDRESS_LONG@.
26462
26463 @item Task_Id values
26464 The Task_Id values assigned will be different in the two systems, and GNAT
26465 does not provide a specified value for the Task_Id of the environment task,
26466 which in GNAT is treated like any other declared task.
26467 @end table
26468
26469 @noindent
26470 For full details on these and other less significant compatibility issues,
26471 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26472 Overview and Comparison on HP Platforms}.
26473
26474 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26475 attributes are recognized, although only a subset of them can sensibly
26476 be implemented.  The description of pragmas in @ref{Implementation
26477 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26478 indicates whether or not they are applicable to non-VMS systems.
26479 @end ifclear
26480
26481 @ifset vms
26482 @node Transitioning to 64-Bit GNAT for OpenVMS
26483 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26484
26485 @noindent
26486 This section is meant to assist users of pre-2006 @value{EDITION}
26487 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26488 the version of the GNAT technology supplied in 2006 and later for
26489 OpenVMS on both Alpha and I64.
26490
26491 @menu
26492 * Introduction to transitioning::
26493 * Migration of 32 bit code::
26494 * Taking advantage of 64 bit addressing::
26495 * Technical details::
26496 @end menu
26497
26498 @node Introduction to transitioning
26499 @subsection Introduction
26500
26501 @noindent
26502 64-bit @value{EDITION} for Open VMS has been designed to meet
26503 three main goals:
26504
26505 @enumerate
26506 @item
26507 Providing a full conforming implementation of Ada 95 and Ada 2005
26508
26509 @item
26510 Allowing maximum backward compatibility, thus easing migration of existing
26511 Ada source code
26512
26513 @item
26514 Supplying a path for exploiting the full 64-bit address range
26515 @end enumerate
26516
26517 @noindent
26518 Ada's strong typing semantics has made it
26519 impractical to have different 32-bit and 64-bit modes. As soon as
26520 one object could possibly be outside the 32-bit address space, this
26521 would make it necessary for the @code{System.Address} type to be 64 bits.
26522 In particular, this would cause inconsistencies if 32-bit code is
26523 called from 64-bit code that raises an exception.
26524
26525 This issue has been resolved by always using 64-bit addressing
26526 at the system level, but allowing for automatic conversions between
26527 32-bit and 64-bit addresses where required. Thus users who
26528 do not currently require 64-bit addressing capabilities, can
26529 recompile their code with only minimal changes (and indeed
26530 if the code is written in portable Ada, with no assumptions about
26531 the size of the @code{Address} type, then no changes at all are necessary).
26532 At the same time,
26533 this approach provides a simple, gradual upgrade path to future
26534 use of larger memories than available for 32-bit systems.
26535 Also, newly written applications or libraries will by default
26536 be fully compatible with future systems exploiting 64-bit
26537 addressing capabilities.
26538
26539 @ref{Migration of 32 bit code}, will focus on porting applications
26540 that do not require more than 2 GB of
26541 addressable memory. This code will be referred to as
26542 @emph{32-bit code}.
26543 For applications intending to exploit the full 64-bit address space,
26544 @ref{Taking advantage of 64 bit addressing},
26545 will consider further changes that may be required.
26546 Such code will be referred to below as @emph{64-bit code}.
26547
26548 @node Migration of 32 bit code
26549 @subsection Migration of 32-bit code
26550
26551 @menu
26552 * Address types::
26553 * Access types and 32/64-bit allocation::
26554 * Unchecked conversions::
26555 * Predefined constants::
26556 * Interfacing with C::
26557 * 32/64-bit descriptors::
26558 * Experience with source compatibility::
26559 @end menu
26560
26561 @node Address types
26562 @subsubsection Address types
26563
26564 @noindent
26565 To solve the problem of mixing 64-bit and 32-bit addressing,
26566 while maintaining maximum backward compatibility, the following
26567 approach has been taken:
26568
26569 @itemize @bullet
26570 @item
26571 @code{System.Address} always has a size of 64 bits
26572 @cindex @code{System.Address} size
26573 @cindex @code{Address} size
26574
26575 @item
26576 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26577 @cindex @code{System.Short_Address} size
26578 @cindex @code{Short_Address} size
26579 @end itemize
26580
26581 @noindent
26582 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26583 a @code{Short_Address}
26584 may be used where an @code{Address} is required, and vice versa, without
26585 needing explicit type conversions.
26586 By virtue of the Open VMS parameter passing conventions,
26587 even imported
26588 and exported subprograms that have 32-bit address parameters are
26589 compatible with those that have 64-bit address parameters.
26590 (See @ref{Making code 64 bit clean} for details.)
26591
26592 The areas that may need attention are those where record types have
26593 been defined that contain components of the type @code{System.Address}, and
26594 where objects of this type are passed to code expecting a record layout with
26595 32-bit addresses.
26596
26597 Different compilers on different platforms cannot be
26598 expected to represent the same type in the same way,
26599 since alignment constraints
26600 and other system-dependent properties affect the compiler's decision.
26601 For that reason, Ada code
26602 generally uses representation clauses to specify the expected
26603 layout where required.
26604
26605 If such a representation clause uses 32 bits for a component having
26606 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26607 will detect that error and produce a specific diagnostic message.
26608 The developer should then determine whether the representation
26609 should be 64 bits or not and make either of two changes:
26610 change the size to 64 bits and leave the type as @code{System.Address}, or
26611 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26612 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26613 required in any code setting or accessing the field; the compiler will
26614 automatically perform any needed conversions between address
26615 formats.
26616
26617 @node Access types and 32/64-bit allocation
26618 @subsubsection Access types and 32/64-bit allocation
26619 @cindex 32-bit allocation
26620 @cindex 64-bit allocation
26621
26622 @noindent
26623 By default, objects designated by access values are always allocated in
26624 the 64-bit address space, and access values themselves are represented
26625 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26626 is required (for example if the address of an allocated object is assigned
26627 to a @code{Short_Address} variable), then several alternatives are available:
26628
26629 @itemize @bullet
26630 @item
26631 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26632 definition is @code{access T} versus @code{access all T} or
26633 @code{access constant T}), may be declared with a @code{'Size} representation
26634 clause that establishes the size as 32 bits.
26635 In such circumstances allocations for that type will
26636 be from the 32-bit heap.  Such a clause is not permitted
26637 for a general access type (declared with @code{access all} or
26638 @code{access constant}) as values of such types must be able to refer
26639 to any object of the designated type, including objects residing outside
26640 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26641 type definitions, however, since general access types were introduced
26642 in @w{Ada 95}.
26643
26644 @item
26645 Switches for @command{GNAT BIND} control whether the internal GNAT
26646 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26647 @cindex @code{__gnat_malloc}
26648 The switches are respectively @option{-H64} (the default) and
26649 @option{-H32}.
26650 @cindex @option{-H32} (@command{gnatbind})
26651 @cindex @option{-H64} (@command{gnatbind})
26652
26653 @item
26654 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26655 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26656 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26657 If this variable is left
26658 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26659 then the default (64-bit) allocation is used.
26660 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26661 then 32-bit allocation is used.  The gnatbind qualifiers described above
26662 override this logical name.
26663
26664 @item
26665 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26666 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26667 at a low level to convert explicit calls to @code{malloc} and related
26668 functions from the C run-time library so that they perform allocations
26669 in the 32-bit heap.
26670 Since all internal allocations from GNAT use @code{__gnat_malloc},
26671 this switch is not required unless the program makes explicit calls on
26672 @code{malloc} (or related functions) from interfaced C code.
26673 @end itemize
26674
26675
26676 @node Unchecked conversions
26677 @subsubsection Unchecked conversions
26678
26679 @noindent
26680 In the case of an @code{Unchecked_Conversion} where the source type is a
26681 64-bit access type or the type @code{System.Address}, and the target
26682 type is a 32-bit type, the compiler will generate a warning.
26683 Even though the generated code will still perform the required
26684 conversions, it is highly recommended in these cases to use
26685 respectively a 32-bit access type or @code{System.Short_Address}
26686 as the source type.
26687
26688 @node Predefined constants
26689 @subsubsection Predefined constants
26690
26691 @noindent
26692 The following table shows the correspondence between pre-2006 versions of
26693 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26694 (``New''):
26695
26696 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26697 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26698 @item   @code{System.Word_Size}          @tab 32      @tab 64
26699 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26700 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26701 @item   @code{System.Address_Size}       @tab 32      @tab 64
26702 @end multitable
26703
26704 @noindent
26705 If you need to refer to the specific
26706 memory size of a 32-bit implementation, instead of the
26707 actual memory size, use @code{System.Short_Memory_Size}
26708 rather than @code{System.Memory_Size}.
26709 Similarly, references to @code{System.Address_Size} may need
26710 to be replaced by @code{System.Short_Address'Size}.
26711 The program @command{gnatfind} may be useful for locating
26712 references to the above constants, so that you can verify that they
26713 are still correct.
26714
26715 @node Interfacing with C
26716 @subsubsection Interfacing with C
26717
26718 @noindent
26719 In order to minimize the impact of the transition to 64-bit addresses on
26720 legacy programs, some fundamental types in the @code{Interfaces.C}
26721 package hierarchy continue to be represented in 32 bits.
26722 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26723 This eases integration with the default HP C layout choices, for example
26724 as found in the system routines in @code{DECC$SHR.EXE}.
26725 Because of this implementation choice, the type fully compatible with
26726 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26727 Depending on the context the compiler will issue a
26728 warning or an error when type @code{Address} is used, alerting the user to a
26729 potential problem. Otherwise 32-bit programs that use
26730 @code{Interfaces.C} should normally not require code modifications
26731
26732 The other issue arising with C interfacing concerns pragma @code{Convention}.
26733 For VMS 64-bit systems, there is an issue of the appropriate default size
26734 of C convention pointers in the absence of an explicit size clause. The HP
26735 C compiler can choose either 32 or 64 bits depending on compiler options.
26736 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26737 clause is given. This proves a better choice for porting 32-bit legacy
26738 applications. In order to have a 64-bit representation, it is necessary to
26739 specify a size representation clause. For example:
26740
26741 @smallexample @c ada
26742 type int_star is access Interfaces.C.int;
26743 pragma Convention(C, int_star);
26744 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26745 @end smallexample
26746
26747 @node 32/64-bit descriptors
26748 @subsubsection 32/64-bit descriptors
26749
26750 @noindent
26751 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
26752 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26753 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26754 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26755 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26756
26757 If the configuration pragma @code{Short_Descriptors} is supplied, then
26758 all descriptors will be 32 bits.
26759 @cindex pragma @code{Short_Descriptors}
26760
26761 @node Experience with source compatibility
26762 @subsubsection Experience with source compatibility
26763
26764 @noindent
26765 The Security Server and STARLET on I64 provide an interesting ``test case''
26766 for source compatibility issues, since it is in such system code
26767 where assumptions about @code{Address} size might be expected to occur.
26768 Indeed, there were a small number of occasions in the Security Server
26769 file @file{jibdef.ads}
26770 where a representation clause for a record type specified
26771 32 bits for a component of type @code{Address}.
26772 All of these errors were detected by the compiler.
26773 The repair was obvious and immediate; to simply replace @code{Address} by
26774 @code{Short_Address}.
26775
26776 In the case of STARLET, there were several record types that should
26777 have had representation clauses but did not.  In these record types
26778 there was an implicit assumption that an @code{Address} value occupied
26779 32 bits.
26780 These compiled without error, but their usage resulted in run-time error
26781 returns from STARLET system calls.
26782 Future GNAT technology enhancements may include a tool that detects and flags
26783 these sorts of potential source code porting problems.
26784
26785 @c ****************************************
26786 @node Taking advantage of 64 bit addressing
26787 @subsection Taking advantage of 64-bit addressing
26788
26789 @menu
26790 * Making code 64 bit clean::
26791 * Allocating memory from the 64 bit storage pool::
26792 * Restrictions on use of 64 bit objects::
26793 * STARLET and other predefined libraries::
26794 @end menu
26795
26796 @node Making code 64 bit clean
26797 @subsubsection Making code 64-bit clean
26798
26799 @noindent
26800 In order to prevent problems that may occur when (parts of) a
26801 system start using memory outside the 32-bit address range,
26802 we recommend some additional guidelines:
26803
26804 @itemize @bullet
26805 @item
26806 For imported subprograms that take parameters of the
26807 type @code{System.Address}, ensure that these subprograms can
26808 indeed handle 64-bit addresses. If not, or when in doubt,
26809 change the subprogram declaration to specify
26810 @code{System.Short_Address} instead.
26811
26812 @item
26813 Resolve all warnings related to size mismatches in
26814 unchecked conversions. Failing to do so causes
26815 erroneous execution if the source object is outside
26816 the 32-bit address space.
26817
26818 @item
26819 (optional) Explicitly use the 32-bit storage pool
26820 for access types used in a 32-bit context, or use
26821 generic access types where possible
26822 (@pxref{Restrictions on use of 64 bit objects}).
26823 @end itemize
26824
26825 @noindent
26826 If these rules are followed, the compiler will automatically insert
26827 any necessary checks to ensure that no addresses or access values
26828 passed to 32-bit code ever refer to objects outside the 32-bit
26829 address range.
26830 Any attempt to do this will raise @code{Constraint_Error}.
26831
26832 @node Allocating memory from the 64 bit storage pool
26833 @subsubsection Allocating memory from the 64-bit storage pool
26834
26835 @noindent
26836 By default, all allocations -- for both pool-specific and general
26837 access types -- use the 64-bit storage pool.  To override
26838 this default, for an individual access type or globally, see
26839 @ref{Access types and 32/64-bit allocation}.
26840
26841 @node Restrictions on use of 64 bit objects
26842 @subsubsection Restrictions on use of 64-bit objects
26843
26844 @noindent
26845 Taking the address of an object allocated from a 64-bit storage pool,
26846 and then passing this address to a subprogram expecting
26847 @code{System.Short_Address},
26848 or assigning it to a variable of type @code{Short_Address}, will cause
26849 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26850 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26851 no exception is raised and execution
26852 will become erroneous.
26853
26854 @node STARLET and other predefined libraries
26855 @subsubsection STARLET and other predefined libraries
26856
26857 @noindent
26858 All code that comes as part of GNAT is 64-bit clean, but the
26859 restrictions given in @ref{Restrictions on use of 64 bit objects},
26860 still apply. Look at the package
26861 specs to see in which contexts objects allocated
26862 in 64-bit address space are acceptable.
26863
26864 @node Technical details
26865 @subsection Technical details
26866
26867 @noindent
26868 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26869 Ada standard with respect to the type of @code{System.Address}. Previous
26870 versions of GNAT Pro have defined this type as private and implemented it as a
26871 modular type.
26872
26873 In order to allow defining @code{System.Short_Address} as a proper subtype,
26874 and to match the implicit sign extension in parameter passing,
26875 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26876 visible (i.e., non-private) integer type.
26877 Standard operations on the type, such as the binary operators ``+'', ``-'',
26878 etc., that take @code{Address} operands and return an @code{Address} result,
26879 have been hidden by declaring these
26880 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26881 ambiguities that would otherwise result from overloading.
26882 (Note that, although @code{Address} is a visible integer type,
26883 good programming practice dictates against exploiting the type's
26884 integer properties such as literals, since this will compromise
26885 code portability.)
26886
26887 Defining @code{Address} as a visible integer type helps achieve
26888 maximum compatibility for existing Ada code,
26889 without sacrificing the capabilities of the 64-bit architecture.
26890 @end ifset
26891
26892 @c ************************************************
26893 @ifset unw
26894 @node Microsoft Windows Topics
26895 @appendix Microsoft Windows Topics
26896 @cindex Windows NT
26897 @cindex Windows 95
26898 @cindex Windows 98
26899
26900 @noindent
26901 This chapter describes topics that are specific to the Microsoft Windows
26902 platforms (NT, 2000, and XP Professional).
26903
26904 @menu
26905 * Using GNAT on Windows::
26906 * Using a network installation of GNAT::
26907 * CONSOLE and WINDOWS subsystems::
26908 * Temporary Files::
26909 * Mixed-Language Programming on Windows::
26910 * Windows Calling Conventions::
26911 * Introduction to Dynamic Link Libraries (DLLs)::
26912 * Using DLLs with GNAT::
26913 * Building DLLs with GNAT Project files::
26914 * Building DLLs with GNAT::
26915 * Building DLLs with gnatdll::
26916 * GNAT and Windows Resources::
26917 * Debugging a DLL::
26918 * Setting Stack Size from gnatlink::
26919 * Setting Heap Size from gnatlink::
26920 @end menu
26921
26922 @node Using GNAT on Windows
26923 @section Using GNAT on Windows
26924
26925 @noindent
26926 One of the strengths of the GNAT technology is that its tool set
26927 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26928 @code{gdb} debugger, etc.) is used in the same way regardless of the
26929 platform.
26930
26931 On Windows this tool set is complemented by a number of Microsoft-specific
26932 tools that have been provided to facilitate interoperability with Windows
26933 when this is required. With these tools:
26934
26935 @itemize @bullet
26936
26937 @item
26938 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26939 subsystems.
26940
26941 @item
26942 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26943 relocatable and non-relocatable DLLs are supported).
26944
26945 @item
26946 You can build Ada DLLs for use in other applications. These applications
26947 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26948 relocatable and non-relocatable Ada DLLs are supported.
26949
26950 @item
26951 You can include Windows resources in your Ada application.
26952
26953 @item
26954 You can use or create COM/DCOM objects.
26955 @end itemize
26956
26957 @noindent
26958 Immediately below are listed all known general GNAT-for-Windows restrictions.
26959 Other restrictions about specific features like Windows Resources and DLLs
26960 are listed in separate sections below.
26961
26962 @itemize @bullet
26963
26964 @item
26965 It is not possible to use @code{GetLastError} and @code{SetLastError}
26966 when tasking, protected records, or exceptions are used. In these
26967 cases, in order to implement Ada semantics, the GNAT run-time system
26968 calls certain Win32 routines that set the last error variable to 0 upon
26969 success. It should be possible to use @code{GetLastError} and
26970 @code{SetLastError} when tasking, protected record, and exception
26971 features are not used, but it is not guaranteed to work.
26972
26973 @item
26974 It is not possible to link against Microsoft libraries except for
26975 import libraries. Interfacing must be done by the mean of DLLs.
26976
26977 @item
26978 When the compilation environment is located on FAT32 drives, users may
26979 experience recompilations of the source files that have not changed if
26980 Daylight Saving Time (DST) state has changed since the last time files
26981 were compiled. NTFS drives do not have this problem.
26982
26983 @item
26984 No components of the GNAT toolset use any entries in the Windows
26985 registry. The only entries that can be created are file associations and
26986 PATH settings, provided the user has chosen to create them at installation
26987 time, as well as some minimal book-keeping information needed to correctly
26988 uninstall or integrate different GNAT products.
26989 @end itemize
26990
26991 @node Using a network installation of GNAT
26992 @section Using a network installation of GNAT
26993
26994 @noindent
26995 Make sure the system on which GNAT is installed is accessible from the
26996 current machine, i.e., the install location is shared over the network.
26997 Shared resources are accessed on Windows by means of UNC paths, which
26998 have the format @code{\\server\sharename\path}
26999
27000 In order to use such a network installation, simply add the UNC path of the
27001 @file{bin} directory of your GNAT installation in front of your PATH. For
27002 example, if GNAT is installed in @file{\GNAT} directory of a share location
27003 called @file{c-drive} on a machine @file{LOKI}, the following command will
27004 make it available:
27005
27006 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27007
27008 Be aware that every compilation using the network installation results in the
27009 transfer of large amounts of data across the network and will likely cause
27010 serious performance penalty.
27011
27012 @node CONSOLE and WINDOWS subsystems
27013 @section CONSOLE and WINDOWS subsystems
27014 @cindex CONSOLE Subsystem
27015 @cindex WINDOWS Subsystem
27016 @cindex -mwindows
27017
27018 @noindent
27019 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27020 (which is the default subsystem) will always create a console when
27021 launching the application. This is not something desirable when the
27022 application has a Windows GUI. To get rid of this console the
27023 application must be using the @code{WINDOWS} subsystem. To do so
27024 the @option{-mwindows} linker option must be specified.
27025
27026 @smallexample
27027 $ gnatmake winprog -largs -mwindows
27028 @end smallexample
27029
27030 @node Temporary Files
27031 @section Temporary Files
27032 @cindex Temporary files
27033
27034 @noindent
27035 It is possible to control where temporary files gets created by setting
27036 the @env{TMP} environment variable. The file will be created:
27037
27038 @itemize
27039 @item Under the directory pointed to by the @env{TMP} environment variable if
27040 this directory exists.
27041
27042 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27043 set (or not pointing to a directory) and if this directory exists.
27044
27045 @item Under the current working directory otherwise.
27046 @end itemize
27047
27048 @noindent
27049 This allows you to determine exactly where the temporary
27050 file will be created. This is particularly useful in networked
27051 environments where you may not have write access to some
27052 directories.
27053
27054 @node Mixed-Language Programming on Windows
27055 @section Mixed-Language Programming on Windows
27056
27057 @noindent
27058 Developing pure Ada applications on Windows is no different than on
27059 other GNAT-supported platforms. However, when developing or porting an
27060 application that contains a mix of Ada and C/C++, the choice of your
27061 Windows C/C++ development environment conditions your overall
27062 interoperability strategy.
27063
27064 If you use @command{gcc} to compile the non-Ada part of your application,
27065 there are no Windows-specific restrictions that affect the overall
27066 interoperability with your Ada code. If you do want to use the
27067 Microsoft tools for your non-Ada code, you have two choices:
27068
27069 @enumerate
27070 @item
27071 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27072 application. In this case, use the Microsoft or whatever environment to
27073 build the DLL and use GNAT to build your executable
27074 (@pxref{Using DLLs with GNAT}).
27075
27076 @item
27077 Or you can encapsulate your Ada code in a DLL to be linked with the
27078 other part of your application. In this case, use GNAT to build the DLL
27079 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27080 or whatever environment to build your executable.
27081 @end enumerate
27082
27083 @node Windows Calling Conventions
27084 @section Windows Calling Conventions
27085 @findex Stdcall
27086 @findex APIENTRY
27087
27088 This section pertain only to Win32. On Win64 there is a single native
27089 calling convention. All convention specifiers are ignored on this
27090 platform.
27091
27092 @menu
27093 * C Calling Convention::
27094 * Stdcall Calling Convention::
27095 * Win32 Calling Convention::
27096 * DLL Calling Convention::
27097 @end menu
27098
27099 @noindent
27100 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27101 (callee), there are several ways to push @code{G}'s parameters on the
27102 stack and there are several possible scenarios to clean up the stack
27103 upon @code{G}'s return. A calling convention is an agreed upon software
27104 protocol whereby the responsibilities between the caller (@code{F}) and
27105 the callee (@code{G}) are clearly defined. Several calling conventions
27106 are available for Windows:
27107
27108 @itemize @bullet
27109 @item
27110 @code{C} (Microsoft defined)
27111
27112 @item
27113 @code{Stdcall} (Microsoft defined)
27114
27115 @item
27116 @code{Win32} (GNAT specific)
27117
27118 @item
27119 @code{DLL} (GNAT specific)
27120 @end itemize
27121
27122 @node C Calling Convention
27123 @subsection @code{C} Calling Convention
27124
27125 @noindent
27126 This is the default calling convention used when interfacing to C/C++
27127 routines compiled with either @command{gcc} or Microsoft Visual C++.
27128
27129 In the @code{C} calling convention subprogram parameters are pushed on the
27130 stack by the caller from right to left. The caller itself is in charge of
27131 cleaning up the stack after the call. In addition, the name of a routine
27132 with @code{C} calling convention is mangled by adding a leading underscore.
27133
27134 The name to use on the Ada side when importing (or exporting) a routine
27135 with @code{C} calling convention is the name of the routine. For
27136 instance the C function:
27137
27138 @smallexample
27139 int get_val (long);
27140 @end smallexample
27141
27142 @noindent
27143 should be imported from Ada as follows:
27144
27145 @smallexample @c ada
27146 @group
27147 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27148 pragma Import (C, Get_Val, External_Name => "get_val");
27149 @end group
27150 @end smallexample
27151
27152 @noindent
27153 Note that in this particular case the @code{External_Name} parameter could
27154 have been omitted since, when missing, this parameter is taken to be the
27155 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27156 is missing, as in the above example, this parameter is set to be the
27157 @code{External_Name} with a leading underscore.
27158
27159 When importing a variable defined in C, you should always use the @code{C}
27160 calling convention unless the object containing the variable is part of a
27161 DLL (in which case you should use the @code{Stdcall} calling
27162 convention, @pxref{Stdcall Calling Convention}).
27163
27164 @node Stdcall Calling Convention
27165 @subsection @code{Stdcall} Calling Convention
27166
27167 @noindent
27168 This convention, which was the calling convention used for Pascal
27169 programs, is used by Microsoft for all the routines in the Win32 API for
27170 efficiency reasons. It must be used to import any routine for which this
27171 convention was specified.
27172
27173 In the @code{Stdcall} calling convention subprogram parameters are pushed
27174 on the stack by the caller from right to left. The callee (and not the
27175 caller) is in charge of cleaning the stack on routine exit. In addition,
27176 the name of a routine with @code{Stdcall} calling convention is mangled by
27177 adding a leading underscore (as for the @code{C} calling convention) and a
27178 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27179 bytes) of the parameters passed to the routine.
27180
27181 The name to use on the Ada side when importing a C routine with a
27182 @code{Stdcall} calling convention is the name of the C routine. The leading
27183 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27184 the compiler. For instance the Win32 function:
27185
27186 @smallexample
27187 @b{APIENTRY} int get_val (long);
27188 @end smallexample
27189
27190 @noindent
27191 should be imported from Ada as follows:
27192
27193 @smallexample @c ada
27194 @group
27195 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27196 pragma Import (Stdcall, Get_Val);
27197 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27198 @end group
27199 @end smallexample
27200
27201 @noindent
27202 As for the @code{C} calling convention, when the @code{External_Name}
27203 parameter is missing, it is taken to be the name of the Ada entity in lower
27204 case. If instead of writing the above import pragma you write:
27205
27206 @smallexample @c ada
27207 @group
27208 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27209 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27210 @end group
27211 @end smallexample
27212
27213 @noindent
27214 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27215 of specifying the @code{External_Name} parameter you specify the
27216 @code{Link_Name} as in the following example:
27217
27218 @smallexample @c ada
27219 @group
27220 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27221 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27222 @end group
27223 @end smallexample
27224
27225 @noindent
27226 then the imported routine is @code{retrieve_val}, that is, there is no
27227 decoration at all. No leading underscore and no Stdcall suffix
27228 @code{@@}@code{@var{nn}}.
27229
27230 @noindent
27231 This is especially important as in some special cases a DLL's entry
27232 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27233 name generated for a call has it.
27234
27235 @noindent
27236 It is also possible to import variables defined in a DLL by using an
27237 import pragma for a variable. As an example, if a DLL contains a
27238 variable defined as:
27239
27240 @smallexample
27241 int my_var;
27242 @end smallexample
27243
27244 @noindent
27245 then, to access this variable from Ada you should write:
27246
27247 @smallexample @c ada
27248 @group
27249 My_Var : Interfaces.C.int;
27250 pragma Import (Stdcall, My_Var);
27251 @end group
27252 @end smallexample
27253
27254 @noindent
27255 Note that to ease building cross-platform bindings this convention
27256 will be handled as a @code{C} calling convention on non-Windows platforms.
27257
27258 @node Win32 Calling Convention
27259 @subsection @code{Win32} Calling Convention
27260
27261 @noindent
27262 This convention, which is GNAT-specific is fully equivalent to the
27263 @code{Stdcall} calling convention described above.
27264
27265 @node DLL Calling Convention
27266 @subsection @code{DLL} Calling Convention
27267
27268 @noindent
27269 This convention, which is GNAT-specific is fully equivalent to the
27270 @code{Stdcall} calling convention described above.
27271
27272 @node Introduction to Dynamic Link Libraries (DLLs)
27273 @section Introduction to Dynamic Link Libraries (DLLs)
27274 @findex DLL
27275
27276 @noindent
27277 A Dynamically Linked Library (DLL) is a library that can be shared by
27278 several applications running under Windows. A DLL can contain any number of
27279 routines and variables.
27280
27281 One advantage of DLLs is that you can change and enhance them without
27282 forcing all the applications that depend on them to be relinked or
27283 recompiled. However, you should be aware than all calls to DLL routines are
27284 slower since, as you will understand below, such calls are indirect.
27285
27286 To illustrate the remainder of this section, suppose that an application
27287 wants to use the services of a DLL @file{API.dll}. To use the services
27288 provided by @file{API.dll} you must statically link against the DLL or
27289 an import library which contains a jump table with an entry for each
27290 routine and variable exported by the DLL. In the Microsoft world this
27291 import library is called @file{API.lib}. When using GNAT this import
27292 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27293 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27294
27295 After you have linked your application with the DLL or the import library
27296 and you run your application, here is what happens:
27297
27298 @enumerate
27299 @item
27300 Your application is loaded into memory.
27301
27302 @item
27303 The DLL @file{API.dll} is mapped into the address space of your
27304 application. This means that:
27305
27306 @itemize @bullet
27307 @item
27308 The DLL will use the stack of the calling thread.
27309
27310 @item
27311 The DLL will use the virtual address space of the calling process.
27312
27313 @item
27314 The DLL will allocate memory from the virtual address space of the calling
27315 process.
27316
27317 @item
27318 Handles (pointers) can be safely exchanged between routines in the DLL
27319 routines and routines in the application using the DLL.
27320 @end itemize
27321
27322 @item
27323 The entries in the jump table (from the import library @file{libAPI.dll.a}
27324 or @file{API.lib} or automatically created when linking against a DLL)
27325 which is part of your application are initialized with the addresses
27326 of the routines and variables in @file{API.dll}.
27327
27328 @item
27329 If present in @file{API.dll}, routines @code{DllMain} or
27330 @code{DllMainCRTStartup} are invoked. These routines typically contain
27331 the initialization code needed for the well-being of the routines and
27332 variables exported by the DLL.
27333 @end enumerate
27334
27335 @noindent
27336 There is an additional point which is worth mentioning. In the Windows
27337 world there are two kind of DLLs: relocatable and non-relocatable
27338 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27339 in the target application address space. If the addresses of two
27340 non-relocatable DLLs overlap and these happen to be used by the same
27341 application, a conflict will occur and the application will run
27342 incorrectly. Hence, when possible, it is always preferable to use and
27343 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27344 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27345 User's Guide) removes the debugging symbols from the DLL but the DLL can
27346 still be relocated.
27347
27348 As a side note, an interesting difference between Microsoft DLLs and
27349 Unix shared libraries, is the fact that on most Unix systems all public
27350 routines are exported by default in a Unix shared library, while under
27351 Windows it is possible (but not required) to list exported routines in
27352 a definition file (@pxref{The Definition File}).
27353
27354 @node Using DLLs with GNAT
27355 @section Using DLLs with GNAT
27356
27357 @menu
27358 * Creating an Ada Spec for the DLL Services::
27359 * Creating an Import Library::
27360 @end menu
27361
27362 @noindent
27363 To use the services of a DLL, say @file{API.dll}, in your Ada application
27364 you must have:
27365
27366 @enumerate
27367 @item
27368 The Ada spec for the routines and/or variables you want to access in
27369 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27370 header files provided with the DLL.
27371
27372 @item
27373 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27374 mentioned an import library is a statically linked library containing the
27375 import table which will be filled at load time to point to the actual
27376 @file{API.dll} routines. Sometimes you don't have an import library for the
27377 DLL you want to use. The following sections will explain how to build
27378 one. Note that this is optional.
27379
27380 @item
27381 The actual DLL, @file{API.dll}.
27382 @end enumerate
27383
27384 @noindent
27385 Once you have all the above, to compile an Ada application that uses the
27386 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27387 you simply issue the command
27388
27389 @smallexample
27390 $ gnatmake my_ada_app -largs -lAPI
27391 @end smallexample
27392
27393 @noindent
27394 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27395 tells the GNAT linker to look for an import library. The linker will
27396 look for a library name in this specific order:
27397
27398 @enumerate
27399 @item @file{libAPI.dll.a}
27400 @item @file{API.dll.a}
27401 @item @file{libAPI.a}
27402 @item @file{API.lib}
27403 @item @file{libAPI.dll}
27404 @item @file{API.dll}
27405 @end enumerate
27406
27407 The first three are the GNU style import libraries. The third is the
27408 Microsoft style import libraries. The last two are the DLL themself.
27409
27410 Note that if the Ada package spec for @file{API.dll} contains the
27411 following pragma
27412
27413 @smallexample @c ada
27414 pragma Linker_Options ("-lAPI");
27415 @end smallexample
27416
27417 @noindent
27418 you do not have to add @option{-largs -lAPI} at the end of the
27419 @command{gnatmake} command.
27420
27421 If any one of the items above is missing you will have to create it
27422 yourself. The following sections explain how to do so using as an
27423 example a fictitious DLL called @file{API.dll}.
27424
27425 @node Creating an Ada Spec for the DLL Services
27426 @subsection Creating an Ada Spec for the DLL Services
27427
27428 @noindent
27429 A DLL typically comes with a C/C++ header file which provides the
27430 definitions of the routines and variables exported by the DLL. The Ada
27431 equivalent of this header file is a package spec that contains definitions
27432 for the imported entities. If the DLL you intend to use does not come with
27433 an Ada spec you have to generate one such spec yourself. For example if
27434 the header file of @file{API.dll} is a file @file{api.h} containing the
27435 following two definitions:
27436
27437 @smallexample
27438 @group
27439 @cartouche
27440 int some_var;
27441 int get (char *);
27442 @end cartouche
27443 @end group
27444 @end smallexample
27445
27446 @noindent
27447 then the equivalent Ada spec could be:
27448
27449 @smallexample @c ada
27450 @group
27451 @cartouche
27452 with Interfaces.C.Strings;
27453 package API is
27454    use Interfaces;
27455
27456    Some_Var : C.int;
27457    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27458
27459 private
27460    pragma Import (C, Get);
27461    pragma Import (DLL, Some_Var);
27462 end API;
27463 @end cartouche
27464 @end group
27465 @end smallexample
27466
27467 @noindent
27468 Note that a variable is
27469 @strong{always imported with a DLL convention}. A function
27470 can have @code{C} or @code{Stdcall} convention.
27471 (@pxref{Windows Calling Conventions}).
27472
27473 @node Creating an Import Library
27474 @subsection Creating an Import Library
27475 @cindex Import library
27476
27477 @menu
27478 * The Definition File::
27479 * GNAT-Style Import Library::
27480 * Microsoft-Style Import Library::
27481 @end menu
27482
27483 @noindent
27484 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27485 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27486 with @file{API.dll} you can skip this section. You can also skip this
27487 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27488 as in this case it is possible to link directly against the
27489 DLL. Otherwise read on.
27490
27491 @node The Definition File
27492 @subsubsection The Definition File
27493 @cindex Definition file
27494 @findex .def
27495
27496 @noindent
27497 As previously mentioned, and unlike Unix systems, the list of symbols
27498 that are exported from a DLL must be provided explicitly in Windows.
27499 The main goal of a definition file is precisely that: list the symbols
27500 exported by a DLL. A definition file (usually a file with a @code{.def}
27501 suffix) has the following structure:
27502
27503 @smallexample
27504 @group
27505 @cartouche
27506 @r{[}LIBRARY @var{name}@r{]}
27507 @r{[}DESCRIPTION @var{string}@r{]}
27508 EXPORTS
27509    @var{symbol1}
27510    @var{symbol2}
27511    @dots{}
27512 @end cartouche
27513 @end group
27514 @end smallexample
27515
27516 @table @code
27517 @item LIBRARY @var{name}
27518 This section, which is optional, gives the name of the DLL.
27519
27520 @item DESCRIPTION @var{string}
27521 This section, which is optional, gives a description string that will be
27522 embedded in the import library.
27523
27524 @item EXPORTS
27525 This section gives the list of exported symbols (procedures, functions or
27526 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27527 section of @file{API.def} looks like:
27528
27529 @smallexample
27530 @group
27531 @cartouche
27532 EXPORTS
27533    some_var
27534    get
27535 @end cartouche
27536 @end group
27537 @end smallexample
27538 @end table
27539
27540 @noindent
27541 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27542 (@pxref{Windows Calling Conventions}) for a Stdcall
27543 calling convention function in the exported symbols list.
27544
27545 @noindent
27546 There can actually be other sections in a definition file, but these
27547 sections are not relevant to the discussion at hand.
27548
27549 @node GNAT-Style Import Library
27550 @subsubsection GNAT-Style Import Library
27551
27552 @noindent
27553 To create a static import library from @file{API.dll} with the GNAT tools
27554 you should proceed as follows:
27555
27556 @enumerate
27557 @item
27558 Create the definition file @file{API.def} (@pxref{The Definition File}).
27559 For that use the @code{dll2def} tool as follows:
27560
27561 @smallexample
27562 $ dll2def API.dll > API.def
27563 @end smallexample
27564
27565 @noindent
27566 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27567 to standard output the list of entry points in the DLL. Note that if
27568 some routines in the DLL have the @code{Stdcall} convention
27569 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27570 suffix then you'll have to edit @file{api.def} to add it, and specify
27571 @option{-k} to @command{gnatdll} when creating the import library.
27572
27573 @noindent
27574 Here are some hints to find the right @code{@@}@var{nn} suffix.
27575
27576 @enumerate
27577 @item
27578 If you have the Microsoft import library (.lib), it is possible to get
27579 the right symbols by using Microsoft @code{dumpbin} tool (see the
27580 corresponding Microsoft documentation for further details).
27581
27582 @smallexample
27583 $ dumpbin /exports api.lib
27584 @end smallexample
27585
27586 @item
27587 If you have a message about a missing symbol at link time the compiler
27588 tells you what symbol is expected. You just have to go back to the
27589 definition file and add the right suffix.
27590 @end enumerate
27591
27592 @item
27593 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27594 (@pxref{Using gnatdll}) as follows:
27595
27596 @smallexample
27597 $ gnatdll -e API.def -d API.dll
27598 @end smallexample
27599
27600 @noindent
27601 @code{gnatdll} takes as input a definition file @file{API.def} and the
27602 name of the DLL containing the services listed in the definition file
27603 @file{API.dll}. The name of the static import library generated is
27604 computed from the name of the definition file as follows: if the
27605 definition file name is @var{xyz}@code{.def}, the import library name will
27606 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27607 @option{-e} could have been removed because the name of the definition
27608 file (before the ``@code{.def}'' suffix) is the same as the name of the
27609 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27610 @end enumerate
27611
27612 @node Microsoft-Style Import Library
27613 @subsubsection Microsoft-Style Import Library
27614
27615 @noindent
27616 With GNAT you can either use a GNAT-style or Microsoft-style import
27617 library. A Microsoft import library is needed only if you plan to make an
27618 Ada DLL available to applications developed with Microsoft
27619 tools (@pxref{Mixed-Language Programming on Windows}).
27620
27621 To create a Microsoft-style import library for @file{API.dll} you
27622 should proceed as follows:
27623
27624 @enumerate
27625 @item
27626 Create the definition file @file{API.def} from the DLL. For this use either
27627 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27628 tool (see the corresponding Microsoft documentation for further details).
27629
27630 @item
27631 Build the actual import library using Microsoft's @code{lib} utility:
27632
27633 @smallexample
27634 $ lib -machine:IX86 -def:API.def -out:API.lib
27635 @end smallexample
27636
27637 @noindent
27638 If you use the above command the definition file @file{API.def} must
27639 contain a line giving the name of the DLL:
27640
27641 @smallexample
27642 LIBRARY      "API"
27643 @end smallexample
27644
27645 @noindent
27646 See the Microsoft documentation for further details about the usage of
27647 @code{lib}.
27648 @end enumerate
27649
27650 @node Building DLLs with GNAT Project files
27651 @section Building DLLs with GNAT Project files
27652 @cindex DLLs, building
27653
27654 @noindent
27655 There is nothing specific to Windows in the build process.
27656 @pxref{Library Projects}.
27657
27658 @noindent
27659 Due to a system limitation, it is not possible under Windows to create threads
27660 when inside the @code{DllMain} routine which is used for auto-initialization
27661 of shared libraries, so it is not possible to have library level tasks in SALs.
27662
27663 @node Building DLLs with GNAT
27664 @section Building DLLs with GNAT
27665 @cindex DLLs, building
27666
27667 @noindent
27668 This section explain how to build DLLs using the GNAT built-in DLL
27669 support. With the following procedure it is straight forward to build
27670 and use DLLs with GNAT.
27671
27672 @enumerate
27673
27674 @item building object files
27675
27676 The first step is to build all objects files that are to be included
27677 into the DLL. This is done by using the standard @command{gnatmake} tool.
27678
27679 @item building the DLL
27680
27681 To build the DLL you must use @command{gcc}'s @option{-shared}
27682 option. It is quite simple to use this method:
27683
27684 @smallexample
27685 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
27686 @end smallexample
27687
27688 It is important to note that in this case all symbols found in the
27689 object files are automatically exported. It is possible to restrict
27690 the set of symbols to export by passing to @command{gcc} a definition
27691 file, @pxref{The Definition File}. For example:
27692
27693 @smallexample
27694 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
27695 @end smallexample
27696
27697 If you use a definition file you must export the elaboration procedures
27698 for every package that required one. Elaboration procedures are named
27699 using the package name followed by "_E".
27700
27701 @item preparing DLL to be used
27702
27703 For the DLL to be used by client programs the bodies must be hidden
27704 from it and the .ali set with read-only attribute. This is very important
27705 otherwise GNAT will recompile all packages and will not actually use
27706 the code in the DLL. For example:
27707
27708 @smallexample
27709 $ mkdir apilib
27710 $ copy *.ads *.ali api.dll apilib
27711 $ attrib +R apilib\*.ali
27712 @end smallexample
27713
27714 @end enumerate
27715
27716 At this point it is possible to use the DLL by directly linking
27717 against it. Note that you must use the GNAT shared runtime when using
27718 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27719 option.
27720
27721 @smallexample
27722 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27723 @end smallexample
27724
27725 @node Building DLLs with gnatdll
27726 @section Building DLLs with gnatdll
27727 @cindex DLLs, building
27728
27729 @menu
27730 * Limitations When Using Ada DLLs from Ada::
27731 * Exporting Ada Entities::
27732 * Ada DLLs and Elaboration::
27733 * Ada DLLs and Finalization::
27734 * Creating a Spec for Ada DLLs::
27735 * Creating the Definition File::
27736 * Using gnatdll::
27737 @end menu
27738
27739 @noindent
27740 Note that it is preferred to use GNAT Project files
27741 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27742 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27743
27744 This section explains how to build DLLs containing Ada code using
27745 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27746 remainder of this section.
27747
27748 The steps required to build an Ada DLL that is to be used by Ada as well as
27749 non-Ada applications are as follows:
27750
27751 @enumerate
27752 @item
27753 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27754 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27755 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27756 skip this step if you plan to use the Ada DLL only from Ada applications.
27757
27758 @item
27759 Your Ada code must export an initialization routine which calls the routine
27760 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27761 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27762 routine exported by the Ada DLL must be invoked by the clients of the DLL
27763 to initialize the DLL.
27764
27765 @item
27766 When useful, the DLL should also export a finalization routine which calls
27767 routine @code{adafinal} generated by @command{gnatbind} to perform the
27768 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27769 The finalization routine exported by the Ada DLL must be invoked by the
27770 clients of the DLL when the DLL services are no further needed.
27771
27772 @item
27773 You must provide a spec for the services exported by the Ada DLL in each
27774 of the programming languages to which you plan to make the DLL available.
27775
27776 @item
27777 You must provide a definition file listing the exported entities
27778 (@pxref{The Definition File}).
27779
27780 @item
27781 Finally you must use @code{gnatdll} to produce the DLL and the import
27782 library (@pxref{Using gnatdll}).
27783 @end enumerate
27784
27785 @noindent
27786 Note that a relocatable DLL stripped using the @code{strip}
27787 binutils tool will not be relocatable anymore. To build a DLL without
27788 debug information pass @code{-largs -s} to @code{gnatdll}. This
27789 restriction does not apply to a DLL built using a Library Project.
27790 @pxref{Library Projects}.
27791
27792 @node Limitations When Using Ada DLLs from Ada
27793 @subsection Limitations When Using Ada DLLs from Ada
27794
27795 @noindent
27796 When using Ada DLLs from Ada applications there is a limitation users
27797 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27798 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27799 each Ada DLL includes the services of the GNAT run time that are necessary
27800 to the Ada code inside the DLL. As a result, when an Ada program uses an
27801 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27802 one in the main program.
27803
27804 It is therefore not possible to exchange GNAT run-time objects between the
27805 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27806 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27807 types, etc.
27808
27809 It is completely safe to exchange plain elementary, array or record types,
27810 Windows object handles, etc.
27811
27812 @node Exporting Ada Entities
27813 @subsection Exporting Ada Entities
27814 @cindex Export table
27815
27816 @noindent
27817 Building a DLL is a way to encapsulate a set of services usable from any
27818 application. As a result, the Ada entities exported by a DLL should be
27819 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27820 any Ada name mangling. As an example here is an Ada package
27821 @code{API}, spec and body, exporting two procedures, a function, and a
27822 variable:
27823
27824 @smallexample @c ada
27825 @group
27826 @cartouche
27827 with Interfaces.C; use Interfaces;
27828 package API is
27829    Count : C.int := 0;
27830    function Factorial (Val : C.int) return C.int;
27831
27832    procedure Initialize_API;
27833    procedure Finalize_API;
27834    --  Initialization & Finalization routines. More in the next section.
27835 private
27836    pragma Export (C, Initialize_API);
27837    pragma Export (C, Finalize_API);
27838    pragma Export (C, Count);
27839    pragma Export (C, Factorial);
27840 end API;
27841 @end cartouche
27842 @end group
27843 @end smallexample
27844
27845 @smallexample @c ada
27846 @group
27847 @cartouche
27848 package body API is
27849    function Factorial (Val : C.int) return C.int is
27850       Fact : C.int := 1;
27851    begin
27852       Count := Count + 1;
27853       for K in 1 .. Val loop
27854          Fact := Fact * K;
27855       end loop;
27856       return Fact;
27857    end Factorial;
27858
27859    procedure Initialize_API is
27860       procedure Adainit;
27861       pragma Import (C, Adainit);
27862    begin
27863       Adainit;
27864    end Initialize_API;
27865
27866    procedure Finalize_API is
27867       procedure Adafinal;
27868       pragma Import (C, Adafinal);
27869    begin
27870       Adafinal;
27871    end Finalize_API;
27872 end API;
27873 @end cartouche
27874 @end group
27875 @end smallexample
27876
27877 @noindent
27878 If the Ada DLL you are building will only be used by Ada applications
27879 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27880 convention. As an example, the previous package could be written as
27881 follows:
27882
27883 @smallexample @c ada
27884 @group
27885 @cartouche
27886 package API is
27887    Count : Integer := 0;
27888    function Factorial (Val : Integer) return Integer;
27889
27890    procedure Initialize_API;
27891    procedure Finalize_API;
27892    --  Initialization and Finalization routines.
27893 end API;
27894 @end cartouche
27895 @end group
27896 @end smallexample
27897
27898 @smallexample @c ada
27899 @group
27900 @cartouche
27901 package body API is
27902    function Factorial (Val : Integer) return Integer is
27903       Fact : Integer := 1;
27904    begin
27905       Count := Count + 1;
27906       for K in 1 .. Val loop
27907          Fact := Fact * K;
27908       end loop;
27909       return Fact;
27910    end Factorial;
27911
27912    @dots{}
27913    --  The remainder of this package body is unchanged.
27914 end API;
27915 @end cartouche
27916 @end group
27917 @end smallexample
27918
27919 @noindent
27920 Note that if you do not export the Ada entities with a @code{C} or
27921 @code{Stdcall} convention you will have to provide the mangled Ada names
27922 in the definition file of the Ada DLL
27923 (@pxref{Creating the Definition File}).
27924
27925 @node Ada DLLs and Elaboration
27926 @subsection Ada DLLs and Elaboration
27927 @cindex DLLs and elaboration
27928
27929 @noindent
27930 The DLL that you are building contains your Ada code as well as all the
27931 routines in the Ada library that are needed by it. The first thing a
27932 user of your DLL must do is elaborate the Ada code
27933 (@pxref{Elaboration Order Handling in GNAT}).
27934
27935 To achieve this you must export an initialization routine
27936 (@code{Initialize_API} in the previous example), which must be invoked
27937 before using any of the DLL services. This elaboration routine must call
27938 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27939 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27940 @code{Initialize_Api} for an example. Note that the GNAT binder is
27941 automatically invoked during the DLL build process by the @code{gnatdll}
27942 tool (@pxref{Using gnatdll}).
27943
27944 When a DLL is loaded, Windows systematically invokes a routine called
27945 @code{DllMain}. It would therefore be possible to call @code{adainit}
27946 directly from @code{DllMain} without having to provide an explicit
27947 initialization routine. Unfortunately, it is not possible to call
27948 @code{adainit} from the @code{DllMain} if your program has library level
27949 tasks because access to the @code{DllMain} entry point is serialized by
27950 the system (that is, only a single thread can execute ``through'' it at a
27951 time), which means that the GNAT run time will deadlock waiting for the
27952 newly created task to complete its initialization.
27953
27954 @node Ada DLLs and Finalization
27955 @subsection Ada DLLs and Finalization
27956 @cindex DLLs and finalization
27957
27958 @noindent
27959 When the services of an Ada DLL are no longer needed, the client code should
27960 invoke the DLL finalization routine, if available. The DLL finalization
27961 routine is in charge of releasing all resources acquired by the DLL. In the
27962 case of the Ada code contained in the DLL, this is achieved by calling
27963 routine @code{adafinal} generated by the GNAT binder
27964 (@pxref{Binding with Non-Ada Main Programs}).
27965 See the body of @code{Finalize_Api} for an
27966 example. As already pointed out the GNAT binder is automatically invoked
27967 during the DLL build process by the @code{gnatdll} tool
27968 (@pxref{Using gnatdll}).
27969
27970 @node Creating a Spec for Ada DLLs
27971 @subsection Creating a Spec for Ada DLLs
27972
27973 @noindent
27974 To use the services exported by the Ada DLL from another programming
27975 language (e.g.@: C), you have to translate the specs of the exported Ada
27976 entities in that language. For instance in the case of @code{API.dll},
27977 the corresponding C header file could look like:
27978
27979 @smallexample
27980 @group
27981 @cartouche
27982 extern int *_imp__count;
27983 #define count (*_imp__count)
27984 int factorial (int);
27985 @end cartouche
27986 @end group
27987 @end smallexample
27988
27989 @noindent
27990 It is important to understand that when building an Ada DLL to be used by
27991 other Ada applications, you need two different specs for the packages
27992 contained in the DLL: one for building the DLL and the other for using
27993 the DLL. This is because the @code{DLL} calling convention is needed to
27994 use a variable defined in a DLL, but when building the DLL, the variable
27995 must have either the @code{Ada} or @code{C} calling convention. As an
27996 example consider a DLL comprising the following package @code{API}:
27997
27998 @smallexample @c ada
27999 @group
28000 @cartouche
28001 package API is
28002    Count : Integer := 0;
28003    @dots{}
28004    --  Remainder of the package omitted.
28005 end API;
28006 @end cartouche
28007 @end group
28008 @end smallexample
28009
28010 @noindent
28011 After producing a DLL containing package @code{API}, the spec that
28012 must be used to import @code{API.Count} from Ada code outside of the
28013 DLL is:
28014
28015 @smallexample @c ada
28016 @group
28017 @cartouche
28018 package API is
28019    Count : Integer;
28020    pragma Import (DLL, Count);
28021 end API;
28022 @end cartouche
28023 @end group
28024 @end smallexample
28025
28026 @node Creating the Definition File
28027 @subsection Creating the Definition File
28028
28029 @noindent
28030 The definition file is the last file needed to build the DLL. It lists
28031 the exported symbols. As an example, the definition file for a DLL
28032 containing only package @code{API} (where all the entities are exported
28033 with a @code{C} calling convention) is:
28034
28035 @smallexample
28036 @group
28037 @cartouche
28038 EXPORTS
28039     count
28040     factorial
28041     finalize_api
28042     initialize_api
28043 @end cartouche
28044 @end group
28045 @end smallexample
28046
28047 @noindent
28048 If the @code{C} calling convention is missing from package @code{API},
28049 then the definition file contains the mangled Ada names of the above
28050 entities, which in this case are:
28051
28052 @smallexample
28053 @group
28054 @cartouche
28055 EXPORTS
28056     api__count
28057     api__factorial
28058     api__finalize_api
28059     api__initialize_api
28060 @end cartouche
28061 @end group
28062 @end smallexample
28063
28064 @node Using gnatdll
28065 @subsection Using @code{gnatdll}
28066 @findex gnatdll
28067
28068 @menu
28069 * gnatdll Example::
28070 * gnatdll behind the Scenes::
28071 * Using dlltool::
28072 @end menu
28073
28074 @noindent
28075 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28076 and non-Ada sources that make up your DLL have been compiled.
28077 @code{gnatdll} is actually in charge of two distinct tasks: build the
28078 static import library for the DLL and the actual DLL. The form of the
28079 @code{gnatdll} command is
28080
28081 @smallexample
28082 @cartouche
28083 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28084 @c Expanding @ovar macro inline (explanation in macro def comments)
28085 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28086 @end cartouche
28087 @end smallexample
28088
28089 @noindent
28090 where @var{list-of-files} is a list of ALI and object files. The object
28091 file list must be the exact list of objects corresponding to the non-Ada
28092 sources whose services are to be included in the DLL. The ALI file list
28093 must be the exact list of ALI files for the corresponding Ada sources
28094 whose services are to be included in the DLL. If @var{list-of-files} is
28095 missing, only the static import library is generated.
28096
28097 @noindent
28098 You may specify any of the following switches to @code{gnatdll}:
28099
28100 @table @code
28101 @c @item -a@ovar{address}
28102 @c Expanding @ovar macro inline (explanation in macro def comments)
28103 @item -a@r{[}@var{address}@r{]}
28104 @cindex @option{-a} (@code{gnatdll})
28105 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28106 specified the default address @var{0x11000000} will be used. By default,
28107 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28108 advise the reader to build relocatable DLL.
28109
28110 @item -b @var{address}
28111 @cindex @option{-b} (@code{gnatdll})
28112 Set the relocatable DLL base address. By default the address is
28113 @code{0x11000000}.
28114
28115 @item -bargs @var{opts}
28116 @cindex @option{-bargs} (@code{gnatdll})
28117 Binder options. Pass @var{opts} to the binder.
28118
28119 @item -d @var{dllfile}
28120 @cindex @option{-d} (@code{gnatdll})
28121 @var{dllfile} is the name of the DLL. This switch must be present for
28122 @code{gnatdll} to do anything. The name of the generated import library is
28123 obtained algorithmically from @var{dllfile} as shown in the following
28124 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28125 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28126 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28127 as shown in the following example:
28128 if @var{dllfile} is @code{xyz.dll}, the definition
28129 file used is @code{xyz.def}.
28130
28131 @item -e @var{deffile}
28132 @cindex @option{-e} (@code{gnatdll})
28133 @var{deffile} is the name of the definition file.
28134
28135 @item -g
28136 @cindex @option{-g} (@code{gnatdll})
28137 Generate debugging information. This information is stored in the object
28138 file and copied from there to the final DLL file by the linker,
28139 where it can be read by the debugger. You must use the
28140 @option{-g} switch if you plan on using the debugger or the symbolic
28141 stack traceback.
28142
28143 @item -h
28144 @cindex @option{-h} (@code{gnatdll})
28145 Help mode. Displays @code{gnatdll} switch usage information.
28146
28147 @item -Idir
28148 @cindex @option{-I} (@code{gnatdll})
28149 Direct @code{gnatdll} to search the @var{dir} directory for source and
28150 object files needed to build the DLL.
28151 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28152
28153 @item -k
28154 @cindex @option{-k} (@code{gnatdll})
28155 Removes the @code{@@}@var{nn} suffix from the import library's exported
28156 names, but keeps them for the link names. You must specify this
28157 option if you want to use a @code{Stdcall} function in a DLL for which
28158 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28159 of the Windows NT DLL for example. This option has no effect when
28160 @option{-n} option is specified.
28161
28162 @item -l @var{file}
28163 @cindex @option{-l} (@code{gnatdll})
28164 The list of ALI and object files used to build the DLL are listed in
28165 @var{file}, instead of being given in the command line. Each line in
28166 @var{file} contains the name of an ALI or object file.
28167
28168 @item -n
28169 @cindex @option{-n} (@code{gnatdll})
28170 No Import. Do not create the import library.
28171
28172 @item -q
28173 @cindex @option{-q} (@code{gnatdll})
28174 Quiet mode. Do not display unnecessary messages.
28175
28176 @item -v
28177 @cindex @option{-v} (@code{gnatdll})
28178 Verbose mode. Display extra information.
28179
28180 @item -largs @var{opts}
28181 @cindex @option{-largs} (@code{gnatdll})
28182 Linker options. Pass @var{opts} to the linker.
28183 @end table
28184
28185 @node gnatdll Example
28186 @subsubsection @code{gnatdll} Example
28187
28188 @noindent
28189 As an example the command to build a relocatable DLL from @file{api.adb}
28190 once @file{api.adb} has been compiled and @file{api.def} created is
28191
28192 @smallexample
28193 $ gnatdll -d api.dll api.ali
28194 @end smallexample
28195
28196 @noindent
28197 The above command creates two files: @file{libapi.dll.a} (the import
28198 library) and @file{api.dll} (the actual DLL). If you want to create
28199 only the DLL, just type:
28200
28201 @smallexample
28202 $ gnatdll -d api.dll -n api.ali
28203 @end smallexample
28204
28205 @noindent
28206 Alternatively if you want to create just the import library, type:
28207
28208 @smallexample
28209 $ gnatdll -d api.dll
28210 @end smallexample
28211
28212 @node gnatdll behind the Scenes
28213 @subsubsection @code{gnatdll} behind the Scenes
28214
28215 @noindent
28216 This section details the steps involved in creating a DLL. @code{gnatdll}
28217 does these steps for you. Unless you are interested in understanding what
28218 goes on behind the scenes, you should skip this section.
28219
28220 We use the previous example of a DLL containing the Ada package @code{API},
28221 to illustrate the steps necessary to build a DLL. The starting point is a
28222 set of objects that will make up the DLL and the corresponding ALI
28223 files. In the case of this example this means that @file{api.o} and
28224 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28225 the following:
28226
28227 @enumerate
28228 @item
28229 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28230 the information necessary to generate relocation information for the
28231 DLL.
28232
28233 @smallexample
28234 @group
28235 $ gnatbind -n api
28236 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28237 @end group
28238 @end smallexample
28239
28240 @noindent
28241 In addition to the base file, the @command{gnatlink} command generates an
28242 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28243 asks @command{gnatlink} to generate the routines @code{DllMain} and
28244 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28245 is loaded into memory.
28246
28247 @item
28248 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28249 export table (@file{api.exp}). The export table contains the relocation
28250 information in a form which can be used during the final link to ensure
28251 that the Windows loader is able to place the DLL anywhere in memory.
28252
28253 @smallexample
28254 @group
28255 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28256           --output-exp api.exp
28257 @end group
28258 @end smallexample
28259
28260 @item
28261 @code{gnatdll} builds the base file using the new export table. Note that
28262 @command{gnatbind} must be called once again since the binder generated file
28263 has been deleted during the previous call to @command{gnatlink}.
28264
28265 @smallexample
28266 @group
28267 $ gnatbind -n api
28268 $ gnatlink api -o api.jnk api.exp -mdll
28269       -Wl,--base-file,api.base
28270 @end group
28271 @end smallexample
28272
28273 @item
28274 @code{gnatdll} builds the new export table using the new base file and
28275 generates the DLL import library @file{libAPI.dll.a}.
28276
28277 @smallexample
28278 @group
28279 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28280           --output-exp api.exp --output-lib libAPI.a
28281 @end group
28282 @end smallexample
28283
28284 @item
28285 Finally @code{gnatdll} builds the relocatable DLL using the final export
28286 table.
28287
28288 @smallexample
28289 @group
28290 $ gnatbind -n api
28291 $ gnatlink api api.exp -o api.dll -mdll
28292 @end group
28293 @end smallexample
28294 @end enumerate
28295
28296 @node Using dlltool
28297 @subsubsection Using @code{dlltool}
28298
28299 @noindent
28300 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28301 DLLs and static import libraries. This section summarizes the most
28302 common @code{dlltool} switches. The form of the @code{dlltool} command
28303 is
28304
28305 @smallexample
28306 @c $ dlltool @ovar{switches}
28307 @c Expanding @ovar macro inline (explanation in macro def comments)
28308 $ dlltool @r{[}@var{switches}@r{]}
28309 @end smallexample
28310
28311 @noindent
28312 @code{dlltool} switches include:
28313
28314 @table @option
28315 @item --base-file @var{basefile}
28316 @cindex @option{--base-file} (@command{dlltool})
28317 Read the base file @var{basefile} generated by the linker. This switch
28318 is used to create a relocatable DLL.
28319
28320 @item --def @var{deffile}
28321 @cindex @option{--def} (@command{dlltool})
28322 Read the definition file.
28323
28324 @item --dllname @var{name}
28325 @cindex @option{--dllname} (@command{dlltool})
28326 Gives the name of the DLL. This switch is used to embed the name of the
28327 DLL in the static import library generated by @code{dlltool} with switch
28328 @option{--output-lib}.
28329
28330 @item -k
28331 @cindex @option{-k} (@command{dlltool})
28332 Kill @code{@@}@var{nn} from exported names
28333 (@pxref{Windows Calling Conventions}
28334 for a discussion about @code{Stdcall}-style symbols.
28335
28336 @item --help
28337 @cindex @option{--help} (@command{dlltool})
28338 Prints the @code{dlltool} switches with a concise description.
28339
28340 @item --output-exp @var{exportfile}
28341 @cindex @option{--output-exp} (@command{dlltool})
28342 Generate an export file @var{exportfile}. The export file contains the
28343 export table (list of symbols in the DLL) and is used to create the DLL.
28344
28345 @item --output-lib @var{libfile}
28346 @cindex @option{--output-lib} (@command{dlltool})
28347 Generate a static import library @var{libfile}.
28348
28349 @item -v
28350 @cindex @option{-v} (@command{dlltool})
28351 Verbose mode.
28352
28353 @item --as @var{assembler-name}
28354 @cindex @option{--as} (@command{dlltool})
28355 Use @var{assembler-name} as the assembler. The default is @code{as}.
28356 @end table
28357
28358 @node GNAT and Windows Resources
28359 @section GNAT and Windows Resources
28360 @cindex Resources, windows
28361
28362 @menu
28363 * Building Resources::
28364 * Compiling Resources::
28365 * Using Resources::
28366 @end menu
28367
28368 @noindent
28369 Resources are an easy way to add Windows specific objects to your
28370 application. The objects that can be added as resources include:
28371
28372 @itemize @bullet
28373 @item
28374 menus
28375
28376 @item
28377 accelerators
28378
28379 @item
28380 dialog boxes
28381
28382 @item
28383 string tables
28384
28385 @item
28386 bitmaps
28387
28388 @item
28389 cursors
28390
28391 @item
28392 icons
28393
28394 @item
28395 fonts
28396 @end itemize
28397
28398 @noindent
28399 This section explains how to build, compile and use resources.
28400
28401 @node Building Resources
28402 @subsection Building Resources
28403 @cindex Resources, building
28404
28405 @noindent
28406 A resource file is an ASCII file. By convention resource files have an
28407 @file{.rc} extension.
28408 The easiest way to build a resource file is to use Microsoft tools
28409 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28410 @code{dlgedit.exe} to build dialogs.
28411 It is always possible to build an @file{.rc} file yourself by writing a
28412 resource script.
28413
28414 It is not our objective to explain how to write a resource file. A
28415 complete description of the resource script language can be found in the
28416 Microsoft documentation.
28417
28418 @node Compiling Resources
28419 @subsection Compiling Resources
28420 @findex rc
28421 @findex windres
28422 @cindex Resources, compiling
28423
28424 @noindent
28425 This section describes how to build a GNAT-compatible (COFF) object file
28426 containing the resources. This is done using the Resource Compiler
28427 @code{windres} as follows:
28428
28429 @smallexample
28430 $ windres -i myres.rc -o myres.o
28431 @end smallexample
28432
28433 @noindent
28434 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28435 file. You can specify an alternate preprocessor (usually named
28436 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28437 parameter. A list of all possible options may be obtained by entering
28438 the command @code{windres} @option{--help}.
28439
28440 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28441 to produce a @file{.res} file (binary resource file). See the
28442 corresponding Microsoft documentation for further details. In this case
28443 you need to use @code{windres} to translate the @file{.res} file to a
28444 GNAT-compatible object file as follows:
28445
28446 @smallexample
28447 $ windres -i myres.res -o myres.o
28448 @end smallexample
28449
28450 @node Using Resources
28451 @subsection Using Resources
28452 @cindex Resources, using
28453
28454 @noindent
28455 To include the resource file in your program just add the
28456 GNAT-compatible object file for the resource(s) to the linker
28457 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28458 option:
28459
28460 @smallexample
28461 $ gnatmake myprog -largs myres.o
28462 @end smallexample
28463
28464 @node Debugging a DLL
28465 @section Debugging a DLL
28466 @cindex DLL debugging
28467
28468 @menu
28469 * Program and DLL Both Built with GCC/GNAT::
28470 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28471 @end menu
28472
28473 @noindent
28474 Debugging a DLL is similar to debugging a standard program. But
28475 we have to deal with two different executable parts: the DLL and the
28476 program that uses it. We have the following four possibilities:
28477
28478 @enumerate 1
28479 @item
28480 The program and the DLL are built with @code{GCC/GNAT}.
28481 @item
28482 The program is built with foreign tools and the DLL is built with
28483 @code{GCC/GNAT}.
28484 @item
28485 The program is built with @code{GCC/GNAT} and the DLL is built with
28486 foreign tools.
28487 @end enumerate
28488
28489 @noindent
28490 In this section we address only cases one and two above.
28491 There is no point in trying to debug
28492 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28493 information in it. To do so you must use a debugger compatible with the
28494 tools suite used to build the DLL.
28495
28496 @node Program and DLL Both Built with GCC/GNAT
28497 @subsection Program and DLL Both Built with GCC/GNAT
28498
28499 @noindent
28500 This is the simplest case. Both the DLL and the program have @code{GDB}
28501 compatible debugging information. It is then possible to break anywhere in
28502 the process. Let's suppose here that the main procedure is named
28503 @code{ada_main} and that in the DLL there is an entry point named
28504 @code{ada_dll}.
28505
28506 @noindent
28507 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28508 program must have been built with the debugging information (see GNAT -g
28509 switch). Here are the step-by-step instructions for debugging it:
28510
28511 @enumerate 1
28512 @item Launch @code{GDB} on the main program.
28513
28514 @smallexample
28515 $ gdb -nw ada_main
28516 @end smallexample
28517
28518 @item Start the program and stop at the beginning of the main procedure
28519
28520 @smallexample
28521 (gdb) start
28522 @end smallexample
28523
28524 @noindent
28525 This step is required to be able to set a breakpoint inside the DLL. As long
28526 as the program is not run, the DLL is not loaded. This has the
28527 consequence that the DLL debugging information is also not loaded, so it is not
28528 possible to set a breakpoint in the DLL.
28529
28530 @item Set a breakpoint inside the DLL
28531
28532 @smallexample
28533 (gdb) break ada_dll
28534 (gdb) cont
28535 @end smallexample
28536
28537 @end enumerate
28538
28539 @noindent
28540 At this stage a breakpoint is set inside the DLL. From there on
28541 you can use the standard approach to debug the whole program
28542 (@pxref{Running and Debugging Ada Programs}).
28543
28544 @ignore
28545 @c This used to work, probably because the DLLs were non-relocatable
28546 @c keep this section around until the problem is sorted out.
28547
28548 To break on the @code{DllMain} routine it is not possible to follow
28549 the procedure above. At the time the program stop on @code{ada_main}
28550 the @code{DllMain} routine as already been called. Either you can use
28551 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28552
28553 @enumerate 1
28554 @item Launch @code{GDB} on the main program.
28555
28556 @smallexample
28557 $ gdb ada_main
28558 @end smallexample
28559
28560 @item Load DLL symbols
28561
28562 @smallexample
28563 (gdb) add-sym api.dll
28564 @end smallexample
28565
28566 @item Set a breakpoint inside the DLL
28567
28568 @smallexample
28569 (gdb) break ada_dll.adb:45
28570 @end smallexample
28571
28572 Note that at this point it is not possible to break using the routine symbol
28573 directly as the program is not yet running. The solution is to break
28574 on the proper line (break in @file{ada_dll.adb} line 45).
28575
28576 @item Start the program
28577
28578 @smallexample
28579 (gdb) run
28580 @end smallexample
28581
28582 @end enumerate
28583 @end ignore
28584
28585 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28586 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28587
28588 @menu
28589 * Debugging the DLL Directly::
28590 * Attaching to a Running Process::
28591 @end menu
28592
28593 @noindent
28594 In this case things are slightly more complex because it is not possible to
28595 start the main program and then break at the beginning to load the DLL and the
28596 associated DLL debugging information. It is not possible to break at the
28597 beginning of the program because there is no @code{GDB} debugging information,
28598 and therefore there is no direct way of getting initial control. This
28599 section addresses this issue by describing some methods that can be used
28600 to break somewhere in the DLL to debug it.
28601
28602 @noindent
28603 First suppose that the main procedure is named @code{main} (this is for
28604 example some C code built with Microsoft Visual C) and that there is a
28605 DLL named @code{test.dll} containing an Ada entry point named
28606 @code{ada_dll}.
28607
28608 @noindent
28609 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28610 been built with debugging information (see GNAT -g option).
28611
28612 @node Debugging the DLL Directly
28613 @subsubsection Debugging the DLL Directly
28614
28615 @enumerate 1
28616 @item
28617 Find out the executable starting address
28618
28619 @smallexample
28620 $ objdump --file-header main.exe
28621 @end smallexample
28622
28623 The starting address is reported on the last line. For example:
28624
28625 @smallexample
28626 main.exe:     file format pei-i386
28627 architecture: i386, flags 0x0000010a:
28628 EXEC_P, HAS_DEBUG, D_PAGED
28629 start address 0x00401010
28630 @end smallexample
28631
28632 @item
28633 Launch the debugger on the executable.
28634
28635 @smallexample
28636 $ gdb main.exe
28637 @end smallexample
28638
28639 @item
28640 Set a breakpoint at the starting address, and launch the program.
28641
28642 @smallexample
28643 $ (gdb) break *0x00401010
28644 $ (gdb) run
28645 @end smallexample
28646
28647 The program will stop at the given address.
28648
28649 @item
28650 Set a breakpoint on a DLL subroutine.
28651
28652 @smallexample
28653 (gdb) break ada_dll.adb:45
28654 @end smallexample
28655
28656 Or if you want to break using a symbol on the DLL, you need first to
28657 select the Ada language (language used by the DLL).
28658
28659 @smallexample
28660 (gdb) set language ada
28661 (gdb) break ada_dll
28662 @end smallexample
28663
28664 @item
28665 Continue the program.
28666
28667 @smallexample
28668 (gdb) cont
28669 @end smallexample
28670
28671 @noindent
28672 This will run the program until it reaches the breakpoint that has been
28673 set. From that point you can use the standard way to debug a program
28674 as described in (@pxref{Running and Debugging Ada Programs}).
28675
28676 @end enumerate
28677
28678 @noindent
28679 It is also possible to debug the DLL by attaching to a running process.
28680
28681 @node Attaching to a Running Process
28682 @subsubsection Attaching to a Running Process
28683 @cindex DLL debugging, attach to process
28684
28685 @noindent
28686 With @code{GDB} it is always possible to debug a running process by
28687 attaching to it. It is possible to debug a DLL this way. The limitation
28688 of this approach is that the DLL must run long enough to perform the
28689 attach operation. It may be useful for instance to insert a time wasting
28690 loop in the code of the DLL to meet this criterion.
28691
28692 @enumerate 1
28693
28694 @item Launch the main program @file{main.exe}.
28695
28696 @smallexample
28697 $ main
28698 @end smallexample
28699
28700 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28701 that the process PID for @file{main.exe} is 208.
28702
28703 @item Launch gdb.
28704
28705 @smallexample
28706 $ gdb
28707 @end smallexample
28708
28709 @item Attach to the running process to be debugged.
28710
28711 @smallexample
28712 (gdb) attach 208
28713 @end smallexample
28714
28715 @item Load the process debugging information.
28716
28717 @smallexample
28718 (gdb) symbol-file main.exe
28719 @end smallexample
28720
28721 @item Break somewhere in the DLL.
28722
28723 @smallexample
28724 (gdb) break ada_dll
28725 @end smallexample
28726
28727 @item Continue process execution.
28728
28729 @smallexample
28730 (gdb) cont
28731 @end smallexample
28732
28733 @end enumerate
28734
28735 @noindent
28736 This last step will resume the process execution, and stop at
28737 the breakpoint we have set. From there you can use the standard
28738 approach to debug a program as described in
28739 (@pxref{Running and Debugging Ada Programs}).
28740
28741 @node Setting Stack Size from gnatlink
28742 @section Setting Stack Size from @command{gnatlink}
28743
28744 @noindent
28745 It is possible to specify the program stack size at link time. On modern
28746 versions of Windows, starting with XP, this is mostly useful to set the size of
28747 the main stack (environment task). The other task stacks are set with pragma
28748 Storage_Size or with the @command{gnatbind -d} command.
28749
28750 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28751 reserve size of individual tasks, the link-time stack size applies to all
28752 tasks, and pragma Storage_Size has no effect.
28753 In particular, Stack Overflow checks are made against this
28754 link-time specified size.
28755
28756 This setting can be done with
28757 @command{gnatlink} using either:
28758
28759 @itemize @bullet
28760
28761 @item using @option{-Xlinker} linker option
28762
28763 @smallexample
28764 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28765 @end smallexample
28766
28767 This sets the stack reserve size to 0x10000 bytes and the stack commit
28768 size to 0x1000 bytes.
28769
28770 @item using @option{-Wl} linker option
28771
28772 @smallexample
28773 $ gnatlink hello -Wl,--stack=0x1000000
28774 @end smallexample
28775
28776 This sets the stack reserve size to 0x1000000 bytes. Note that with
28777 @option{-Wl} option it is not possible to set the stack commit size
28778 because the coma is a separator for this option.
28779
28780 @end itemize
28781
28782 @node Setting Heap Size from gnatlink
28783 @section Setting Heap Size from @command{gnatlink}
28784
28785 @noindent
28786 Under Windows systems, it is possible to specify the program heap size from
28787 @command{gnatlink} using either:
28788
28789 @itemize @bullet
28790
28791 @item using @option{-Xlinker} linker option
28792
28793 @smallexample
28794 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28795 @end smallexample
28796
28797 This sets the heap reserve size to 0x10000 bytes and the heap commit
28798 size to 0x1000 bytes.
28799
28800 @item using @option{-Wl} linker option
28801
28802 @smallexample
28803 $ gnatlink hello -Wl,--heap=0x1000000
28804 @end smallexample
28805
28806 This sets the heap reserve size to 0x1000000 bytes. Note that with
28807 @option{-Wl} option it is not possible to set the heap commit size
28808 because the coma is a separator for this option.
28809
28810 @end itemize
28811
28812 @end ifset
28813
28814 @c **********************************
28815 @c * GNU Free Documentation License *
28816 @c **********************************
28817 @include fdl.texi
28818 @c GNU Free Documentation License
28819
28820 @node Index,,GNU Free Documentation License, Top
28821 @unnumbered Index
28822
28823 @printindex cp
28824
28825 @contents
28826 @c Put table of contents at end, otherwise it precedes the "title page" in
28827 @c the .txt version
28828 @c Edit the pdf file to move the contents to the beginning, after the title
28829 @c page
28830
28831 @bye