OSDN Git Service

2011-08-05 Yannick Moy <moy@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c                     Copyright (C) 1992-2011, 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 Sample Bodies Using gnatstub
467
468 * Running gnatstub::
469 * Switches for gnatstub::
470
471 Other Utility Programs
472
473 * Using Other Utility Programs with GNAT::
474 * The External Symbol Naming Scheme of GNAT::
475 * Converting Ada Files to html with gnathtml::
476
477 @ifclear vms
478 Code Coverage and Profiling
479
480 * Code Coverage of Ada Programs using gcov::
481 * Profiling an Ada Program using gprof::
482 @end ifclear
483
484 Running and Debugging Ada Programs
485
486 * The GNAT Debugger GDB::
487 * Running GDB::
488 * Introduction to GDB Commands::
489 * Using Ada Expressions::
490 * Calling User-Defined Subprograms::
491 * Using the Next Command in a Function::
492 * Ada Exceptions::
493 * Ada Tasks::
494 * Debugging Generic Units::
495 * Remote Debugging using gdbserver::
496 * GNAT Abnormal Termination or Failure to Terminate::
497 * Naming Conventions for GNAT Source Files::
498 * Getting Internal Debugging Information::
499 * Stack Traceback::
500
501 @ifset vms
502 * LSE::
503 @end ifset
504
505 @ifset vms
506 Compatibility with HP Ada
507
508 * Ada Language Compatibility::
509 * Differences in the Definition of Package System::
510 * Language-Related Features::
511 * The Package STANDARD::
512 * The Package SYSTEM::
513 * Tasking and Task-Related Features::
514 * Pragmas and Pragma-Related Features::
515 * Library of Predefined Units::
516 * Bindings::
517 * Main Program Definition::
518 * Implementation-Defined Attributes::
519 * Compiler and Run-Time Interfacing::
520 * Program Compilation and Library Management::
521 * Input-Output::
522 * Implementation Limits::
523 * Tools and Utilities::
524
525 Language-Related Features
526
527 * Integer Types and Representations::
528 * Floating-Point Types and Representations::
529 * Pragmas Float_Representation and Long_Float::
530 * Fixed-Point Types and Representations::
531 * Record and Array Component Alignment::
532 * Address Clauses::
533 * Other Representation Clauses::
534
535 Tasking and Task-Related Features
536
537 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
538 * Assigning Task IDs::
539 * Task IDs and Delays::
540 * Task-Related Pragmas::
541 * Scheduling and Task Priority::
542 * The Task Stack::
543 * External Interrupts::
544
545 Pragmas and Pragma-Related Features
546
547 * Restrictions on the Pragma INLINE::
548 * Restrictions on the Pragma INTERFACE::
549 * Restrictions on the Pragma SYSTEM_NAME::
550
551 Library of Predefined Units
552
553 * Changes to DECLIB::
554
555 Bindings
556
557 * Shared Libraries and Options Files::
558 * Interfaces to C::
559 @end ifset
560
561 Platform-Specific Information for the Run-Time Libraries
562
563 * Summary of Run-Time Configurations::
564 * Specifying a Run-Time Library::
565 * Choosing the Scheduling Policy::
566 * Solaris-Specific Considerations::
567 * Linux-Specific Considerations::
568 * AIX-Specific Considerations::
569 * Irix-Specific Considerations::
570 * RTX-Specific Considerations::
571 * HP-UX-Specific Considerations::
572
573 Example of Binder Output File
574
575 Elaboration Order Handling in GNAT
576
577 * Elaboration Code::
578 * Checking the Elaboration Order::
579 * Controlling the Elaboration Order::
580 * Controlling Elaboration in GNAT - Internal Calls::
581 * Controlling Elaboration in GNAT - External Calls::
582 * Default Behavior in GNAT - Ensuring Safety::
583 * Treatment of Pragma Elaborate::
584 * Elaboration Issues for Library Tasks::
585 * Mixing Elaboration Models::
586 * What to Do If the Default Elaboration Behavior Fails::
587 * Elaboration for Access-to-Subprogram Values::
588 * Summary of Procedures for Elaboration Control::
589 * Other Elaboration Order Considerations::
590
591 Conditional Compilation
592 * Use of Boolean Constants::
593 * Debugging - A Special Case::
594 * Conditionalizing Declarations::
595 * Use of Alternative Implementations::
596 * Preprocessing::
597
598 Inline Assembler
599
600 * Basic Assembler Syntax::
601 * A Simple Example of Inline Assembler::
602 * Output Variables in Inline Assembler::
603 * Input Variables in Inline Assembler::
604 * Inlining Inline Assembler Code::
605 * Other Asm Functionality::
606
607 Compatibility and Porting Guide
608
609 * Compatibility with Ada 83::
610 * Compatibility between Ada 95 and Ada 2005::
611 * Implementation-dependent characteristics::
612 @ifclear vms
613 @c This brief section is only in the non-VMS version
614 @c The complete chapter on HP Ada issues is in the VMS version
615 * Compatibility with HP Ada 83::
616 @end ifclear
617 * Compatibility with Other Ada Systems::
618 * Representation Clauses::
619 @ifset vms
620 * Transitioning to 64-Bit GNAT for OpenVMS::
621 @end ifset
622
623 @ifset unw
624 Microsoft Windows Topics
625
626 * Using GNAT on Windows::
627 * CONSOLE and WINDOWS subsystems::
628 * Temporary Files::
629 * Mixed-Language Programming on Windows::
630 * Windows Calling Conventions::
631 * Introduction to Dynamic Link Libraries (DLLs)::
632 * Using DLLs with GNAT::
633 * Building DLLs with GNAT::
634 * GNAT and Windows Resources::
635 * Debugging a DLL::
636 * Setting Stack Size from gnatlink::
637 * Setting Heap Size from gnatlink::
638 @end ifset
639
640 * Index::
641 @end menu
642 @end ifnottex
643
644 @node About This Guide
645 @unnumbered About This Guide
646
647 @noindent
648 @ifset vms
649 This guide describes the use of @value{EDITION},
650 a compiler and software development toolset for the full Ada
651 programming language, implemented on OpenVMS for HP's Alpha and
652 Integrity server (I64) platforms.
653 @end ifset
654 @ifclear vms
655 This guide describes the use of @value{EDITION},
656 a compiler and software development
657 toolset for the full Ada programming language.
658 @end ifclear
659 It documents the features of the compiler and tools, and explains
660 how to use them to build Ada applications.
661
662 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
663 Ada 83 compatibility mode.
664 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
665 but you can override with a compiler switch
666 (@pxref{Compiling Different Versions of Ada})
667 to explicitly specify the language version.
668 Throughout this manual, references to ``Ada'' without a year suffix
669 apply to both the Ada 95 and Ada 2005 versions of the language.
670
671
672 @ifclear FSFEDITION
673 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
674 ``GNAT'' in the remainder of this document.
675 @end ifclear
676
677
678
679
680 @menu
681 * What This Guide Contains::
682 * What You Should Know before Reading This Guide::
683 * Related Information::
684 * Conventions::
685 @end menu
686
687 @node What This Guide Contains
688 @unnumberedsec What This Guide Contains
689
690 @noindent
691 This guide contains the following chapters:
692 @itemize @bullet
693
694 @item
695 @ref{Getting Started with GNAT}, describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
697 @item
698 @ref{The GNAT Compilation Model}, describes the compilation model used
699 by GNAT.
700
701 @item
702 @ref{Compiling Using gcc}, describes how to compile
703 Ada programs with @command{gcc}, the Ada compiler.
704
705 @item
706 @ref{Binding Using gnatbind}, describes how to
707 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
708 utility.
709
710 @item
711 @ref{Linking Using gnatlink},
712 describes @command{gnatlink}, a
713 program that provides for linking using the GNAT run-time library to
714 construct a program. @command{gnatlink} can also incorporate foreign language
715 object units into the executable.
716
717 @item
718 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
719 utility that automatically determines the set of sources
720 needed by an Ada compilation unit, and executes the necessary compilations
721 binding and link.
722
723 @item
724 @ref{Improving Performance}, shows various techniques for making your
725 Ada program run faster or take less space.
726 It discusses the effect of the compiler's optimization switch and
727 also describes the @command{gnatelim} tool and unused subprogram/data
728 elimination.
729
730 @item
731 @ref{Renaming Files Using gnatchop}, describes
732 @code{gnatchop}, a utility that allows you to preprocess a file that
733 contains Ada source code, and split it into one or more new files, one
734 for each compilation unit.
735
736 @item
737 @ref{Configuration Pragmas}, describes the configuration pragmas
738 handled by GNAT.
739
740 @item
741 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
742 shows how to override the default GNAT file naming conventions,
743 either for an individual unit or globally.
744
745 @item
746 @ref{GNAT Project Manager}, describes how to use project files
747 to organize large projects.
748
749 @item
750 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
751 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
752 way to navigate through sources.
753
754 @item
755 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
756 version of an Ada source file with control over casing, indentation,
757 comment placement, and other elements of program presentation style.
758
759 @item
760 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
761 metrics for an Ada source file, such as the number of types and subprograms,
762 and assorted complexity measures.
763
764 @item
765 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
766 file name krunching utility, used to handle shortened
767 file names on operating systems with a limit on the length of names.
768
769 @item
770 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
771 preprocessor utility that allows a single source file to be used to
772 generate multiple or parameterized source files by means of macro
773 substitution.
774
775 @item
776 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
777 utility that displays information about compiled units, including dependences
778 on the corresponding sources files, and consistency of compilations.
779
780 @item
781 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
782 to delete files that are produced by the compiler, binder and linker.
783
784 @ifclear vms
785 @item
786 @ref{GNAT and Libraries}, describes the process of creating and using
787 Libraries with GNAT. It also describes how to recompile the GNAT run-time
788 library.
789
790 @item
791 @ref{Using the GNU make Utility}, describes some techniques for using
792 the GNAT toolset in Makefiles.
793 @end ifclear
794
795 @item
796 @ref{Memory Management Issues}, describes some useful predefined storage pools
797 and in particular the GNAT Debug Pool facility, which helps detect incorrect
798 memory references.
799 @ifclear vms
800 It also describes @command{gnatmem}, a utility that monitors dynamic
801 allocation and deallocation and helps detect ``memory leaks''.
802 @end ifclear
803
804 @item
805 @ref{Stack Related Facilities}, describes some useful tools associated with
806 stack checking and analysis.
807
808 @item
809 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
810 a utility that checks Ada code against a set of rules.
811
812 @item
813 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
814 a utility that generates empty but compilable bodies for library units.
815
816 @item
817 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
818 generate automatically Ada bindings from C and C++ headers.
819
820 @item
821 @ref{Other Utility Programs}, discusses several other GNAT utilities,
822 including @code{gnathtml}.
823
824 @ifclear vms
825 @item
826 @ref{Code Coverage and Profiling}, describes how to perform a structural
827 coverage and profile the execution of Ada programs.
828 @end ifclear
829
830 @item
831 @ref{Running and Debugging Ada Programs}, describes how to run and debug
832 Ada programs.
833
834 @ifset vms
835 @item
836 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
837 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
838 developed by Digital Equipment Corporation and currently supported by HP.}
839 for OpenVMS Alpha. This product was formerly known as DEC Ada,
840 @cindex DEC Ada
841 and for
842 historical compatibility reasons, the relevant libraries still use the
843 DEC prefix.
844 @end ifset
845
846 @item
847 @ref{Platform-Specific Information for the Run-Time Libraries},
848 describes the various run-time
849 libraries supported by GNAT on various platforms and explains how to
850 choose a particular library.
851
852 @item
853 @ref{Example of Binder Output File}, shows the source code for the binder
854 output file for a sample program.
855
856 @item
857 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
858 you deal with elaboration order issues.
859
860 @item
861 @ref{Conditional Compilation}, describes how to model conditional compilation,
862 both with Ada in general and with GNAT facilities in particular.
863
864 @item
865 @ref{Inline Assembler}, shows how to use the inline assembly facility
866 in an Ada program.
867
868 @item
869 @ref{Compatibility and Porting Guide}, contains sections on compatibility
870 of GNAT with other Ada development environments (including Ada 83 systems),
871 to assist in porting code from those environments.
872
873 @ifset unw
874 @item
875 @ref{Microsoft Windows Topics}, presents information relevant to the
876 Microsoft Windows platform.
877 @end ifset
878 @end itemize
879
880 @c *************************************************
881 @node What You Should Know before Reading This Guide
882 @c *************************************************
883 @unnumberedsec What You Should Know before Reading This Guide
884
885 @cindex Ada 95 Language Reference Manual
886 @cindex Ada 2005 Language Reference Manual
887 @noindent
888 This guide assumes a basic familiarity with the Ada 95 language, as
889 described in the International Standard ANSI/ISO/IEC-8652:1995, January
890 1995.
891 It does not require knowledge of the new features introduced by Ada 2005,
892 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
893 and Amendment 1).
894 Both reference manuals are included in the GNAT documentation
895 package.
896
897 @node Related Information
898 @unnumberedsec Related Information
899
900 @noindent
901 For further information about related tools, refer to the following
902 documents:
903
904 @itemize @bullet
905 @item
906 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
907 Reference Manual}, which contains all reference material for the GNAT
908 implementation of Ada.
909
910 @ifset unw
911 @item
912 @cite{Using the GNAT Programming Studio}, which describes the GPS
913 Integrated Development Environment.
914
915 @item
916 @cite{GNAT Programming Studio Tutorial}, which introduces the
917 main GPS features through examples.
918 @end ifset
919
920 @item
921 @cite{Ada 95 Reference Manual}, which contains reference
922 material for the Ada 95 programming language.
923
924 @item
925 @cite{Ada 2005 Reference Manual}, which contains reference
926 material for the Ada 2005 programming language.
927
928 @item
929 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
930 @ifset vms
931 in the GNU:[DOCS] directory,
932 @end ifset
933 for all details on the use of the GNU source-level debugger.
934
935 @item
936 @xref{Top,, The extensible self-documenting text editor, emacs,
937 GNU Emacs Manual},
938 @ifset vms
939 located in the GNU:[DOCS] directory if the EMACS kit is installed,
940 @end ifset
941 for full information on the extensible editor and programming
942 environment Emacs.
943
944 @end itemize
945
946 @c **************
947 @node Conventions
948 @unnumberedsec Conventions
949 @cindex Conventions
950 @cindex Typographical conventions
951
952 @noindent
953 Following are examples of the typographical and graphic conventions used
954 in this guide:
955
956 @itemize @bullet
957 @item
958 @code{Functions}, @command{utility program names}, @code{standard names},
959 and @code{classes}.
960
961 @item
962 @option{Option flags}
963
964 @item
965 @file{File names}, @samp{button names}, and @samp{field names}.
966
967 @item
968 @code{Variables}, @env{environment variables}, and @var{metasyntactic
969 variables}.
970
971 @item
972 @emph{Emphasis}.
973
974 @item
975 @r{[}optional information or parameters@r{]}
976
977 @item
978 Examples are described by text
979 @smallexample
980 and then shown this way.
981 @end smallexample
982 @end itemize
983
984 @noindent
985 Commands that are entered by the user are preceded in this manual by the
986 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
987 uses this sequence as a prompt, then the commands will appear exactly as
988 you see them in the manual. If your system uses some other prompt, then
989 the command will appear with the @code{$} replaced by whatever prompt
990 character you are using.
991
992 @ifset unw
993 Full file names are shown with the ``@code{/}'' character
994 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
995 If you are using GNAT on a Windows platform, please note that
996 the ``@code{\}'' character should be used instead.
997 @end ifset
998
999 @c ****************************
1000 @node Getting Started with GNAT
1001 @chapter Getting Started with GNAT
1002
1003 @noindent
1004 This chapter describes some simple ways of using GNAT to build
1005 executable Ada programs.
1006 @ifset unw
1007 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1008 show how to use the command line environment.
1009 @ref{Introduction to GPS}, provides a brief
1010 introduction to the GNAT Programming Studio, a visually-oriented
1011 Integrated Development Environment for GNAT.
1012 GPS offers a graphical ``look and feel'', support for development in
1013 other programming languages, comprehensive browsing features, and
1014 many other capabilities.
1015 For information on GPS please refer to
1016 @cite{Using the GNAT Programming Studio}.
1017 @end ifset
1018
1019 @menu
1020 * Running GNAT::
1021 * Running a Simple Ada Program::
1022 * Running a Program with Multiple Units::
1023 * Using the gnatmake Utility::
1024 @ifset vms
1025 * Editing with Emacs::
1026 @end ifset
1027 @ifclear vms
1028 * Introduction to GPS::
1029 @end ifclear
1030 @end menu
1031
1032 @node Running GNAT
1033 @section Running GNAT
1034
1035 @noindent
1036 Three steps are needed to create an executable file from an Ada source
1037 file:
1038
1039 @enumerate
1040 @item
1041 The source file(s) must be compiled.
1042 @item
1043 The file(s) must be bound using the GNAT binder.
1044 @item
1045 All appropriate object files must be linked to produce an executable.
1046 @end enumerate
1047
1048 @noindent
1049 All three steps are most commonly handled by using the @command{gnatmake}
1050 utility program that, given the name of the main program, automatically
1051 performs the necessary compilation, binding and linking steps.
1052
1053 @node Running a Simple Ada Program
1054 @section Running a Simple Ada Program
1055
1056 @noindent
1057 Any text editor may be used to prepare an Ada program.
1058 (If @code{Emacs} is
1059 used, the optional Ada mode may be helpful in laying out the program.)
1060 The
1061 program text is a normal text file. We will assume in our initial
1062 example that you have used your editor to prepare the following
1063 standard format text file:
1064
1065 @smallexample @c ada
1066 @cartouche
1067 with Ada.Text_IO; use Ada.Text_IO;
1068 procedure Hello is
1069 begin
1070    Put_Line ("Hello WORLD!");
1071 end Hello;
1072 @end cartouche
1073 @end smallexample
1074
1075 @noindent
1076 This file should be named @file{hello.adb}.
1077 With the normal default file naming conventions, GNAT requires
1078 that each file
1079 contain a single compilation unit whose file name is the
1080 unit name,
1081 with periods replaced by hyphens; the
1082 extension is @file{ads} for a
1083 spec and @file{adb} for a body.
1084 You can override this default file naming convention by use of the
1085 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1086 Alternatively, if you want to rename your files according to this default
1087 convention, which is probably more convenient if you will be using GNAT
1088 for all your compilations, then the @code{gnatchop} utility
1089 can be used to generate correctly-named source files
1090 (@pxref{Renaming Files Using gnatchop}).
1091
1092 You can compile the program using the following command (@code{$} is used
1093 as the command prompt in the examples in this document):
1094
1095 @smallexample
1096 $ gcc -c hello.adb
1097 @end smallexample
1098
1099 @noindent
1100 @command{gcc} is the command used to run the compiler. This compiler is
1101 capable of compiling programs in several languages, including Ada and
1102 C. It assumes that you have given it an Ada program if the file extension is
1103 either @file{.ads} or @file{.adb}, and it will then call
1104 the GNAT compiler to compile the specified file.
1105
1106 @ifclear vms
1107 The @option{-c} switch is required. It tells @command{gcc} to only do a
1108 compilation. (For C programs, @command{gcc} can also do linking, but this
1109 capability is not used directly for Ada programs, so the @option{-c}
1110 switch must always be present.)
1111 @end ifclear
1112
1113 This compile command generates a file
1114 @file{hello.o}, which is the object
1115 file corresponding to your Ada program. It also generates
1116 an ``Ada Library Information'' file @file{hello.ali},
1117 which contains additional information used to check
1118 that an Ada program is consistent.
1119 To build an executable file,
1120 use @code{gnatbind} to bind the program
1121 and @command{gnatlink} to link it. The
1122 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1123 @file{ALI} file, but the default extension of @file{.ali} can
1124 be omitted. This means that in the most common case, the argument
1125 is simply the name of the main program:
1126
1127 @smallexample
1128 $ gnatbind hello
1129 $ gnatlink hello
1130 @end smallexample
1131
1132 @noindent
1133 A simpler method of carrying out these steps is to use
1134 @command{gnatmake},
1135 a master program that invokes all the required
1136 compilation, binding and linking tools in the correct order. In particular,
1137 @command{gnatmake} automatically recompiles any sources that have been
1138 modified since they were last compiled, or sources that depend
1139 on such modified sources, so that ``version skew'' is avoided.
1140 @cindex Version skew (avoided by @command{gnatmake})
1141
1142 @smallexample
1143 $ gnatmake hello.adb
1144 @end smallexample
1145
1146 @noindent
1147 The result is an executable program called @file{hello}, which can be
1148 run by entering:
1149
1150 @smallexample
1151 $ ^hello^RUN HELLO^
1152 @end smallexample
1153
1154 @noindent
1155 assuming that the current directory is on the search path
1156 for executable programs.
1157
1158 @noindent
1159 and, if all has gone well, you will see
1160
1161 @smallexample
1162 Hello WORLD!
1163 @end smallexample
1164
1165 @noindent
1166 appear in response to this command.
1167
1168 @c ****************************************
1169 @node Running a Program with Multiple Units
1170 @section Running a Program with Multiple Units
1171
1172 @noindent
1173 Consider a slightly more complicated example that has three files: a
1174 main program, and the spec and body of a package:
1175
1176 @smallexample @c ada
1177 @cartouche
1178 @group
1179 package Greetings is
1180    procedure Hello;
1181    procedure Goodbye;
1182 end Greetings;
1183
1184 with Ada.Text_IO; use Ada.Text_IO;
1185 package body Greetings is
1186    procedure Hello is
1187    begin
1188       Put_Line ("Hello WORLD!");
1189    end Hello;
1190
1191    procedure Goodbye is
1192    begin
1193       Put_Line ("Goodbye WORLD!");
1194    end Goodbye;
1195 end Greetings;
1196 @end group
1197
1198 @group
1199 with Greetings;
1200 procedure Gmain is
1201 begin
1202    Greetings.Hello;
1203    Greetings.Goodbye;
1204 end Gmain;
1205 @end group
1206 @end cartouche
1207 @end smallexample
1208
1209 @noindent
1210 Following the one-unit-per-file rule, place this program in the
1211 following three separate files:
1212
1213 @table @file
1214 @item greetings.ads
1215 spec of package @code{Greetings}
1216
1217 @item greetings.adb
1218 body of package @code{Greetings}
1219
1220 @item gmain.adb
1221 body of main program
1222 @end table
1223
1224 @noindent
1225 To build an executable version of
1226 this program, we could use four separate steps to compile, bind, and link
1227 the program, as follows:
1228
1229 @smallexample
1230 $ gcc -c gmain.adb
1231 $ gcc -c greetings.adb
1232 $ gnatbind gmain
1233 $ gnatlink gmain
1234 @end smallexample
1235
1236 @noindent
1237 Note that there is no required order of compilation when using GNAT.
1238 In particular it is perfectly fine to compile the main program first.
1239 Also, it is not necessary to compile package specs in the case where
1240 there is an accompanying body; you only need to compile the body. If you want
1241 to submit these files to the compiler for semantic checking and not code
1242 generation, then use the
1243 @option{-gnatc} switch:
1244
1245 @smallexample
1246 $ gcc -c greetings.ads -gnatc
1247 @end smallexample
1248
1249 @noindent
1250 Although the compilation can be done in separate steps as in the
1251 above example, in practice it is almost always more convenient
1252 to use the @command{gnatmake} tool. All you need to know in this case
1253 is the name of the main program's source file. The effect of the above four
1254 commands can be achieved with a single one:
1255
1256 @smallexample
1257 $ gnatmake gmain.adb
1258 @end smallexample
1259
1260 @noindent
1261 In the next section we discuss the advantages of using @command{gnatmake} in
1262 more detail.
1263
1264 @c *****************************
1265 @node Using the gnatmake Utility
1266 @section Using the @command{gnatmake} Utility
1267
1268 @noindent
1269 If you work on a program by compiling single components at a time using
1270 @command{gcc}, you typically keep track of the units you modify. In order to
1271 build a consistent system, you compile not only these units, but also any
1272 units that depend on the units you have modified.
1273 For example, in the preceding case,
1274 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1275 you edit @file{greetings.ads}, you must recompile both
1276 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1277 units that depend on @file{greetings.ads}.
1278
1279 @code{gnatbind} will warn you if you forget one of these compilation
1280 steps, so that it is impossible to generate an inconsistent program as a
1281 result of forgetting to do a compilation. Nevertheless it is tedious and
1282 error-prone to keep track of dependencies among units.
1283 One approach to handle the dependency-bookkeeping is to use a
1284 makefile. However, makefiles present maintenance problems of their own:
1285 if the dependencies change as you change the program, you must make
1286 sure that the makefile is kept up-to-date manually, which is also an
1287 error-prone process.
1288
1289 The @command{gnatmake} utility takes care of these details automatically.
1290 Invoke it using either one of the following forms:
1291
1292 @smallexample
1293 $ gnatmake gmain.adb
1294 $ gnatmake ^gmain^GMAIN^
1295 @end smallexample
1296
1297 @noindent
1298 The argument is the name of the file containing the main program;
1299 you may omit the extension. @command{gnatmake}
1300 examines the environment, automatically recompiles any files that need
1301 recompiling, and binds and links the resulting set of object files,
1302 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1303 In a large program, it
1304 can be extremely helpful to use @command{gnatmake}, because working out by hand
1305 what needs to be recompiled can be difficult.
1306
1307 Note that @command{gnatmake}
1308 takes into account all the Ada rules that
1309 establish dependencies among units. These include dependencies that result
1310 from inlining subprogram bodies, and from
1311 generic instantiation. Unlike some other
1312 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1313 found by the compiler on a previous compilation, which may possibly
1314 be wrong when sources change. @command{gnatmake} determines the exact set of
1315 dependencies from scratch each time it is run.
1316
1317 @ifset vms
1318 @node Editing with Emacs
1319 @section Editing with Emacs
1320 @cindex Emacs
1321
1322 @noindent
1323 Emacs is an extensible self-documenting text editor that is available in a
1324 separate VMSINSTAL kit.
1325
1326 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1327 click on the Emacs Help menu and run the Emacs Tutorial.
1328 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1329 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1330
1331 Documentation on Emacs and other tools is available in Emacs under the
1332 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1333 use the middle mouse button to select a topic (e.g.@: Emacs).
1334
1335 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1336 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1337 get to the Emacs manual.
1338 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1339 prompt.
1340
1341 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1342 which is sufficiently extensible to provide for a complete programming
1343 environment and shell for the sophisticated user.
1344 @end ifset
1345
1346 @ifclear vms
1347 @node Introduction to GPS
1348 @section Introduction to GPS
1349 @cindex GPS (GNAT Programming Studio)
1350 @cindex GNAT Programming Studio (GPS)
1351 @noindent
1352 Although the command line interface (@command{gnatmake}, etc.) alone
1353 is sufficient, a graphical Interactive Development
1354 Environment can make it easier for you to compose, navigate, and debug
1355 programs.  This section describes the main features of GPS
1356 (``GNAT Programming Studio''), the GNAT graphical IDE.
1357 You will see how to use GPS to build and debug an executable, and
1358 you will also learn some of the basics of the GNAT ``project'' facility.
1359
1360 GPS enables you to do much more than is presented here;
1361 e.g., you can produce a call graph, interface to a third-party
1362 Version Control System, and inspect the generated assembly language
1363 for a program.
1364 Indeed, GPS also supports languages other than Ada.
1365 Such additional information, and an explanation of all of the GPS menu
1366 items. may be found in the on-line help, which includes
1367 a user's guide and a tutorial (these are also accessible from the GNAT
1368 startup menu).
1369
1370 @menu
1371 * Building a New Program with GPS::
1372 * Simple Debugging with GPS::
1373 @end menu
1374
1375 @node Building a New Program with GPS
1376 @subsection Building a New Program with GPS
1377 @noindent
1378 GPS invokes the GNAT compilation tools using information
1379 contained in a @emph{project} (also known as a @emph{project file}):
1380 a collection of properties such
1381 as source directories, identities of main subprograms, tool switches, etc.,
1382 and their associated values.
1383 See @ref{GNAT Project Manager} for details.
1384 In order to run GPS, you will need to either create a new project
1385 or else open an existing one.
1386
1387 This section will explain how you can use GPS to create a project,
1388 to associate Ada source files with a project, and to build and run
1389 programs.
1390
1391 @enumerate
1392 @item @emph{Creating a project}
1393
1394 Invoke GPS, either from the command line or the platform's IDE.
1395 After it starts, GPS will display a ``Welcome'' screen with three
1396 radio buttons:
1397
1398 @itemize @bullet
1399 @item
1400 @code{Start with default project in directory}
1401
1402 @item
1403 @code{Create new project with wizard}
1404
1405 @item
1406 @code{Open existing project}
1407 @end itemize
1408
1409 @noindent
1410 Select @code{Create new project with wizard} and press @code{OK}.
1411 A new window will appear.  In the text box labeled with
1412 @code{Enter the name of the project to create}, type @file{sample}
1413 as the project name.
1414 In the next box, browse to choose the directory in which you
1415 would like to create the project file.
1416 After selecting an appropriate directory, press @code{Forward}.
1417
1418 A window will appear with the title
1419 @code{Version Control System Configuration}.
1420 Simply press @code{Forward}.
1421
1422 A window will appear with the title
1423 @code{Please select the source directories for this project}.
1424 The directory that you specified for the project file will be selected
1425 by default as the one to use for sources; simply press @code{Forward}.
1426
1427 A window will appear with the title
1428 @code{Please select the build directory for this project}.
1429 The directory that you specified for the project file will be selected
1430 by default for object files and executables;
1431 simply press @code{Forward}.
1432
1433 A window will appear with the title
1434 @code{Please select the main units for this project}.
1435 You will supply this information later, after creating the source file.
1436 Simply press @code{Forward} for now.
1437
1438 A window will appear with the title
1439 @code{Please select the switches to build the project}.
1440 Press @code{Apply}.  This will create a project file named
1441 @file{sample.prj} in the directory that you had specified.
1442
1443 @item @emph{Creating and saving the source file}
1444
1445 After you create the new project, a GPS window will appear, which is
1446 partitioned into two main sections:
1447
1448 @itemize @bullet
1449 @item
1450 A @emph{Workspace area}, initially greyed out, which you will use for
1451 creating and editing source files
1452
1453 @item
1454 Directly below, a @emph{Messages area}, which initially displays a
1455 ``Welcome'' message.
1456 (If the Messages area is not visible, drag its border upward to expand it.)
1457 @end itemize
1458
1459 @noindent
1460 Select @code{File} on the menu bar, and then the @code{New} command.
1461 The Workspace area will become white, and you can now
1462 enter the source program explicitly.
1463 Type the following text
1464
1465 @smallexample @c ada
1466 @group
1467 with Ada.Text_IO; use Ada.Text_IO;
1468 procedure Hello is
1469 begin
1470   Put_Line("Hello from GPS!");
1471 end Hello;
1472 @end group
1473 @end smallexample
1474
1475 @noindent
1476 Select @code{File}, then @code{Save As}, and enter the source file name
1477 @file{hello.adb}.
1478 The file will be saved in the same directory you specified as the
1479 location of the default project file.
1480
1481 @item @emph{Updating the project file}
1482
1483 You need to add the new source file to the project.
1484 To do this, select
1485 the @code{Project} menu and then @code{Edit project properties}.
1486 Click the @code{Main files} tab on the left, and then the
1487 @code{Add} button.
1488 Choose @file{hello.adb} from the list, and press @code{Open}.
1489 The project settings window will reflect this action.
1490 Click @code{OK}.
1491
1492 @item @emph{Building and running the program}
1493
1494 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1495 and select @file{hello.adb}.
1496 The Messages window will display the resulting invocations of @command{gcc},
1497 @command{gnatbind}, and @command{gnatlink}
1498 (reflecting the default switch settings from the
1499 project file that you created) and then a ``successful compilation/build''
1500 message.
1501
1502 To run the program, choose the @code{Build} menu, then @code{Run}, and
1503 select @command{hello}.
1504 An @emph{Arguments Selection} window will appear.
1505 There are no command line arguments, so just click @code{OK}.
1506
1507 The Messages window will now display the program's output (the string
1508 @code{Hello from GPS}), and at the bottom of the GPS window a status
1509 update is displayed (@code{Run: hello}).
1510 Close the GPS window (or select @code{File}, then @code{Exit}) to
1511 terminate this GPS session.
1512 @end enumerate
1513
1514 @node Simple Debugging with GPS
1515 @subsection Simple Debugging with GPS
1516 @noindent
1517 This section illustrates basic debugging techniques (setting breakpoints,
1518 examining/modifying variables, single stepping).
1519
1520 @enumerate
1521 @item @emph{Opening a project}
1522
1523 Start GPS and select @code{Open existing project}; browse to
1524 specify the project file @file{sample.prj} that you had created in the
1525 earlier example.
1526
1527 @item @emph{Creating a source file}
1528
1529 Select @code{File}, then @code{New}, and type in the following program:
1530
1531 @smallexample @c ada
1532 @group
1533 with Ada.Text_IO; use Ada.Text_IO;
1534 procedure Example is
1535    Line : String (1..80);
1536    N    : Natural;
1537 begin
1538    Put_Line("Type a line of text at each prompt; an empty line to exit");
1539    loop
1540       Put(": ");
1541       Get_Line (Line, N);
1542       Put_Line (Line (1..N) );
1543       exit when N=0;
1544    end loop;
1545 end Example;
1546 @end group
1547 @end smallexample
1548
1549 @noindent
1550 Select @code{File}, then @code{Save as}, and enter the file name
1551 @file{example.adb}.
1552
1553 @item @emph{Updating the project file}
1554
1555 Add @code{Example} as a new main unit for the project:
1556 @enumerate a
1557 @item
1558 Select @code{Project}, then @code{Edit Project Properties}.
1559
1560 @item
1561 Select the @code{Main files} tab, click @code{Add}, then
1562 select the file @file{example.adb} from the list, and
1563 click @code{Open}.
1564 You will see the file name appear in the list of main units
1565
1566 @item
1567 Click @code{OK}
1568 @end enumerate
1569
1570 @item @emph{Building/running the executable}
1571
1572 To build the executable
1573 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1574
1575 Run the program to see its effect (in the Messages area).
1576 Each line that you enter is displayed; an empty line will
1577 cause the loop to exit and the program to terminate.
1578
1579 @item @emph{Debugging the program}
1580
1581 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1582 which are required for debugging, are on by default when you create
1583 a new project.
1584 Thus unless you intentionally remove these settings, you will be able
1585 to debug any program that you develop using GPS.
1586
1587 @enumerate a
1588 @item @emph{Initializing}
1589
1590 Select @code{Debug}, then @code{Initialize}, then @file{example}
1591
1592 @item @emph{Setting a breakpoint}
1593
1594 After performing the initialization step, you will observe a small
1595 icon to the right of each line number.
1596 This serves as a toggle for breakpoints; clicking the icon will
1597 set a breakpoint at the corresponding line (the icon will change to
1598 a red circle with an ``x''), and clicking it again
1599 will remove the breakpoint / reset the icon.
1600
1601 For purposes of this example, set a breakpoint at line 10 (the
1602 statement @code{Put_Line@ (Line@ (1..N));}
1603
1604 @item @emph{Starting program execution}
1605
1606 Select @code{Debug}, then @code{Run}.  When the
1607 @code{Program Arguments} window appears, click @code{OK}.
1608 A console window will appear; enter some line of text,
1609 e.g.@: @code{abcde}, at the prompt.
1610 The program will pause execution when it gets to the
1611 breakpoint, and the corresponding line is highlighted.
1612
1613 @item @emph{Examining a variable}
1614
1615 Move the mouse over one of the occurrences of the variable @code{N}.
1616 You will see the value (5) displayed, in ``tool tip'' fashion.
1617 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1618 You will see information about @code{N} appear in the @code{Debugger Data}
1619 pane, showing the value as 5.
1620
1621 @item @emph{Assigning a new value to a variable}
1622
1623 Right click on the @code{N} in the @code{Debugger Data} pane, and
1624 select @code{Set value of N}.
1625 When the input window appears, enter the value @code{4} and click
1626 @code{OK}.
1627 This value does not automatically appear in the @code{Debugger Data}
1628 pane; to see it, right click again on the @code{N} in the
1629 @code{Debugger Data} pane and select @code{Update value}.
1630 The new value, 4, will appear in red.
1631
1632 @item @emph{Single stepping}
1633
1634 Select @code{Debug}, then @code{Next}.
1635 This will cause the next statement to be executed, in this case the
1636 call of @code{Put_Line} with the string slice.
1637 Notice in the console window that the displayed string is simply
1638 @code{abcd} and not @code{abcde} which you had entered.
1639 This is because the upper bound of the slice is now 4 rather than 5.
1640
1641 @item @emph{Removing a breakpoint}
1642
1643 Toggle the breakpoint icon at line 10.
1644
1645 @item @emph{Resuming execution from a breakpoint}
1646
1647 Select @code{Debug}, then @code{Continue}.
1648 The program will reach the next iteration of the loop, and
1649 wait for input after displaying the prompt.
1650 This time, just hit the @kbd{Enter} key.
1651 The value of @code{N} will be 0, and the program will terminate.
1652 The console window will disappear.
1653 @end enumerate
1654 @end enumerate
1655 @end ifclear
1656
1657 @node The GNAT Compilation Model
1658 @chapter The GNAT Compilation Model
1659 @cindex GNAT compilation model
1660 @cindex Compilation model
1661
1662 @menu
1663 * Source Representation::
1664 * Foreign Language Representation::
1665 * File Naming Rules::
1666 * Using Other File Names::
1667 * Alternative File Naming Schemes::
1668 * Generating Object Files::
1669 * Source Dependencies::
1670 * The Ada Library Information Files::
1671 * Binding an Ada Program::
1672 * Mixed Language Programming::
1673 @ifclear vms
1674 * Building Mixed Ada & C++ Programs::
1675 * Comparison between GNAT and C/C++ Compilation Models::
1676 @end ifclear
1677 * Comparison between GNAT and Conventional Ada Library Models::
1678 @ifset vms
1679 * Placement of temporary files::
1680 @end ifset
1681 @end menu
1682
1683 @noindent
1684 This chapter describes the compilation model used by GNAT. Although
1685 similar to that used by other languages, such as C and C++, this model
1686 is substantially different from the traditional Ada compilation models,
1687 which are based on a library. The model is initially described without
1688 reference to the library-based model. If you have not previously used an
1689 Ada compiler, you need only read the first part of this chapter. The
1690 last section describes and discusses the differences between the GNAT
1691 model and the traditional Ada compiler models. If you have used other
1692 Ada compilers, this section will help you to understand those
1693 differences, and the advantages of the GNAT model.
1694
1695 @node Source Representation
1696 @section Source Representation
1697 @cindex Latin-1
1698
1699 @noindent
1700 Ada source programs are represented in standard text files, using
1701 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1702 7-bit ASCII set, plus additional characters used for
1703 representing foreign languages (@pxref{Foreign Language Representation}
1704 for support of non-USA character sets). The format effector characters
1705 are represented using their standard ASCII encodings, as follows:
1706
1707 @table @code
1708 @item VT
1709 @findex VT
1710 Vertical tab, @code{16#0B#}
1711
1712 @item HT
1713 @findex HT
1714 Horizontal tab, @code{16#09#}
1715
1716 @item CR
1717 @findex CR
1718 Carriage return, @code{16#0D#}
1719
1720 @item LF
1721 @findex LF
1722 Line feed, @code{16#0A#}
1723
1724 @item FF
1725 @findex FF
1726 Form feed, @code{16#0C#}
1727 @end table
1728
1729 @noindent
1730 Source files are in standard text file format. In addition, GNAT will
1731 recognize a wide variety of stream formats, in which the end of
1732 physical lines is marked by any of the following sequences:
1733 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1734 in accommodating files that are imported from other operating systems.
1735
1736 @cindex End of source file
1737 @cindex Source file, end
1738 @findex SUB
1739 The end of a source file is normally represented by the physical end of
1740 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1741 recognized as signalling the end of the source file. Again, this is
1742 provided for compatibility with other operating systems where this
1743 code is used to represent the end of file.
1744
1745 Each file contains a single Ada compilation unit, including any pragmas
1746 associated with the unit. For example, this means you must place a
1747 package declaration (a package @dfn{spec}) and the corresponding body in
1748 separate files. An Ada @dfn{compilation} (which is a sequence of
1749 compilation units) is represented using a sequence of files. Similarly,
1750 you will place each subunit or child unit in a separate file.
1751
1752 @node Foreign Language Representation
1753 @section Foreign Language Representation
1754
1755 @noindent
1756 GNAT supports the standard character sets defined in Ada as well as
1757 several other non-standard character sets for use in localized versions
1758 of the compiler (@pxref{Character Set Control}).
1759 @menu
1760 * Latin-1::
1761 * Other 8-Bit Codes::
1762 * Wide Character Encodings::
1763 @end menu
1764
1765 @node Latin-1
1766 @subsection Latin-1
1767 @cindex Latin-1
1768
1769 @noindent
1770 The basic character set is Latin-1. This character set is defined by ISO
1771 standard 8859, part 1. The lower half (character codes @code{16#00#}
1772 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1773 half is used to represent additional characters. These include extended letters
1774 used by European languages, such as French accents, the vowels with umlauts
1775 used in German, and the extra letter A-ring used in Swedish.
1776
1777 @findex Ada.Characters.Latin_1
1778 For a complete list of Latin-1 codes and their encodings, see the source
1779 file of library unit @code{Ada.Characters.Latin_1} in file
1780 @file{a-chlat1.ads}.
1781 You may use any of these extended characters freely in character or
1782 string literals. In addition, the extended characters that represent
1783 letters can be used in identifiers.
1784
1785 @node Other 8-Bit Codes
1786 @subsection Other 8-Bit Codes
1787
1788 @noindent
1789 GNAT also supports several other 8-bit coding schemes:
1790
1791 @table @asis
1792 @item ISO 8859-2 (Latin-2)
1793 @cindex Latin-2
1794 @cindex ISO 8859-2
1795 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1796 equivalence.
1797
1798 @item ISO 8859-3 (Latin-3)
1799 @cindex Latin-3
1800 @cindex ISO 8859-3
1801 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1802 equivalence.
1803
1804 @item ISO 8859-4 (Latin-4)
1805 @cindex Latin-4
1806 @cindex ISO 8859-4
1807 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1808 equivalence.
1809
1810 @item ISO 8859-5 (Cyrillic)
1811 @cindex ISO 8859-5
1812 @cindex Cyrillic
1813 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1814 lowercase equivalence.
1815
1816 @item ISO 8859-15 (Latin-9)
1817 @cindex ISO 8859-15
1818 @cindex Latin-9
1819 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1820 lowercase equivalence
1821
1822 @item IBM PC (code page 437)
1823 @cindex code page 437
1824 This code page is the normal default for PCs in the U.S. It corresponds
1825 to the original IBM PC character set. This set has some, but not all, of
1826 the extended Latin-1 letters, but these letters do not have the same
1827 encoding as Latin-1. In this mode, these letters are allowed in
1828 identifiers with uppercase and lowercase equivalence.
1829
1830 @item IBM PC (code page 850)
1831 @cindex code page 850
1832 This code page is a modification of 437 extended to include all the
1833 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1834 mode, all these letters are allowed in identifiers with uppercase and
1835 lowercase equivalence.
1836
1837 @item Full Upper 8-bit
1838 Any character in the range 80-FF allowed in identifiers, and all are
1839 considered distinct. In other words, there are no uppercase and lowercase
1840 equivalences in this range. This is useful in conjunction with
1841 certain encoding schemes used for some foreign character sets (e.g.,
1842 the typical method of representing Chinese characters on the PC).
1843
1844 @item No Upper-Half
1845 No upper-half characters in the range 80-FF are allowed in identifiers.
1846 This gives Ada 83 compatibility for identifier names.
1847 @end table
1848
1849 @noindent
1850 For precise data on the encodings permitted, and the uppercase and lowercase
1851 equivalences that are recognized, see the file @file{csets.adb} in
1852 the GNAT compiler sources. You will need to obtain a full source release
1853 of GNAT to obtain this file.
1854
1855 @node Wide Character Encodings
1856 @subsection Wide Character Encodings
1857
1858 @noindent
1859 GNAT allows wide character codes to appear in character and string
1860 literals, and also optionally in identifiers, by means of the following
1861 possible encoding schemes:
1862
1863 @table @asis
1864
1865 @item Hex Coding
1866 In this encoding, a wide character is represented by the following five
1867 character sequence:
1868
1869 @smallexample
1870 ESC a b c d
1871 @end smallexample
1872
1873 @noindent
1874 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1875 characters (using uppercase letters) of the wide character code. For
1876 example, ESC A345 is used to represent the wide character with code
1877 @code{16#A345#}.
1878 This scheme is compatible with use of the full Wide_Character set.
1879
1880 @item Upper-Half Coding
1881 @cindex Upper-Half Coding
1882 The wide character with encoding @code{16#abcd#} where the upper bit is on
1883 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1884 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1885 character, but is not required to be in the upper half. This method can
1886 be also used for shift-JIS or EUC, where the internal coding matches the
1887 external coding.
1888
1889 @item Shift JIS Coding
1890 @cindex Shift JIS Coding
1891 A wide character is represented by a two-character sequence,
1892 @code{16#ab#} and
1893 @code{16#cd#}, with the restrictions described for upper-half encoding as
1894 described above. The internal character code is the corresponding JIS
1895 character according to the standard algorithm for Shift-JIS
1896 conversion. Only characters defined in the JIS code set table can be
1897 used with this encoding method.
1898
1899 @item EUC Coding
1900 @cindex EUC Coding
1901 A wide character is represented by a two-character sequence
1902 @code{16#ab#} and
1903 @code{16#cd#}, with both characters being in the upper half. The internal
1904 character code is the corresponding JIS character according to the EUC
1905 encoding algorithm. Only characters defined in the JIS code set table
1906 can be used with this encoding method.
1907
1908 @item UTF-8 Coding
1909 A wide character is represented using
1910 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1911 10646-1/Am.2. Depending on the character value, the representation
1912 is a one, two, or three byte sequence:
1913 @smallexample
1914 @iftex
1915 @leftskip=.7cm
1916 @end iftex
1917 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1918 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1919 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1920
1921 @end smallexample
1922
1923 @noindent
1924 where the @var{xxx} bits correspond to the left-padded bits of the
1925 16-bit character value. Note that all lower half ASCII characters
1926 are represented as ASCII bytes and all upper half characters and
1927 other wide characters are represented as sequences of upper-half
1928 (The full UTF-8 scheme allows for encoding 31-bit characters as
1929 6-byte sequences, but in this implementation, all UTF-8 sequences
1930 of four or more bytes length will be treated as illegal).
1931 @item Brackets Coding
1932 In this encoding, a wide character is represented by the following eight
1933 character sequence:
1934
1935 @smallexample
1936 [ " a b c d " ]
1937 @end smallexample
1938
1939 @noindent
1940 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1941 characters (using uppercase letters) of the wide character code. For
1942 example, [``A345''] is used to represent the wide character with code
1943 @code{16#A345#}. It is also possible (though not required) to use the
1944 Brackets coding for upper half characters. For example, the code
1945 @code{16#A3#} can be represented as @code{[``A3'']}.
1946
1947 This scheme is compatible with use of the full Wide_Character set,
1948 and is also the method used for wide character encoding in the standard
1949 ACVC (Ada Compiler Validation Capability) test suite distributions.
1950
1951 @end table
1952
1953 @noindent
1954 Note: Some of these coding schemes do not permit the full use of the
1955 Ada character set. For example, neither Shift JIS, nor EUC allow the
1956 use of the upper half of the Latin-1 set.
1957
1958 @node File Naming Rules
1959 @section File Naming Rules
1960
1961 @noindent
1962 The default file name is determined by the name of the unit that the
1963 file contains. The name is formed by taking the full expanded name of
1964 the unit and replacing the separating dots with hyphens and using
1965 ^lowercase^uppercase^ for all letters.
1966
1967 An exception arises if the file name generated by the above rules starts
1968 with one of the characters
1969 @ifset vms
1970 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1971 @end ifset
1972 @ifclear vms
1973 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1974 @end ifclear
1975 and the second character is a
1976 minus. In this case, the character ^tilde^dollar sign^ is used in place
1977 of the minus. The reason for this special rule is to avoid clashes with
1978 the standard names for child units of the packages System, Ada,
1979 Interfaces, and GNAT, which use the prefixes
1980 @ifset vms
1981 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1982 @end ifset
1983 @ifclear vms
1984 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1985 @end ifclear
1986 respectively.
1987
1988 The file extension is @file{.ads} for a spec and
1989 @file{.adb} for a body. The following list shows some
1990 examples of these rules.
1991
1992 @table @file
1993 @item main.ads
1994 Main (spec)
1995 @item main.adb
1996 Main (body)
1997 @item arith_functions.ads
1998 Arith_Functions (package spec)
1999 @item arith_functions.adb
2000 Arith_Functions (package body)
2001 @item func-spec.ads
2002 Func.Spec (child package spec)
2003 @item func-spec.adb
2004 Func.Spec (child package body)
2005 @item main-sub.adb
2006 Sub (subunit of Main)
2007 @item ^a~bad.adb^A$BAD.ADB^
2008 A.Bad (child package body)
2009 @end table
2010
2011 @noindent
2012 Following these rules can result in excessively long
2013 file names if corresponding
2014 unit names are long (for example, if child units or subunits are
2015 heavily nested). An option is available to shorten such long file names
2016 (called file name ``krunching''). This may be particularly useful when
2017 programs being developed with GNAT are to be used on operating systems
2018 with limited file name lengths. @xref{Using gnatkr}.
2019
2020 Of course, no file shortening algorithm can guarantee uniqueness over
2021 all possible unit names; if file name krunching is used, it is your
2022 responsibility to ensure no name clashes occur. Alternatively you
2023 can specify the exact file names that you want used, as described
2024 in the next section. Finally, if your Ada programs are migrating from a
2025 compiler with a different naming convention, you can use the gnatchop
2026 utility to produce source files that follow the GNAT naming conventions.
2027 (For details @pxref{Renaming Files Using gnatchop}.)
2028
2029 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2030 systems, case is not significant. So for example on @code{Windows XP}
2031 if the canonical name is @code{main-sub.adb}, you can use the file name
2032 @code{Main-Sub.adb} instead. However, case is significant for other
2033 operating systems, so for example, if you want to use other than
2034 canonically cased file names on a Unix system, you need to follow
2035 the procedures described in the next section.
2036
2037 @node Using Other File Names
2038 @section Using Other File Names
2039 @cindex File names
2040
2041 @noindent
2042 In the previous section, we have described the default rules used by
2043 GNAT to determine the file name in which a given unit resides. It is
2044 often convenient to follow these default rules, and if you follow them,
2045 the compiler knows without being explicitly told where to find all
2046 the files it needs.
2047
2048 However, in some cases, particularly when a program is imported from
2049 another Ada compiler environment, it may be more convenient for the
2050 programmer to specify which file names contain which units. GNAT allows
2051 arbitrary file names to be used by means of the Source_File_Name pragma.
2052 The form of this pragma is as shown in the following examples:
2053 @cindex Source_File_Name pragma
2054
2055 @smallexample @c ada
2056 @cartouche
2057 pragma Source_File_Name (My_Utilities.Stacks,
2058   Spec_File_Name => "myutilst_a.ada");
2059 pragma Source_File_name (My_Utilities.Stacks,
2060   Body_File_Name => "myutilst.ada");
2061 @end cartouche
2062 @end smallexample
2063
2064 @noindent
2065 As shown in this example, the first argument for the pragma is the unit
2066 name (in this example a child unit). The second argument has the form
2067 of a named association. The identifier
2068 indicates whether the file name is for a spec or a body;
2069 the file name itself is given by a string literal.
2070
2071 The source file name pragma is a configuration pragma, which means that
2072 normally it will be placed in the @file{gnat.adc}
2073 file used to hold configuration
2074 pragmas that apply to a complete compilation environment.
2075 For more details on how the @file{gnat.adc} file is created and used
2076 see @ref{Handling of Configuration Pragmas}.
2077 @cindex @file{gnat.adc}
2078
2079 @ifclear vms
2080 GNAT allows completely arbitrary file names to be specified using the
2081 source file name pragma. However, if the file name specified has an
2082 extension other than @file{.ads} or @file{.adb} it is necessary to use
2083 a special syntax when compiling the file. The name in this case must be
2084 preceded by the special sequence @option{-x} followed by a space and the name
2085 of the language, here @code{ada}, as in:
2086
2087 @smallexample
2088 $ gcc -c -x ada peculiar_file_name.sim
2089 @end smallexample
2090 @end ifclear
2091
2092 @noindent
2093 @command{gnatmake} handles non-standard file names in the usual manner (the
2094 non-standard file name for the main program is simply used as the
2095 argument to gnatmake). Note that if the extension is also non-standard,
2096 then it must be included in the @command{gnatmake} command, it may not
2097 be omitted.
2098
2099 @node Alternative File Naming Schemes
2100 @section Alternative File Naming Schemes
2101 @cindex File naming schemes, alternative
2102 @cindex File names
2103
2104 In the previous section, we described the use of the @code{Source_File_Name}
2105 pragma to allow arbitrary names to be assigned to individual source files.
2106 However, this approach requires one pragma for each file, and especially in
2107 large systems can result in very long @file{gnat.adc} files, and also create
2108 a maintenance problem.
2109
2110 GNAT also provides a facility for specifying systematic file naming schemes
2111 other than the standard default naming scheme previously described. An
2112 alternative scheme for naming is specified by the use of
2113 @code{Source_File_Name} pragmas having the following format:
2114 @cindex Source_File_Name pragma
2115
2116 @smallexample @c ada
2117 pragma Source_File_Name (
2118    Spec_File_Name  => FILE_NAME_PATTERN
2119  @r{[},Casing          => CASING_SPEC@r{]}
2120  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2121
2122 pragma Source_File_Name (
2123    Body_File_Name  => FILE_NAME_PATTERN
2124  @r{[},Casing          => CASING_SPEC@r{]}
2125  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2126
2127 pragma Source_File_Name (
2128    Subunit_File_Name  => FILE_NAME_PATTERN
2129  @r{[},Casing             => CASING_SPEC@r{]}
2130  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2131
2132 FILE_NAME_PATTERN ::= STRING_LITERAL
2133 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2134 @end smallexample
2135
2136 @noindent
2137 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2138 It contains a single asterisk character, and the unit name is substituted
2139 systematically for this asterisk. The optional parameter
2140 @code{Casing} indicates
2141 whether the unit name is to be all upper-case letters, all lower-case letters,
2142 or mixed-case. If no
2143 @code{Casing} parameter is used, then the default is all
2144 ^lower-case^upper-case^.
2145
2146 The optional @code{Dot_Replacement} string is used to replace any periods
2147 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2148 argument is used then separating dots appear unchanged in the resulting
2149 file name.
2150 Although the above syntax indicates that the
2151 @code{Casing} argument must appear
2152 before the @code{Dot_Replacement} argument, but it
2153 is also permissible to write these arguments in the opposite order.
2154
2155 As indicated, it is possible to specify different naming schemes for
2156 bodies, specs, and subunits. Quite often the rule for subunits is the
2157 same as the rule for bodies, in which case, there is no need to give
2158 a separate @code{Subunit_File_Name} rule, and in this case the
2159 @code{Body_File_name} rule is used for subunits as well.
2160
2161 The separate rule for subunits can also be used to implement the rather
2162 unusual case of a compilation environment (e.g.@: a single directory) which
2163 contains a subunit and a child unit with the same unit name. Although
2164 both units cannot appear in the same partition, the Ada Reference Manual
2165 allows (but does not require) the possibility of the two units coexisting
2166 in the same environment.
2167
2168 The file name translation works in the following steps:
2169
2170 @itemize @bullet
2171
2172 @item
2173 If there is a specific @code{Source_File_Name} pragma for the given unit,
2174 then this is always used, and any general pattern rules are ignored.
2175
2176 @item
2177 If there is a pattern type @code{Source_File_Name} pragma that applies to
2178 the unit, then the resulting file name will be used if the file exists. If
2179 more than one pattern matches, the latest one will be tried first, and the
2180 first attempt resulting in a reference to a file that exists will be used.
2181
2182 @item
2183 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2184 for which the corresponding file exists, then the standard GNAT default
2185 naming rules are used.
2186
2187 @end itemize
2188
2189 @noindent
2190 As an example of the use of this mechanism, consider a commonly used scheme
2191 in which file names are all lower case, with separating periods copied
2192 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2193 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2194 two pragmas appear:
2195
2196 @smallexample @c ada
2197 pragma Source_File_Name
2198   (Spec_File_Name => "*.1.ada");
2199 pragma Source_File_Name
2200   (Body_File_Name => "*.2.ada");
2201 @end smallexample
2202
2203 @noindent
2204 The default GNAT scheme is actually implemented by providing the following
2205 default pragmas internally:
2206
2207 @smallexample @c ada
2208 pragma Source_File_Name
2209   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2210 pragma Source_File_Name
2211   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2212 @end smallexample
2213
2214 @noindent
2215 Our final example implements a scheme typically used with one of the
2216 Ada 83 compilers, where the separator character for subunits was ``__''
2217 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2218 by adding @file{.ADA}, and subunits by
2219 adding @file{.SEP}. All file names were
2220 upper case. Child units were not present of course since this was an
2221 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2222 the same double underscore separator for child units.
2223
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226   (Spec_File_Name => "*_.ADA",
2227    Dot_Replacement => "__",
2228    Casing = Uppercase);
2229 pragma Source_File_Name
2230   (Body_File_Name => "*.ADA",
2231    Dot_Replacement => "__",
2232    Casing = Uppercase);
2233 pragma Source_File_Name
2234   (Subunit_File_Name => "*.SEP",
2235    Dot_Replacement => "__",
2236    Casing = Uppercase);
2237 @end smallexample
2238
2239 @node Generating Object Files
2240 @section Generating Object Files
2241
2242 @noindent
2243 An Ada program consists of a set of source files, and the first step in
2244 compiling the program is to generate the corresponding object files.
2245 These are generated by compiling a subset of these source files.
2246 The files you need to compile are the following:
2247
2248 @itemize @bullet
2249 @item
2250 If a package spec has no body, compile the package spec to produce the
2251 object file for the package.
2252
2253 @item
2254 If a package has both a spec and a body, compile the body to produce the
2255 object file for the package. The source file for the package spec need
2256 not be compiled in this case because there is only one object file, which
2257 contains the code for both the spec and body of the package.
2258
2259 @item
2260 For a subprogram, compile the subprogram body to produce the object file
2261 for the subprogram. The spec, if one is present, is as usual in a
2262 separate file, and need not be compiled.
2263
2264 @item
2265 @cindex Subunits
2266 In the case of subunits, only compile the parent unit. A single object
2267 file is generated for the entire subunit tree, which includes all the
2268 subunits.
2269
2270 @item
2271 Compile child units independently of their parent units
2272 (though, of course, the spec of all the ancestor unit must be present in order
2273 to compile a child unit).
2274
2275 @item
2276 @cindex Generics
2277 Compile generic units in the same manner as any other units. The object
2278 files in this case are small dummy files that contain at most the
2279 flag used for elaboration checking. This is because GNAT always handles generic
2280 instantiation by means of macro expansion. However, it is still necessary to
2281 compile generic units, for dependency checking and elaboration purposes.
2282 @end itemize
2283
2284 @noindent
2285 The preceding rules describe the set of files that must be compiled to
2286 generate the object files for a program. Each object file has the same
2287 name as the corresponding source file, except that the extension is
2288 @file{.o} as usual.
2289
2290 You may wish to compile other files for the purpose of checking their
2291 syntactic and semantic correctness. For example, in the case where a
2292 package has a separate spec and body, you would not normally compile the
2293 spec. However, it is convenient in practice to compile the spec to make
2294 sure it is error-free before compiling clients of this spec, because such
2295 compilations will fail if there is an error in the spec.
2296
2297 GNAT provides an option for compiling such files purely for the
2298 purposes of checking correctness; such compilations are not required as
2299 part of the process of building a program. To compile a file in this
2300 checking mode, use the @option{-gnatc} switch.
2301
2302 @node Source Dependencies
2303 @section Source Dependencies
2304
2305 @noindent
2306 A given object file clearly depends on the source file which is compiled
2307 to produce it. Here we are using @dfn{depends} in the sense of a typical
2308 @code{make} utility; in other words, an object file depends on a source
2309 file if changes to the source file require the object file to be
2310 recompiled.
2311 In addition to this basic dependency, a given object may depend on
2312 additional source files as follows:
2313
2314 @itemize @bullet
2315 @item
2316 If a file being compiled @code{with}'s a unit @var{X}, the object file
2317 depends on the file containing the spec of unit @var{X}. This includes
2318 files that are @code{with}'ed implicitly either because they are parents
2319 of @code{with}'ed child units or they are run-time units required by the
2320 language constructs used in a particular unit.
2321
2322 @item
2323 If a file being compiled instantiates a library level generic unit, the
2324 object file depends on both the spec and body files for this generic
2325 unit.
2326
2327 @item
2328 If a file being compiled instantiates a generic unit defined within a
2329 package, the object file depends on the body file for the package as
2330 well as the spec file.
2331
2332 @item
2333 @findex Inline
2334 @cindex @option{-gnatn} switch
2335 If a file being compiled contains a call to a subprogram for which
2336 pragma @code{Inline} applies and inlining is activated with the
2337 @option{-gnatn} switch, the object file depends on the file containing the
2338 body of this subprogram as well as on the file containing the spec. Note
2339 that for inlining to actually occur as a result of the use of this switch,
2340 it is necessary to compile in optimizing mode.
2341
2342 @cindex @option{-gnatN} switch
2343 The use of @option{-gnatN} activates  inlining optimization
2344 that is performed by the front end of the compiler. This inlining does
2345 not require that the code generation be optimized. Like @option{-gnatn},
2346 the use of this switch generates additional dependencies.
2347
2348 When using a gcc-based back end (in practice this means using any version
2349 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2350 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2351 Historically front end inlining was more extensive than the gcc back end
2352 inlining, but that is no longer the case.
2353
2354 @item
2355 If an object file @file{O} depends on the proper body of a subunit through
2356 inlining or instantiation, it depends on the parent unit of the subunit.
2357 This means that any modification of the parent unit or one of its subunits
2358 affects the compilation of @file{O}.
2359
2360 @item
2361 The object file for a parent unit depends on all its subunit body files.
2362
2363 @item
2364 The previous two rules meant that for purposes of computing dependencies and
2365 recompilation, a body and all its subunits are treated as an indivisible whole.
2366
2367 @noindent
2368 These rules are applied transitively: if unit @code{A} @code{with}'s
2369 unit @code{B}, whose elaboration calls an inlined procedure in package
2370 @code{C}, the object file for unit @code{A} will depend on the body of
2371 @code{C}, in file @file{c.adb}.
2372
2373 The set of dependent files described by these rules includes all the
2374 files on which the unit is semantically dependent, as dictated by the
2375 Ada language standard. However, it is a superset of what the
2376 standard describes, because it includes generic, inline, and subunit
2377 dependencies.
2378
2379 An object file must be recreated by recompiling the corresponding source
2380 file if any of the source files on which it depends are modified. For
2381 example, if the @code{make} utility is used to control compilation,
2382 the rule for an Ada object file must mention all the source files on
2383 which the object file depends, according to the above definition.
2384 The determination of the necessary
2385 recompilations is done automatically when one uses @command{gnatmake}.
2386 @end itemize
2387
2388 @node The Ada Library Information Files
2389 @section The Ada Library Information Files
2390 @cindex Ada Library Information files
2391 @cindex @file{ALI} files
2392
2393 @noindent
2394 Each compilation actually generates two output files. The first of these
2395 is the normal object file that has a @file{.o} extension. The second is a
2396 text file containing full dependency information. It has the same
2397 name as the source file, but an @file{.ali} extension.
2398 This file is known as the Ada Library Information (@file{ALI}) file.
2399 The following information is contained in the @file{ALI} file.
2400
2401 @itemize @bullet
2402 @item
2403 Version information (indicates which version of GNAT was used to compile
2404 the unit(s) in question)
2405
2406 @item
2407 Main program information (including priority and time slice settings,
2408 as well as the wide character encoding used during compilation).
2409
2410 @item
2411 List of arguments used in the @command{gcc} command for the compilation
2412
2413 @item
2414 Attributes of the unit, including configuration pragmas used, an indication
2415 of whether the compilation was successful, exception model used etc.
2416
2417 @item
2418 A list of relevant restrictions applying to the unit (used for consistency)
2419 checking.
2420
2421 @item
2422 Categorization information (e.g.@: use of pragma @code{Pure}).
2423
2424 @item
2425 Information on all @code{with}'ed units, including presence of
2426 @code{Elaborate} or @code{Elaborate_All} pragmas.
2427
2428 @item
2429 Information from any @code{Linker_Options} pragmas used in the unit
2430
2431 @item
2432 Information on the use of @code{Body_Version} or @code{Version}
2433 attributes in the unit.
2434
2435 @item
2436 Dependency information. This is a list of files, together with
2437 time stamp and checksum information. These are files on which
2438 the unit depends in the sense that recompilation is required
2439 if any of these units are modified.
2440
2441 @item
2442 Cross-reference data. Contains information on all entities referenced
2443 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2444 provide cross-reference information.
2445
2446 @end itemize
2447
2448 @noindent
2449 For a full detailed description of the format of the @file{ALI} file,
2450 see the source of the body of unit @code{Lib.Writ}, contained in file
2451 @file{lib-writ.adb} in the GNAT compiler sources.
2452
2453 @node Binding an Ada Program
2454 @section Binding an Ada Program
2455
2456 @noindent
2457 When using languages such as C and C++, once the source files have been
2458 compiled the only remaining step in building an executable program
2459 is linking the object modules together. This means that it is possible to
2460 link an inconsistent version of a program, in which two units have
2461 included different versions of the same header.
2462
2463 The rules of Ada do not permit such an inconsistent program to be built.
2464 For example, if two clients have different versions of the same package,
2465 it is illegal to build a program containing these two clients.
2466 These rules are enforced by the GNAT binder, which also determines an
2467 elaboration order consistent with the Ada rules.
2468
2469 The GNAT binder is run after all the object files for a program have
2470 been created. It is given the name of the main program unit, and from
2471 this it determines the set of units required by the program, by reading the
2472 corresponding ALI files. It generates error messages if the program is
2473 inconsistent or if no valid order of elaboration exists.
2474
2475 If no errors are detected, the binder produces a main program, in Ada by
2476 default, that contains calls to the elaboration procedures of those
2477 compilation unit that require them, followed by
2478 a call to the main program. This Ada program is compiled to generate the
2479 object file for the main program. The name of
2480 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2481 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2482 main program unit.
2483
2484 Finally, the linker is used to build the resulting executable program,
2485 using the object from the main program from the bind step as well as the
2486 object files for the Ada units of the program.
2487
2488 @node Mixed Language Programming
2489 @section Mixed Language Programming
2490 @cindex Mixed Language Programming
2491
2492 @noindent
2493 This section describes how to develop a mixed-language program,
2494 specifically one that comprises units in both Ada and C.
2495
2496 @menu
2497 * Interfacing to C::
2498 * Calling Conventions::
2499 @end menu
2500
2501 @node Interfacing to C
2502 @subsection Interfacing to C
2503 @noindent
2504 Interfacing Ada with a foreign language such as C involves using
2505 compiler directives to import and/or export entity definitions in each
2506 language---using @code{extern} statements in C, for instance, and the
2507 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2508 A full treatment of these topics is provided in Appendix B, section 1
2509 of the Ada Reference Manual.
2510
2511 There are two ways to build a program using GNAT that contains some Ada
2512 sources and some foreign language sources, depending on whether or not
2513 the main subprogram is written in Ada.  Here is a source example with
2514 the main subprogram in Ada:
2515
2516 @smallexample
2517 /* file1.c */
2518 #include <stdio.h>
2519
2520 void print_num (int num)
2521 @{
2522   printf ("num is %d.\n", num);
2523   return;
2524 @}
2525
2526 /* file2.c */
2527
2528 /* num_from_Ada is declared in my_main.adb */
2529 extern int num_from_Ada;
2530
2531 int get_num (void)
2532 @{
2533   return num_from_Ada;
2534 @}
2535 @end smallexample
2536
2537 @smallexample @c ada
2538 --  my_main.adb
2539 procedure My_Main is
2540
2541    --  Declare then export an Integer entity called num_from_Ada
2542    My_Num : Integer := 10;
2543    pragma Export (C, My_Num, "num_from_Ada");
2544
2545    --  Declare an Ada function spec for Get_Num, then use
2546    --  C function get_num for the implementation.
2547    function Get_Num return Integer;
2548    pragma Import (C, Get_Num, "get_num");
2549
2550    --  Declare an Ada procedure spec for Print_Num, then use
2551    --  C function print_num for the implementation.
2552    procedure Print_Num (Num : Integer);
2553    pragma Import (C, Print_Num, "print_num");
2554
2555 begin
2556    Print_Num (Get_Num);
2557 end My_Main;
2558 @end smallexample
2559
2560 @enumerate
2561 @item
2562 To build this example, first compile the foreign language files to
2563 generate object files:
2564 @smallexample
2565 ^gcc -c file1.c^gcc -c FILE1.C^
2566 ^gcc -c file2.c^gcc -c FILE2.C^
2567 @end smallexample
2568
2569 @item
2570 Then, compile the Ada units to produce a set of object files and ALI
2571 files:
2572 @smallexample
2573 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2574 @end smallexample
2575
2576 @item
2577 Run the Ada binder on the Ada main program:
2578 @smallexample
2579 gnatbind my_main.ali
2580 @end smallexample
2581
2582 @item
2583 Link the Ada main program, the Ada objects and the other language
2584 objects:
2585 @smallexample
2586 gnatlink my_main.ali file1.o file2.o
2587 @end smallexample
2588 @end enumerate
2589
2590 The last three steps can be grouped in a single command:
2591 @smallexample
2592 gnatmake my_main.adb -largs file1.o file2.o
2593 @end smallexample
2594
2595 @cindex Binder output file
2596 @noindent
2597 If the main program is in a language other than Ada, then you may have
2598 more than one entry point into the Ada subsystem. You must use a special
2599 binder option to generate callable routines that initialize and
2600 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2601 Calls to the initialization and finalization routines must be inserted
2602 in the main program, or some other appropriate point in the code. The
2603 call to initialize the Ada units must occur before the first Ada
2604 subprogram is called, and the call to finalize the Ada units must occur
2605 after the last Ada subprogram returns. The binder will place the
2606 initialization and finalization subprograms into the
2607 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2608 sources.  To illustrate, we have the following example:
2609
2610 @smallexample
2611 /* main.c */
2612 extern void adainit (void);
2613 extern void adafinal (void);
2614 extern int add (int, int);
2615 extern int sub (int, int);
2616
2617 int main (int argc, char *argv[])
2618 @{
2619   int a = 21, b = 7;
2620
2621   adainit();
2622
2623   /* Should print "21 + 7 = 28" */
2624   printf ("%d + %d = %d\n", a, b, add (a, b));
2625   /* Should print "21 - 7 = 14" */
2626   printf ("%d - %d = %d\n", a, b, sub (a, b));
2627
2628   adafinal();
2629 @}
2630 @end smallexample
2631
2632 @smallexample @c ada
2633 --  unit1.ads
2634 package Unit1 is
2635    function Add (A, B : Integer) return Integer;
2636    pragma Export (C, Add, "add");
2637 end Unit1;
2638
2639 --  unit1.adb
2640 package body Unit1 is
2641    function Add (A, B : Integer) return Integer is
2642    begin
2643       return A + B;
2644    end Add;
2645 end Unit1;
2646
2647 --  unit2.ads
2648 package Unit2 is
2649    function Sub (A, B : Integer) return Integer;
2650    pragma Export (C, Sub, "sub");
2651 end Unit2;
2652
2653 --  unit2.adb
2654 package body Unit2 is
2655    function Sub (A, B : Integer) return Integer is
2656    begin
2657       return A - B;
2658    end Sub;
2659 end Unit2;
2660 @end smallexample
2661
2662 @enumerate
2663 @item
2664 The build procedure for this application is similar to the last
2665 example's.  First, compile the foreign language files to generate object
2666 files:
2667 @smallexample
2668 ^gcc -c main.c^gcc -c main.c^
2669 @end smallexample
2670
2671 @item
2672 Next, compile the Ada units to produce a set of object files and ALI
2673 files:
2674 @smallexample
2675 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2676 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2677 @end smallexample
2678
2679 @item
2680 Run the Ada binder on every generated ALI file.  Make sure to use the
2681 @option{-n} option to specify a foreign main program:
2682 @smallexample
2683 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2684 @end smallexample
2685
2686 @item
2687 Link the Ada main program, the Ada objects and the foreign language
2688 objects. You need only list the last ALI file here:
2689 @smallexample
2690 gnatlink unit2.ali main.o -o exec_file
2691 @end smallexample
2692
2693 This procedure yields a binary executable called @file{exec_file}.
2694 @end enumerate
2695
2696 @noindent
2697 Depending on the circumstances (for example when your non-Ada main object
2698 does not provide symbol @code{main}), you may also need to instruct the
2699 GNAT linker not to include the standard startup objects by passing the
2700 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2701
2702 @node Calling Conventions
2703 @subsection Calling Conventions
2704 @cindex Foreign Languages
2705 @cindex Calling Conventions
2706 GNAT follows standard calling sequence conventions and will thus interface
2707 to any other language that also follows these conventions. The following
2708 Convention identifiers are recognized by GNAT:
2709
2710 @table @code
2711 @cindex Interfacing to Ada
2712 @cindex Other Ada compilers
2713 @cindex Convention Ada
2714 @item Ada
2715 This indicates that the standard Ada calling sequence will be
2716 used and all Ada data items may be passed without any limitations in the
2717 case where GNAT is used to generate both the caller and callee. It is also
2718 possible to mix GNAT generated code and code generated by another Ada
2719 compiler. In this case, the data types should be restricted to simple
2720 cases, including primitive types. Whether complex data types can be passed
2721 depends on the situation. Probably it is safe to pass simple arrays, such
2722 as arrays of integers or floats. Records may or may not work, depending
2723 on whether both compilers lay them out identically. Complex structures
2724 involving variant records, access parameters, tasks, or protected types,
2725 are unlikely to be able to be passed.
2726
2727 Note that in the case of GNAT running
2728 on a platform that supports HP Ada 83, a higher degree of compatibility
2729 can be guaranteed, and in particular records are layed out in an identical
2730 manner in the two compilers. Note also that if output from two different
2731 compilers is mixed, the program is responsible for dealing with elaboration
2732 issues. Probably the safest approach is to write the main program in the
2733 version of Ada other than GNAT, so that it takes care of its own elaboration
2734 requirements, and then call the GNAT-generated adainit procedure to ensure
2735 elaboration of the GNAT components. Consult the documentation of the other
2736 Ada compiler for further details on elaboration.
2737
2738 However, it is not possible to mix the tasking run time of GNAT and
2739 HP Ada 83, All the tasking operations must either be entirely within
2740 GNAT compiled sections of the program, or entirely within HP Ada 83
2741 compiled sections of the program.
2742
2743 @cindex Interfacing to Assembly
2744 @cindex Convention Assembler
2745 @item Assembler
2746 Specifies assembler as the convention. In practice this has the
2747 same effect as convention Ada (but is not equivalent in the sense of being
2748 considered the same convention).
2749
2750 @cindex Convention Asm
2751 @findex Asm
2752 @item Asm
2753 Equivalent to Assembler.
2754
2755 @cindex Interfacing to COBOL
2756 @cindex Convention COBOL
2757 @findex COBOL
2758 @item COBOL
2759 Data will be passed according to the conventions described
2760 in section B.4 of the Ada Reference Manual.
2761
2762 @findex C
2763 @cindex Interfacing to C
2764 @cindex Convention C
2765 @item C
2766 Data will be passed according to the conventions described
2767 in section B.3 of the Ada Reference Manual.
2768
2769 A note on interfacing to a C ``varargs'' function:
2770 @findex C varargs function
2771 @cindex Interfacing to C varargs function
2772 @cindex varargs function interfaces
2773
2774 @itemize @bullet
2775 @item
2776 In C, @code{varargs} allows a function to take a variable number of
2777 arguments. There is no direct equivalent in this to Ada. One
2778 approach that can be used is to create a C wrapper for each
2779 different profile and then interface to this C wrapper. For
2780 example, to print an @code{int} value using @code{printf},
2781 create a C function @code{printfi} that takes two arguments, a
2782 pointer to a string and an int, and calls @code{printf}.
2783 Then in the Ada program, use pragma @code{Import} to
2784 interface to @code{printfi}.
2785
2786 @item
2787 It may work on some platforms to directly interface to
2788 a @code{varargs} function by providing a specific Ada profile
2789 for a particular call. However, this does not work on
2790 all platforms, since there is no guarantee that the
2791 calling sequence for a two argument normal C function
2792 is the same as for calling a @code{varargs} C function with
2793 the same two arguments.
2794 @end itemize
2795
2796 @cindex Convention Default
2797 @findex Default
2798 @item Default
2799 Equivalent to C.
2800
2801 @cindex Convention External
2802 @findex External
2803 @item External
2804 Equivalent to C.
2805
2806 @ifclear vms
2807 @findex C++
2808 @cindex Interfacing to C++
2809 @cindex Convention C++
2810 @item C_Plus_Plus (or CPP)
2811 This stands for C++. For most purposes this is identical to C.
2812 See the separate description of the specialized GNAT pragmas relating to
2813 C++ interfacing for further details.
2814 @end ifclear
2815
2816 @findex Fortran
2817 @cindex Interfacing to Fortran
2818 @cindex Convention Fortran
2819 @item Fortran
2820 Data will be passed according to the conventions described
2821 in section B.5 of the Ada Reference Manual.
2822
2823 @item Intrinsic
2824 This applies to an intrinsic operation, as defined in the Ada
2825 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2826 this means that the body of the subprogram is provided by the compiler itself,
2827 usually by means of an efficient code sequence, and that the user does not
2828 supply an explicit body for it. In an application program, the pragma may
2829 be applied to the following sets of names:
2830
2831 @itemize @bullet
2832 @item
2833 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2834 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2835 two formal parameters. The
2836 first one must be a signed integer type or a modular type with a binary
2837 modulus, and the second parameter must be of type Natural.
2838 The return type must be the same as the type of the first argument. The size
2839 of this type can only be 8, 16, 32, or 64.
2840
2841 @item
2842 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2843 The corresponding operator declaration must have parameters and result type
2844 that have the same root numeric type (for example, all three are long_float
2845 types). This simplifies the definition of operations that use type checking
2846 to perform dimensional checks:
2847
2848 @smallexample @c ada
2849 type Distance is new Long_Float;
2850 type Time     is new Long_Float;
2851 type Velocity is new Long_Float;
2852 function "/" (D : Distance; T : Time)
2853   return Velocity;
2854 pragma Import (Intrinsic, "/");
2855 @end smallexample
2856
2857 @noindent
2858 This common idiom is often programmed with a generic definition and an
2859 explicit body. The pragma makes it simpler to introduce such declarations.
2860 It incurs no overhead in compilation time or code size, because it is
2861 implemented as a single machine instruction.
2862
2863 @item
2864 General subprogram entities, to bind an Ada subprogram declaration to
2865 a compiler builtin by name with back-ends where such interfaces are
2866 available. A typical example is the set of ``__builtin'' functions
2867 exposed by the GCC back-end, as in the following example:
2868
2869 @smallexample @c ada
2870    function builtin_sqrt (F : Float) return Float;
2871    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2872 @end smallexample
2873
2874 Most of the GCC builtins are accessible this way, and as for other
2875 import conventions (e.g. C), it is the user's responsibility to ensure
2876 that the Ada subprogram profile matches the underlying builtin
2877 expectations.
2878 @end itemize
2879
2880 @noindent
2881
2882 @ifset unw
2883 @findex Stdcall
2884 @cindex Convention Stdcall
2885 @item Stdcall
2886 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2887 and specifies that the @code{Stdcall} calling sequence will be used,
2888 as defined by the NT API. Nevertheless, to ease building
2889 cross-platform bindings this convention will be handled as a @code{C} calling
2890 convention on non-Windows platforms.
2891
2892 @findex DLL
2893 @cindex Convention DLL
2894 @item DLL
2895 This is equivalent to @code{Stdcall}.
2896
2897 @findex Win32
2898 @cindex Convention Win32
2899 @item Win32
2900 This is equivalent to @code{Stdcall}.
2901 @end ifset
2902
2903 @findex Stubbed
2904 @cindex Convention Stubbed
2905 @item Stubbed
2906 This is a special convention that indicates that the compiler
2907 should provide a stub body that raises @code{Program_Error}.
2908 @end table
2909
2910 @noindent
2911 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2912 that can be used to parameterize conventions and allow additional synonyms
2913 to be specified. For example if you have legacy code in which the convention
2914 identifier Fortran77 was used for Fortran, you can use the configuration
2915 pragma:
2916
2917 @smallexample @c ada
2918 pragma Convention_Identifier (Fortran77, Fortran);
2919 @end smallexample
2920
2921 @noindent
2922 And from now on the identifier Fortran77 may be used as a convention
2923 identifier (for example in an @code{Import} pragma) with the same
2924 meaning as Fortran.
2925
2926 @ifclear vms
2927 @node Building Mixed Ada & C++ Programs
2928 @section Building Mixed Ada and C++ Programs
2929
2930 @noindent
2931 A programmer inexperienced with mixed-language development may find that
2932 building an application containing both Ada and C++ code can be a
2933 challenge.  This section gives a few
2934 hints that should make this task easier. The first section addresses
2935 the differences between interfacing with C and interfacing with C++.
2936 The second section
2937 looks into the delicate problem of linking the complete application from
2938 its Ada and C++ parts. The last section gives some hints on how the GNAT
2939 run-time library can be adapted in order to allow inter-language dispatching
2940 with a new C++ compiler.
2941
2942 @menu
2943 * Interfacing to C++::
2944 * Linking a Mixed C++ & Ada Program::
2945 * A Simple Example::
2946 * Interfacing with C++ constructors::
2947 * Interfacing with C++ at the Class Level::
2948 @end menu
2949
2950 @node Interfacing to C++
2951 @subsection Interfacing to C++
2952
2953 @noindent
2954 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2955 generating code that is compatible with the G++ Application Binary
2956 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2957
2958 @noindent
2959 Interfacing can be done at 3 levels: simple data, subprograms, and
2960 classes. In the first two cases, GNAT offers a specific @code{Convention
2961 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2962 Usually, C++ mangles the names of subprograms. To generate proper mangled
2963 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2964 This problem can also be addressed manually in two ways:
2965
2966 @itemize @bullet
2967 @item
2968 by modifying the C++ code in order to force a C convention using
2969 the @code{extern "C"} syntax.
2970
2971 @item
2972 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2973 Link_Name argument of the pragma import.
2974 @end itemize
2975
2976 @noindent
2977 Interfacing at the class level can be achieved by using the GNAT specific
2978 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2979 gnat_rm, GNAT Reference Manual}, for additional information.
2980
2981 @node Linking a Mixed C++ & Ada Program
2982 @subsection Linking a Mixed C++ & Ada Program
2983
2984 @noindent
2985 Usually the linker of the C++ development system must be used to link
2986 mixed applications because most C++ systems will resolve elaboration
2987 issues (such as calling constructors on global class instances)
2988 transparently during the link phase. GNAT has been adapted to ease the
2989 use of a foreign linker for the last phase. Three cases can be
2990 considered:
2991 @enumerate
2992
2993 @item
2994 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2995 The C++ linker can simply be called by using the C++ specific driver
2996 called @code{g++}.
2997
2998 Note that if the C++ code uses inline functions, you will need to
2999 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3000 order to provide an existing function implementation that the Ada code can
3001 link with.
3002
3003 @smallexample
3004 $ g++ -c -fkeep-inline-functions file1.C
3005 $ g++ -c -fkeep-inline-functions file2.C
3006 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3007 @end smallexample
3008
3009 @item
3010 Using GNAT and G++ from two different GCC installations: If both
3011 compilers are on the @env{PATH}, the previous method may be used. It is
3012 important to note that environment variables such as
3013 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3014 @env{GCC_ROOT} will affect both compilers
3015 at the same time and may make one of the two compilers operate
3016 improperly if set during invocation of the wrong compiler.  It is also
3017 very important that the linker uses the proper @file{libgcc.a} GCC
3018 library -- that is, the one from the C++ compiler installation. The
3019 implicit link command as suggested in the @command{gnatmake} command
3020 from the former example can be replaced by an explicit link command with
3021 the full-verbosity option in order to verify which library is used:
3022 @smallexample
3023 $ gnatbind ada_unit
3024 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3025 @end smallexample
3026 If there is a problem due to interfering environment variables, it can
3027 be worked around by using an intermediate script. The following example
3028 shows the proper script to use when GNAT has not been installed at its
3029 default location and g++ has been installed at its default location:
3030
3031 @smallexample
3032 $ cat ./my_script
3033 #!/bin/sh
3034 unset BINUTILS_ROOT
3035 unset GCC_ROOT
3036 c++ $*
3037 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3038 @end smallexample
3039
3040 @item
3041 Using a non-GNU C++ compiler: The commands previously described can be
3042 used to insure that the C++ linker is used. Nonetheless, you need to add
3043 a few more parameters to the link command line, depending on the exception
3044 mechanism used.
3045
3046 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3047 to the libgcc libraries are required:
3048
3049 @smallexample
3050 $ cat ./my_script
3051 #!/bin/sh
3052 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3053 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3054 @end smallexample
3055
3056 Where CC is the name of the non-GNU C++ compiler.
3057
3058 If the @code{zero cost} exception mechanism is used, and the platform
3059 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3060 paths to more objects are required:
3061
3062 @smallexample
3063 $ cat ./my_script
3064 #!/bin/sh
3065 CC `gcc -print-file-name=crtbegin.o` $* \
3066 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3067 `gcc -print-file-name=crtend.o`
3068 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3069 @end smallexample
3070
3071 If the @code{zero cost} exception mechanism is used, and the platform
3072 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3073 Tru64 or AIX), the simple approach described above will not work and
3074 a pre-linking phase using GNAT will be necessary.
3075
3076 @end enumerate
3077
3078 Another alternative is to use the @command{gprbuild} multi-language builder
3079 which has a large knowledge base and knows how to link Ada and C++ code
3080 together automatically in most cases.
3081
3082 @node A Simple Example
3083 @subsection  A Simple Example
3084 @noindent
3085 The following example, provided as part of the GNAT examples, shows how
3086 to achieve procedural interfacing between Ada and C++ in both
3087 directions. The C++ class A has two methods. The first method is exported
3088 to Ada by the means of an extern C wrapper function. The second method
3089 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3090 a limited record with a layout comparable to the C++ class. The Ada
3091 subprogram, in turn, calls the C++ method. So, starting from the C++
3092 main program, the process passes back and forth between the two
3093 languages.
3094
3095 @noindent
3096 Here are the compilation commands:
3097 @smallexample
3098 $ gnatmake -c simple_cpp_interface
3099 $ g++ -c cpp_main.C
3100 $ g++ -c ex7.C
3101 $ gnatbind -n simple_cpp_interface
3102 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3103       -lstdc++ ex7.o cpp_main.o
3104 @end smallexample
3105
3106 @noindent
3107 Here are the corresponding sources:
3108 @smallexample
3109
3110 //cpp_main.C
3111
3112 #include "ex7.h"
3113
3114 extern "C" @{
3115   void adainit (void);
3116   void adafinal (void);
3117   void method1 (A *t);
3118 @}
3119
3120 void method1 (A *t)
3121 @{
3122   t->method1 ();
3123 @}
3124
3125 int main ()
3126 @{
3127   A obj;
3128   adainit ();
3129   obj.method2 (3030);
3130   adafinal ();
3131 @}
3132
3133 //ex7.h
3134
3135 class Origin @{
3136  public:
3137   int o_value;
3138 @};
3139 class A : public Origin @{
3140  public:
3141   void method1 (void);
3142   void method2 (int v);
3143   A();
3144   int   a_value;
3145 @};
3146
3147 //ex7.C
3148
3149 #include "ex7.h"
3150 #include <stdio.h>
3151
3152 extern "C" @{ void ada_method2 (A *t, int v);@}
3153
3154 void A::method1 (void)
3155 @{
3156   a_value = 2020;
3157   printf ("in A::method1, a_value = %d \n",a_value);
3158
3159 @}
3160
3161 void A::method2 (int v)
3162 @{
3163    ada_method2 (this, v);
3164    printf ("in A::method2, a_value = %d \n",a_value);
3165
3166 @}
3167
3168 A::A(void)
3169 @{
3170    a_value = 1010;
3171   printf ("in A::A, a_value = %d \n",a_value);
3172 @}
3173 @end smallexample
3174
3175 @smallexample @c ada
3176 -- Ada sources
3177 package body Simple_Cpp_Interface is
3178
3179    procedure Ada_Method2 (This : in out A; V : Integer) is
3180    begin
3181       Method1 (This);
3182       This.A_Value := V;
3183    end Ada_Method2;
3184
3185 end Simple_Cpp_Interface;
3186
3187 with System;
3188 package Simple_Cpp_Interface is
3189    type A is limited
3190       record
3191          Vptr    : System.Address;
3192          O_Value : Integer;
3193          A_Value : Integer;
3194       end record;
3195    pragma Convention (C, A);
3196
3197    procedure Method1 (This : in out A);
3198    pragma Import (C, Method1);
3199
3200    procedure Ada_Method2 (This : in out A; V : Integer);
3201    pragma Export (C, Ada_Method2);
3202
3203 end Simple_Cpp_Interface;
3204 @end smallexample
3205
3206 @node Interfacing with C++ constructors
3207 @subsection Interfacing with C++ constructors
3208 @noindent
3209
3210 In order to interface with C++ constructors GNAT provides the
3211 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3212 gnat_rm, GNAT Reference Manual}, for additional information).
3213 In this section we present some common uses of C++ constructors
3214 in mixed-languages programs in GNAT.
3215
3216 Let us assume that we need to interface with the following
3217 C++ class:
3218
3219 @smallexample
3220 @b{class} Root @{
3221 @b{public}:
3222   int  a_value;
3223   int  b_value;
3224   @b{virtual} int Get_Value ();
3225   Root();              // Default constructor
3226   Root(int v);         // 1st non-default constructor
3227   Root(int v, int w);  // 2nd non-default constructor
3228 @};
3229 @end smallexample
3230
3231 For this purpose we can write the following package spec (further
3232 information on how to build this spec is available in
3233 @ref{Interfacing with C++ at the Class Level} and
3234 @ref{Generating Ada Bindings for C and C++ headers}).
3235
3236 @smallexample @c ada
3237 with Interfaces.C; use Interfaces.C;
3238 package Pkg_Root is
3239   type Root is tagged limited record
3240      A_Value : int;
3241      B_Value : int;
3242   end record;
3243   pragma Import (CPP, Root);
3244
3245   function Get_Value (Obj : Root) return int;
3246   pragma Import (CPP, Get_Value);
3247
3248   function Constructor return Root;
3249   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3250
3251   function Constructor (v : Integer) return Root;
3252   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3253
3254   function Constructor (v, w : Integer) return Root;
3255   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3256 end Pkg_Root;
3257 @end smallexample
3258
3259 On the Ada side the constructor is represented by a function (whose
3260 name is arbitrary) that returns the classwide type corresponding to
3261 the imported C++ class. Although the constructor is described as a
3262 function, it is typically a procedure with an extra implicit argument
3263 (the object being initialized) at the implementation level. GNAT
3264 issues the appropriate call, whatever it is, to get the object
3265 properly initialized.
3266
3267 Constructors can only appear in the following contexts:
3268
3269 @itemize @bullet
3270 @item
3271 On the right side of an initialization of an object of type @var{T}.
3272 @item
3273 On the right side of an initialization of a record component of type @var{T}.
3274 @item
3275 In an Ada 2005 limited aggregate.
3276 @item
3277 In an Ada 2005 nested limited aggregate.
3278 @item
3279 In an Ada 2005 limited aggregate that initializes an object built in
3280 place by an extended return statement.
3281 @end itemize
3282
3283 @noindent
3284 In a declaration of an object whose type is a class imported from C++,
3285 either the default C++ constructor is implicitly called by GNAT, or
3286 else the required C++ constructor must be explicitly called in the
3287 expression that initializes the object. For example:
3288
3289 @smallexample @c ada
3290   Obj1 : Root;
3291   Obj2 : Root := Constructor;
3292   Obj3 : Root := Constructor (v => 10);
3293   Obj4 : Root := Constructor (30, 40);
3294 @end smallexample
3295
3296 The first two declarations are equivalent: in both cases the default C++
3297 constructor is invoked (in the former case the call to the constructor is
3298 implicit, and in the latter case the call is explicit in the object
3299 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3300 that takes an integer argument, and @code{Obj4} is initialized by the
3301 non-default C++ constructor that takes two integers.
3302
3303 Let us derive the imported C++ class in the Ada side. For example:
3304
3305 @smallexample @c ada
3306   type DT is new Root with record
3307      C_Value : Natural := 2009;
3308   end record;
3309 @end smallexample
3310
3311 In this case the components DT inherited from the C++ side must be
3312 initialized by a C++ constructor, and the additional Ada components
3313 of type DT are initialized by GNAT. The initialization of such an
3314 object is done either by default, or by means of a function returning
3315 an aggregate of type DT, or by means of an extension aggregate.
3316
3317 @smallexample @c ada
3318   Obj5 : DT;
3319   Obj6 : DT := Function_Returning_DT (50);
3320   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3321 @end smallexample
3322
3323 The declaration of @code{Obj5} invokes the default constructors: the
3324 C++ default constructor of the parent type takes care of the initialization
3325 of the components inherited from Root, and GNAT takes care of the default
3326 initialization of the additional Ada components of type DT (that is,
3327 @code{C_Value} is initialized to value 2009). The order of invocation of
3328 the constructors is consistent with the order of elaboration required by
3329 Ada and C++. That is, the constructor of the parent type is always called
3330 before the constructor of the derived type.
3331
3332 Let us now consider a record that has components whose type is imported
3333 from C++. For example:
3334
3335 @smallexample @c ada
3336   type Rec1 is limited record
3337      Data1 : Root := Constructor (10);
3338      Value : Natural := 1000;
3339   end record;
3340
3341   type Rec2 (D : Integer := 20) is limited record
3342      Rec   : Rec1;
3343      Data2 : Root := Constructor (D, 30);
3344   end record;
3345 @end smallexample
3346
3347 The initialization of an object of type @code{Rec2} will call the
3348 non-default C++ constructors specified for the imported components.
3349 For example:
3350
3351 @smallexample @c ada
3352   Obj8 : Rec2 (40);
3353 @end smallexample
3354
3355 Using Ada 2005 we can use limited aggregates to initialize an object
3356 invoking C++ constructors that differ from those specified in the type
3357 declarations. For example:
3358
3359 @smallexample @c ada
3360   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3361                           others => <>),
3362                   others => <>);
3363 @end smallexample
3364
3365 The above declaration uses an Ada 2005 limited aggregate to
3366 initialize @code{Obj9}, and the C++ constructor that has two integer
3367 arguments is invoked to initialize the @code{Data1} component instead
3368 of the constructor specified in the declaration of type @code{Rec1}. In
3369 Ada 2005 the box in the aggregate indicates that unspecified components
3370 are initialized using the expression (if any) available in the component
3371 declaration. That is, in this case discriminant @code{D} is initialized
3372 to value @code{20}, @code{Value} is initialized to value 1000, and the
3373 non-default C++ constructor that handles two integers takes care of
3374 initializing component @code{Data2} with values @code{20,30}.
3375
3376 In Ada 2005 we can use the extended return statement to build the Ada
3377 equivalent to C++ non-default constructors. For example:
3378
3379 @smallexample @c ada
3380   function Constructor (V : Integer) return Rec2 is
3381   begin
3382      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3383                                    others => <>),
3384                            others => <>) do
3385         --  Further actions required for construction of
3386         --  objects of type Rec2
3387         ...
3388      end record;
3389   end Constructor;
3390 @end smallexample
3391
3392 In this example the extended return statement construct is used to
3393 build in place the returned object whose components are initialized
3394 by means of a limited aggregate. Any further action associated with
3395 the constructor can be placed inside the construct.
3396
3397 @node Interfacing with C++ at the Class Level
3398 @subsection Interfacing with C++ at the Class Level
3399 @noindent
3400 In this section we demonstrate the GNAT features for interfacing with
3401 C++ by means of an example making use of Ada 2005 abstract interface
3402 types. This example consists of a classification of animals; classes
3403 have been used to model our main classification of animals, and
3404 interfaces provide support for the management of secondary
3405 classifications. We first demonstrate a case in which the types and
3406 constructors are defined on the C++ side and imported from the Ada
3407 side, and latter the reverse case.
3408
3409 The root of our derivation will be the @code{Animal} class, with a
3410 single private attribute (the @code{Age} of the animal) and two public
3411 primitives to set and get the value of this attribute.
3412
3413 @smallexample
3414 @b{class} Animal @{
3415  @b{public}:
3416    @b{virtual} void Set_Age (int New_Age);
3417    @b{virtual} int Age ();
3418  @b{private}:
3419    int Age_Count;
3420 @};
3421 @end smallexample
3422
3423 Abstract interface types are defined in C++ by means of classes with pure
3424 virtual functions and no data members. In our example we will use two
3425 interfaces that provide support for the common management of @code{Carnivore}
3426 and @code{Domestic} animals:
3427
3428 @smallexample
3429 @b{class} Carnivore @{
3430 @b{public}:
3431    @b{virtual} int Number_Of_Teeth () = 0;
3432 @};
3433
3434 @b{class} Domestic @{
3435 @b{public}:
3436    @b{virtual void} Set_Owner (char* Name) = 0;
3437 @};
3438 @end smallexample
3439
3440 Using these declarations, we can now say that a @code{Dog} is an animal that is
3441 both Carnivore and Domestic, that is:
3442
3443 @smallexample
3444 @b{class} Dog : Animal, Carnivore, Domestic @{
3445  @b{public}:
3446    @b{virtual} int  Number_Of_Teeth ();
3447    @b{virtual} void Set_Owner (char* Name);
3448
3449    Dog(); // Constructor
3450  @b{private}:
3451    int  Tooth_Count;
3452    char *Owner;
3453 @};
3454 @end smallexample
3455
3456 In the following examples we will assume that the previous declarations are
3457 located in a file named @code{animals.h}. The following package demonstrates
3458 how to import these C++ declarations from the Ada side:
3459
3460 @smallexample @c ada
3461 with Interfaces.C.Strings; use Interfaces.C.Strings;
3462 package Animals is
3463   type Carnivore is interface;
3464   pragma Convention (C_Plus_Plus, Carnivore);
3465   function Number_Of_Teeth (X : Carnivore)
3466      return Natural is abstract;
3467
3468   type Domestic is interface;
3469   pragma Convention (C_Plus_Plus, Set_Owner);
3470   procedure Set_Owner
3471     (X    : in out Domestic;
3472      Name : Chars_Ptr) is abstract;
3473
3474   type Animal is tagged record
3475     Age : Natural := 0;
3476   end record;
3477   pragma Import (C_Plus_Plus, Animal);
3478
3479   procedure Set_Age (X : in out Animal; Age : Integer);
3480   pragma Import (C_Plus_Plus, Set_Age);
3481
3482   function Age (X : Animal) return Integer;
3483   pragma Import (C_Plus_Plus, Age);
3484
3485   type Dog is new Animal and Carnivore and Domestic with record
3486     Tooth_Count : Natural;
3487     Owner       : String (1 .. 30);
3488   end record;
3489   pragma Import (C_Plus_Plus, Dog);
3490
3491   function Number_Of_Teeth (A : Dog) return Integer;
3492   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3493
3494   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3495   pragma Import (C_Plus_Plus, Set_Owner);
3496
3497   function New_Dog return Dog;
3498   pragma CPP_Constructor (New_Dog);
3499   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3500 end Animals;
3501 @end smallexample
3502
3503 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3504 interfacing with these C++ classes is easy. The only requirement is that all
3505 the primitives and components must be declared exactly in the same order in
3506 the two languages.
3507
3508 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3509 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3510 the arguments to the called primitives will be the same as for C++. For the
3511 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3512 to indicate that they have been defined on the C++ side; this is required
3513 because the dispatch table associated with these tagged types will be built
3514 in the C++ side and therefore will not contain the predefined Ada primitives
3515 which Ada would otherwise expect.
3516
3517 As the reader can see there is no need to indicate the C++ mangled names
3518 associated with each subprogram because it is assumed that all the calls to
3519 these primitives will be dispatching calls. The only exception is the
3520 constructor, which must be registered with the compiler by means of
3521 @code{pragma CPP_Constructor} and needs to provide its associated C++
3522 mangled name because the Ada compiler generates direct calls to it.
3523
3524 With the above packages we can now declare objects of type Dog on the Ada side
3525 and dispatch calls to the corresponding subprograms on the C++ side. We can
3526 also extend the tagged type Dog with further fields and primitives, and
3527 override some of its C++ primitives on the Ada side. For example, here we have
3528 a type derivation defined on the Ada side that inherits all the dispatching
3529 primitives of the ancestor from the C++ side.
3530
3531 @smallexample
3532 @b{with} Animals; @b{use} Animals;
3533 @b{package} Vaccinated_Animals @b{is}
3534   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3535   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3536 @b{end} Vaccinated_Animals;
3537 @end smallexample
3538
3539 It is important to note that, because of the ABI compatibility, the programmer
3540 does not need to add any further information to indicate either the object
3541 layout or the dispatch table entry associated with each dispatching operation.
3542
3543 Now let us define all the types and constructors on the Ada side and export
3544 them to C++, using the same hierarchy of our previous example:
3545
3546 @smallexample @c ada
3547 with Interfaces.C.Strings;
3548 use Interfaces.C.Strings;
3549 package Animals is
3550   type Carnivore is interface;
3551   pragma Convention (C_Plus_Plus, Carnivore);
3552   function Number_Of_Teeth (X : Carnivore)
3553      return Natural is abstract;
3554
3555   type Domestic is interface;
3556   pragma Convention (C_Plus_Plus, Set_Owner);
3557   procedure Set_Owner
3558     (X    : in out Domestic;
3559      Name : Chars_Ptr) is abstract;
3560
3561   type Animal is tagged record
3562     Age : Natural := 0;
3563   end record;
3564   pragma Convention (C_Plus_Plus, Animal);
3565
3566   procedure Set_Age (X : in out Animal; Age : Integer);
3567   pragma Export (C_Plus_Plus, Set_Age);
3568
3569   function Age (X : Animal) return Integer;
3570   pragma Export (C_Plus_Plus, Age);
3571
3572   type Dog is new Animal and Carnivore and Domestic with record
3573     Tooth_Count : Natural;
3574     Owner       : String (1 .. 30);
3575   end record;
3576   pragma Convention (C_Plus_Plus, Dog);
3577
3578   function Number_Of_Teeth (A : Dog) return Integer;
3579   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3580
3581   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3582   pragma Export (C_Plus_Plus, Set_Owner);
3583
3584   function New_Dog return Dog'Class;
3585   pragma Export (C_Plus_Plus, New_Dog);
3586 end Animals;
3587 @end smallexample
3588
3589 Compared with our previous example the only difference is the use of
3590 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3591 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3592 nothing else to be done; as explained above, the only requirement is that all
3593 the primitives and components are declared in exactly the same order.
3594
3595 For completeness, let us see a brief C++ main program that uses the
3596 declarations available in @code{animals.h} (presented in our first example) to
3597 import and use the declarations from the Ada side, properly initializing and
3598 finalizing the Ada run-time system along the way:
3599
3600 @smallexample
3601 @b{#include} "animals.h"
3602 @b{#include} <iostream>
3603 @b{using namespace} std;
3604
3605 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3606 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3607 void Check_Animal (Animal *obj)       @{@dots{}@}
3608 void Check_Dog (Dog *obj)             @{@dots{}@}
3609
3610 @b{extern} "C" @{
3611   void adainit (void);
3612   void adafinal (void);
3613   Dog* new_dog ();
3614 @}
3615
3616 void test ()
3617 @{
3618   Dog *obj = new_dog();  // Ada constructor
3619   Check_Carnivore (obj); // Check secondary DT
3620   Check_Domestic (obj);  // Check secondary DT
3621   Check_Animal (obj);    // Check primary DT
3622   Check_Dog (obj);       // Check primary DT
3623 @}
3624
3625 int main ()
3626 @{
3627   adainit ();  test();  adafinal ();
3628   return 0;
3629 @}
3630 @end smallexample
3631
3632 @node Comparison between GNAT and C/C++ Compilation Models
3633 @section Comparison between GNAT and C/C++ Compilation Models
3634
3635 @noindent
3636 The GNAT model of compilation is close to the C and C++ models. You can
3637 think of Ada specs as corresponding to header files in C. As in C, you
3638 don't need to compile specs; they are compiled when they are used. The
3639 Ada @code{with} is similar in effect to the @code{#include} of a C
3640 header.
3641
3642 One notable difference is that, in Ada, you may compile specs separately
3643 to check them for semantic and syntactic accuracy. This is not always
3644 possible with C headers because they are fragments of programs that have
3645 less specific syntactic or semantic rules.
3646
3647 The other major difference is the requirement for running the binder,
3648 which performs two important functions. First, it checks for
3649 consistency. In C or C++, the only defense against assembling
3650 inconsistent programs lies outside the compiler, in a makefile, for
3651 example. The binder satisfies the Ada requirement that it be impossible
3652 to construct an inconsistent program when the compiler is used in normal
3653 mode.
3654
3655 @cindex Elaboration order control
3656 The other important function of the binder is to deal with elaboration
3657 issues. There are also elaboration issues in C++ that are handled
3658 automatically. This automatic handling has the advantage of being
3659 simpler to use, but the C++ programmer has no control over elaboration.
3660 Where @code{gnatbind} might complain there was no valid order of
3661 elaboration, a C++ compiler would simply construct a program that
3662 malfunctioned at run time.
3663 @end ifclear
3664
3665 @node Comparison between GNAT and Conventional Ada Library Models
3666 @section Comparison between GNAT and Conventional Ada Library Models
3667
3668 @noindent
3669 This section is intended for Ada programmers who have
3670 used an Ada compiler implementing the traditional Ada library
3671 model, as described in the Ada Reference Manual.
3672
3673 @cindex GNAT library
3674 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3675 source files themselves acts as the library. Compiling Ada programs does
3676 not generate any centralized information, but rather an object file and
3677 a ALI file, which are of interest only to the binder and linker.
3678 In a traditional system, the compiler reads information not only from
3679 the source file being compiled, but also from the centralized library.
3680 This means that the effect of a compilation depends on what has been
3681 previously compiled. In particular:
3682
3683 @itemize @bullet
3684 @item
3685 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3686 to the version of the unit most recently compiled into the library.
3687
3688 @item
3689 Inlining is effective only if the necessary body has already been
3690 compiled into the library.
3691
3692 @item
3693 Compiling a unit may obsolete other units in the library.
3694 @end itemize
3695
3696 @noindent
3697 In GNAT, compiling one unit never affects the compilation of any other
3698 units because the compiler reads only source files. Only changes to source
3699 files can affect the results of a compilation. In particular:
3700
3701 @itemize @bullet
3702 @item
3703 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3704 to the source version of the unit that is currently accessible to the
3705 compiler.
3706
3707 @item
3708 @cindex Inlining
3709 Inlining requires the appropriate source files for the package or
3710 subprogram bodies to be available to the compiler. Inlining is always
3711 effective, independent of the order in which units are complied.
3712
3713 @item
3714 Compiling a unit never affects any other compilations. The editing of
3715 sources may cause previous compilations to be out of date if they
3716 depended on the source file being modified.
3717 @end itemize
3718
3719 @noindent
3720 The most important result of these differences is that order of compilation
3721 is never significant in GNAT. There is no situation in which one is
3722 required to do one compilation before another. What shows up as order of
3723 compilation requirements in the traditional Ada library becomes, in
3724 GNAT, simple source dependencies; in other words, there is only a set
3725 of rules saying what source files must be present when a file is
3726 compiled.
3727
3728 @ifset vms
3729 @node Placement of temporary files
3730 @section Placement of temporary files
3731 @cindex Temporary files (user control over placement)
3732
3733 @noindent
3734 GNAT creates temporary files in the directory designated by the environment
3735 variable @env{TMPDIR}.
3736 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3737 for detailed information on how environment variables are resolved.
3738 For most users the easiest way to make use of this feature is to simply
3739 define @env{TMPDIR} as a job level logical name).
3740 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3741 for compiler temporary files, then you can include something like the
3742 following command in your @file{LOGIN.COM} file:
3743
3744 @smallexample
3745 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3746 @end smallexample
3747
3748 @noindent
3749 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3750 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3751 designated by @env{TEMP}.
3752 If none of these environment variables are defined then GNAT uses the
3753 directory designated by the logical name @code{SYS$SCRATCH:}
3754 (by default the user's home directory). If all else fails
3755 GNAT uses the current directory for temporary files.
3756 @end ifset
3757
3758 @c *************************
3759 @node Compiling Using gcc
3760 @chapter Compiling Using @command{gcc}
3761
3762 @noindent
3763 This chapter discusses how to compile Ada programs using the @command{gcc}
3764 command. It also describes the set of switches
3765 that can be used to control the behavior of the compiler.
3766 @menu
3767 * Compiling Programs::
3768 * Switches for gcc::
3769 * Search Paths and the Run-Time Library (RTL)::
3770 * Order of Compilation Issues::
3771 * Examples::
3772 @end menu
3773
3774 @node Compiling Programs
3775 @section Compiling Programs
3776
3777 @noindent
3778 The first step in creating an executable program is to compile the units
3779 of the program using the @command{gcc} command. You must compile the
3780 following files:
3781
3782 @itemize @bullet
3783 @item
3784 the body file (@file{.adb}) for a library level subprogram or generic
3785 subprogram
3786
3787 @item
3788 the spec file (@file{.ads}) for a library level package or generic
3789 package that has no body
3790
3791 @item
3792 the body file (@file{.adb}) for a library level package
3793 or generic package that has a body
3794
3795 @end itemize
3796
3797 @noindent
3798 You need @emph{not} compile the following files
3799
3800 @itemize @bullet
3801
3802 @item
3803 the spec of a library unit which has a body
3804
3805 @item
3806 subunits
3807 @end itemize
3808
3809 @noindent
3810 because they are compiled as part of compiling related units. GNAT
3811 package specs
3812 when the corresponding body is compiled, and subunits when the parent is
3813 compiled.
3814
3815 @cindex cannot generate code
3816 If you attempt to compile any of these files, you will get one of the
3817 following error messages (where @var{fff} is the name of the file you
3818 compiled):
3819
3820 @smallexample
3821 cannot generate code for file @var{fff} (package spec)
3822 to check package spec, use -gnatc
3823
3824 cannot generate code for file @var{fff} (missing subunits)
3825 to check parent unit, use -gnatc
3826
3827 cannot generate code for file @var{fff} (subprogram spec)
3828 to check subprogram spec, use -gnatc
3829
3830 cannot generate code for file @var{fff} (subunit)
3831 to check subunit, use -gnatc
3832 @end smallexample
3833
3834 @noindent
3835 As indicated by the above error messages, if you want to submit
3836 one of these files to the compiler to check for correct semantics
3837 without generating code, then use the @option{-gnatc} switch.
3838
3839 The basic command for compiling a file containing an Ada unit is
3840
3841 @smallexample
3842 @c $ gcc -c @ovar{switches} @file{file name}
3843 @c Expanding @ovar macro inline (explanation in macro def comments)
3844 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3845 @end smallexample
3846
3847 @noindent
3848 where @var{file name} is the name of the Ada file (usually
3849 having an extension
3850 @file{.ads} for a spec or @file{.adb} for a body).
3851 @ifclear vms
3852 You specify the
3853 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3854 @end ifclear
3855 The result of a successful compilation is an object file, which has the
3856 same name as the source file but an extension of @file{.o} and an Ada
3857 Library Information (ALI) file, which also has the same name as the
3858 source file, but with @file{.ali} as the extension. GNAT creates these
3859 two output files in the current directory, but you may specify a source
3860 file in any directory using an absolute or relative path specification
3861 containing the directory information.
3862
3863 @findex gnat1
3864 @command{gcc} is actually a driver program that looks at the extensions of
3865 the file arguments and loads the appropriate compiler. For example, the
3866 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3867 These programs are in directories known to the driver program (in some
3868 configurations via environment variables you set), but need not be in
3869 your path. The @command{gcc} driver also calls the assembler and any other
3870 utilities needed to complete the generation of the required object
3871 files.
3872
3873 It is possible to supply several file names on the same @command{gcc}
3874 command. This causes @command{gcc} to call the appropriate compiler for
3875 each file. For example, the following command lists three separate
3876 files to be compiled:
3877
3878 @smallexample
3879 $ gcc -c x.adb y.adb z.c
3880 @end smallexample
3881
3882 @noindent
3883 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3884 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3885 The compiler generates three object files @file{x.o}, @file{y.o} and
3886 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3887 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3888 @ifclear vms
3889 except for
3890 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3891 @end ifclear
3892
3893 @node Switches for gcc
3894 @section Switches for @command{gcc}
3895
3896 @noindent
3897 The @command{gcc} command accepts switches that control the
3898 compilation process. These switches are fully described in this section.
3899 First we briefly list all the switches, in alphabetical order, then we
3900 describe the switches in more detail in functionally grouped sections.
3901
3902 More switches exist for GCC than those documented here, especially
3903 for specific targets. However, their use is not recommended as
3904 they may change code generation in ways that are incompatible with
3905 the Ada run-time library, or can cause inconsistencies between
3906 compilation units.
3907
3908 @menu
3909 * Output and Error Message Control::
3910 * Warning Message Control::
3911 * Debugging and Assertion Control::
3912 * Validity Checking::
3913 * Style Checking::
3914 * Run-Time Checks::
3915 * Using gcc for Syntax Checking::
3916 * Using gcc for Semantic Checking::
3917 * Compiling Different Versions of Ada::
3918 * Character Set Control::
3919 * File Naming Control::
3920 * Subprogram Inlining Control::
3921 * Auxiliary Output Control::
3922 * Debugging Control::
3923 * Exception Handling Control::
3924 * Units to Sources Mapping Files::
3925 * Integrated Preprocessing::
3926 * Code Generation Control::
3927 @ifset vms
3928 * Return Codes::
3929 @end ifset
3930 @end menu
3931
3932 @table @option
3933 @c !sort!
3934 @ifclear vms
3935 @cindex @option{-b} (@command{gcc})
3936 @item -b @var{target}
3937 Compile your program to run on @var{target}, which is the name of a
3938 system configuration. You must have a GNAT cross-compiler built if
3939 @var{target} is not the same as your host system.
3940
3941 @item -B@var{dir}
3942 @cindex @option{-B} (@command{gcc})
3943 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3944 from @var{dir} instead of the default location. Only use this switch
3945 when multiple versions of the GNAT compiler are available.
3946 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3947 GNU Compiler Collection (GCC)}, for further details. You would normally
3948 use the @option{-b} or @option{-V} switch instead.
3949
3950 @item -c
3951 @cindex @option{-c} (@command{gcc})
3952 Compile. Always use this switch when compiling Ada programs.
3953
3954 Note: for some other languages when using @command{gcc}, notably in
3955 the case of C and C++, it is possible to use
3956 use @command{gcc} without a @option{-c} switch to
3957 compile and link in one step. In the case of GNAT, you
3958 cannot use this approach, because the binder must be run
3959 and @command{gcc} cannot be used to run the GNAT binder.
3960 @end ifclear
3961
3962 @item -fno-inline
3963 @cindex @option{-fno-inline} (@command{gcc})
3964 Suppresses all inlining, even if other optimization or inlining
3965 switches are set.  This includes suppression of inlining that
3966 results from the use of the pragma @code{Inline_Always}.
3967 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3968 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3969 effect if this switch is present.
3970
3971 @item -fno-inline-functions
3972 @cindex @option{-fno-inline-functions} (@command{gcc})
3973 Suppresses automatic inlining of subprograms, which is enabled
3974 if @option{-O3} is used.
3975
3976 @item -fno-inline-small-functions
3977 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3978 Suppresses automatic inlining of small subprograms, which is enabled
3979 if @option{-O2} is used.
3980
3981 @item -fno-inline-functions-called-once
3982 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3983 Suppresses inlining of subprograms local to the unit and called once
3984 from within it, which is enabled if @option{-O1} is used.
3985
3986 @item -fno-ivopts
3987 @cindex @option{-fno-ivopts} (@command{gcc})
3988 Suppresses high-level loop induction variable optimizations, which are
3989 enabled if @option{-O1} is used. These optimizations are generally
3990 profitable but, for some specific cases of loops with numerous uses
3991 of the iteration variable that follow a common pattern, they may end
3992 up destroying the regularity that could be exploited at a lower level
3993 and thus producing inferior code.
3994
3995 @item -fno-strict-aliasing
3996 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3997 Causes the compiler to avoid assumptions regarding non-aliasing
3998 of objects of different types. See
3999 @ref{Optimization and Strict Aliasing} for details.
4000
4001 @item -fstack-check
4002 @cindex @option{-fstack-check} (@command{gcc})
4003 Activates stack checking.
4004 See @ref{Stack Overflow Checking} for details.
4005
4006 @item -fstack-usage
4007 @cindex @option{-fstack-usage} (@command{gcc})
4008 Makes the compiler output stack usage information for the program, on a
4009 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4010
4011 @item -fcallgraph-info@r{[}=su@r{]}
4012 @cindex @option{-fcallgraph-info} (@command{gcc})
4013 Makes the compiler output callgraph information for the program, on a
4014 per-file basis.  The information is generated in the VCG format.  It can
4015 be decorated with stack-usage per-node information.
4016
4017 @item ^-g^/DEBUG^
4018 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4019 Generate debugging information. This information is stored in the object
4020 file and copied from there to the final executable file by the linker,
4021 where it can be read by the debugger. You must use the
4022 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4023
4024 @item -gnat83
4025 @cindex @option{-gnat83} (@command{gcc})
4026 Enforce Ada 83 restrictions.
4027
4028 @item -gnat95
4029 @cindex @option{-gnat95} (@command{gcc})
4030 Enforce Ada 95 restrictions.
4031
4032 @item -gnat05
4033 @cindex @option{-gnat05} (@command{gcc})
4034 Allow full Ada 2005 features.
4035
4036 @item -gnat2005
4037 @cindex @option{-gnat2005} (@command{gcc})
4038 Allow full Ada 2005 features (same as @option{-gnat05})
4039
4040 @item -gnat12
4041 @cindex @option{-gnat12} (@command{gcc})
4042
4043 @item -gnat2012
4044 @cindex @option{-gnat2012} (@command{gcc})
4045 Allow full Ada 2012 features (same as @option{-gnat12})
4046
4047 @item -gnata
4048 @cindex @option{-gnata} (@command{gcc})
4049 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4050 activated. Note that these pragmas can also be controlled using the
4051 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4052 It also activates pragmas @code{Check}, @code{Precondition}, and
4053 @code{Postcondition}. Note that these pragmas can also be controlled
4054 using the configuration pragma @code{Check_Policy}.
4055
4056 @item -gnatA
4057 @cindex @option{-gnatA} (@command{gcc})
4058 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4059 it will be ignored.
4060
4061 @item -gnatb
4062 @cindex @option{-gnatb} (@command{gcc})
4063 Generate brief messages to @file{stderr} even if verbose mode set.
4064
4065 @item -gnatB
4066 @cindex @option{-gnatB} (@command{gcc})
4067 Assume no invalid (bad) values except for 'Valid attribute use
4068 (@pxref{Validity Checking}).
4069
4070 @item -gnatc
4071 @cindex @option{-gnatc} (@command{gcc})
4072 Check syntax and semantics only (no code generation attempted).
4073
4074 @item -gnatC
4075 @cindex @option{-gnatC} (@command{gcc})
4076 Generate CodePeer information (no code generation attempted).
4077 This switch will generate an intermediate representation suitable for
4078 use by CodePeer (@file{.scil} files). This switch is not compatible with
4079 code generation (it will, among other things, disable some switches such
4080 as -gnatn, and enable others such as -gnata).
4081
4082 @item -gnatd
4083 @cindex @option{-gnatd} (@command{gcc})
4084 Specify debug options for the compiler. The string of characters after
4085 the @option{-gnatd} specify the specific debug options. The possible
4086 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4087 compiler source file @file{debug.adb} for details of the implemented
4088 debug options. Certain debug options are relevant to applications
4089 programmers, and these are documented at appropriate points in this
4090 users guide.
4091
4092 @ifclear vms
4093 @item -gnatD
4094 @cindex @option{-gnatD[nn]} (@command{gcc})
4095 @end ifclear
4096 @ifset vms
4097 @item /XDEBUG /LXDEBUG=nnn
4098 @end ifset
4099 Create expanded source files for source level debugging. This switch
4100 also suppress generation of cross-reference information
4101 (see @option{-gnatx}).
4102
4103 @item -gnatec=@var{path}
4104 @cindex @option{-gnatec} (@command{gcc})
4105 Specify a configuration pragma file
4106 @ifclear vms
4107 (the equal sign is optional)
4108 @end ifclear
4109 (@pxref{The Configuration Pragmas Files}).
4110
4111 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4112 @cindex @option{-gnateD} (@command{gcc})
4113 Defines a symbol, associated with @var{value}, for preprocessing.
4114 (@pxref{Integrated Preprocessing}).
4115
4116 @item -gnateE
4117 @cindex @option{-gnateE} (@command{gcc})
4118 Generate extra information in exception messages. In particular, display
4119 extra column information and the value and range associated with index and
4120 range check failures, and extra column information for access checks.
4121 In cases where the compiler is able to determine at compile time that
4122 a check will fail, it gives a warning, and the extra information is not
4123 produced at run time.
4124
4125 @item -gnatef
4126 @cindex @option{-gnatef} (@command{gcc})
4127 Display full source path name in brief error messages.
4128
4129 @item -gnateG
4130 @cindex @option{-gnateG} (@command{gcc})
4131 Save result of preprocessing in a text file.
4132
4133 @item -gnatem=@var{path}
4134 @cindex @option{-gnatem} (@command{gcc})
4135 Specify a mapping file
4136 @ifclear vms
4137 (the equal sign is optional)
4138 @end ifclear
4139 (@pxref{Units to Sources Mapping Files}).
4140
4141 @item -gnatep=@var{file}
4142 @cindex @option{-gnatep} (@command{gcc})
4143 Specify a preprocessing data file
4144 @ifclear vms
4145 (the equal sign is optional)
4146 @end ifclear
4147 (@pxref{Integrated Preprocessing}).
4148
4149 @item -gnateP
4150 @cindex @option{-gnateP} (@command{gcc})
4151 Turn categorization dependency errors into warnings.
4152 Ada requires that units that WITH one another have compatible categories, for
4153 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4154 these errors become warnings (which can be ignored, or suppressed in the usual
4155 manner). This can be useful in some specialized circumstances such as the
4156 temporary use of special test software.
4157 @item -gnateS
4158 @cindex @option{-gnateS} (@command{gcc})
4159 Generate SCO (Source Coverage Obligation) information in the ALI
4160 file. This information is used by advanced coverage tools. See
4161 unit @file{SCOs} in the compiler sources for details in files
4162 @file{scos.ads} and @file{scos.adb}.
4163
4164 @item -gnatE
4165 @cindex @option{-gnatE} (@command{gcc})
4166 Full dynamic elaboration checks.
4167
4168 @item -gnatf
4169 @cindex @option{-gnatf} (@command{gcc})
4170 Full errors. Multiple errors per line, all undefined references, do not
4171 attempt to suppress cascaded errors.
4172
4173 @item -gnatF
4174 @cindex @option{-gnatF} (@command{gcc})
4175 Externals names are folded to all uppercase.
4176
4177 @item ^-gnatg^/GNAT_INTERNAL^
4178 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4179 Internal GNAT implementation mode. This should not be used for
4180 applications programs, it is intended only for use by the compiler
4181 and its run-time library. For documentation, see the GNAT sources.
4182 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4183 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4184 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4185 so that all standard warnings and all standard style options are turned on.
4186 All warnings and style messages are treated as errors.
4187
4188 @ifclear vms
4189 @item -gnatG=nn
4190 @cindex @option{-gnatG[nn]} (@command{gcc})
4191 @end ifclear
4192 @ifset vms
4193 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4194 @end ifset
4195 List generated expanded code in source form.
4196
4197 @item ^-gnath^/HELP^
4198 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4199 Output usage information. The output is written to @file{stdout}.
4200
4201 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4202 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4203 Identifier character set
4204 @ifclear vms
4205 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4206 @end ifclear
4207 For details of the possible selections for @var{c},
4208 see @ref{Character Set Control}.
4209
4210 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4211 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4212 Ignore representation clauses. When this switch is used,
4213 representation clauses are treated as comments. This is useful
4214 when initially porting code where you want to ignore rep clause
4215 problems, and also for compiling foreign code (particularly
4216 for use with ASIS). The representation clauses that are ignored
4217 are: enumeration_representation_clause, record_representation_clause,
4218 and attribute_definition_clause for the following attributes:
4219 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4220 Object_Size, Size, Small, Stream_Size, and Value_Size.
4221 Note that this option should be used only for compiling -- the
4222 code is likely to malfunction at run time.
4223
4224 @item -gnatjnn
4225 @cindex @option{-gnatjnn} (@command{gcc})
4226 Reformat error messages to fit on nn character lines
4227
4228 @item -gnatk=@var{n}
4229 @cindex @option{-gnatk} (@command{gcc})
4230 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4231
4232 @item -gnatl
4233 @cindex @option{-gnatl} (@command{gcc})
4234 Output full source listing with embedded error messages.
4235
4236 @item -gnatL
4237 @cindex @option{-gnatL} (@command{gcc})
4238 Used in conjunction with -gnatG or -gnatD to intersperse original
4239 source lines (as comment lines with line numbers) in the expanded
4240 source output.
4241
4242 @item -gnatm=@var{n}
4243 @cindex @option{-gnatm} (@command{gcc})
4244 Limit number of detected error or warning messages to @var{n}
4245 where @var{n} is in the range 1..999999. The default setting if
4246 no switch is given is 9999. If the number of warnings reaches this
4247 limit, then a message is output and further warnings are suppressed,
4248 but the compilation is continued. If the number of error messages
4249 reaches this limit, then a message is output and the compilation
4250 is abandoned. The equal sign here is optional. A value of zero
4251 means that no limit applies.
4252
4253 @item -gnatn
4254 @cindex @option{-gnatn} (@command{gcc})
4255 Activate inlining for subprograms for which
4256 pragma @code{Inline} is specified. This inlining is performed
4257 by the GCC back-end.
4258
4259 @item -gnatN
4260 @cindex @option{-gnatN} (@command{gcc})
4261 Activate front end inlining for subprograms for which
4262 pragma @code{Inline} is specified. This inlining is performed
4263 by the front end and will be visible in the
4264 @option{-gnatG} output.
4265
4266 When using a gcc-based back end (in practice this means using any version
4267 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4268 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4269 Historically front end inlining was more extensive than the gcc back end
4270 inlining, but that is no longer the case.
4271
4272 @item -gnato
4273 @cindex @option{-gnato} (@command{gcc})
4274 Enable numeric overflow checking (which is not normally enabled by
4275 default). Note that division by zero is a separate check that is not
4276 controlled by this switch (division by zero checking is on by default).
4277
4278 @item -gnatp
4279 @cindex @option{-gnatp} (@command{gcc})
4280 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4281 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4282
4283 @item -gnat-p
4284 @cindex @option{-gnat-p} (@command{gcc})
4285 Cancel effect of previous @option{-gnatp} switch.
4286
4287 @item -gnatP
4288 @cindex @option{-gnatP} (@command{gcc})
4289 Enable polling. This is required on some systems (notably Windows NT) to
4290 obtain asynchronous abort and asynchronous transfer of control capability.
4291 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4292 details.
4293
4294 @item -gnatq
4295 @cindex @option{-gnatq} (@command{gcc})
4296 Don't quit. Try semantics, even if parse errors.
4297
4298 @item -gnatQ
4299 @cindex @option{-gnatQ} (@command{gcc})
4300 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4301
4302 @item -gnatr
4303 @cindex @option{-gnatr} (@command{gcc})
4304 Treat pragma Restrictions as Restriction_Warnings.
4305
4306 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4307 @cindex @option{-gnatR} (@command{gcc})
4308 Output representation information for declared types and objects.
4309
4310 @item -gnats
4311 @cindex @option{-gnats} (@command{gcc})
4312 Syntax check only.
4313
4314 @item -gnatS
4315 @cindex @option{-gnatS} (@command{gcc})
4316 Print package Standard.
4317
4318 @item -gnatt
4319 @cindex @option{-gnatt} (@command{gcc})
4320 Generate tree output file.
4321
4322 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4323 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4324 All compiler tables start at @var{nnn} times usual starting size.
4325
4326 @item -gnatu
4327 @cindex @option{-gnatu} (@command{gcc})
4328 List units for this compilation.
4329
4330 @item -gnatU
4331 @cindex @option{-gnatU} (@command{gcc})
4332 Tag all error messages with the unique string ``error:''
4333
4334 @item -gnatv
4335 @cindex @option{-gnatv} (@command{gcc})
4336 Verbose mode. Full error output with source lines to @file{stdout}.
4337
4338 @item -gnatV
4339 @cindex @option{-gnatV} (@command{gcc})
4340 Control level of validity checking (@pxref{Validity Checking}).
4341
4342 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4343 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4344 Warning mode where
4345 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4346 the exact warnings that
4347 are enabled or disabled (@pxref{Warning Message Control}).
4348
4349 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4350 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4351 Wide character encoding method
4352 @ifclear vms
4353 (@var{e}=n/h/u/s/e/8).
4354 @end ifclear
4355 @ifset vms
4356 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4357 @end ifset
4358
4359 @item -gnatx
4360 @cindex @option{-gnatx} (@command{gcc})
4361 Suppress generation of cross-reference information.
4362
4363 @item -gnatX
4364 @cindex @option{-gnatX} (@command{gcc})
4365 Enable GNAT implementation extensions and latest Ada version.
4366
4367 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4368 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4369 Enable built-in style checks (@pxref{Style Checking}).
4370
4371 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4372 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4373 Distribution stub generation and compilation
4374 @ifclear vms
4375 (@var{m}=r/c for receiver/caller stubs).
4376 @end ifclear
4377 @ifset vms
4378 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4379 to be generated and compiled).
4380 @end ifset
4381
4382 @item ^-I^/SEARCH=^@var{dir}
4383 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4384 @cindex RTL
4385 Direct GNAT to search the @var{dir} directory for source files needed by
4386 the current compilation
4387 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4388
4389 @item ^-I-^/NOCURRENT_DIRECTORY^
4390 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4391 @cindex RTL
4392 Except for the source file named in the command line, do not look for source
4393 files in the directory containing the source file named in the command line
4394 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4395
4396 @ifclear vms
4397 @item -mbig-switch
4398 @cindex @option{-mbig-switch} (@command{gcc})
4399 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4400 This standard gcc switch causes the compiler to use larger offsets in its
4401 jump table representation for @code{case} statements.
4402 This may result in less efficient code, but is sometimes necessary
4403 (for example on HP-UX targets)
4404 @cindex HP-UX and @option{-mbig-switch} option
4405 in order to compile large and/or nested @code{case} statements.
4406
4407 @item -o @var{file}
4408 @cindex @option{-o} (@command{gcc})
4409 This switch is used in @command{gcc} to redirect the generated object file
4410 and its associated ALI file. Beware of this switch with GNAT, because it may
4411 cause the object file and ALI file to have different names which in turn
4412 may confuse the binder and the linker.
4413 @end ifclear
4414
4415 @item -nostdinc
4416 @cindex @option{-nostdinc} (@command{gcc})
4417 Inhibit the search of the default location for the GNAT Run Time
4418 Library (RTL) source files.
4419
4420 @item -nostdlib
4421 @cindex @option{-nostdlib} (@command{gcc})
4422 Inhibit the search of the default location for the GNAT Run Time
4423 Library (RTL) ALI files.
4424
4425 @ifclear vms
4426 @c @item -O@ovar{n}
4427 @c Expanding @ovar macro inline (explanation in macro def comments)
4428 @item -O@r{[}@var{n}@r{]}
4429 @cindex @option{-O} (@command{gcc})
4430 @var{n} controls the optimization level.
4431
4432 @table @asis
4433 @item n = 0
4434 No optimization, the default setting if no @option{-O} appears
4435
4436 @item n = 1
4437 Normal optimization, the default if you specify @option{-O} without
4438 an operand. A good compromise between code quality and compilation
4439 time.
4440
4441 @item n = 2
4442 Extensive optimization, may improve execution time, possibly at the cost of
4443 substantially increased compilation time.
4444
4445 @item n = 3
4446 Same as @option{-O2}, and also includes inline expansion for small subprograms
4447 in the same unit.
4448
4449 @item n = s
4450 Optimize space usage
4451 @end table
4452
4453 @noindent
4454 See also @ref{Optimization Levels}.
4455 @end ifclear
4456
4457 @ifset vms
4458 @item  /NOOPTIMIZE
4459 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4460 Equivalent to @option{/OPTIMIZE=NONE}.
4461 This is the default behavior in the absence of an @option{/OPTIMIZE}
4462 qualifier.
4463
4464 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4465 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4466 Selects the level of optimization for your program. The supported
4467 keywords are as follows:
4468 @table @code
4469 @item   ALL
4470 Perform most optimizations, including those that
4471 are expensive.
4472 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4473 without keyword options.
4474
4475 @item   NONE
4476 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4477
4478 @item SOME
4479 Perform some optimizations, but omit ones that are costly.
4480
4481 @item   DEVELOPMENT
4482 Same as @code{SOME}.
4483
4484 @item INLINING
4485 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4486 automatic inlining of small subprograms within a unit
4487
4488 @item   UNROLL_LOOPS
4489 Try to unroll loops. This keyword may be specified together with
4490 any keyword above other than @code{NONE}. Loop unrolling
4491 usually, but not always, improves the performance of programs.
4492
4493 @item SPACE
4494 Optimize space usage
4495 @end table
4496
4497 @noindent
4498 See also @ref{Optimization Levels}.
4499 @end ifset
4500
4501 @ifclear vms
4502 @item -pass-exit-codes
4503 @cindex @option{-pass-exit-codes} (@command{gcc})
4504 Catch exit codes from the compiler and use the most meaningful as
4505 exit status.
4506 @end ifclear
4507
4508 @item --RTS=@var{rts-path}
4509 @cindex @option{--RTS} (@command{gcc})
4510 Specifies the default location of the runtime library. Same meaning as the
4511 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4512
4513 @item ^-S^/ASM^
4514 @cindex @option{^-S^/ASM^} (@command{gcc})
4515 ^Used in place of @option{-c} to^Used to^
4516 cause the assembler source file to be
4517 generated, using @file{^.s^.S^} as the extension,
4518 instead of the object file.
4519 This may be useful if you need to examine the generated assembly code.
4520
4521 @item ^-fverbose-asm^/VERBOSE_ASM^
4522 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4523 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4524 to cause the generated assembly code file to be annotated with variable
4525 names, making it significantly easier to follow.
4526
4527 @item ^-v^/VERBOSE^
4528 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4529 Show commands generated by the @command{gcc} driver. Normally used only for
4530 debugging purposes or if you need to be sure what version of the
4531 compiler you are executing.
4532
4533 @ifclear vms
4534 @item -V @var{ver}
4535 @cindex @option{-V} (@command{gcc})
4536 Execute @var{ver} version of the compiler. This is the @command{gcc}
4537 version, not the GNAT version.
4538 @end ifclear
4539
4540 @item ^-w^/NO_BACK_END_WARNINGS^
4541 @cindex @option{-w} (@command{gcc})
4542 Turn off warnings generated by the back end of the compiler. Use of
4543 this switch also causes the default for front end warnings to be set
4544 to suppress (as though @option{-gnatws} had appeared at the start of
4545 the options).
4546
4547 @end table
4548
4549 @ifclear vms
4550 @c Combining qualifiers does not work on VMS
4551 You may combine a sequence of GNAT switches into a single switch. For
4552 example, the combined switch
4553
4554 @cindex Combining GNAT switches
4555 @smallexample
4556 -gnatofi3
4557 @end smallexample
4558
4559 @noindent
4560 is equivalent to specifying the following sequence of switches:
4561
4562 @smallexample
4563 -gnato -gnatf -gnati3
4564 @end smallexample
4565 @end ifclear
4566
4567 @noindent
4568 The following restrictions apply to the combination of switches
4569 in this manner:
4570
4571 @itemize @bullet
4572 @item
4573 The switch @option{-gnatc} if combined with other switches must come
4574 first in the string.
4575
4576 @item
4577 The switch @option{-gnats} if combined with other switches must come
4578 first in the string.
4579
4580 @item
4581 The switches
4582 ^^@option{/DISTRIBUTION_STUBS=},^
4583 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4584 switches, and only one of them may appear in the command line.
4585
4586 @item
4587 The switch @option{-gnat-p} may not be combined with any other switch.
4588
4589 @ifclear vms
4590 @item
4591 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4592 switch), then all further characters in the switch are interpreted
4593 as style modifiers (see description of @option{-gnaty}).
4594
4595 @item
4596 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4597 switch), then all further characters in the switch are interpreted
4598 as debug flags (see description of @option{-gnatd}).
4599
4600 @item
4601 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4602 switch), then all further characters in the switch are interpreted
4603 as warning mode modifiers (see description of @option{-gnatw}).
4604
4605 @item
4606 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4607 switch), then all further characters in the switch are interpreted
4608 as validity checking options (@pxref{Validity Checking}).
4609
4610 @item
4611 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4612 a combined list of options.
4613 @end ifclear
4614 @end itemize
4615
4616 @node Output and Error Message Control
4617 @subsection Output and Error Message Control
4618 @findex stderr
4619
4620 @noindent
4621 The standard default format for error messages is called ``brief format''.
4622 Brief format messages are written to @file{stderr} (the standard error
4623 file) and have the following form:
4624
4625 @smallexample
4626 e.adb:3:04: Incorrect spelling of keyword "function"
4627 e.adb:4:20: ";" should be "is"
4628 @end smallexample
4629
4630 @noindent
4631 The first integer after the file name is the line number in the file,
4632 and the second integer is the column number within the line.
4633 @ifclear vms
4634 @code{GPS} can parse the error messages
4635 and point to the referenced character.
4636 @end ifclear
4637 The following switches provide control over the error message
4638 format:
4639
4640 @table @option
4641 @c !sort!
4642 @item -gnatv
4643 @cindex @option{-gnatv} (@command{gcc})
4644 @findex stdout
4645 @ifclear vms
4646 The v stands for verbose.
4647 @end ifclear
4648 The effect of this setting is to write long-format error
4649 messages to @file{stdout} (the standard output file.
4650 The same program compiled with the
4651 @option{-gnatv} switch would generate:
4652
4653 @smallexample
4654 @cartouche
4655 3. funcion X (Q : Integer)
4656    |
4657 >>> Incorrect spelling of keyword "function"
4658 4. return Integer;
4659                  |
4660 >>> ";" should be "is"
4661 @end cartouche
4662 @end smallexample
4663
4664 @noindent
4665 The vertical bar indicates the location of the error, and the @samp{>>>}
4666 prefix can be used to search for error messages. When this switch is
4667 used the only source lines output are those with errors.
4668
4669 @item -gnatl
4670 @cindex @option{-gnatl} (@command{gcc})
4671 @ifclear vms
4672 The @code{l} stands for list.
4673 @end ifclear
4674 This switch causes a full listing of
4675 the file to be generated. In the case where a body is
4676 compiled, the corresponding spec is also listed, along
4677 with any subunits. Typical output from compiling a package
4678 body @file{p.adb} might look like:
4679
4680 @smallexample @c ada
4681 @cartouche
4682  Compiling: p.adb
4683
4684      1. package body p is
4685      2.    procedure a;
4686      3.    procedure a is separate;
4687      4. begin
4688      5.    null
4689                |
4690         >>> missing ";"
4691
4692      6. end;
4693
4694 Compiling: p.ads
4695
4696      1. package p is
4697      2.    pragma Elaborate_Body
4698                                 |
4699         >>> missing ";"
4700
4701      3. end p;
4702
4703 Compiling: p-a.adb
4704
4705      1. separate p
4706                 |
4707         >>> missing "("
4708
4709      2. procedure a is
4710      3. begin
4711      4.    null
4712                |
4713         >>> missing ";"
4714
4715      5. end;
4716 @end cartouche
4717 @end smallexample
4718
4719 @noindent
4720 @findex stderr
4721 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4722 standard output is redirected, a brief summary is written to
4723 @file{stderr} (standard error) giving the number of error messages and
4724 warning messages generated.
4725
4726 @item ^-gnatl^/OUTPUT_FILE^=file
4727 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4728 This has the same effect as @option{-gnatl} except that the output is
4729 written to a file instead of to standard output. If the given name
4730 @file{fname} does not start with a period, then it is the full name
4731 of the file to be written. If @file{fname} is an extension, it is
4732 appended to the name of the file being compiled. For example, if
4733 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4734 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4735
4736 @item -gnatU
4737 @cindex @option{-gnatU} (@command{gcc})
4738 This switch forces all error messages to be preceded by the unique
4739 string ``error:''. This means that error messages take a few more
4740 characters in space, but allows easy searching for and identification
4741 of error messages.
4742
4743 @item -gnatb
4744 @cindex @option{-gnatb} (@command{gcc})
4745 @ifclear vms
4746 The @code{b} stands for brief.
4747 @end ifclear
4748 This switch causes GNAT to generate the
4749 brief format error messages to @file{stderr} (the standard error
4750 file) as well as the verbose
4751 format message or full listing (which as usual is written to
4752 @file{stdout} (the standard output file).
4753
4754 @item -gnatm=@var{n}
4755 @cindex @option{-gnatm} (@command{gcc})
4756 @ifclear vms
4757 The @code{m} stands for maximum.
4758 @end ifclear
4759 @var{n} is a decimal integer in the
4760 range of 1 to 999999 and limits the number of error or warning
4761 messages to be generated. For example, using
4762 @option{-gnatm2} might yield
4763
4764 @smallexample
4765 e.adb:3:04: Incorrect spelling of keyword "function"
4766 e.adb:5:35: missing ".."
4767 fatal error: maximum number of errors detected
4768 compilation abandoned
4769 @end smallexample
4770
4771 @noindent
4772 The default setting if
4773 no switch is given is 9999. If the number of warnings reaches this
4774 limit, then a message is output and further warnings are suppressed,
4775 but the compilation is continued. If the number of error messages
4776 reaches this limit, then a message is output and the compilation
4777 is abandoned. A value of zero means that no limit applies.
4778
4779 @noindent
4780 Note that the equal sign is optional, so the switches
4781 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4782
4783 @item -gnatf
4784 @cindex @option{-gnatf} (@command{gcc})
4785 @cindex Error messages, suppressing
4786 @ifclear vms
4787 The @code{f} stands for full.
4788 @end ifclear
4789 Normally, the compiler suppresses error messages that are likely to be
4790 redundant. This switch causes all error
4791 messages to be generated. In particular, in the case of
4792 references to undefined variables. If a given variable is referenced
4793 several times, the normal format of messages is
4794 @smallexample
4795 e.adb:7:07: "V" is undefined (more references follow)
4796 @end smallexample
4797
4798 @noindent
4799 where the parenthetical comment warns that there are additional
4800 references to the variable @code{V}. Compiling the same program with the
4801 @option{-gnatf} switch yields
4802
4803 @smallexample
4804 e.adb:7:07: "V" is undefined
4805 e.adb:8:07: "V" is undefined
4806 e.adb:8:12: "V" is undefined
4807 e.adb:8:16: "V" is undefined
4808 e.adb:9:07: "V" is undefined
4809 e.adb:9:12: "V" is undefined
4810 @end smallexample
4811
4812 @noindent
4813 The @option{-gnatf} switch also generates additional information for
4814 some error messages.  Some examples are:
4815
4816 @itemize @bullet
4817 @item
4818 Details on possibly non-portable unchecked conversion
4819 @item
4820 List possible interpretations for ambiguous calls
4821 @item
4822 Additional details on incorrect parameters
4823 @end itemize
4824
4825 @item -gnatjnn
4826 @cindex @option{-gnatjnn} (@command{gcc})
4827 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4828 with continuation lines are treated as though the continuation lines were
4829 separate messages (and so a warning with two continuation lines counts as
4830 three warnings, and is listed as three separate messages).
4831
4832 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4833 messages are output in a different manner. A message and all its continuation
4834 lines are treated as a unit, and count as only one warning or message in the
4835 statistics totals. Furthermore, the message is reformatted so that no line
4836 is longer than nn characters.
4837
4838 @item -gnatq
4839 @cindex @option{-gnatq} (@command{gcc})
4840 @ifclear vms
4841 The @code{q} stands for quit (really ``don't quit'').
4842 @end ifclear
4843 In normal operation mode, the compiler first parses the program and
4844 determines if there are any syntax errors. If there are, appropriate
4845 error messages are generated and compilation is immediately terminated.
4846 This switch tells
4847 GNAT to continue with semantic analysis even if syntax errors have been
4848 found. This may enable the detection of more errors in a single run. On
4849 the other hand, the semantic analyzer is more likely to encounter some
4850 internal fatal error when given a syntactically invalid tree.
4851
4852 @item -gnatQ
4853 @cindex @option{-gnatQ} (@command{gcc})
4854 In normal operation mode, the @file{ALI} file is not generated if any
4855 illegalities are detected in the program. The use of @option{-gnatQ} forces
4856 generation of the @file{ALI} file. This file is marked as being in
4857 error, so it cannot be used for binding purposes, but it does contain
4858 reasonably complete cross-reference information, and thus may be useful
4859 for use by tools (e.g., semantic browsing tools or integrated development
4860 environments) that are driven from the @file{ALI} file. This switch
4861 implies @option{-gnatq}, since the semantic phase must be run to get a
4862 meaningful ALI file.
4863
4864 In addition, if @option{-gnatt} is also specified, then the tree file is
4865 generated even if there are illegalities. It may be useful in this case
4866 to also specify @option{-gnatq} to ensure that full semantic processing
4867 occurs. The resulting tree file can be processed by ASIS, for the purpose
4868 of providing partial information about illegal units, but if the error
4869 causes the tree to be badly malformed, then ASIS may crash during the
4870 analysis.
4871
4872 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4873 being in error, @command{gnatmake} will attempt to recompile the source when it
4874 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4875
4876 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4877 since ALI files are never generated if @option{-gnats} is set.
4878
4879 @end table
4880
4881 @node Warning Message Control
4882 @subsection Warning Message Control
4883 @cindex Warning messages
4884 @noindent
4885 In addition to error messages, which correspond to illegalities as defined
4886 in the Ada Reference Manual, the compiler detects two kinds of warning
4887 situations.
4888
4889 First, the compiler considers some constructs suspicious and generates a
4890 warning message to alert you to a possible error. Second, if the
4891 compiler detects a situation that is sure to raise an exception at
4892 run time, it generates a warning message. The following shows an example
4893 of warning messages:
4894 @smallexample
4895 e.adb:4:24: warning: creation of object may raise Storage_Error
4896 e.adb:10:17: warning: static value out of range
4897 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4898 @end smallexample
4899
4900 @noindent
4901 GNAT considers a large number of situations as appropriate
4902 for the generation of warning messages. As always, warnings are not
4903 definite indications of errors. For example, if you do an out-of-range
4904 assignment with the deliberate intention of raising a
4905 @code{Constraint_Error} exception, then the warning that may be
4906 issued does not indicate an error. Some of the situations for which GNAT
4907 issues warnings (at least some of the time) are given in the following
4908 list. This list is not complete, and new warnings are often added to
4909 subsequent versions of GNAT. The list is intended to give a general idea
4910 of the kinds of warnings that are generated.
4911
4912 @itemize @bullet
4913 @item
4914 Possible infinitely recursive calls
4915
4916 @item
4917 Out-of-range values being assigned
4918
4919 @item
4920 Possible order of elaboration problems
4921
4922 @item
4923 Assertions (pragma Assert) that are sure to fail
4924
4925 @item
4926 Unreachable code
4927
4928 @item
4929 Address clauses with possibly unaligned values, or where an attempt is
4930 made to overlay a smaller variable with a larger one.
4931
4932 @item
4933 Fixed-point type declarations with a null range
4934
4935 @item
4936 Direct_IO or Sequential_IO instantiated with a type that has access values
4937
4938 @item
4939 Variables that are never assigned a value
4940
4941 @item
4942 Variables that are referenced before being initialized
4943
4944 @item
4945 Task entries with no corresponding @code{accept} statement
4946
4947 @item
4948 Duplicate accepts for the same task entry in a @code{select}
4949
4950 @item
4951 Objects that take too much storage
4952
4953 @item
4954 Unchecked conversion between types of differing sizes
4955
4956 @item
4957 Missing @code{return} statement along some execution path in a function
4958
4959 @item
4960 Incorrect (unrecognized) pragmas
4961
4962 @item
4963 Incorrect external names
4964
4965 @item
4966 Allocation from empty storage pool
4967
4968 @item
4969 Potentially blocking operation in protected type
4970
4971 @item
4972 Suspicious parenthesization of expressions
4973
4974 @item
4975 Mismatching bounds in an aggregate
4976
4977 @item
4978 Attempt to return local value by reference
4979
4980 @item
4981 Premature instantiation of a generic body
4982
4983 @item
4984 Attempt to pack aliased components
4985
4986 @item
4987 Out of bounds array subscripts
4988
4989 @item
4990 Wrong length on string assignment
4991
4992 @item
4993 Violations of style rules if style checking is enabled
4994
4995 @item
4996 Unused @code{with} clauses
4997
4998 @item
4999 @code{Bit_Order} usage that does not have any effect
5000
5001 @item
5002 @code{Standard.Duration} used to resolve universal fixed expression
5003
5004 @item
5005 Dereference of possibly null value
5006
5007 @item
5008 Declaration that is likely to cause storage error
5009
5010 @item
5011 Internal GNAT unit @code{with}'ed by application unit
5012
5013 @item
5014 Values known to be out of range at compile time
5015
5016 @item
5017 Unreferenced labels and variables
5018
5019 @item
5020 Address overlays that could clobber memory
5021
5022 @item
5023 Unexpected initialization when address clause present
5024
5025 @item
5026 Bad alignment for address clause
5027
5028 @item
5029 Useless type conversions
5030
5031 @item
5032 Redundant assignment statements and other redundant constructs
5033
5034 @item
5035 Useless exception handlers
5036
5037 @item
5038 Accidental hiding of name by child unit
5039
5040 @item
5041 Access before elaboration detected at compile time
5042
5043 @item
5044 A range in a @code{for} loop that is known to be null or might be null
5045
5046 @end itemize
5047
5048 @noindent
5049 The following section lists compiler switches that are available
5050 to control the handling of warning messages. It is also possible
5051 to exercise much finer control over what warnings are issued and
5052 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5053 gnat_rm, GNAT Reference manual}.
5054
5055 @table @option
5056 @c !sort!
5057 @item -gnatwa
5058 @emph{Activate most optional warnings.}
5059 @cindex @option{-gnatwa} (@command{gcc})
5060 This switch activates most optional warning messages.  See the remaining list
5061 in this section for details on optional warning messages that can be
5062 individually controlled.  The warnings that are not turned on by this
5063 switch are
5064 @option{-gnatwd} (implicit dereferencing),
5065 @option{-gnatwh} (hiding),
5066 @option{-gnatw.h} (holes (gaps) in record layouts)
5067 @option{-gnatwl} (elaboration warnings),
5068 @option{-gnatw.o} (warn on values set by out parameters ignored)
5069 and @option{-gnatwt} (tracking of deleted conditional code).
5070 All other optional warnings are turned on.
5071
5072 @item -gnatwA
5073 @emph{Suppress all optional errors.}
5074 @cindex @option{-gnatwA} (@command{gcc})
5075 This switch suppresses all optional warning messages, see remaining list
5076 in this section for details on optional warning messages that can be
5077 individually controlled.
5078
5079 @item -gnatw.a
5080 @emph{Activate warnings on failing assertions.}
5081 @cindex @option{-gnatw.a} (@command{gcc})
5082 @cindex Assert failures
5083 This switch activates warnings for assertions where the compiler can tell at
5084 compile time that the assertion will fail. Note that this warning is given
5085 even if assertions are disabled. The default is that such warnings are
5086 generated.
5087
5088 @item -gnatw.A
5089 @emph{Suppress warnings on failing assertions.}
5090 @cindex @option{-gnatw.A} (@command{gcc})
5091 @cindex Assert failures
5092 This switch suppresses warnings for assertions where the compiler can tell at
5093 compile time that the assertion will fail.
5094
5095 @item -gnatwb
5096 @emph{Activate warnings on bad fixed values.}
5097 @cindex @option{-gnatwb} (@command{gcc})
5098 @cindex Bad fixed values
5099 @cindex Fixed-point Small value
5100 @cindex Small value
5101 This switch activates warnings for static fixed-point expressions whose
5102 value is not an exact multiple of Small. Such values are implementation
5103 dependent, since an implementation is free to choose either of the multiples
5104 that surround the value. GNAT always chooses the closer one, but this is not
5105 required behavior, and it is better to specify a value that is an exact
5106 multiple, ensuring predictable execution. The default is that such warnings
5107 are not generated.
5108
5109 @item -gnatwB
5110 @emph{Suppress warnings on bad fixed values.}
5111 @cindex @option{-gnatwB} (@command{gcc})
5112 This switch suppresses warnings for static fixed-point expressions whose
5113 value is not an exact multiple of Small.
5114
5115 @item -gnatw.b
5116 @emph{Activate warnings on biased representation.}
5117 @cindex @option{-gnatw.b} (@command{gcc})
5118 @cindex Biased representation
5119 This switch activates warnings when a size clause, value size clause, component
5120 clause, or component size clause forces the use of biased representation for an
5121 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5122 to represent 10/11). The default is that such warnings are generated.
5123
5124 @item -gnatw.B
5125 @emph{Suppress warnings on biased representation.}
5126 @cindex @option{-gnatwB} (@command{gcc})
5127 This switch suppresses warnings for representation clauses that force the use
5128 of biased representation.
5129
5130 @item -gnatwc
5131 @emph{Activate warnings on conditionals.}
5132 @cindex @option{-gnatwc} (@command{gcc})
5133 @cindex Conditionals, constant
5134 This switch activates warnings for conditional expressions used in
5135 tests that are known to be True or False at compile time. The default
5136 is that such warnings are not generated.
5137 Note that this warning does
5138 not get issued for the use of boolean variables or constants whose
5139 values are known at compile time, since this is a standard technique
5140 for conditional compilation in Ada, and this would generate too many
5141 false positive warnings.
5142
5143 This warning option also activates a special test for comparisons using
5144 the operators ``>='' and`` <=''.
5145 If the compiler can tell that only the equality condition is possible,
5146 then it will warn that the ``>'' or ``<'' part of the test
5147 is useless and that the operator could be replaced by ``=''.
5148 An example would be comparing a @code{Natural} variable <= 0.
5149
5150 This warning option also generates warnings if
5151 one or both tests is optimized away in a membership test for integer
5152 values if the result can be determined at compile time. Range tests on
5153 enumeration types are not included, since it is common for such tests
5154 to include an end point.
5155
5156 This warning can also be turned on using @option{-gnatwa}.
5157
5158 @item -gnatwC
5159 @emph{Suppress warnings on conditionals.}
5160 @cindex @option{-gnatwC} (@command{gcc})
5161 This switch suppresses warnings for conditional expressions used in
5162 tests that are known to be True or False at compile time.
5163
5164 @item -gnatw.c
5165 @emph{Activate warnings on missing component clauses.}
5166 @cindex @option{-gnatw.c} (@command{gcc})
5167 @cindex Component clause, missing
5168 This switch activates warnings for record components where a record
5169 representation clause is present and has component clauses for the
5170 majority, but not all, of the components. A warning is given for each
5171 component for which no component clause is present.
5172
5173 This warning can also be turned on using @option{-gnatwa}.
5174
5175 @item -gnatw.C
5176 @emph{Suppress warnings on missing component clauses.}
5177 @cindex @option{-gnatwC} (@command{gcc})
5178 This switch suppresses warnings for record components that are
5179 missing a component clause in the situation described above.
5180
5181 @item -gnatwd
5182 @emph{Activate warnings on implicit dereferencing.}
5183 @cindex @option{-gnatwd} (@command{gcc})
5184 If this switch is set, then the use of a prefix of an access type
5185 in an indexed component, slice, or selected component without an
5186 explicit @code{.all} will generate a warning. With this warning
5187 enabled, access checks occur only at points where an explicit
5188 @code{.all} appears in the source code (assuming no warnings are
5189 generated as a result of this switch). The default is that such
5190 warnings are not generated.
5191 Note that @option{-gnatwa} does not affect the setting of
5192 this warning option.
5193
5194 @item -gnatwD
5195 @emph{Suppress warnings on implicit dereferencing.}
5196 @cindex @option{-gnatwD} (@command{gcc})
5197 @cindex Implicit dereferencing
5198 @cindex Dereferencing, implicit
5199 This switch suppresses warnings for implicit dereferences in
5200 indexed components, slices, and selected components.
5201
5202 @item -gnatwe
5203 @emph{Treat warnings and style checks as errors.}
5204 @cindex @option{-gnatwe} (@command{gcc})
5205 @cindex Warnings, treat as error
5206 This switch causes warning messages and style check messages to be
5207 treated as errors.
5208 The warning string still appears, but the warning messages are counted
5209 as errors, and prevent the generation of an object file. Note that this
5210 is the only -gnatw switch that affects the handling of style check messages.
5211
5212 @item -gnatw.e
5213 @emph{Activate every optional warning}
5214 @cindex @option{-gnatw.e} (@command{gcc})
5215 @cindex Warnings, activate every optional warning
5216 This switch activates all optional warnings, including those which
5217 are not activated by @code{-gnatwa}.
5218
5219 @item -gnatwf
5220 @emph{Activate warnings on unreferenced formals.}
5221 @cindex @option{-gnatwf} (@command{gcc})
5222 @cindex Formals, unreferenced
5223 This switch causes a warning to be generated if a formal parameter
5224 is not referenced in the body of the subprogram. This warning can
5225 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5226 default is that these warnings are not generated.
5227
5228 @item -gnatwF
5229 @emph{Suppress warnings on unreferenced formals.}
5230 @cindex @option{-gnatwF} (@command{gcc})
5231 This switch suppresses warnings for unreferenced formal
5232 parameters. Note that the
5233 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5234 effect of warning on unreferenced entities other than subprogram
5235 formals.
5236
5237 @item -gnatwg
5238 @emph{Activate warnings on unrecognized pragmas.}
5239 @cindex @option{-gnatwg} (@command{gcc})
5240 @cindex Pragmas, unrecognized
5241 This switch causes a warning to be generated if an unrecognized
5242 pragma is encountered. Apart from issuing this warning, the
5243 pragma is ignored and has no effect. This warning can
5244 also be turned on using @option{-gnatwa}. The default
5245 is that such warnings are issued (satisfying the Ada Reference
5246 Manual requirement that such warnings appear).
5247
5248 @item -gnatwG
5249 @emph{Suppress warnings on unrecognized pragmas.}
5250 @cindex @option{-gnatwG} (@command{gcc})
5251 This switch suppresses warnings for unrecognized pragmas.
5252
5253 @item -gnatwh
5254 @emph{Activate warnings on hiding.}
5255 @cindex @option{-gnatwh} (@command{gcc})
5256 @cindex Hiding of Declarations
5257 This switch activates warnings on hiding declarations.
5258 A declaration is considered hiding
5259 if it is for a non-overloadable entity, and it declares an entity with the
5260 same name as some other entity that is directly or use-visible. The default
5261 is that such warnings are not generated.
5262 Note that @option{-gnatwa} does not affect the setting of this warning option.
5263
5264 @item -gnatwH
5265 @emph{Suppress warnings on hiding.}
5266 @cindex @option{-gnatwH} (@command{gcc})
5267 This switch suppresses warnings on hiding declarations.
5268
5269 @item -gnatw.h
5270 @emph{Activate warnings on holes/gaps in records.}
5271 @cindex @option{-gnatw.h} (@command{gcc})
5272 @cindex Record Representation (gaps)
5273 This switch activates warnings on component clauses in record
5274 representation clauses that leave holes (gaps) in the record layout.
5275 If this warning option is active, then record representation clauses
5276 should specify a contiguous layout, adding unused fill fields if needed.
5277 Note that @option{-gnatwa} does not affect the setting of this warning option.
5278
5279 @item -gnatw.H
5280 @emph{Suppress warnings on holes/gaps in records.}
5281 @cindex @option{-gnatw.H} (@command{gcc})
5282 This switch suppresses warnings on component clauses in record
5283 representation clauses that leave holes (haps) in the record layout.
5284
5285 @item -gnatwi
5286 @emph{Activate warnings on implementation units.}
5287 @cindex @option{-gnatwi} (@command{gcc})
5288 This switch activates warnings for a @code{with} of an internal GNAT
5289 implementation unit, defined as any unit from the @code{Ada},
5290 @code{Interfaces}, @code{GNAT},
5291 ^^@code{DEC},^ or @code{System}
5292 hierarchies that is not
5293 documented in either the Ada Reference Manual or the GNAT
5294 Programmer's Reference Manual. Such units are intended only
5295 for internal implementation purposes and should not be @code{with}'ed
5296 by user programs. The default is that such warnings are generated
5297 This warning can also be turned on using @option{-gnatwa}.
5298
5299 @item -gnatwI
5300 @emph{Disable warnings on implementation units.}
5301 @cindex @option{-gnatwI} (@command{gcc})
5302 This switch disables warnings for a @code{with} of an internal GNAT
5303 implementation unit.
5304
5305 @item -gnatw.i
5306 @emph{Activate warnings on overlapping actuals.}
5307 @cindex @option{-gnatw.i} (@command{gcc})
5308 This switch enables a warning on statically detectable overlapping actuals in
5309 a subprogram call, when one of the actuals is an in-out parameter, and the
5310 types of the actuals are not by-copy types. The warning is off by default,
5311 and is not included under -gnatwa.
5312
5313 @item -gnatw.I
5314 @emph{Disable warnings on overlapping actuals.}
5315 @cindex @option{-gnatw.I} (@command{gcc})
5316 This switch disables warnings on overlapping actuals in a call..
5317
5318 @item -gnatwj
5319 @emph{Activate warnings on obsolescent features (Annex J).}
5320 @cindex @option{-gnatwj} (@command{gcc})
5321 @cindex Features, obsolescent
5322 @cindex Obsolescent features
5323 If this warning option is activated, then warnings are generated for
5324 calls to subprograms marked with @code{pragma Obsolescent} and
5325 for use of features in Annex J of the Ada Reference Manual. In the
5326 case of Annex J, not all features are flagged. In particular use
5327 of the renamed packages (like @code{Text_IO}) and use of package
5328 @code{ASCII} are not flagged, since these are very common and
5329 would generate many annoying positive warnings. The default is that
5330 such warnings are not generated. This warning is also turned on by
5331 the use of @option{-gnatwa}.
5332
5333 In addition to the above cases, warnings are also generated for
5334 GNAT features that have been provided in past versions but which
5335 have been superseded (typically by features in the new Ada standard).
5336 For example, @code{pragma Ravenscar} will be flagged since its
5337 function is replaced by @code{pragma Profile(Ravenscar)}.
5338
5339 Note that this warning option functions differently from the
5340 restriction @code{No_Obsolescent_Features} in two respects.
5341 First, the restriction applies only to annex J features.
5342 Second, the restriction does flag uses of package @code{ASCII}.
5343
5344 @item -gnatwJ
5345 @emph{Suppress warnings on obsolescent features (Annex J).}
5346 @cindex @option{-gnatwJ} (@command{gcc})
5347 This switch disables warnings on use of obsolescent features.
5348
5349 @item -gnatwk
5350 @emph{Activate warnings on variables that could be constants.}
5351 @cindex @option{-gnatwk} (@command{gcc})
5352 This switch activates warnings for variables that are initialized but
5353 never modified, and then could be declared constants. The default is that
5354 such warnings are not given.
5355 This warning can also be turned on using @option{-gnatwa}.
5356
5357 @item -gnatwK
5358 @emph{Suppress warnings on variables that could be constants.}
5359 @cindex @option{-gnatwK} (@command{gcc})
5360 This switch disables warnings on variables that could be declared constants.
5361
5362 @item -gnatwl
5363 @emph{Activate warnings for elaboration pragmas.}
5364 @cindex @option{-gnatwl} (@command{gcc})
5365 @cindex Elaboration, warnings
5366 This switch activates warnings on missing
5367 @code{Elaborate_All} and @code{Elaborate} pragmas.
5368 See the section in this guide on elaboration checking for details on
5369 when such pragmas should be used. In dynamic elaboration mode, this switch
5370 generations warnings about the need to add elaboration pragmas. Note however,
5371 that if you blindly follow these warnings, and add @code{Elaborate_All}
5372 warnings wherever they are recommended, you basically end up with the
5373 equivalent of the static elaboration model, which may not be what you want for
5374 legacy code for which the static model does not work.
5375
5376 For the static model, the messages generated are labeled "info:" (for
5377 information messages). They are not warnings to add elaboration pragmas,
5378 merely informational messages showing what implicit elaboration pragmas
5379 have been added, for use in analyzing elaboration circularity problems.
5380
5381 Warnings are also generated if you
5382 are using the static mode of elaboration, and a @code{pragma Elaborate}
5383 is encountered. The default is that such warnings
5384 are not generated.
5385 This warning is not automatically turned on by the use of @option{-gnatwa}.
5386
5387 @item -gnatwL
5388 @emph{Suppress warnings for elaboration pragmas.}
5389 @cindex @option{-gnatwL} (@command{gcc})
5390 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5391 See the section in this guide on elaboration checking for details on
5392 when such pragmas should be used.
5393
5394 @item -gnatwm
5395 @emph{Activate warnings on modified but unreferenced variables.}
5396 @cindex @option{-gnatwm} (@command{gcc})
5397 This switch activates warnings for variables that are assigned (using
5398 an initialization value or with one or more assignment statements) but
5399 whose value is never read. The warning is suppressed for volatile
5400 variables and also for variables that are renamings of other variables
5401 or for which an address clause is given.
5402 This warning can also be turned on using @option{-gnatwa}.
5403 The default is that these warnings are not given.
5404
5405 @item -gnatwM
5406 @emph{Disable warnings on modified but unreferenced variables.}
5407 @cindex @option{-gnatwM} (@command{gcc})
5408 This switch disables warnings for variables that are assigned or
5409 initialized, but never read.
5410
5411 @item -gnatw.m
5412 @emph{Activate warnings on suspicious modulus values.}
5413 @cindex @option{-gnatw.m} (@command{gcc})
5414 This switch activates warnings for modulus values that seem suspicious.
5415 The cases caught are where the size is the same as the modulus (e.g.
5416 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5417 with no size clause. The guess in both cases is that 2**x was intended
5418 rather than x. The default is that these warnings are given.
5419
5420 @item -gnatw.M
5421 @emph{Disable warnings on suspicious modulus values.}
5422 @cindex @option{-gnatw.M} (@command{gcc})
5423 This switch disables warnings for suspicious modulus values.
5424
5425 @item -gnatwn
5426 @emph{Set normal warnings mode.}
5427 @cindex @option{-gnatwn} (@command{gcc})
5428 This switch sets normal warning mode, in which enabled warnings are
5429 issued and treated as warnings rather than errors. This is the default
5430 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5431 an explicit @option{-gnatws} or
5432 @option{-gnatwe}. It also cancels the effect of the
5433 implicit @option{-gnatwe} that is activated by the
5434 use of @option{-gnatg}.
5435
5436 @item -gnatwo
5437 @emph{Activate warnings on address clause overlays.}
5438 @cindex @option{-gnatwo} (@command{gcc})
5439 @cindex Address Clauses, warnings
5440 This switch activates warnings for possibly unintended initialization
5441 effects of defining address clauses that cause one variable to overlap
5442 another. The default is that such warnings are generated.
5443 This warning can also be turned on using @option{-gnatwa}.
5444
5445 @item -gnatwO
5446 @emph{Suppress warnings on address clause overlays.}
5447 @cindex @option{-gnatwO} (@command{gcc})
5448 This switch suppresses warnings on possibly unintended initialization
5449 effects of defining address clauses that cause one variable to overlap
5450 another.
5451
5452 @item -gnatw.o
5453 @emph{Activate warnings on modified but unreferenced out parameters.}
5454 @cindex @option{-gnatw.o} (@command{gcc})
5455 This switch activates warnings for variables that are modified by using
5456 them as actuals for a call to a procedure with an out mode formal, where
5457 the resulting assigned value is never read. It is applicable in the case
5458 where there is more than one out mode formal. If there is only one out
5459 mode formal, the warning is issued by default (controlled by -gnatwu).
5460 The warning is suppressed for volatile
5461 variables and also for variables that are renamings of other variables
5462 or for which an address clause is given.
5463 The default is that these warnings are not given. Note that this warning
5464 is not included in -gnatwa, it must be activated explicitly.
5465
5466 @item -gnatw.O
5467 @emph{Disable warnings on modified but unreferenced out parameters.}
5468 @cindex @option{-gnatw.O} (@command{gcc})
5469 This switch suppresses warnings for variables that are modified by using
5470 them as actuals for a call to a procedure with an out mode formal, where
5471 the resulting assigned value is never read.
5472
5473 @item -gnatwp
5474 @emph{Activate warnings on ineffective pragma Inlines.}
5475 @cindex @option{-gnatwp} (@command{gcc})
5476 @cindex Inlining, warnings
5477 This switch activates warnings for failure of front end inlining
5478 (activated by @option{-gnatN}) to inline a particular call. There are
5479 many reasons for not being able to inline a call, including most
5480 commonly that the call is too complex to inline. The default is
5481 that such warnings are not given.
5482 This warning can also be turned on using @option{-gnatwa}.
5483 Warnings on ineffective inlining by the gcc back-end can be activated
5484 separately, using the gcc switch -Winline.
5485
5486 @item -gnatwP
5487 @emph{Suppress warnings on ineffective pragma Inlines.}
5488 @cindex @option{-gnatwP} (@command{gcc})
5489 This switch suppresses warnings on ineffective pragma Inlines. If the
5490 inlining mechanism cannot inline a call, it will simply ignore the
5491 request silently.
5492
5493 @item -gnatw.p
5494 @emph{Activate warnings on parameter ordering.}
5495 @cindex @option{-gnatw.p} (@command{gcc})
5496 @cindex Parameter order, warnings
5497 This switch activates warnings for cases of suspicious parameter
5498 ordering when the list of arguments are all simple identifiers that
5499 match the names of the formals, but are in a different order. The
5500 warning is suppressed if any use of named parameter notation is used,
5501 so this is the appropriate way to suppress a false positive (and
5502 serves to emphasize that the "misordering" is deliberate). The
5503 default is
5504 that such warnings are not given.
5505 This warning can also be turned on using @option{-gnatwa}.
5506
5507 @item -gnatw.P
5508 @emph{Suppress warnings on parameter ordering.}
5509 @cindex @option{-gnatw.P} (@command{gcc})
5510 This switch suppresses warnings on cases of suspicious parameter
5511 ordering.
5512
5513 @item -gnatwq
5514 @emph{Activate warnings on questionable missing parentheses.}
5515 @cindex @option{-gnatwq} (@command{gcc})
5516 @cindex Parentheses, warnings
5517 This switch activates warnings for cases where parentheses are not used and
5518 the result is potential ambiguity from a readers point of view. For example
5519 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5520 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5521 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5522 follow the rule of always parenthesizing to make the association clear, and
5523 this warning switch warns if such parentheses are not present. The default
5524 is that these warnings are given.
5525 This warning can also be turned on using @option{-gnatwa}.
5526
5527 @item -gnatwQ
5528 @emph{Suppress warnings on questionable missing parentheses.}
5529 @cindex @option{-gnatwQ} (@command{gcc})
5530 This switch suppresses warnings for cases where the association is not
5531 clear and the use of parentheses is preferred.
5532
5533 @item -gnatwr
5534 @emph{Activate warnings on redundant constructs.}
5535 @cindex @option{-gnatwr} (@command{gcc})
5536 This switch activates warnings for redundant constructs. The following
5537 is the current list of constructs regarded as redundant:
5538
5539 @itemize @bullet
5540 @item
5541 Assignment of an item to itself.
5542 @item
5543 Type conversion that converts an expression to its own type.
5544 @item
5545 Use of the attribute @code{Base} where @code{typ'Base} is the same
5546 as @code{typ}.
5547 @item
5548 Use of pragma @code{Pack} when all components are placed by a record
5549 representation clause.
5550 @item
5551 Exception handler containing only a reraise statement (raise with no
5552 operand) which has no effect.
5553 @item
5554 Use of the operator abs on an operand that is known at compile time
5555 to be non-negative
5556 @item
5557 Comparison of boolean expressions to an explicit True value.
5558 @end itemize
5559
5560 This warning can also be turned on using @option{-gnatwa}.
5561 The default is that warnings for redundant constructs are not given.
5562
5563 @item -gnatwR
5564 @emph{Suppress warnings on redundant constructs.}
5565 @cindex @option{-gnatwR} (@command{gcc})
5566 This switch suppresses warnings for redundant constructs.
5567
5568 @item -gnatw.r
5569 @emph{Activate warnings for object renaming function.}
5570 @cindex @option{-gnatw.r} (@command{gcc})
5571 This switch activates warnings for an object renaming that renames a
5572 function call, which is equivalent to a constant declaration (as
5573 opposed to renaming the function itself).  The default is that these
5574 warnings are given.  This warning can also be turned on using
5575 @option{-gnatwa}.
5576
5577 @item -gnatw.R
5578 @emph{Suppress warnings for object renaming function.}
5579 @cindex @option{-gnatwT} (@command{gcc})
5580 This switch suppresses warnings for object renaming function.
5581
5582 @item -gnatws
5583 @emph{Suppress all warnings.}
5584 @cindex @option{-gnatws} (@command{gcc})
5585 This switch completely suppresses the
5586 output of all warning messages from the GNAT front end.
5587 Note that it does not suppress warnings from the @command{gcc} back end.
5588 To suppress these back end warnings as well, use the switch @option{-w}
5589 in addition to @option{-gnatws}. Also this switch has no effect on the
5590 handling of style check messages.
5591
5592 @item -gnatw.s
5593 @emph{Activate warnings on overridden size clauses.}
5594 @cindex @option{-gnatw.s} (@command{gcc})
5595 @cindex Record Representation (component sizes)
5596 This switch activates warnings on component clauses in record
5597 representation clauses where the length given overrides that
5598 specified by an explicit size clause for the component type. A
5599 warning is similarly given in the array case if a specified
5600 component size overrides an explicit size clause for the array
5601 component type.
5602 Note that @option{-gnatwa} does not affect the setting of this warning option.
5603
5604 @item -gnatw.S
5605 @emph{Suppress warnings on overridden size clauses.}
5606 @cindex @option{-gnatw.S} (@command{gcc})
5607 This switch suppresses warnings on component clauses in record
5608 representation clauses that override size clauses, and similar
5609 warnings when an array component size overrides a size clause.
5610
5611 @item -gnatwt
5612 @emph{Activate warnings for tracking of deleted conditional code.}
5613 @cindex @option{-gnatwt} (@command{gcc})
5614 @cindex Deactivated code, warnings
5615 @cindex Deleted code, warnings
5616 This switch activates warnings for tracking of code in conditionals (IF and
5617 CASE statements) that is detected to be dead code which cannot be executed, and
5618 which is removed by the front end. This warning is off by default, and is not
5619 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5620 useful for detecting deactivated code in certified applications.
5621
5622 @item -gnatwT
5623 @emph{Suppress warnings for tracking of deleted conditional code.}
5624 @cindex @option{-gnatwT} (@command{gcc})
5625 This switch suppresses warnings for tracking of deleted conditional code.
5626
5627 @item -gnatwu
5628 @emph{Activate warnings on unused entities.}
5629 @cindex @option{-gnatwu} (@command{gcc})
5630 This switch activates warnings to be generated for entities that
5631 are declared but not referenced, and for units that are @code{with}'ed
5632 and not
5633 referenced. In the case of packages, a warning is also generated if
5634 no entities in the package are referenced. This means that if the package
5635 is referenced but the only references are in @code{use}
5636 clauses or @code{renames}
5637 declarations, a warning is still generated. A warning is also generated
5638 for a generic package that is @code{with}'ed but never instantiated.
5639 In the case where a package or subprogram body is compiled, and there
5640 is a @code{with} on the corresponding spec
5641 that is only referenced in the body,
5642 a warning is also generated, noting that the
5643 @code{with} can be moved to the body. The default is that
5644 such warnings are not generated.
5645 This switch also activates warnings on unreferenced formals
5646 (it includes the effect of @option{-gnatwf}).
5647 This warning can also be turned on using @option{-gnatwa}.
5648
5649 @item -gnatwU
5650 @emph{Suppress warnings on unused entities.}
5651 @cindex @option{-gnatwU} (@command{gcc})
5652 This switch suppresses warnings for unused entities and packages.
5653 It also turns off warnings on unreferenced formals (and thus includes
5654 the effect of @option{-gnatwF}).
5655
5656 @item -gnatw.u
5657 @emph{Activate warnings on unordered enumeration types.}
5658 @cindex @option{-gnatw.u} (@command{gcc})
5659 This switch causes enumeration types to be considered as conceptually
5660 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5661 The effect is to generate warnings in clients that use explicit comparisons
5662 or subranges, since these constructs both treat objects of the type as
5663 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5664 which the type is declared, or its body or subunits.) Please refer to
5665 the description of pragma @code{Ordered} in the
5666 @cite{@value{EDITION} Reference Manual} for further details.
5667
5668 @item -gnatw.U
5669 @emph{Deactivate warnings on unordered enumeration types.}
5670 @cindex @option{-gnatw.U} (@command{gcc})
5671 This switch causes all enumeration types to be considered as ordered, so
5672 that no warnings are given for comparisons or subranges for any type.
5673
5674 @item -gnatwv
5675 @emph{Activate warnings on unassigned variables.}
5676 @cindex @option{-gnatwv} (@command{gcc})
5677 @cindex Unassigned variable warnings
5678 This switch activates warnings for access to variables which
5679 may not be properly initialized. The default is that
5680 such warnings are generated.
5681 This warning can also be turned on using @option{-gnatwa}.
5682
5683 @item -gnatwV
5684 @emph{Suppress warnings on unassigned variables.}
5685 @cindex @option{-gnatwV} (@command{gcc})
5686 This switch suppresses warnings for access to variables which
5687 may not be properly initialized.
5688 For variables of a composite type, the warning can also be suppressed in
5689 Ada 2005 by using a default initialization with a box. For example, if
5690 Table is an array of records whose components are only partially uninitialized,
5691 then the following code:
5692
5693 @smallexample @c ada
5694    Tab : Table := (others => <>);
5695 @end smallexample
5696
5697 will suppress warnings on subsequent statements that access components
5698 of variable Tab.
5699
5700 @item -gnatww
5701 @emph{Activate warnings on wrong low bound assumption.}
5702 @cindex @option{-gnatww} (@command{gcc})
5703 @cindex String indexing warnings
5704 This switch activates warnings for indexing an unconstrained string parameter
5705 with a literal or S'Length. This is a case where the code is assuming that the
5706 low bound is one, which is in general not true (for example when a slice is
5707 passed). The default is that such warnings are generated.
5708 This warning can also be turned on using @option{-gnatwa}.
5709
5710 @item -gnatwW
5711 @emph{Suppress warnings on wrong low bound assumption.}
5712 @cindex @option{-gnatwW} (@command{gcc})
5713 This switch suppresses warnings for indexing an unconstrained string parameter
5714 with a literal or S'Length. Note that this warning can also be suppressed
5715 in a particular case by adding an
5716 assertion that the lower bound is 1,
5717 as shown in the following example.
5718
5719 @smallexample @c ada
5720    procedure K (S : String) is
5721       pragma Assert (S'First = 1);
5722       @dots{}
5723 @end smallexample
5724
5725 @item -gnatw.w
5726 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5727 @cindex @option{-gnatw.w} (@command{gcc})
5728 @cindex Warnings Off control
5729 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5730 where either the pragma is entirely useless (because it suppresses no
5731 warnings), or it could be replaced by @code{pragma Unreferenced} or
5732 @code{pragma Unmodified}.The default is that these warnings are not given.
5733 Note that this warning is not included in -gnatwa, it must be
5734 activated explicitly.
5735
5736 @item -gnatw.W
5737 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5738 @cindex @option{-gnatw.W} (@command{gcc})
5739 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5740
5741 @item -gnatwx
5742 @emph{Activate warnings on Export/Import pragmas.}
5743 @cindex @option{-gnatwx} (@command{gcc})
5744 @cindex Export/Import pragma warnings
5745 This switch activates warnings on Export/Import pragmas when
5746 the compiler detects a possible conflict between the Ada and
5747 foreign language calling sequences. For example, the use of
5748 default parameters in a convention C procedure is dubious
5749 because the C compiler cannot supply the proper default, so
5750 a warning is issued. The default is that such warnings are
5751 generated.
5752 This warning can also be turned on using @option{-gnatwa}.
5753
5754 @item -gnatwX
5755 @emph{Suppress warnings on Export/Import pragmas.}
5756 @cindex @option{-gnatwX} (@command{gcc})
5757 This switch suppresses warnings on Export/Import pragmas.
5758 The sense of this is that you are telling the compiler that
5759 you know what you are doing in writing the pragma, and it
5760 should not complain at you.
5761
5762 @item -gnatw.x
5763 @emph{Activate warnings for No_Exception_Propagation mode.}
5764 @cindex @option{-gnatwm} (@command{gcc})
5765 This switch activates warnings for exception usage when pragma Restrictions
5766 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5767 explicit exception raises which are not covered by a local handler, and for
5768 exception handlers which do not cover a local raise. The default is that these
5769 warnings are not given.
5770
5771 @item -gnatw.X
5772 @emph{Disable warnings for No_Exception_Propagation mode.}
5773 This switch disables warnings for exception usage when pragma Restrictions
5774 (No_Exception_Propagation) is in effect.
5775
5776 @item -gnatwy
5777 @emph{Activate warnings for Ada 2005 compatibility issues.}
5778 @cindex @option{-gnatwy} (@command{gcc})
5779 @cindex Ada 2005 compatibility issues warnings
5780 For the most part Ada 2005 is upwards compatible with Ada 95,
5781 but there are some exceptions (for example the fact that
5782 @code{interface} is now a reserved word in Ada 2005). This
5783 switch activates several warnings to help in identifying
5784 and correcting such incompatibilities. The default is that
5785 these warnings are generated. Note that at one point Ada 2005
5786 was called Ada 0Y, hence the choice of character.
5787 This warning can also be turned on using @option{-gnatwa}.
5788
5789 @item -gnatwY
5790 @emph{Disable warnings for Ada 2005 compatibility issues.}
5791 @cindex @option{-gnatwY} (@command{gcc})
5792 @cindex Ada 2005 compatibility issues warnings
5793 This switch suppresses several warnings intended to help in identifying
5794 incompatibilities between Ada 95 and Ada 2005.
5795
5796 @item -gnatwz
5797 @emph{Activate warnings on unchecked conversions.}
5798 @cindex @option{-gnatwz} (@command{gcc})
5799 @cindex Unchecked_Conversion warnings
5800 This switch activates warnings for unchecked conversions
5801 where the types are known at compile time to have different
5802 sizes. The default
5803 is that such warnings are generated. Warnings are also
5804 generated for subprogram pointers with different conventions,
5805 and, on VMS only, for data pointers with different conventions.
5806 This warning can also be turned on using @option{-gnatwa}.
5807
5808 @item -gnatwZ
5809 @emph{Suppress warnings on unchecked conversions.}
5810 @cindex @option{-gnatwZ} (@command{gcc})
5811 This switch suppresses warnings for unchecked conversions
5812 where the types are known at compile time to have different
5813 sizes or conventions.
5814
5815 @item ^-Wunused^WARNINGS=UNUSED^
5816 @cindex @option{-Wunused}
5817 The warnings controlled by the @option{-gnatw} switch are generated by
5818 the front end of the compiler. The @option{GCC} back end can provide
5819 additional warnings and they are controlled by the @option{-W} switch.
5820 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5821 warnings for entities that are declared but not referenced.
5822
5823 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5824 @cindex @option{-Wuninitialized}
5825 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5826 the back end warning for uninitialized variables. This switch must be
5827 used in conjunction with an optimization level greater than zero.
5828
5829 @item -Wstack-usage=@var{len}
5830 @cindex @option{-Wstack-usage}
5831 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5832 See @ref{Static Stack Usage Analysis} for details.
5833
5834 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5835 @cindex @option{-Wall}
5836 This switch enables most warnings from the @option{GCC} back end.
5837 The code generator detects a number of warning situations that are missed
5838 by the @option{GNAT} front end, and this switch can be used to activate them.
5839 The use of this switch also sets the default front end warning mode to
5840 @option{-gnatwa}, that is, most front end warnings activated as well.
5841
5842 @item ^-w^/NO_BACK_END_WARNINGS^
5843 @cindex @option{-w}
5844 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5845 The use of this switch also sets the default front end warning mode to
5846 @option{-gnatws}, that is, front end warnings suppressed as well.
5847
5848 @end table
5849
5850 @noindent
5851 @ifclear vms
5852 A string of warning parameters can be used in the same parameter. For example:
5853
5854 @smallexample
5855 -gnatwaLe
5856 @end smallexample
5857
5858 @noindent
5859 will turn on all optional warnings except for elaboration pragma warnings,
5860 and also specify that warnings should be treated as errors.
5861 @end ifclear
5862 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5863
5864 @table @option
5865 @c !sort!
5866 @item -gnatwC
5867 @item -gnatwD
5868 @item -gnatwF
5869 @item -gnatwg
5870 @item -gnatwH
5871 @item -gnatwi
5872 @item -gnatwJ
5873 @item -gnatwK
5874 @item -gnatwL
5875 @item -gnatwM
5876 @item -gnatwn
5877 @item -gnatwo
5878 @item -gnatwP
5879 @item -gnatwR
5880 @item -gnatwU
5881 @item -gnatwv
5882 @item -gnatwz
5883 @item -gnatwx
5884
5885 @end table
5886
5887 @node Debugging and Assertion Control
5888 @subsection Debugging and Assertion Control
5889
5890 @table @option
5891 @item -gnata
5892 @cindex @option{-gnata} (@command{gcc})
5893 @findex Assert
5894 @findex Debug
5895 @cindex Assertions
5896
5897 @noindent
5898 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5899 are ignored. This switch, where @samp{a} stands for assert, causes
5900 @code{Assert} and @code{Debug} pragmas to be activated.
5901
5902 The pragmas have the form:
5903
5904 @smallexample
5905 @cartouche
5906    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5907                       @var{static-string-expression}@r{]})
5908    @b{pragma} Debug (@var{procedure call})
5909 @end cartouche
5910 @end smallexample
5911
5912 @noindent
5913 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5914 If the result is @code{True}, the pragma has no effect (other than
5915 possible side effects from evaluating the expression). If the result is
5916 @code{False}, the exception @code{Assert_Failure} declared in the package
5917 @code{System.Assertions} is
5918 raised (passing @var{static-string-expression}, if present, as the
5919 message associated with the exception). If no string expression is
5920 given the default is a string giving the file name and line number
5921 of the pragma.
5922
5923 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5924 @code{pragma Debug} may appear within a declaration sequence, allowing
5925 debugging procedures to be called between declarations.
5926
5927 @ifset vms
5928 @item /DEBUG@r{[}=debug-level@r{]}
5929 @itemx  /NODEBUG
5930 Specifies how much debugging information is to be included in
5931 the resulting object file where 'debug-level' is one of the following:
5932 @table @code
5933 @item   TRACEBACK
5934 Include both debugger symbol records and traceback
5935 the object file.
5936 This is the default setting.
5937 @item   ALL
5938 Include both debugger symbol records and traceback in
5939 object file.
5940 @item   NONE
5941 Excludes both debugger symbol records and traceback
5942 the object file. Same as /NODEBUG.
5943 @item   SYMBOLS
5944 Includes only debugger symbol records in the object
5945 file. Note that this doesn't include traceback information.
5946 @end table
5947 @end ifset
5948 @end table
5949
5950 @node Validity Checking
5951 @subsection Validity Checking
5952 @findex Validity Checking
5953
5954 @noindent
5955 The Ada Reference Manual defines the concept of invalid values (see
5956 RM 13.9.1). The primary source of invalid values is uninitialized
5957 variables. A scalar variable that is left uninitialized may contain
5958 an invalid value; the concept of invalid does not apply to access or
5959 composite types.
5960
5961 It is an error to read an invalid value, but the RM does not require
5962 run-time checks to detect such errors, except for some minimal
5963 checking to prevent erroneous execution (i.e. unpredictable
5964 behavior). This corresponds to the @option{-gnatVd} switch below,
5965 which is the default. For example, by default, if the expression of a
5966 case statement is invalid, it will raise Constraint_Error rather than
5967 causing a wild jump, and if an array index on the left-hand side of an
5968 assignment is invalid, it will raise Constraint_Error rather than
5969 overwriting an arbitrary memory location.
5970
5971 The @option{-gnatVa} may be used to enable additional validity checks,
5972 which are not required by the RM. These checks are often very
5973 expensive (which is why the RM does not require them). These checks
5974 are useful in tracking down uninitialized variables, but they are
5975 not usually recommended for production builds.
5976
5977 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5978 control; you can enable whichever validity checks you desire. However,
5979 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5980 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5981 sufficient for non-debugging use.
5982
5983 The @option{-gnatB} switch tells the compiler to assume that all
5984 values are valid (that is, within their declared subtype range)
5985 except in the context of a use of the Valid attribute. This means
5986 the compiler can generate more efficient code, since the range
5987 of values is better known at compile time. However, an uninitialized
5988 variable can cause wild jumps and memory corruption in this mode.
5989
5990 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5991 checking mode as described below.
5992 @ifclear vms
5993 The @code{x} argument is a string of letters that
5994 indicate validity checks that are performed or not performed in addition
5995 to the default checks required by Ada as described above.
5996 @end ifclear
5997 @ifset vms
5998 The options allowed for this qualifier
5999 indicate validity checks that are performed or not performed in addition
6000 to the default checks required by Ada as described above.
6001 @end ifset
6002
6003 @table @option
6004 @c !sort!
6005 @item -gnatVa
6006 @emph{All validity checks.}
6007 @cindex @option{-gnatVa} (@command{gcc})
6008 All validity checks are turned on.
6009 @ifclear vms
6010 That is, @option{-gnatVa} is
6011 equivalent to @option{gnatVcdfimorst}.
6012 @end ifclear
6013
6014 @item -gnatVc
6015 @emph{Validity checks for copies.}
6016 @cindex @option{-gnatVc} (@command{gcc})
6017 The right hand side of assignments, and the initializing values of
6018 object declarations are validity checked.
6019
6020 @item -gnatVd
6021 @emph{Default (RM) validity checks.}
6022 @cindex @option{-gnatVd} (@command{gcc})
6023 Some validity checks are done by default following normal Ada semantics
6024 (RM 13.9.1 (9-11)).
6025 A check is done in case statements that the expression is within the range
6026 of the subtype. If it is not, Constraint_Error is raised.
6027 For assignments to array components, a check is done that the expression used
6028 as index is within the range. If it is not, Constraint_Error is raised.
6029 Both these validity checks may be turned off using switch @option{-gnatVD}.
6030 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6031 switch @option{-gnatVd} will leave the checks turned on.
6032 Switch @option{-gnatVD} should be used only if you are sure that all such
6033 expressions have valid values. If you use this switch and invalid values
6034 are present, then the program is erroneous, and wild jumps or memory
6035 overwriting may occur.
6036
6037 @item -gnatVe
6038 @emph{Validity checks for elementary components.}
6039 @cindex @option{-gnatVe} (@command{gcc})
6040 In the absence of this switch, assignments to record or array components are
6041 not validity checked, even if validity checks for assignments generally
6042 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6043 require valid data, but assignment of individual components does. So for
6044 example, there is a difference between copying the elements of an array with a
6045 slice assignment, compared to assigning element by element in a loop. This
6046 switch allows you to turn off validity checking for components, even when they
6047 are assigned component by component.
6048
6049 @item -gnatVf
6050 @emph{Validity checks for floating-point values.}
6051 @cindex @option{-gnatVf} (@command{gcc})
6052 In the absence of this switch, validity checking occurs only for discrete
6053 values. If @option{-gnatVf} is specified, then validity checking also applies
6054 for floating-point values, and NaNs and infinities are considered invalid,
6055 as well as out of range values for constrained types. Note that this means
6056 that standard IEEE infinity mode is not allowed. The exact contexts
6057 in which floating-point values are checked depends on the setting of other
6058 options. For example,
6059 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6060 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6061 (the order does not matter) specifies that floating-point parameters of mode
6062 @code{in} should be validity checked.
6063
6064 @item -gnatVi
6065 @emph{Validity checks for @code{in} mode parameters}
6066 @cindex @option{-gnatVi} (@command{gcc})
6067 Arguments for parameters of mode @code{in} are validity checked in function
6068 and procedure calls at the point of call.
6069
6070 @item -gnatVm
6071 @emph{Validity checks for @code{in out} mode parameters.}
6072 @cindex @option{-gnatVm} (@command{gcc})
6073 Arguments for parameters of mode @code{in out} are validity checked in
6074 procedure calls at the point of call. The @code{'m'} here stands for
6075 modify, since this concerns parameters that can be modified by the call.
6076 Note that there is no specific option to test @code{out} parameters,
6077 but any reference within the subprogram will be tested in the usual
6078 manner, and if an invalid value is copied back, any reference to it
6079 will be subject to validity checking.
6080
6081 @item -gnatVn
6082 @emph{No validity checks.}
6083 @cindex @option{-gnatVn} (@command{gcc})
6084 This switch turns off all validity checking, including the default checking
6085 for case statements and left hand side subscripts. Note that the use of
6086 the switch @option{-gnatp} suppresses all run-time checks, including
6087 validity checks, and thus implies @option{-gnatVn}. When this switch
6088 is used, it cancels any other @option{-gnatV} previously issued.
6089
6090 @item -gnatVo
6091 @emph{Validity checks for operator and attribute operands.}
6092 @cindex @option{-gnatVo} (@command{gcc})
6093 Arguments for predefined operators and attributes are validity checked.
6094 This includes all operators in package @code{Standard},
6095 the shift operators defined as intrinsic in package @code{Interfaces}
6096 and operands for attributes such as @code{Pos}. Checks are also made
6097 on individual component values for composite comparisons, and on the
6098 expressions in type conversions and qualified expressions. Checks are
6099 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6100
6101 @item -gnatVp
6102 @emph{Validity checks for parameters.}
6103 @cindex @option{-gnatVp} (@command{gcc})
6104 This controls the treatment of parameters within a subprogram (as opposed
6105 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6106 of parameters on a call. If either of these call options is used, then
6107 normally an assumption is made within a subprogram that the input arguments
6108 have been validity checking at the point of call, and do not need checking
6109 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6110 is not made, and parameters are not assumed to be valid, so their validity
6111 will be checked (or rechecked) within the subprogram.
6112
6113 @item -gnatVr
6114 @emph{Validity checks for function returns.}
6115 @cindex @option{-gnatVr} (@command{gcc})
6116 The expression in @code{return} statements in functions is validity
6117 checked.
6118
6119 @item -gnatVs
6120 @emph{Validity checks for subscripts.}
6121 @cindex @option{-gnatVs} (@command{gcc})
6122 All subscripts expressions are checked for validity, whether they appear
6123 on the right side or left side (in default mode only left side subscripts
6124 are validity checked).
6125
6126 @item -gnatVt
6127 @emph{Validity checks for tests.}
6128 @cindex @option{-gnatVt} (@command{gcc})
6129 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6130 statements are checked, as well as guard expressions in entry calls.
6131
6132 @end table
6133
6134 @noindent
6135 The @option{-gnatV} switch may be followed by
6136 ^a string of letters^a list of options^
6137 to turn on a series of validity checking options.
6138 For example,
6139 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6140 specifies that in addition to the default validity checking, copies and
6141 function return expressions are to be validity checked.
6142 In order to make it easier
6143 to specify the desired combination of effects,
6144 @ifclear vms
6145 the upper case letters @code{CDFIMORST} may
6146 be used to turn off the corresponding lower case option.
6147 @end ifclear
6148 @ifset vms
6149 the prefix @code{NO} on an option turns off the corresponding validity
6150 checking:
6151 @itemize @bullet
6152 @item @code{NOCOPIES}
6153 @item @code{NODEFAULT}
6154 @item @code{NOFLOATS}
6155 @item @code{NOIN_PARAMS}
6156 @item @code{NOMOD_PARAMS}
6157 @item @code{NOOPERANDS}
6158 @item @code{NORETURNS}
6159 @item @code{NOSUBSCRIPTS}
6160 @item @code{NOTESTS}
6161 @end itemize
6162 @end ifset
6163 Thus
6164 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6165 turns on all validity checking options except for
6166 checking of @code{@b{in out}} procedure arguments.
6167
6168 The specification of additional validity checking generates extra code (and
6169 in the case of @option{-gnatVa} the code expansion can be substantial).
6170 However, these additional checks can be very useful in detecting
6171 uninitialized variables, incorrect use of unchecked conversion, and other
6172 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6173 is useful in conjunction with the extra validity checking, since this
6174 ensures that wherever possible uninitialized variables have invalid values.
6175
6176 See also the pragma @code{Validity_Checks} which allows modification of
6177 the validity checking mode at the program source level, and also allows for
6178 temporary disabling of validity checks.
6179
6180 @node Style Checking
6181 @subsection Style Checking
6182 @findex Style checking
6183
6184 @noindent
6185 The @option{-gnaty^x^(option,option,@dots{})^} switch
6186 @cindex @option{-gnaty} (@command{gcc})
6187 causes the compiler to
6188 enforce specified style rules. A limited set of style rules has been used
6189 in writing the GNAT sources themselves. This switch allows user programs
6190 to activate all or some of these checks. If the source program fails a
6191 specified style check, an appropriate message is given, preceded by
6192 the character sequence ``(style)''. This message does not prevent
6193 successful compilation (unless the @option{-gnatwe} switch is used).
6194
6195 Note that this is by no means intended to be a general facility for
6196 checking arbitrary coding standards. It is simply an embedding of the
6197 style rules we have chosen for the GNAT sources. If you are starting
6198 a project which does not have established style standards, you may
6199 find it useful to adopt the entire set of GNAT coding standards, or
6200 some subset of them. If you already have an established set of coding
6201 standards, then it may be that selected style checking options do
6202 indeed correspond to choices you have made, but for general checking
6203 of an existing set of coding rules, you should look to the gnatcheck
6204 tool, which is designed for that purpose.
6205
6206 @ifset vms
6207 @code{(option,option,@dots{})} is a sequence of keywords
6208 @end ifset
6209 @ifclear vms
6210 The string @var{x} is a sequence of letters or digits
6211 @end ifclear
6212 indicating the particular style
6213 checks to be performed. The following checks are defined:
6214
6215 @table @option
6216 @c !sort!
6217 @item 0-9
6218 @emph{Specify indentation level.}
6219 If a digit from 1-9 appears
6220 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6221 then proper indentation is checked, with the digit indicating the
6222 indentation level required. A value of zero turns off this style check.
6223 The general style of required indentation is as specified by
6224 the examples in the Ada Reference Manual. Full line comments must be
6225 aligned with the @code{--} starting on a column that is a multiple of
6226 the alignment level, or they may be aligned the same way as the following
6227 non-blank line (this is useful when full line comments appear in the middle
6228 of a statement.
6229
6230 @item ^a^ATTRIBUTE^
6231 @emph{Check attribute casing.}
6232 Attribute names, including the case of keywords such as @code{digits}
6233 used as attributes names, must be written in mixed case, that is, the
6234 initial letter and any letter following an underscore must be uppercase.
6235 All other letters must be lowercase.
6236
6237 @item ^A^ARRAY_INDEXES^
6238 @emph{Use of array index numbers in array attributes.}
6239 When using the array attributes First, Last, Range,
6240 or Length, the index number must be omitted for one-dimensional arrays
6241 and is required for multi-dimensional arrays.
6242
6243 @item ^b^BLANKS^
6244 @emph{Blanks not allowed at statement end.}
6245 Trailing blanks are not allowed at the end of statements. The purpose of this
6246 rule, together with h (no horizontal tabs), is to enforce a canonical format
6247 for the use of blanks to separate source tokens.
6248
6249 @item ^B^BOOLEAN_OPERATORS^
6250 @emph{Check Boolean operators.}
6251 The use of AND/OR operators is not permitted except in the cases of modular
6252 operands, array operands, and simple stand-alone boolean variables or
6253 boolean constants. In all other cases AND THEN/OR ELSE are required.
6254
6255 @item ^c^COMMENTS^
6256 @emph{Check comments.}
6257 Comments must meet the following set of rules:
6258
6259 @itemize @bullet
6260
6261 @item
6262 The ``@code{--}'' that starts the column must either start in column one,
6263 or else at least one blank must precede this sequence.
6264
6265 @item
6266 Comments that follow other tokens on a line must have at least one blank
6267 following the ``@code{--}'' at the start of the comment.
6268
6269 @item
6270 Full line comments must have at least two blanks following the
6271 ``@code{--}'' that starts the comment, with the following exceptions.
6272
6273 @item
6274 A line consisting only of the ``@code{--}'' characters, possibly preceded
6275 by blanks is permitted.
6276
6277 @item
6278 A comment starting with ``@code{--x}'' where @code{x} is a special character
6279 is permitted.
6280 This allows proper processing of the output generated by specialized tools
6281 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6282 annotation
6283 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6284 special character is defined as being in one of the ASCII ranges
6285 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6286 Note that this usage is not permitted
6287 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6288
6289 @item
6290 A line consisting entirely of minus signs, possibly preceded by blanks, is
6291 permitted. This allows the construction of box comments where lines of minus
6292 signs are used to form the top and bottom of the box.
6293
6294 @item
6295 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6296 least one blank follows the initial ``@code{--}''. Together with the preceding
6297 rule, this allows the construction of box comments, as shown in the following
6298 example:
6299 @smallexample
6300 ---------------------------
6301 -- This is a box comment --
6302 -- with two text lines.  --
6303 ---------------------------
6304 @end smallexample
6305 @end itemize
6306
6307 @item ^d^DOS_LINE_ENDINGS^
6308 @emph{Check no DOS line terminators present.}
6309 All lines must be terminated by a single ASCII.LF
6310 character (in particular the DOS line terminator sequence CR/LF is not
6311 allowed).
6312
6313 @item ^e^END^
6314 @emph{Check end/exit labels.}
6315 Optional labels on @code{end} statements ending subprograms and on
6316 @code{exit} statements exiting named loops, are required to be present.
6317
6318 @item ^f^VTABS^
6319 @emph{No form feeds or vertical tabs.}
6320 Neither form feeds nor vertical tab characters are permitted
6321 in the source text.
6322
6323 @item ^g^GNAT^
6324 @emph{GNAT style mode}
6325 The set of style check switches is set to match that used by the GNAT sources.
6326 This may be useful when developing code that is eventually intended to be
6327 incorporated into GNAT. For further details, see GNAT sources.
6328
6329 @item ^h^HTABS^
6330 @emph{No horizontal tabs.}
6331 Horizontal tab characters are not permitted in the source text.
6332 Together with the b (no blanks at end of line) check, this
6333 enforces a canonical form for the use of blanks to separate
6334 source tokens.
6335
6336 @item ^i^IF_THEN^
6337 @emph{Check if-then layout.}
6338 The keyword @code{then} must appear either on the same
6339 line as corresponding @code{if}, or on a line on its own, lined
6340 up under the @code{if} with at least one non-blank line in between
6341 containing all or part of the condition to be tested.
6342
6343 @item ^I^IN_MODE^
6344 @emph{check mode IN keywords}
6345 Mode @code{in} (the default mode) is not
6346 allowed to be given explicitly. @code{in out} is fine,
6347 but not @code{in} on its own.
6348
6349 @item ^k^KEYWORD^
6350 @emph{Check keyword casing.}
6351 All keywords must be in lower case (with the exception of keywords
6352 such as @code{digits} used as attribute names to which this check
6353 does not apply).
6354
6355 @item ^l^LAYOUT^
6356 @emph{Check layout.}
6357 Layout of statement and declaration constructs must follow the
6358 recommendations in the Ada Reference Manual, as indicated by the
6359 form of the syntax rules. For example an @code{else} keyword must
6360 be lined up with the corresponding @code{if} keyword.
6361
6362 There are two respects in which the style rule enforced by this check
6363 option are more liberal than those in the Ada Reference Manual. First
6364 in the case of record declarations, it is permissible to put the
6365 @code{record} keyword on the same line as the @code{type} keyword, and
6366 then the @code{end} in @code{end record} must line up under @code{type}.
6367 This is also permitted when the type declaration is split on two lines.
6368 For example, any of the following three layouts is acceptable:
6369
6370 @smallexample @c ada
6371 @cartouche
6372 type q is record
6373    a : integer;
6374    b : integer;
6375 end record;
6376
6377 type q is
6378    record
6379       a : integer;
6380       b : integer;
6381    end record;
6382
6383 type q is
6384    record
6385       a : integer;
6386       b : integer;
6387 end record;
6388
6389 @end cartouche
6390 @end smallexample
6391
6392 @noindent
6393 Second, in the case of a block statement, a permitted alternative
6394 is to put the block label on the same line as the @code{declare} or
6395 @code{begin} keyword, and then line the @code{end} keyword up under
6396 the block label. For example both the following are permitted:
6397
6398 @smallexample @c ada
6399 @cartouche
6400 Block : declare
6401    A : Integer := 3;
6402 begin
6403    Proc (A, A);
6404 end Block;
6405
6406 Block :
6407    declare
6408       A : Integer := 3;
6409    begin
6410       Proc (A, A);
6411    end Block;
6412 @end cartouche
6413 @end smallexample
6414
6415 @noindent
6416 The same alternative format is allowed for loops. For example, both of
6417 the following are permitted:
6418
6419 @smallexample @c ada
6420 @cartouche
6421 Clear : while J < 10 loop
6422    A (J) := 0;
6423 end loop Clear;
6424
6425 Clear :
6426    while J < 10 loop
6427       A (J) := 0;
6428    end loop Clear;
6429 @end cartouche
6430 @end smallexample
6431
6432 @item ^Lnnn^MAX_NESTING=nnn^
6433 @emph{Set maximum nesting level}
6434 The maximum level of nesting of constructs (including subprograms, loops,
6435 blocks, packages, and conditionals) may not exceed the given value
6436 @option{nnn}. A value of zero disconnects this style check.
6437
6438 @item ^m^LINE_LENGTH^
6439 @emph{Check maximum line length.}
6440 The length of source lines must not exceed 79 characters, including
6441 any trailing blanks. The value of 79 allows convenient display on an
6442 80 character wide device or window, allowing for possible special
6443 treatment of 80 character lines. Note that this count is of
6444 characters in the source text. This means that a tab character counts
6445 as one character in this count but a wide character sequence counts as
6446 a single character (however many bytes are needed in the encoding).
6447
6448 @item ^Mnnn^MAX_LENGTH=nnn^
6449 @emph{Set maximum line length.}
6450 The length of lines must not exceed the
6451 given value @option{nnn}. The maximum value that can be specified is 32767.
6452
6453 @item ^n^STANDARD_CASING^
6454 @emph{Check casing of entities in Standard.}
6455 Any identifier from Standard must be cased
6456 to match the presentation in the Ada Reference Manual (for example,
6457 @code{Integer} and @code{ASCII.NUL}).
6458
6459 @item ^N^NONE^
6460 @emph{Turn off all style checks}
6461 All style check options are turned off.
6462
6463 @item ^o^ORDERED_SUBPROGRAMS^
6464 @emph{Check order of subprogram bodies.}
6465 All subprogram bodies in a given scope
6466 (e.g.@: a package body) must be in alphabetical order. The ordering
6467 rule uses normal Ada rules for comparing strings, ignoring casing
6468 of letters, except that if there is a trailing numeric suffix, then
6469 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6470 before Junk10).
6471
6472 @item ^O^OVERRIDING_INDICATORS^
6473 @emph{Check that overriding subprograms are explicitly marked as such.}
6474 The declaration of a primitive operation of a type extension that overrides
6475 an inherited operation must carry an overriding indicator.
6476
6477 @item ^p^PRAGMA^
6478 @emph{Check pragma casing.}
6479 Pragma names must be written in mixed case, that is, the
6480 initial letter and any letter following an underscore must be uppercase.
6481 All other letters must be lowercase.
6482
6483 @item ^r^REFERENCES^
6484 @emph{Check references.}
6485 All identifier references must be cased in the same way as the
6486 corresponding declaration. No specific casing style is imposed on
6487 identifiers. The only requirement is for consistency of references
6488 with declarations.
6489
6490 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6491 @emph{Check no statements after THEN/ELSE.}
6492 No statements are allowed
6493 on the same line as a THEN or ELSE keyword following the
6494 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6495 and a special exception allows a pragma to appear after ELSE.
6496
6497 @item ^s^SPECS^
6498 @emph{Check separate specs.}
6499 Separate declarations (``specs'') are required for subprograms (a
6500 body is not allowed to serve as its own declaration). The only
6501 exception is that parameterless library level procedures are
6502 not required to have a separate declaration. This exception covers
6503 the most frequent form of main program procedures.
6504
6505 @item ^t^TOKEN^
6506 @emph{Check token spacing.}
6507 The following token spacing rules are enforced:
6508
6509 @itemize @bullet
6510
6511 @item
6512 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6513
6514 @item
6515 The token @code{=>} must be surrounded by spaces.
6516
6517 @item
6518 The token @code{<>} must be preceded by a space or a left parenthesis.
6519
6520 @item
6521 Binary operators other than @code{**} must be surrounded by spaces.
6522 There is no restriction on the layout of the @code{**} binary operator.
6523
6524 @item
6525 Colon must be surrounded by spaces.
6526
6527 @item
6528 Colon-equal (assignment, initialization) must be surrounded by spaces.
6529
6530 @item
6531 Comma must be the first non-blank character on the line, or be
6532 immediately preceded by a non-blank character, and must be followed
6533 by a space.
6534
6535 @item
6536 If the token preceding a left parenthesis ends with a letter or digit, then
6537 a space must separate the two tokens.
6538
6539 @item
6540 if the token following a right parenthesis starts with a letter or digit, then
6541 a space must separate the two tokens.
6542
6543 @item
6544 A right parenthesis must either be the first non-blank character on
6545 a line, or it must be preceded by a non-blank character.
6546
6547 @item
6548 A semicolon must not be preceded by a space, and must not be followed by
6549 a non-blank character.
6550
6551 @item
6552 A unary plus or minus may not be followed by a space.
6553
6554 @item
6555 A vertical bar must be surrounded by spaces.
6556 @end itemize
6557
6558 @item ^u^UNNECESSARY_BLANK_LINES^
6559 @emph{Check unnecessary blank lines.}
6560 Unnecessary blank lines are not allowed. A blank line is considered
6561 unnecessary if it appears at the end of the file, or if more than
6562 one blank line occurs in sequence.
6563
6564 @item ^x^XTRA_PARENS^
6565 @emph{Check extra parentheses.}
6566 Unnecessary extra level of parentheses (C-style) are not allowed
6567 around conditions in @code{if} statements, @code{while} statements and
6568 @code{exit} statements.
6569
6570 @item ^y^ALL_BUILTIN^
6571 @emph{Set all standard style check options}
6572 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6573 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6574 @option{-gnatyS}, @option{-gnatyLnnn},
6575 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6576
6577 @ifclear vms
6578 @item -
6579 @emph{Remove style check options}
6580 This causes any subsequent options in the string to act as canceling the
6581 corresponding style check option. To cancel maximum nesting level control,
6582 use @option{L} parameter witout any integer value after that, because any
6583 digit following @option{-} in the parameter string of the @option{-gnaty}
6584 option will be threated as canceling indentation check. The same is true
6585 for @option{M} parameter. @option{y} and @option{N} parameters are not
6586 allowed after @option{-}.
6587
6588 @item +
6589 This causes any subsequent options in the string to enable the corresponding
6590 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6591 if any.
6592 @end ifclear
6593
6594 @ifset vms
6595 @item NOxxx
6596 @emph{Removing style check options}
6597 If the name of a style check is preceded by @option{NO} then the corresponding
6598 style check is turned off. For example @option{NOCOMMENTS} turns off style
6599 checking for comments.
6600 @end ifset
6601 @end table
6602
6603 @noindent
6604 In the above rules, appearing in column one is always permitted, that is,
6605 counts as meeting either a requirement for a required preceding space,
6606 or as meeting a requirement for no preceding space.
6607
6608 Appearing at the end of a line is also always permitted, that is, counts
6609 as meeting either a requirement for a following space, or as meeting
6610 a requirement for no following space.
6611
6612 @noindent
6613 If any of these style rules is violated, a message is generated giving
6614 details on the violation. The initial characters of such messages are
6615 always ``@code{(style)}''. Note that these messages are treated as warning
6616 messages, so they normally do not prevent the generation of an object
6617 file. The @option{-gnatwe} switch can be used to treat warning messages,
6618 including style messages, as fatal errors.
6619
6620 The switch
6621 @ifclear vms
6622 @option{-gnaty} on its own (that is not
6623 followed by any letters or digits), then the effect is equivalent
6624 to the use of @option{-gnatyy}, as described above, that is all
6625 built-in standard style check options are enabled.
6626
6627 @end ifclear
6628 @ifset vms
6629 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6630 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6631 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6632 @end ifset
6633
6634 The switch
6635 @ifclear vms
6636 @option{-gnatyN}
6637 @end ifclear
6638 @ifset vms
6639 /STYLE_CHECKS=NONE
6640 @end ifset
6641 clears any previously set style checks.
6642
6643 @node Run-Time Checks
6644 @subsection Run-Time Checks
6645 @cindex Division by zero
6646 @cindex Access before elaboration
6647 @cindex Checks, division by zero
6648 @cindex Checks, access before elaboration
6649 @cindex Checks, stack overflow checking
6650
6651 @noindent
6652 By default, the following checks are suppressed: integer overflow
6653 checks, stack overflow checks, and checks for access before
6654 elaboration on subprogram calls. All other checks, including range
6655 checks and array bounds checks, are turned on by default. The
6656 following @command{gcc} switches refine this default behavior.
6657
6658 @table @option
6659 @c !sort!
6660 @item -gnatp
6661 @cindex @option{-gnatp} (@command{gcc})
6662 @cindex Suppressing checks
6663 @cindex Checks, suppressing
6664 @findex Suppress
6665 This switch causes the unit to be compiled
6666 as though @code{pragma Suppress (All_checks)}
6667 had been present in the source. Validity checks are also eliminated (in
6668 other words @option{-gnatp} also implies @option{-gnatVn}.
6669 Use this switch to improve the performance
6670 of the code at the expense of safety in the presence of invalid data or
6671 program bugs.
6672
6673 Note that when checks are suppressed, the compiler is allowed, but not
6674 required, to omit the checking code. If the run-time cost of the
6675 checking code is zero or near-zero, the compiler will generate it even
6676 if checks are suppressed. In particular, if the compiler can prove
6677 that a certain check will necessarily fail, it will generate code to
6678 do an unconditional ``raise'', even if checks are suppressed. The
6679 compiler warns in this case. Another case in which checks may not be
6680 eliminated is when they are embedded in certain run time routines such
6681 as math library routines.
6682
6683 Of course, run-time checks are omitted whenever the compiler can prove
6684 that they will not fail, whether or not checks are suppressed.
6685
6686 Note that if you suppress a check that would have failed, program
6687 execution is erroneous, which means the behavior is totally
6688 unpredictable. The program might crash, or print wrong answers, or
6689 do anything else. It might even do exactly what you wanted it to do
6690 (and then it might start failing mysteriously next week or next
6691 year). The compiler will generate code based on the assumption that
6692 the condition being checked is true, which can result in disaster if
6693 that assumption is wrong.
6694
6695 The @option{-gnatp} switch has no effect if a subsequent
6696 @option{-gnat-p} switch appears.
6697
6698 @item -gnat-p
6699 @cindex @option{-gnat-p} (@command{gcc})
6700 @cindex Suppressing checks
6701 @cindex Checks, suppressing
6702 @findex Suppress
6703 This switch cancels the effect of a previous @option{gnatp} switch.
6704
6705 @item -gnato
6706 @cindex @option{-gnato} (@command{gcc})
6707 @cindex Overflow checks
6708 @cindex Check, overflow
6709 Enables overflow checking for integer operations.
6710 This causes GNAT to generate slower and larger executable
6711 programs by adding code to check for overflow (resulting in raising
6712 @code{Constraint_Error} as required by standard Ada
6713 semantics). These overflow checks correspond to situations in which
6714 the true value of the result of an operation may be outside the base
6715 range of the result type. The following example shows the distinction:
6716
6717 @smallexample @c ada
6718 X1 : Integer := "Integer'Last";
6719 X2 : Integer range 1 .. 5 := "5";
6720 X3 : Integer := "Integer'Last";
6721 X4 : Integer range 1 .. 5 := "5";
6722 F  : Float := "2.0E+20";
6723 @dots{}
6724 X1 := X1 + 1;
6725 X2 := X2 + 1;
6726 X3 := Integer (F);
6727 X4 := Integer (F);
6728 @end smallexample
6729
6730 @noindent
6731 Note that if explicit values are assigned at compile time, the
6732 compiler may be able to detect overflow at compile time, in which case
6733 no actual run-time checking code is required, and Constraint_Error
6734 will be raised unconditionally, with or without
6735 @option{-gnato}. That's why the assigned values in the above fragment
6736 are in quotes, the meaning is "assign a value not known to the
6737 compiler that happens to be equal to ...". The remaining discussion
6738 assumes that the compiler cannot detect the values at compile time.
6739
6740 Here the first addition results in a value that is outside the base range
6741 of Integer, and hence requires an overflow check for detection of the
6742 constraint error. Thus the first assignment to @code{X1} raises a
6743 @code{Constraint_Error} exception only if @option{-gnato} is set.
6744
6745 The second increment operation results in a violation of the explicit
6746 range constraint; such range checks are performed by default, and are
6747 unaffected by @option{-gnato}.
6748
6749 The two conversions of @code{F} both result in values that are outside
6750 the base range of type @code{Integer} and thus will raise
6751 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6752 The fact that the result of the second conversion is assigned to
6753 variable @code{X4} with a restricted range is irrelevant, since the problem
6754 is in the conversion, not the assignment.
6755
6756 Basically the rule is that in the default mode (@option{-gnato} not
6757 used), the generated code assures that all integer variables stay
6758 within their declared ranges, or within the base range if there is
6759 no declared range. This prevents any serious problems like indexes
6760 out of range for array operations.
6761
6762 What is not checked in default mode is an overflow that results in
6763 an in-range, but incorrect value. In the above example, the assignments
6764 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6765 range of the target variable, but the result is wrong in the sense that
6766 it is too large to be represented correctly. Typically the assignment
6767 to @code{X1} will result in wrap around to the largest negative number.
6768 The conversions of @code{F} will result in some @code{Integer} value
6769 and if that integer value is out of the @code{X4} range then the
6770 subsequent assignment would generate an exception.
6771
6772 @findex Machine_Overflows
6773 Note that the @option{-gnato} switch does not affect the code generated
6774 for any floating-point operations; it applies only to integer
6775 semantics).
6776 For floating-point, GNAT has the @code{Machine_Overflows}
6777 attribute set to @code{False} and the normal mode of operation is to
6778 generate IEEE NaN and infinite values on overflow or invalid operations
6779 (such as dividing 0.0 by 0.0).
6780
6781 The reason that we distinguish overflow checking from other kinds of
6782 range constraint checking is that a failure of an overflow check, unlike
6783 for example the failure of a range check, can result in an incorrect
6784 value, but cannot cause random memory destruction (like an out of range
6785 subscript), or a wild jump (from an out of range case value). Overflow
6786 checking is also quite expensive in time and space, since in general it
6787 requires the use of double length arithmetic.
6788
6789 Note again that @option{-gnato} is off by default, so overflow checking is
6790 not performed in default mode. This means that out of the box, with the
6791 default settings, GNAT does not do all the checks expected from the
6792 language description in the Ada Reference Manual. If you want all constraint
6793 checks to be performed, as described in this Manual, then you must
6794 explicitly use the -gnato switch either on the @command{gnatmake} or
6795 @command{gcc} command.
6796
6797 @item -gnatE
6798 @cindex @option{-gnatE} (@command{gcc})
6799 @cindex Elaboration checks
6800 @cindex Check, elaboration
6801 Enables dynamic checks for access-before-elaboration
6802 on subprogram calls and generic instantiations.
6803 Note that @option{-gnatE} is not necessary for safety, because in the
6804 default mode, GNAT ensures statically that the checks would not fail.
6805 For full details of the effect and use of this switch,
6806 @xref{Compiling Using gcc}.
6807
6808 @item -fstack-check
6809 @cindex @option{-fstack-check} (@command{gcc})
6810 @cindex Stack Overflow Checking
6811 @cindex Checks, stack overflow checking
6812 Activates stack overflow checking. For full details of the effect and use of
6813 this switch see @ref{Stack Overflow Checking}.
6814 @end table
6815
6816 @findex Unsuppress
6817 @noindent
6818 The setting of these switches only controls the default setting of the
6819 checks. You may modify them using either @code{Suppress} (to remove
6820 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6821 the program source.
6822
6823 @node Using gcc for Syntax Checking
6824 @subsection Using @command{gcc} for Syntax Checking
6825 @table @option
6826 @item -gnats
6827 @cindex @option{-gnats} (@command{gcc})
6828 @ifclear vms
6829
6830 @noindent
6831 The @code{s} stands for ``syntax''.
6832 @end ifclear
6833
6834 Run GNAT in syntax checking only mode. For
6835 example, the command
6836
6837 @smallexample
6838 $ gcc -c -gnats x.adb
6839 @end smallexample
6840
6841 @noindent
6842 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6843 series of files in a single command
6844 @ifclear vms
6845 , and can use wild cards to specify such a group of files.
6846 Note that you must specify the @option{-c} (compile
6847 only) flag in addition to the @option{-gnats} flag.
6848 @end ifclear
6849 .
6850 You may use other switches in conjunction with @option{-gnats}. In
6851 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6852 format of any generated error messages.
6853
6854 When the source file is empty or contains only empty lines and/or comments,
6855 the output is a warning:
6856
6857 @smallexample
6858 $ gcc -c -gnats -x ada toto.txt
6859 toto.txt:1:01: warning: empty file, contains no compilation units
6860 $
6861 @end smallexample
6862
6863 Otherwise, the output is simply the error messages, if any. No object file or
6864 ALI file is generated by a syntax-only compilation. Also, no units other
6865 than the one specified are accessed. For example, if a unit @code{X}
6866 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6867 check only mode does not access the source file containing unit
6868 @code{Y}.
6869
6870 @cindex Multiple units, syntax checking
6871 Normally, GNAT allows only a single unit in a source file. However, this
6872 restriction does not apply in syntax-check-only mode, and it is possible
6873 to check a file containing multiple compilation units concatenated
6874 together. This is primarily used by the @code{gnatchop} utility
6875 (@pxref{Renaming Files Using gnatchop}).
6876 @end table
6877
6878 @node Using gcc for Semantic Checking
6879 @subsection Using @command{gcc} for Semantic Checking
6880 @table @option
6881 @item -gnatc
6882 @cindex @option{-gnatc} (@command{gcc})
6883
6884 @ifclear vms
6885 @noindent
6886 The @code{c} stands for ``check''.
6887 @end ifclear
6888 Causes the compiler to operate in semantic check mode,
6889 with full checking for all illegalities specified in the
6890 Ada Reference Manual, but without generation of any object code
6891 (no object file is generated).
6892
6893 Because dependent files must be accessed, you must follow the GNAT
6894 semantic restrictions on file structuring to operate in this mode:
6895
6896 @itemize @bullet
6897 @item
6898 The needed source files must be accessible
6899 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6900
6901 @item
6902 Each file must contain only one compilation unit.
6903
6904 @item
6905 The file name and unit name must match (@pxref{File Naming Rules}).
6906 @end itemize
6907
6908 The output consists of error messages as appropriate. No object file is
6909 generated. An @file{ALI} file is generated for use in the context of
6910 cross-reference tools, but this file is marked as not being suitable
6911 for binding (since no object file is generated).
6912 The checking corresponds exactly to the notion of
6913 legality in the Ada Reference Manual.
6914
6915 Any unit can be compiled in semantics-checking-only mode, including
6916 units that would not normally be compiled (subunits,
6917 and specifications where a separate body is present).
6918 @end table
6919
6920 @node Compiling Different Versions of Ada
6921 @subsection Compiling Different Versions of Ada
6922
6923 @noindent
6924 The switches described in this section allow you to explicitly specify
6925 the version of the Ada language that your programs are written in.
6926 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6927 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6928 indicate Ada 83 compatibility mode.
6929
6930 @table @option
6931 @cindex Compatibility with Ada 83
6932
6933 @item -gnat83 (Ada 83 Compatibility Mode)
6934 @cindex @option{-gnat83} (@command{gcc})
6935 @cindex ACVC, Ada 83 tests
6936 @cindex Ada 83 mode
6937
6938 @noindent
6939 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6940 specifies that the program is to be compiled in Ada 83 mode. With
6941 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6942 semantics where this can be done easily.
6943 It is not possible to guarantee this switch does a perfect
6944 job; some subtle tests, such as are
6945 found in earlier ACVC tests (and that have been removed from the ACATS suite
6946 for Ada 95), might not compile correctly.
6947 Nevertheless, this switch may be useful in some circumstances, for example
6948 where, due to contractual reasons, existing code needs to be maintained
6949 using only Ada 83 features.
6950
6951 With few exceptions (most notably the need to use @code{<>} on
6952 @cindex Generic formal parameters
6953 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6954 reserved words, and the use of packages
6955 with optional bodies), it is not necessary to specify the
6956 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6957 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6958 a correct Ada 83 program is usually also a correct program
6959 in these later versions of the language standard.
6960 For further information, please refer to @ref{Compatibility and Porting Guide}.
6961
6962 @item -gnat95 (Ada 95 mode)
6963 @cindex @option{-gnat95} (@command{gcc})
6964 @cindex Ada 95 mode
6965
6966 @noindent
6967 This switch directs the compiler to implement the Ada 95 version of the
6968 language.
6969 Since Ada 95 is almost completely upwards
6970 compatible with Ada 83, Ada 83 programs may generally be compiled using
6971 this switch (see the description of the @option{-gnat83} switch for further
6972 information about Ada 83 mode).
6973 If an Ada 2005 program is compiled in Ada 95 mode,
6974 uses of the new Ada 2005 features will cause error
6975 messages or warnings.
6976
6977 This switch also can be used to cancel the effect of a previous
6978 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6979 switch earlier in the command line.
6980
6981 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6982 @cindex @option{-gnat05} (@command{gcc})
6983 @cindex @option{-gnat2005} (@command{gcc})
6984 @cindex Ada 2005 mode
6985
6986 @noindent
6987 This switch directs the compiler to implement the Ada 2005 version of the
6988 language, as documented in the official Ada standards document.
6989 Since Ada 2005 is almost completely upwards
6990 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6991 may generally be compiled using this switch (see the description of the
6992 @option{-gnat83} and @option{-gnat95} switches for further
6993 information).
6994
6995 @ifset PROEDITION
6996 Note that even though Ada 2005 is the current official version of the
6997 language, GNAT still compiles in Ada 95 mode by default, so if you are
6998 using Ada 2005 features in your program, you must use this switch (or
6999 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7000 @end ifset
7001
7002 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7003 @cindex @option{-gnat12} (@command{gcc})
7004 @cindex @option{-gnat2012} (@command{gcc})
7005 @cindex Ada 2012 mode
7006
7007 @noindent
7008 This switch directs the compiler to implement the Ada 2012 version of the
7009 language.
7010 Since Ada 2012 is almost completely upwards
7011 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7012 Ada 83 and Ada 95 programs
7013 may generally be compiled using this switch (see the description of the
7014 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7015 for further information).
7016
7017 For information about the approved ``Ada Issues'' that have been incorporated
7018 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7019 Included with GNAT releases is a file @file{features-ada12} that describes
7020 the set of implemented Ada 2012 features.
7021
7022 @item -gnatX (Enable GNAT Extensions)
7023 @cindex @option{-gnatX} (@command{gcc})
7024 @cindex Ada language extensions
7025 @cindex GNAT extensions
7026
7027 @noindent
7028 This switch directs the compiler to implement the latest version of the
7029 language (currently Ada 2012) and also to enable certain GNAT implementation
7030 extensions that are not part of any Ada standard. For a full list of these
7031 extensions, see the GNAT reference manual.
7032
7033 @end table
7034
7035 @node Character Set Control
7036 @subsection Character Set Control
7037 @table @option
7038 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7039 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7040
7041 @noindent
7042 Normally GNAT recognizes the Latin-1 character set in source program
7043 identifiers, as described in the Ada Reference Manual.
7044 This switch causes
7045 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7046 single character ^^or word^ indicating the character set, as follows:
7047
7048 @table @code
7049 @item 1
7050 ISO 8859-1 (Latin-1) identifiers
7051
7052 @item 2
7053 ISO 8859-2 (Latin-2) letters allowed in identifiers
7054
7055 @item 3
7056 ISO 8859-3 (Latin-3) letters allowed in identifiers
7057
7058 @item 4
7059 ISO 8859-4 (Latin-4) letters allowed in identifiers
7060
7061 @item 5
7062 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7063
7064 @item 9
7065 ISO 8859-15 (Latin-9) letters allowed in identifiers
7066
7067 @item ^p^PC^
7068 IBM PC letters (code page 437) allowed in identifiers
7069
7070 @item ^8^PC850^
7071 IBM PC letters (code page 850) allowed in identifiers
7072
7073 @item ^f^FULL_UPPER^
7074 Full upper-half codes allowed in identifiers
7075
7076 @item ^n^NO_UPPER^
7077 No upper-half codes allowed in identifiers
7078
7079 @item ^w^WIDE^
7080 Wide-character codes (that is, codes greater than 255)
7081 allowed in identifiers
7082 @end table
7083
7084 @xref{Foreign Language Representation}, for full details on the
7085 implementation of these character sets.
7086
7087 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7088 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7089 Specify the method of encoding for wide characters.
7090 @var{e} is one of the following:
7091
7092 @table @code
7093
7094 @item ^h^HEX^
7095 Hex encoding (brackets coding also recognized)
7096
7097 @item ^u^UPPER^
7098 Upper half encoding (brackets encoding also recognized)
7099
7100 @item ^s^SHIFT_JIS^
7101 Shift/JIS encoding (brackets encoding also recognized)
7102
7103 @item ^e^EUC^
7104 EUC encoding (brackets encoding also recognized)
7105
7106 @item ^8^UTF8^
7107 UTF-8 encoding (brackets encoding also recognized)
7108
7109 @item ^b^BRACKETS^
7110 Brackets encoding only (default value)
7111 @end table
7112 For full details on these encoding
7113 methods see @ref{Wide Character Encodings}.
7114 Note that brackets coding is always accepted, even if one of the other
7115 options is specified, so for example @option{-gnatW8} specifies that both
7116 brackets and UTF-8 encodings will be recognized. The units that are
7117 with'ed directly or indirectly will be scanned using the specified
7118 representation scheme, and so if one of the non-brackets scheme is
7119 used, it must be used consistently throughout the program. However,
7120 since brackets encoding is always recognized, it may be conveniently
7121 used in standard libraries, allowing these libraries to be used with
7122 any of the available coding schemes.
7123 scheme.
7124
7125 If no @option{-gnatW?} parameter is present, then the default
7126 representation is normally Brackets encoding only. However, if the
7127 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7128 byte order mark or BOM for UTF-8), then these three characters are
7129 skipped and the default representation for the file is set to UTF-8.
7130
7131 Note that the wide character representation that is specified (explicitly
7132 or by default) for the main program also acts as the default encoding used
7133 for Wide_Text_IO files if not specifically overridden by a WCEM form
7134 parameter.
7135
7136 @end table
7137 @node File Naming Control
7138 @subsection File Naming Control
7139
7140 @table @option
7141 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7142 @cindex @option{-gnatk} (@command{gcc})
7143 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7144 1-999, indicates the maximum allowable length of a file name (not
7145 including the @file{.ads} or @file{.adb} extension). The default is not
7146 to enable file name krunching.
7147
7148 For the source file naming rules, @xref{File Naming Rules}.
7149 @end table
7150
7151 @node Subprogram Inlining Control
7152 @subsection Subprogram Inlining Control
7153
7154 @table @option
7155 @c !sort!
7156 @item -gnatn
7157 @cindex @option{-gnatn} (@command{gcc})
7158 @ifclear vms
7159 The @code{n} here is intended to suggest the first syllable of the
7160 word ``inline''.
7161 @end ifclear
7162 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7163 inlining to actually occur, optimization must be enabled. To enable
7164 inlining of subprograms specified by pragma @code{Inline},
7165 you must also specify this switch.
7166 In the absence of this switch, GNAT does not attempt
7167 inlining and does not need to access the bodies of
7168 subprograms for which @code{pragma Inline} is specified if they are not
7169 in the current unit.
7170
7171 If you specify this switch the compiler will access these bodies,
7172 creating an extra source dependency for the resulting object file, and
7173 where possible, the call will be inlined.
7174 For further details on when inlining is possible
7175 see @ref{Inlining of Subprograms}.
7176
7177 @item -gnatN
7178 @cindex @option{-gnatN} (@command{gcc})
7179 This switch activates front-end inlining which also
7180 generates additional dependencies.
7181
7182 When using a gcc-based back end (in practice this means using any version
7183 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7184 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7185 Historically front end inlining was more extensive than the gcc back end
7186 inlining, but that is no longer the case.
7187 @end table
7188
7189 @node Auxiliary Output Control
7190 @subsection Auxiliary Output Control
7191
7192 @table @option
7193 @item -gnatt
7194 @cindex @option{-gnatt} (@command{gcc})
7195 @cindex Writing internal trees
7196 @cindex Internal trees, writing to file
7197 Causes GNAT to write the internal tree for a unit to a file (with the
7198 extension @file{.adt}.
7199 This not normally required, but is used by separate analysis tools.
7200 Typically
7201 these tools do the necessary compilations automatically, so you should
7202 not have to specify this switch in normal operation.
7203 Note that the combination of switches @option{-gnatct}
7204 generates a tree in the form required by ASIS applications.
7205
7206 @item -gnatu
7207 @cindex @option{-gnatu} (@command{gcc})
7208 Print a list of units required by this compilation on @file{stdout}.
7209 The listing includes all units on which the unit being compiled depends
7210 either directly or indirectly.
7211
7212 @ifclear vms
7213 @item -pass-exit-codes
7214 @cindex @option{-pass-exit-codes} (@command{gcc})
7215 If this switch is not used, the exit code returned by @command{gcc} when
7216 compiling multiple files indicates whether all source files have
7217 been successfully used to generate object files or not.
7218
7219 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7220 exit status and allows an integrated development environment to better
7221 react to a compilation failure. Those exit status are:
7222
7223 @table @asis
7224 @item 5
7225 There was an error in at least one source file.
7226 @item 3
7227 At least one source file did not generate an object file.
7228 @item 2
7229 The compiler died unexpectedly (internal error for example).
7230 @item 0
7231 An object file has been generated for every source file.
7232 @end table
7233 @end ifclear
7234 @end table
7235
7236 @node Debugging Control
7237 @subsection Debugging Control
7238
7239 @table @option
7240 @c !sort!
7241 @cindex Debugging options
7242 @ifclear vms
7243 @item -gnatd@var{x}
7244 @cindex @option{-gnatd} (@command{gcc})
7245 Activate internal debugging switches. @var{x} is a letter or digit, or
7246 string of letters or digits, which specifies the type of debugging
7247 outputs desired. Normally these are used only for internal development
7248 or system debugging purposes. You can find full documentation for these
7249 switches in the body of the @code{Debug} unit in the compiler source
7250 file @file{debug.adb}.
7251 @end ifclear
7252
7253 @item -gnatG[=nn]
7254 @cindex @option{-gnatG} (@command{gcc})
7255 This switch causes the compiler to generate auxiliary output containing
7256 a pseudo-source listing of the generated expanded code. Like most Ada
7257 compilers, GNAT works by first transforming the high level Ada code into
7258 lower level constructs. For example, tasking operations are transformed
7259 into calls to the tasking run-time routines. A unique capability of GNAT
7260 is to list this expanded code in a form very close to normal Ada source.
7261 This is very useful in understanding the implications of various Ada
7262 usage on the efficiency of the generated code. There are many cases in
7263 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7264 generate a lot of run-time code. By using @option{-gnatG} you can identify
7265 these cases, and consider whether it may be desirable to modify the coding
7266 approach to improve efficiency.
7267
7268 The optional parameter @code{nn} if present after -gnatG specifies an
7269 alternative maximum line length that overrides the normal default of 72.
7270 This value is in the range 40-999999, values less than 40 being silently
7271 reset to 40. The equal sign is optional.
7272
7273 The format of the output is very similar to standard Ada source, and is
7274 easily understood by an Ada programmer. The following special syntactic
7275 additions correspond to low level features used in the generated code that
7276 do not have any exact analogies in pure Ada source form. The following
7277 is a partial list of these special constructions. See the spec
7278 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7279
7280 If the switch @option{-gnatL} is used in conjunction with
7281 @cindex @option{-gnatL} (@command{gcc})
7282 @option{-gnatG}, then the original source lines are interspersed
7283 in the expanded source (as comment lines with the original line number).
7284
7285 @table @code
7286 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7287 Shows the storage pool being used for an allocator.
7288
7289 @item at end @var{procedure-name};
7290 Shows the finalization (cleanup) procedure for a scope.
7291
7292 @item (if @var{expr} then @var{expr} else @var{expr})
7293 Conditional expression equivalent to the @code{x?y:z} construction in C.
7294
7295 @item @var{target}^^^(@var{source})
7296 A conversion with floating-point truncation instead of rounding.
7297
7298 @item @var{target}?(@var{source})
7299 A conversion that bypasses normal Ada semantic checking. In particular
7300 enumeration types and fixed-point types are treated simply as integers.
7301
7302 @item @var{target}?^^^(@var{source})
7303 Combines the above two cases.
7304
7305 @item @var{x} #/ @var{y}
7306 @itemx @var{x} #mod @var{y}
7307 @itemx @var{x} #* @var{y}
7308 @itemx @var{x} #rem @var{y}
7309 A division or multiplication of fixed-point values which are treated as
7310 integers without any kind of scaling.
7311
7312 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7313 Shows the storage pool associated with a @code{free} statement.
7314
7315 @item [subtype or type declaration]
7316 Used to list an equivalent declaration for an internally generated
7317 type that is referenced elsewhere in the listing.
7318
7319 @c @item freeze @var{type-name} @ovar{actions}
7320 @c Expanding @ovar macro inline (explanation in macro def comments)
7321 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7322 Shows the point at which @var{type-name} is frozen, with possible
7323 associated actions to be performed at the freeze point.
7324
7325 @item reference @var{itype}
7326 Reference (and hence definition) to internal type @var{itype}.
7327
7328 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7329 Intrinsic function call.
7330
7331 @item @var{label-name} : label
7332 Declaration of label @var{labelname}.
7333
7334 @item #$ @var{subprogram-name}
7335 An implicit call to a run-time support routine
7336 (to meet the requirement of H.3.1(9) in a
7337 convenient manner).
7338
7339 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7340 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7341 @var{expr}, but handled more efficiently).
7342
7343 @item [constraint_error]
7344 Raise the @code{Constraint_Error} exception.
7345
7346 @item @var{expression}'reference
7347 A pointer to the result of evaluating @var{expression}.
7348
7349 @item @var{target-type}!(@var{source-expression})
7350 An unchecked conversion of @var{source-expression} to @var{target-type}.
7351
7352 @item [@var{numerator}/@var{denominator}]
7353 Used to represent internal real literals (that) have no exact
7354 representation in base 2-16 (for example, the result of compile time
7355 evaluation of the expression 1.0/27.0).
7356 @end table
7357
7358 @item -gnatD[=nn]
7359 @cindex @option{-gnatD} (@command{gcc})
7360 When used in conjunction with @option{-gnatG}, this switch causes
7361 the expanded source, as described above for
7362 @option{-gnatG} to be written to files with names
7363 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7364 instead of to the standard output file. For
7365 example, if the source file name is @file{hello.adb}, then a file
7366 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7367 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7368 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7369 you to do source level debugging using the generated code which is
7370 sometimes useful for complex code, for example to find out exactly
7371 which part of a complex construction raised an exception. This switch
7372 also suppress generation of cross-reference information (see
7373 @option{-gnatx}) since otherwise the cross-reference information
7374 would refer to the @file{^.dg^.DG^} file, which would cause
7375 confusion since this is not the original source file.
7376
7377 Note that @option{-gnatD} actually implies @option{-gnatG}
7378 automatically, so it is not necessary to give both options.
7379 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7380
7381 If the switch @option{-gnatL} is used in conjunction with
7382 @cindex @option{-gnatL} (@command{gcc})
7383 @option{-gnatDG}, then the original source lines are interspersed
7384 in the expanded source (as comment lines with the original line number).
7385
7386 The optional parameter @code{nn} if present after -gnatD specifies an
7387 alternative maximum line length that overrides the normal default of 72.
7388 This value is in the range 40-999999, values less than 40 being silently
7389 reset to 40. The equal sign is optional.
7390
7391 @item -gnatr
7392 @cindex @option{-gnatr} (@command{gcc})
7393 @cindex pragma Restrictions
7394 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7395 so that violation of restrictions causes warnings rather than illegalities.
7396 This is useful during the development process when new restrictions are added
7397 or investigated. The switch also causes pragma Profile to be treated as
7398 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7399 restriction warnings rather than restrictions.
7400
7401 @ifclear vms
7402 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7403 @cindex @option{-gnatR} (@command{gcc})
7404 This switch controls output from the compiler of a listing showing
7405 representation information for declared types and objects. For
7406 @option{-gnatR0}, no information is output (equivalent to omitting
7407 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7408 so @option{-gnatR} with no parameter has the same effect), size and alignment
7409 information is listed for declared array and record types. For
7410 @option{-gnatR2}, size and alignment information is listed for all
7411 declared types and objects. Finally @option{-gnatR3} includes symbolic
7412 expressions for values that are computed at run time for
7413 variant records. These symbolic expressions have a mostly obvious
7414 format with #n being used to represent the value of the n'th
7415 discriminant. See source files @file{repinfo.ads/adb} in the
7416 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7417 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7418 the output is to a file with the name @file{^file.rep^file_REP^} where
7419 file is the name of the corresponding source file.
7420 @end ifclear
7421 @ifset vms
7422 @item /REPRESENTATION_INFO
7423 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7424 This qualifier controls output from the compiler of a listing showing
7425 representation information for declared types and objects. For
7426 @option{/REPRESENTATION_INFO=NONE}, no information is output
7427 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7428 @option{/REPRESENTATION_INFO} without option is equivalent to
7429 @option{/REPRESENTATION_INFO=ARRAYS}.
7430 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7431 information is listed for declared array and record types. For
7432 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7433 is listed for all expression information for values that are computed
7434 at run time for variant records. These symbolic expressions have a mostly
7435 obvious format with #n being used to represent the value of the n'th
7436 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7437 @code{GNAT} sources for full details on the format of
7438 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7439 If _FILE is added at the end of an option
7440 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7441 then the output is to a file with the name @file{file_REP} where
7442 file is the name of the corresponding source file.
7443 @end ifset
7444 Note that it is possible for record components to have zero size. In
7445 this case, the component clause uses an obvious extension of permitted
7446 Ada syntax, for example @code{at 0 range 0 .. -1}.
7447
7448 Representation information requires that code be generated (since it is the
7449 code generator that lays out complex data structures). If an attempt is made
7450 to output representation information when no code is generated, for example
7451 when a subunit is compiled on its own, then no information can be generated
7452 and the compiler outputs a message to this effect.
7453
7454 @item -gnatS
7455 @cindex @option{-gnatS} (@command{gcc})
7456 The use of the switch @option{-gnatS} for an
7457 Ada compilation will cause the compiler to output a
7458 representation of package Standard in a form very
7459 close to standard Ada. It is not quite possible to
7460 do this entirely in standard Ada (since new
7461 numeric base types cannot be created in standard
7462 Ada), but the output is easily
7463 readable to any Ada programmer, and is useful to
7464 determine the characteristics of target dependent
7465 types in package Standard.
7466
7467 @item -gnatx
7468 @cindex @option{-gnatx} (@command{gcc})
7469 Normally the compiler generates full cross-referencing information in
7470 the @file{ALI} file. This information is used by a number of tools,
7471 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7472 suppresses this information. This saves some space and may slightly
7473 speed up compilation, but means that these tools cannot be used.
7474 @end table
7475
7476 @node Exception Handling Control
7477 @subsection Exception Handling Control
7478
7479 @noindent
7480 GNAT uses two methods for handling exceptions at run-time. The
7481 @code{setjmp/longjmp} method saves the context when entering
7482 a frame with an exception handler. Then when an exception is
7483 raised, the context can be restored immediately, without the
7484 need for tracing stack frames. This method provides very fast
7485 exception propagation, but introduces significant overhead for
7486 the use of exception handlers, even if no exception is raised.
7487
7488 The other approach is called ``zero cost'' exception handling.
7489 With this method, the compiler builds static tables to describe
7490 the exception ranges. No dynamic code is required when entering
7491 a frame containing an exception handler. When an exception is
7492 raised, the tables are used to control a back trace of the
7493 subprogram invocation stack to locate the required exception
7494 handler. This method has considerably poorer performance for
7495 the propagation of exceptions, but there is no overhead for
7496 exception handlers if no exception is raised. Note that in this
7497 mode and in the context of mixed Ada and C/C++ programming,
7498 to propagate an exception through a C/C++ code, the C/C++ code
7499 must be compiled with the @option{-funwind-tables} GCC's
7500 option.
7501
7502 The following switches may be used to control which of the
7503 two exception handling methods is used.
7504
7505 @table @option
7506 @c !sort!
7507
7508 @item --RTS=sjlj
7509 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7510 This switch causes the setjmp/longjmp run-time (when available) to be used
7511 for exception handling. If the default
7512 mechanism for the target is zero cost exceptions, then
7513 this switch can be used to modify this default, and must be
7514 used for all units in the partition.
7515 This option is rarely used. One case in which it may be
7516 advantageous is if you have an application where exception
7517 raising is common and the overall performance of the
7518 application is improved by favoring exception propagation.
7519
7520 @item --RTS=zcx
7521 @cindex @option{--RTS=zcx} (@command{gnatmake})
7522 @cindex Zero Cost Exceptions
7523 This switch causes the zero cost approach to be used
7524 for exception handling. If this is the default mechanism for the
7525 target (see below), then this switch is unneeded. If the default
7526 mechanism for the target is setjmp/longjmp exceptions, then
7527 this switch can be used to modify this default, and must be
7528 used for all units in the partition.
7529 This option can only be used if the zero cost approach
7530 is available for the target in use, otherwise it will generate an error.
7531 @end table
7532
7533 @noindent
7534 The same option @option{--RTS} must be used both for @command{gcc}
7535 and @command{gnatbind}. Passing this option to @command{gnatmake}
7536 (@pxref{Switches for gnatmake}) will ensure the required consistency
7537 through the compilation and binding steps.
7538
7539 @node Units to Sources Mapping Files
7540 @subsection Units to Sources Mapping Files
7541
7542 @table @option
7543
7544 @item -gnatem=@var{path}
7545 @cindex @option{-gnatem} (@command{gcc})
7546 A mapping file is a way to communicate to the compiler two mappings:
7547 from unit names to file names (without any directory information) and from
7548 file names to path names (with full directory information). These mappings
7549 are used by the compiler to short-circuit the path search.
7550
7551 The use of mapping files is not required for correct operation of the
7552 compiler, but mapping files can improve efficiency, particularly when
7553 sources are read over a slow network connection. In normal operation,
7554 you need not be concerned with the format or use of mapping files,
7555 and the @option{-gnatem} switch is not a switch that you would use
7556 explicitly. It is intended primarily for use by automatic tools such as
7557 @command{gnatmake} running under the project file facility. The
7558 description here of the format of mapping files is provided
7559 for completeness and for possible use by other tools.
7560
7561 A mapping file is a sequence of sets of three lines. In each set, the
7562 first line is the unit name, in lower case, with @code{%s} appended
7563 for specs and @code{%b} appended for bodies; the second line is the
7564 file name; and the third line is the path name.
7565
7566 Example:
7567 @smallexample
7568    main%b
7569    main.2.ada
7570    /gnat/project1/sources/main.2.ada
7571 @end smallexample
7572
7573 When the switch @option{-gnatem} is specified, the compiler will
7574 create in memory the two mappings from the specified file. If there is
7575 any problem (nonexistent file, truncated file or duplicate entries),
7576 no mapping will be created.
7577
7578 Several @option{-gnatem} switches may be specified; however, only the
7579 last one on the command line will be taken into account.
7580
7581 When using a project file, @command{gnatmake} creates a temporary
7582 mapping file and communicates it to the compiler using this switch.
7583
7584 @end table
7585
7586 @node Integrated Preprocessing
7587 @subsection Integrated Preprocessing
7588
7589 @noindent
7590 GNAT sources may be preprocessed immediately before compilation.
7591 In this case, the actual
7592 text of the source is not the text of the source file, but is derived from it
7593 through a process called preprocessing. Integrated preprocessing is specified
7594 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7595 indicates, through a text file, the preprocessing data to be used.
7596 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7597
7598 @noindent
7599 Note that when integrated preprocessing is used, the output from the
7600 preprocessor is not written to any external file. Instead it is passed
7601 internally to the compiler. If you need to preserve the result of
7602 preprocessing in a file, then you should use @command{gnatprep}
7603 to perform the desired preprocessing in stand-alone mode.
7604
7605 @noindent
7606 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7607 used when Integrated Preprocessing is used. The reason is that preprocessing
7608 with another Preprocessing Data file without changing the sources will
7609 not trigger recompilation without this switch.
7610
7611 @noindent
7612 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7613 always trigger recompilation for sources that are preprocessed,
7614 because @command{gnatmake} cannot compute the checksum of the source after
7615 preprocessing.
7616
7617 @noindent
7618 The actual preprocessing function is described in details in section
7619 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7620 preprocessing is triggered and parameterized.
7621
7622 @table @code
7623
7624 @item -gnatep=@var{file}
7625 @cindex @option{-gnatep} (@command{gcc})
7626 This switch indicates to the compiler the file name (without directory
7627 information) of the preprocessor data file to use. The preprocessor data file
7628 should be found in the source directories.
7629
7630 @noindent
7631 A preprocessing data file is a text file with significant lines indicating
7632 how should be preprocessed either a specific source or all sources not
7633 mentioned in other lines. A significant line is a nonempty, non-comment line.
7634 Comments are similar to Ada comments.
7635
7636 @noindent
7637 Each significant line starts with either a literal string or the character '*'.
7638 A literal string is the file name (without directory information) of the source
7639 to preprocess. A character '*' indicates the preprocessing for all the sources
7640 that are not specified explicitly on other lines (order of the lines is not
7641 significant). It is an error to have two lines with the same file name or two
7642 lines starting with the character '*'.
7643
7644 @noindent
7645 After the file name or the character '*', another optional literal string
7646 indicating the file name of the definition file to be used for preprocessing
7647 (@pxref{Form of Definitions File}). The definition files are found by the
7648 compiler in one of the source directories. In some cases, when compiling
7649 a source in a directory other than the current directory, if the definition
7650 file is in the current directory, it may be necessary to add the current
7651 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7652 the compiler would not find the definition file.
7653
7654 @noindent
7655 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7656 be found. Those ^switches^switches^ are:
7657
7658 @table @code
7659
7660 @item -b
7661 Causes both preprocessor lines and the lines deleted by
7662 preprocessing to be replaced by blank lines, preserving the line number.
7663 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7664 it cancels the effect of @option{-c}.
7665
7666 @item -c
7667 Causes both preprocessor lines and the lines deleted
7668 by preprocessing to be retained as comments marked
7669 with the special string ``@code{--! }''.
7670
7671 @item -Dsymbol=value
7672 Define or redefine a symbol, associated with value. A symbol is an Ada
7673 identifier, or an Ada reserved word, with the exception of @code{if},
7674 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7675 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7676 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7677 same name defined in a definition file.
7678
7679 @item -s
7680 Causes a sorted list of symbol names and values to be
7681 listed on the standard output file.
7682
7683 @item -u
7684 Causes undefined symbols to be treated as having the value @code{FALSE}
7685 in the context
7686 of a preprocessor test. In the absence of this option, an undefined symbol in
7687 a @code{#if} or @code{#elsif} test will be treated as an error.
7688
7689 @end table
7690
7691 @noindent
7692 Examples of valid lines in a preprocessor data file:
7693
7694 @smallexample
7695   "toto.adb"  "prep.def" -u
7696   --  preprocess "toto.adb", using definition file "prep.def",
7697   --  undefined symbol are False.
7698
7699   * -c -DVERSION=V101
7700   --  preprocess all other sources without a definition file;
7701   --  suppressed lined are commented; symbol VERSION has the value V101.
7702
7703   "titi.adb" "prep2.def" -s
7704   --  preprocess "titi.adb", using definition file "prep2.def";
7705   --  list all symbols with their values.
7706 @end smallexample
7707
7708 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7709 @cindex @option{-gnateD} (@command{gcc})
7710 Define or redefine a preprocessing symbol, associated with value. If no value
7711 is given on the command line, then the value of the symbol is @code{True}.
7712 A symbol is an identifier, following normal Ada (case-insensitive)
7713 rules for its syntax, and value is any sequence (including an empty sequence)
7714 of characters from the set (letters, digits, period, underline).
7715 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7716 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7717
7718 @noindent
7719 A symbol declared with this ^switch^switch^ on the command line replaces a
7720 symbol with the same name either in a definition file or specified with a
7721 ^switch^switch^ -D in the preprocessor data file.
7722
7723 @noindent
7724 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7725
7726 @item -gnateG
7727 When integrated preprocessing is performed and the preprocessor modifies
7728 the source text, write the result of this preprocessing into a file
7729 <source>^.prep^_prep^.
7730
7731 @end table
7732
7733 @node Code Generation Control
7734 @subsection Code Generation Control
7735
7736 @noindent
7737
7738 The GCC technology provides a wide range of target dependent
7739 @option{-m} switches for controlling
7740 details of code generation with respect to different versions of
7741 architectures. This includes variations in instruction sets (e.g.@:
7742 different members of the power pc family), and different requirements
7743 for optimal arrangement of instructions (e.g.@: different members of
7744 the x86 family). The list of available @option{-m} switches may be
7745 found in the GCC documentation.
7746
7747 Use of these @option{-m} switches may in some cases result in improved
7748 code performance.
7749
7750 The GNAT Pro technology is tested and qualified without any
7751 @option{-m} switches,
7752 so generally the most reliable approach is to avoid the use of these
7753 switches. However, we generally expect most of these switches to work
7754 successfully with GNAT Pro, and many customers have reported successful
7755 use of these options.
7756
7757 Our general advice is to avoid the use of @option{-m} switches unless
7758 special needs lead to requirements in this area. In particular,
7759 there is no point in using @option{-m} switches to improve performance
7760 unless you actually see a performance improvement.
7761
7762 @ifset vms
7763 @node Return Codes
7764 @subsection Return Codes
7765 @cindex Return Codes
7766 @cindex @option{/RETURN_CODES=VMS}
7767
7768 @noindent
7769 On VMS, GNAT compiled programs return POSIX-style codes by default,
7770 e.g.@: @option{/RETURN_CODES=POSIX}.
7771
7772 To enable VMS style return codes, use GNAT BIND and LINK with the option
7773 @option{/RETURN_CODES=VMS}. For example:
7774
7775 @smallexample
7776 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7777 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7778 @end smallexample
7779
7780 @noindent
7781 Programs built with /RETURN_CODES=VMS are suitable to be called in
7782 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7783 are suitable for spawning with appropriate GNAT RTL routines.
7784
7785 @end ifset
7786
7787 @node Search Paths and the Run-Time Library (RTL)
7788 @section Search Paths and the Run-Time Library (RTL)
7789
7790 @noindent
7791 With the GNAT source-based library system, the compiler must be able to
7792 find source files for units that are needed by the unit being compiled.
7793 Search paths are used to guide this process.
7794
7795 The compiler compiles one source file whose name must be given
7796 explicitly on the command line. In other words, no searching is done
7797 for this file. To find all other source files that are needed (the most
7798 common being the specs of units), the compiler examines the following
7799 directories, in the following order:
7800
7801 @enumerate
7802 @item
7803 The directory containing the source file of the main unit being compiled
7804 (the file name on the command line).
7805
7806 @item
7807 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7808 @command{gcc} command line, in the order given.
7809
7810 @item
7811 @findex ADA_PRJ_INCLUDE_FILE
7812 Each of the directories listed in the text file whose name is given
7813 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7814
7815 @noindent
7816 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7817 driver when project files are used. It should not normally be set
7818 by other means.
7819
7820 @item
7821 @findex ADA_INCLUDE_PATH
7822 Each of the directories listed in the value of the
7823 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7824 @ifclear vms
7825 Construct this value
7826 exactly as the @env{PATH} environment variable: a list of directory
7827 names separated by colons (semicolons when working with the NT version).
7828 @end ifclear
7829 @ifset vms
7830 Normally, define this value as a logical name containing a comma separated
7831 list of directory names.
7832
7833 This variable can also be defined by means of an environment string
7834 (an argument to the HP C exec* set of functions).
7835
7836 Logical Name:
7837 @smallexample
7838 DEFINE ANOTHER_PATH FOO:[BAG]
7839 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7840 @end smallexample
7841
7842 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7843 first, followed by the standard Ada
7844 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7845 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7846 (Text_IO, Sequential_IO, etc)
7847 instead of the standard Ada packages. Thus, in order to get the standard Ada
7848 packages by default, ADA_INCLUDE_PATH must be redefined.
7849 @end ifset
7850
7851 @item
7852 The content of the @file{ada_source_path} file which is part of the GNAT
7853 installation tree and is used to store standard libraries such as the
7854 GNAT Run Time Library (RTL) source files.
7855 @ifclear vms
7856 @ref{Installing a library}
7857 @end ifclear
7858 @end enumerate
7859
7860 @noindent
7861 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7862 inhibits the use of the directory
7863 containing the source file named in the command line. You can still
7864 have this directory on your search path, but in this case it must be
7865 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7866
7867 Specifying the switch @option{-nostdinc}
7868 inhibits the search of the default location for the GNAT Run Time
7869 Library (RTL) source files.
7870
7871 The compiler outputs its object files and ALI files in the current
7872 working directory.
7873 @ifclear vms
7874 Caution: The object file can be redirected with the @option{-o} switch;
7875 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7876 so the @file{ALI} file will not go to the right place. Therefore, you should
7877 avoid using the @option{-o} switch.
7878 @end ifclear
7879
7880 @findex System.IO
7881 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7882 children make up the GNAT RTL, together with the simple @code{System.IO}
7883 package used in the @code{"Hello World"} example. The sources for these units
7884 are needed by the compiler and are kept together in one directory. Not
7885 all of the bodies are needed, but all of the sources are kept together
7886 anyway. In a normal installation, you need not specify these directory
7887 names when compiling or binding. Either the environment variables or
7888 the built-in defaults cause these files to be found.
7889
7890 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7891 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7892 consisting of child units of @code{GNAT}. This is a collection of generally
7893 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7894 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7895
7896 Besides simplifying access to the RTL, a major use of search paths is
7897 in compiling sources from multiple directories. This can make
7898 development environments much more flexible.
7899
7900 @node Order of Compilation Issues
7901 @section Order of Compilation Issues
7902
7903 @noindent
7904 If, in our earlier example, there was a spec for the @code{hello}
7905 procedure, it would be contained in the file @file{hello.ads}; yet this
7906 file would not have to be explicitly compiled. This is the result of the
7907 model we chose to implement library management. Some of the consequences
7908 of this model are as follows:
7909
7910 @itemize @bullet
7911 @item
7912 There is no point in compiling specs (except for package
7913 specs with no bodies) because these are compiled as needed by clients. If
7914 you attempt a useless compilation, you will receive an error message.
7915 It is also useless to compile subunits because they are compiled as needed
7916 by the parent.
7917
7918 @item
7919 There are no order of compilation requirements: performing a
7920 compilation never obsoletes anything. The only way you can obsolete
7921 something and require recompilations is to modify one of the
7922 source files on which it depends.
7923
7924 @item
7925 There is no library as such, apart from the ALI files
7926 (@pxref{The Ada Library Information Files}, for information on the format
7927 of these files). For now we find it convenient to create separate ALI files,
7928 but eventually the information therein may be incorporated into the object
7929 file directly.
7930
7931 @item
7932 When you compile a unit, the source files for the specs of all units
7933 that it @code{with}'s, all its subunits, and the bodies of any generics it
7934 instantiates must be available (reachable by the search-paths mechanism
7935 described above), or you will receive a fatal error message.
7936 @end itemize
7937
7938 @node Examples
7939 @section Examples
7940
7941 @noindent
7942 The following are some typical Ada compilation command line examples:
7943
7944 @table @code
7945 @item $ gcc -c xyz.adb
7946 Compile body in file @file{xyz.adb} with all default options.
7947
7948 @ifclear vms
7949 @item $ gcc -c -O2 -gnata xyz-def.adb
7950 @end ifclear
7951 @ifset vms
7952 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7953 @end ifset
7954
7955 Compile the child unit package in file @file{xyz-def.adb} with extensive
7956 optimizations, and pragma @code{Assert}/@code{Debug} statements
7957 enabled.
7958
7959 @item $ gcc -c -gnatc abc-def.adb
7960 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7961 mode.
7962 @end table
7963
7964 @node Binding Using gnatbind
7965 @chapter Binding Using @code{gnatbind}
7966 @findex gnatbind
7967
7968 @menu
7969 * Running gnatbind::
7970 * Switches for gnatbind::
7971 * Command-Line Access::
7972 * Search Paths for gnatbind::
7973 * Examples of gnatbind Usage::
7974 @end menu
7975
7976 @noindent
7977 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7978 to bind compiled GNAT objects.
7979
7980 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7981 driver (see @ref{The GNAT Driver and Project Files}).
7982
7983 The @code{gnatbind} program performs four separate functions:
7984
7985 @enumerate
7986 @item
7987 Checks that a program is consistent, in accordance with the rules in
7988 Chapter 10 of the Ada Reference Manual. In particular, error
7989 messages are generated if a program uses inconsistent versions of a
7990 given unit.
7991
7992 @item
7993 Checks that an acceptable order of elaboration exists for the program
7994 and issues an error message if it cannot find an order of elaboration
7995 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7996
7997 @item
7998 Generates a main program incorporating the given elaboration order.
7999 This program is a small Ada package (body and spec) that
8000 must be subsequently compiled
8001 using the GNAT compiler. The necessary compilation step is usually
8002 performed automatically by @command{gnatlink}. The two most important
8003 functions of this program
8004 are to call the elaboration routines of units in an appropriate order
8005 and to call the main program.
8006
8007 @item
8008 Determines the set of object files required by the given main program.
8009 This information is output in the forms of comments in the generated program,
8010 to be read by the @command{gnatlink} utility used to link the Ada application.
8011 @end enumerate
8012
8013 @node Running gnatbind
8014 @section Running @code{gnatbind}
8015
8016 @noindent
8017 The form of the @code{gnatbind} command is
8018
8019 @smallexample
8020 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8021 @c Expanding @ovar macro inline (explanation in macro def comments)
8022 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8023 @end smallexample
8024
8025 @noindent
8026 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8027 unit body. @code{gnatbind} constructs an Ada
8028 package in two files whose names are
8029 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8030 For example, if given the
8031 parameter @file{hello.ali}, for a main program contained in file
8032 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8033 and @file{b~hello.adb}.
8034
8035 When doing consistency checking, the binder takes into consideration
8036 any source files it can locate. For example, if the binder determines
8037 that the given main program requires the package @code{Pack}, whose
8038 @file{.ALI}
8039 file is @file{pack.ali} and whose corresponding source spec file is
8040 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8041 (using the same search path conventions as previously described for the
8042 @command{gcc} command). If it can locate this source file, it checks that
8043 the time stamps
8044 or source checksums of the source and its references to in @file{ALI} files
8045 match. In other words, any @file{ALI} files that mentions this spec must have
8046 resulted from compiling this version of the source file (or in the case
8047 where the source checksums match, a version close enough that the
8048 difference does not matter).
8049
8050 @cindex Source files, use by binder
8051 The effect of this consistency checking, which includes source files, is
8052 that the binder ensures that the program is consistent with the latest
8053 version of the source files that can be located at bind time. Editing a
8054 source file without compiling files that depend on the source file cause
8055 error messages to be generated by the binder.
8056
8057 For example, suppose you have a main program @file{hello.adb} and a
8058 package @code{P}, from file @file{p.ads} and you perform the following
8059 steps:
8060
8061 @enumerate
8062 @item
8063 Enter @code{gcc -c hello.adb} to compile the main program.
8064
8065 @item
8066 Enter @code{gcc -c p.ads} to compile package @code{P}.
8067
8068 @item
8069 Edit file @file{p.ads}.
8070
8071 @item
8072 Enter @code{gnatbind hello}.
8073 @end enumerate
8074
8075 @noindent
8076 At this point, the file @file{p.ali} contains an out-of-date time stamp
8077 because the file @file{p.ads} has been edited. The attempt at binding
8078 fails, and the binder generates the following error messages:
8079
8080 @smallexample
8081 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8082 error: "p.ads" has been modified and must be recompiled
8083 @end smallexample
8084
8085 @noindent
8086 Now both files must be recompiled as indicated, and then the bind can
8087 succeed, generating a main program. You need not normally be concerned
8088 with the contents of this file, but for reference purposes a sample
8089 binder output file is given in @ref{Example of Binder Output File}.
8090
8091 In most normal usage, the default mode of @command{gnatbind} which is to
8092 generate the main package in Ada, as described in the previous section.
8093 In particular, this means that any Ada programmer can read and understand
8094 the generated main program. It can also be debugged just like any other
8095 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8096 @command{gnatbind} and @command{gnatlink}.
8097
8098 @node Switches for gnatbind
8099 @section Switches for @command{gnatbind}
8100
8101 @noindent
8102 The following switches are available with @code{gnatbind}; details will
8103 be presented in subsequent sections.
8104
8105 @menu
8106 * Consistency-Checking Modes::
8107 * Binder Error Message Control::
8108 * Elaboration Control::
8109 * Output Control::
8110 * Dynamic Allocation Control::
8111 * Binding with Non-Ada Main Programs::
8112 * Binding Programs with No Main Subprogram::
8113 @end menu
8114
8115 @table @option
8116 @c !sort!
8117
8118 @item --version
8119 @cindex @option{--version} @command{gnatbind}
8120 Display Copyright and version, then exit disregarding all other options.
8121
8122 @item --help
8123 @cindex @option{--help} @command{gnatbind}
8124 If @option{--version} was not used, display usage, then exit disregarding
8125 all other options.
8126
8127 @item -a
8128 @cindex @option{-a} @command{gnatbind}
8129 Indicates that, if supported by the platform, the adainit procedure should
8130 be treated as an initialisation routine by the linker (a constructor). This
8131 is intended to be used by the Project Manager to automatically initialize
8132 shared Stand-Alone Libraries.
8133
8134 @item ^-aO^/OBJECT_SEARCH^
8135 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8136 Specify directory to be searched for ALI files.
8137
8138 @item ^-aI^/SOURCE_SEARCH^
8139 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8140 Specify directory to be searched for source file.
8141
8142 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8143 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8144 Output ALI list (to standard output or to the named file).
8145
8146 @item ^-b^/REPORT_ERRORS=BRIEF^
8147 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8148 Generate brief messages to @file{stderr} even if verbose mode set.
8149
8150 @item ^-c^/NOOUTPUT^
8151 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8152 Check only, no generation of binder output file.
8153
8154 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8155 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8156 This switch can be used to change the default task stack size value
8157 to a specified size @var{nn}, which is expressed in bytes by default, or
8158 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8159 with @var{m}.
8160 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8161 in effect, to completing all task specs with
8162 @smallexample @c ada
8163    pragma Storage_Size (nn);
8164 @end smallexample
8165 When they do not already have such a pragma.
8166
8167 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8168 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8169 This switch can be used to change the default secondary stack size value
8170 to a specified size @var{nn}, which is expressed in bytes by default, or
8171 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8172 with @var{m}.
8173
8174 The secondary stack is used to deal with functions that return a variable
8175 sized result, for example a function returning an unconstrained
8176 String. There are two ways in which this secondary stack is allocated.
8177
8178 For most targets, the secondary stack is growing on demand and is allocated
8179 as a chain of blocks in the heap. The -D option is not very
8180 relevant. It only give some control over the size of the allocated
8181 blocks (whose size is the minimum of the default secondary stack size value,
8182 and the actual size needed for the current allocation request).
8183
8184 For certain targets, notably VxWorks 653,
8185 the secondary stack is allocated by carving off a fixed ratio chunk of the
8186 primary task stack. The -D option is used to define the
8187 size of the environment task's secondary stack.
8188
8189 @item ^-e^/ELABORATION_DEPENDENCIES^
8190 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8191 Output complete list of elaboration-order dependencies.
8192
8193 @item ^-E^/STORE_TRACEBACKS^
8194 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8195 Store tracebacks in exception occurrences when the target supports it.
8196 @ignore
8197 @c The following may get moved to an appendix
8198 This option is currently supported on the following targets:
8199 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8200 @end ignore
8201 See also the packages @code{GNAT.Traceback} and
8202 @code{GNAT.Traceback.Symbolic} for more information.
8203 @ifclear vms
8204 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8205 @command{gcc} option.
8206 @end ifclear
8207
8208 @item ^-F^/FORCE_ELABS_FLAGS^
8209 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8210 Force the checks of elaboration flags. @command{gnatbind} does not normally
8211 generate checks of elaboration flags for the main executable, except when
8212 a Stand-Alone Library is used. However, there are cases when this cannot be
8213 detected by gnatbind. An example is importing an interface of a Stand-Alone
8214 Library through a pragma Import and only specifying through a linker switch
8215 this Stand-Alone Library. This switch is used to guarantee that elaboration
8216 flag checks are generated.
8217
8218 @item ^-h^/HELP^
8219 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8220 Output usage (help) information
8221
8222 @item ^-H32^/32_MALLOC^
8223 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8224 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8225 For further details see @ref{Dynamic Allocation Control}.
8226
8227 @item ^-H64^/64_MALLOC^
8228 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8229 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8230 @cindex @code{__gnat_malloc}
8231 For further details see @ref{Dynamic Allocation Control}.
8232
8233 @item ^-I^/SEARCH^
8234 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8235 Specify directory to be searched for source and ALI files.
8236
8237 @item ^-I-^/NOCURRENT_DIRECTORY^
8238 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8239 Do not look for sources in the current directory where @code{gnatbind} was
8240 invoked, and do not look for ALI files in the directory containing the
8241 ALI file named in the @code{gnatbind} command line.
8242
8243 @item ^-l^/ORDER_OF_ELABORATION^
8244 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8245 Output chosen elaboration order.
8246
8247 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8248 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8249 Bind the units for library building. In this case the adainit and
8250 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8251 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8252 ^@var{xxx}final^@var{XXX}FINAL^.
8253 Implies ^-n^/NOCOMPILE^.
8254 @ifclear vms
8255 (@xref{GNAT and Libraries}, for more details.)
8256 @end ifclear
8257 @ifset vms
8258 On OpenVMS, these init and final procedures are exported in uppercase
8259 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8260 the init procedure will be "TOTOINIT" and the exported name of the final
8261 procedure will be "TOTOFINAL".
8262 @end ifset
8263
8264 @item ^-Mxyz^/RENAME_MAIN=xyz^
8265 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8266 Rename generated main program from main to xyz. This option is
8267 supported on cross environments only.
8268
8269 @item ^-m^/ERROR_LIMIT=^@var{n}
8270 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8271 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8272 in the range 1..999999. The default value if no switch is
8273 given is 9999. If the number of warnings reaches this limit, then a
8274 message is output and further warnings are suppressed, the bind
8275 continues in this case. If the number of errors reaches this
8276 limit, then a message is output and the bind is abandoned.
8277 A value of zero means that no limit is enforced. The equal
8278 sign is optional.
8279
8280 @ifset unw
8281 Furthermore, under Windows, the sources pointed to by the libraries path
8282 set in the registry are not searched for.
8283 @end ifset
8284
8285 @item ^-n^/NOMAIN^
8286 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8287 No main program.
8288
8289 @item -nostdinc
8290 @cindex @option{-nostdinc} (@command{gnatbind})
8291 Do not look for sources in the system default directory.
8292
8293 @item -nostdlib
8294 @cindex @option{-nostdlib} (@command{gnatbind})
8295 Do not look for library files in the system default directory.
8296
8297 @item --RTS=@var{rts-path}
8298 @cindex @option{--RTS} (@code{gnatbind})
8299 Specifies the default location of the runtime library. Same meaning as the
8300 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8301
8302 @item ^-o ^/OUTPUT=^@var{file}
8303 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8304 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8305 Note that if this option is used, then linking must be done manually,
8306 gnatlink cannot be used.
8307
8308 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8309 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8310 Output object list (to standard output or to the named file).
8311
8312 @item ^-p^/PESSIMISTIC_ELABORATION^
8313 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8314 Pessimistic (worst-case) elaboration order
8315
8316 @item ^-P^-P^
8317 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8318 Generate binder file suitable for CodePeer.
8319
8320 @item ^-R^-R^
8321 @cindex @option{^-R^-R^} (@command{gnatbind})
8322 Output closure source list.
8323
8324 @item ^-s^/READ_SOURCES=ALL^
8325 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8326 Require all source files to be present.
8327
8328 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8329 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8330 Specifies the value to be used when detecting uninitialized scalar
8331 objects with pragma Initialize_Scalars.
8332 The @var{xxx} ^string specified with the switch^option^ may be either
8333 @itemize @bullet
8334 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8335 @item ``@option{^lo^LOW^}'' for the lowest possible value
8336 @item ``@option{^hi^HIGH^}'' for the highest possible value
8337 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8338 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8339 @end itemize
8340
8341 In addition, you can specify @option{-Sev} to indicate that the value is
8342 to be set at run time. In this case, the program will look for an environment
8343 @cindex GNAT_INIT_SCALARS
8344 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8345 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8346 If no environment variable is found, or if it does not have a valid value,
8347 then the default is @option{in} (invalid values).
8348
8349 @ifclear vms
8350 @item -static
8351 @cindex @option{-static} (@code{gnatbind})
8352 Link against a static GNAT run time.
8353
8354 @item -shared
8355 @cindex @option{-shared} (@code{gnatbind})
8356 Link against a shared GNAT run time when available.
8357 @end ifclear
8358
8359 @item ^-t^/NOTIME_STAMP_CHECK^
8360 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8361 Tolerate time stamp and other consistency errors
8362
8363 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8364 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8365 Set the time slice value to @var{n} milliseconds. If the system supports
8366 the specification of a specific time slice value, then the indicated value
8367 is used. If the system does not support specific time slice values, but
8368 does support some general notion of round-robin scheduling, then any
8369 nonzero value will activate round-robin scheduling.
8370
8371 A value of zero is treated specially. It turns off time
8372 slicing, and in addition, indicates to the tasking run time that the
8373 semantics should match as closely as possible the Annex D
8374 requirements of the Ada RM, and in particular sets the default
8375 scheduling policy to @code{FIFO_Within_Priorities}.
8376
8377 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8378 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8379 Enable dynamic stack usage, with @var{n} results stored and displayed
8380 at program termination. A result is generated when a task
8381 terminates. Results that can't be stored are displayed on the fly, at
8382 task termination. This option is currently not supported on Itanium
8383 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8384
8385 @item ^-v^/REPORT_ERRORS=VERBOSE^
8386 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8387 Verbose mode. Write error messages, header, summary output to
8388 @file{stdout}.
8389
8390 @ifclear vms
8391 @item -w@var{x}
8392 @cindex @option{-w} (@code{gnatbind})
8393 Warning mode (@var{x}=s/e for suppress/treat as error)
8394 @end ifclear
8395
8396 @ifset vms
8397 @item /WARNINGS=NORMAL
8398 @cindex @option{/WARNINGS} (@code{gnatbind})
8399 Normal warnings mode. Warnings are issued but ignored
8400
8401 @item /WARNINGS=SUPPRESS
8402 @cindex @option{/WARNINGS} (@code{gnatbind})
8403 All warning messages are suppressed
8404
8405 @item /WARNINGS=ERROR
8406 @cindex @option{/WARNINGS} (@code{gnatbind})
8407 Warning messages are treated as fatal errors
8408 @end ifset
8409
8410 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8411 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8412 Override default wide character encoding for standard Text_IO files.
8413
8414 @item ^-x^/READ_SOURCES=NONE^
8415 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8416 Exclude source files (check object consistency only).
8417
8418 @ifset vms
8419 @item /READ_SOURCES=AVAILABLE
8420 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8421 Default mode, in which sources are checked for consistency only if
8422 they are available.
8423 @end ifset
8424
8425 @item ^-y^/ENABLE_LEAP_SECONDS^
8426 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8427 Enable leap seconds support in @code{Ada.Calendar} and its children.
8428
8429 @item ^-z^/ZERO_MAIN^
8430 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8431 No main subprogram.
8432 @end table
8433
8434 @ifclear vms
8435 @noindent
8436 You may obtain this listing of switches by running @code{gnatbind} with
8437 no arguments.
8438 @end ifclear
8439
8440 @node Consistency-Checking Modes
8441 @subsection Consistency-Checking Modes
8442
8443 @noindent
8444 As described earlier, by default @code{gnatbind} checks
8445 that object files are consistent with one another and are consistent
8446 with any source files it can locate. The following switches control binder
8447 access to sources.
8448
8449 @table @option
8450 @c !sort!
8451 @item ^-s^/READ_SOURCES=ALL^
8452 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8453 Require source files to be present. In this mode, the binder must be
8454 able to locate all source files that are referenced, in order to check
8455 their consistency. In normal mode, if a source file cannot be located it
8456 is simply ignored. If you specify this switch, a missing source
8457 file is an error.
8458
8459 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8460 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8461 Override default wide character encoding for standard Text_IO files.
8462 Normally the default wide character encoding method used for standard
8463 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8464 the main source input (see description of switch
8465 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8466 use of this switch for the binder (which has the same set of
8467 possible arguments) overrides this default as specified.
8468
8469 @item ^-x^/READ_SOURCES=NONE^
8470 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8471 Exclude source files. In this mode, the binder only checks that ALI
8472 files are consistent with one another. Source files are not accessed.
8473 The binder runs faster in this mode, and there is still a guarantee that
8474 the resulting program is self-consistent.
8475 If a source file has been edited since it was last compiled, and you
8476 specify this switch, the binder will not detect that the object
8477 file is out of date with respect to the source file. Note that this is the
8478 mode that is automatically used by @command{gnatmake} because in this
8479 case the checking against sources has already been performed by
8480 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8481
8482 @ifset vms
8483 @item /READ_SOURCES=AVAILABLE
8484 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8485 This is the default mode in which source files are checked if they are
8486 available, and ignored if they are not available.
8487 @end ifset
8488 @end table
8489
8490 @node Binder Error Message Control
8491 @subsection Binder Error Message Control
8492
8493 @noindent
8494 The following switches provide control over the generation of error
8495 messages from the binder:
8496
8497 @table @option
8498 @c !sort!
8499 @item ^-v^/REPORT_ERRORS=VERBOSE^
8500 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8501 Verbose mode. In the normal mode, brief error messages are generated to
8502 @file{stderr}. If this switch is present, a header is written
8503 to @file{stdout} and any error messages are directed to @file{stdout}.
8504 All that is written to @file{stderr} is a brief summary message.
8505
8506 @item ^-b^/REPORT_ERRORS=BRIEF^
8507 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8508 Generate brief error messages to @file{stderr} even if verbose mode is
8509 specified. This is relevant only when used with the
8510 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8511
8512 @ifclear vms
8513 @item -m@var{n}
8514 @cindex @option{-m} (@code{gnatbind})
8515 Limits the number of error messages to @var{n}, a decimal integer in the
8516 range 1-999. The binder terminates immediately if this limit is reached.
8517
8518 @item -M@var{xxx}
8519 @cindex @option{-M} (@code{gnatbind})
8520 Renames the generated main program from @code{main} to @code{xxx}.
8521 This is useful in the case of some cross-building environments, where
8522 the actual main program is separate from the one generated
8523 by @code{gnatbind}.
8524 @end ifclear
8525
8526 @item ^-ws^/WARNINGS=SUPPRESS^
8527 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8528 @cindex Warnings
8529 Suppress all warning messages.
8530
8531 @item ^-we^/WARNINGS=ERROR^
8532 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8533 Treat any warning messages as fatal errors.
8534
8535 @ifset vms
8536 @item /WARNINGS=NORMAL
8537 Standard mode with warnings generated, but warnings do not get treated
8538 as errors.
8539 @end ifset
8540
8541 @item ^-t^/NOTIME_STAMP_CHECK^
8542 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8543 @cindex Time stamp checks, in binder
8544 @cindex Binder consistency checks
8545 @cindex Consistency checks, in binder
8546 The binder performs a number of consistency checks including:
8547
8548 @itemize @bullet
8549 @item
8550 Check that time stamps of a given source unit are consistent
8551 @item
8552 Check that checksums of a given source unit are consistent
8553 @item
8554 Check that consistent versions of @code{GNAT} were used for compilation
8555 @item
8556 Check consistency of configuration pragmas as required
8557 @end itemize
8558
8559 @noindent
8560 Normally failure of such checks, in accordance with the consistency
8561 requirements of the Ada Reference Manual, causes error messages to be
8562 generated which abort the binder and prevent the output of a binder
8563 file and subsequent link to obtain an executable.
8564
8565 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8566 into warnings, so that
8567 binding and linking can continue to completion even in the presence of such
8568 errors. The result may be a failed link (due to missing symbols), or a
8569 non-functional executable which has undefined semantics.
8570 @emph{This means that
8571 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8572 with extreme care.}
8573 @end table
8574
8575 @node Elaboration Control
8576 @subsection Elaboration Control
8577
8578 @noindent
8579 The following switches provide additional control over the elaboration
8580 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8581
8582 @table @option
8583 @item ^-p^/PESSIMISTIC_ELABORATION^
8584 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8585 Normally the binder attempts to choose an elaboration order that is
8586 likely to minimize the likelihood of an elaboration order error resulting
8587 in raising a @code{Program_Error} exception. This switch reverses the
8588 action of the binder, and requests that it deliberately choose an order
8589 that is likely to maximize the likelihood of an elaboration error.
8590 This is useful in ensuring portability and avoiding dependence on
8591 accidental fortuitous elaboration ordering.
8592
8593 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8594 switch if dynamic
8595 elaboration checking is used (@option{-gnatE} switch used for compilation).
8596 This is because in the default static elaboration mode, all necessary
8597 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8598 These implicit pragmas are still respected by the binder in
8599 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8600 safe elaboration order is assured.
8601 @end table
8602
8603 @node Output Control
8604 @subsection Output Control
8605
8606 @noindent
8607 The following switches allow additional control over the output
8608 generated by the binder.
8609
8610 @table @option
8611 @c !sort!
8612
8613 @item ^-c^/NOOUTPUT^
8614 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8615 Check only. Do not generate the binder output file. In this mode the
8616 binder performs all error checks but does not generate an output file.
8617
8618 @item ^-e^/ELABORATION_DEPENDENCIES^
8619 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8620 Output complete list of elaboration-order dependencies, showing the
8621 reason for each dependency. This output can be rather extensive but may
8622 be useful in diagnosing problems with elaboration order. The output is
8623 written to @file{stdout}.
8624
8625 @item ^-h^/HELP^
8626 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8627 Output usage information. The output is written to @file{stdout}.
8628
8629 @item ^-K^/LINKER_OPTION_LIST^
8630 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8631 Output linker options to @file{stdout}. Includes library search paths,
8632 contents of pragmas Ident and Linker_Options, and libraries added
8633 by @code{gnatbind}.
8634
8635 @item ^-l^/ORDER_OF_ELABORATION^
8636 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8637 Output chosen elaboration order. The output is written to @file{stdout}.
8638
8639 @item ^-O^/OBJECT_LIST^
8640 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8641 Output full names of all the object files that must be linked to provide
8642 the Ada component of the program. The output is written to @file{stdout}.
8643 This list includes the files explicitly supplied and referenced by the user
8644 as well as implicitly referenced run-time unit files. The latter are
8645 omitted if the corresponding units reside in shared libraries. The
8646 directory names for the run-time units depend on the system configuration.
8647
8648 @item ^-o ^/OUTPUT=^@var{file}
8649 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8650 Set name of output file to @var{file} instead of the normal
8651 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8652 binder generated body filename.
8653 Note that if this option is used, then linking must be done manually.
8654 It is not possible to use gnatlink in this case, since it cannot locate
8655 the binder file.
8656
8657 @item ^-r^/RESTRICTION_LIST^
8658 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8659 Generate list of @code{pragma Restrictions} that could be applied to
8660 the current unit. This is useful for code audit purposes, and also may
8661 be used to improve code generation in some cases.
8662
8663 @end table
8664
8665 @node Dynamic Allocation Control
8666 @subsection Dynamic Allocation Control
8667
8668 @noindent
8669 The heap control switches -- @option{-H32} and @option{-H64} --
8670 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8671 They only affect compiler-generated allocations via @code{__gnat_malloc};
8672 explicit calls to @code{malloc} and related functions from the C
8673 run-time library are unaffected.
8674
8675 @table @option
8676 @item -H32
8677 Allocate memory on 32-bit heap
8678
8679 @item -H64
8680 Allocate memory on 64-bit heap.  This is the default
8681 unless explicitly overridden by a @code{'Size} clause on the access type.
8682 @end table
8683
8684 @ifset vms
8685 @noindent
8686 See also @ref{Access types and 32/64-bit allocation}.
8687 @end ifset
8688 @ifclear vms
8689 @noindent
8690 These switches are only effective on VMS platforms.
8691 @end ifclear
8692
8693
8694 @node Binding with Non-Ada Main Programs
8695 @subsection Binding with Non-Ada Main Programs
8696
8697 @noindent
8698 In our description so far we have assumed that the main
8699 program is in Ada, and that the task of the binder is to generate a
8700 corresponding function @code{main} that invokes this Ada main
8701 program. GNAT also supports the building of executable programs where
8702 the main program is not in Ada, but some of the called routines are
8703 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8704 The following switch is used in this situation:
8705
8706 @table @option
8707 @item ^-n^/NOMAIN^
8708 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8709 No main program. The main program is not in Ada.
8710 @end table
8711
8712 @noindent
8713 In this case, most of the functions of the binder are still required,
8714 but instead of generating a main program, the binder generates a file
8715 containing the following callable routines:
8716
8717 @table @code
8718 @item adainit
8719 @findex adainit
8720 You must call this routine to initialize the Ada part of the program by
8721 calling the necessary elaboration routines. A call to @code{adainit} is
8722 required before the first call to an Ada subprogram.
8723
8724 Note that it is assumed that the basic execution environment must be setup
8725 to be appropriate for Ada execution at the point where the first Ada
8726 subprogram is called. In particular, if the Ada code will do any
8727 floating-point operations, then the FPU must be setup in an appropriate
8728 manner. For the case of the x86, for example, full precision mode is
8729 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8730 that the FPU is in the right state.
8731
8732 @item adafinal
8733 @findex adafinal
8734 You must call this routine to perform any library-level finalization
8735 required by the Ada subprograms. A call to @code{adafinal} is required
8736 after the last call to an Ada subprogram, and before the program
8737 terminates.
8738 @end table
8739
8740 @noindent
8741 If the @option{^-n^/NOMAIN^} switch
8742 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8743 @cindex Binder, multiple input files
8744 is given, more than one ALI file may appear on
8745 the command line for @code{gnatbind}. The normal @dfn{closure}
8746 calculation is performed for each of the specified units. Calculating
8747 the closure means finding out the set of units involved by tracing
8748 @code{with} references. The reason it is necessary to be able to
8749 specify more than one ALI file is that a given program may invoke two or
8750 more quite separate groups of Ada units.
8751
8752 The binder takes the name of its output file from the last specified ALI
8753 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8754 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8755 The output is an Ada unit in source form that can be compiled with GNAT.
8756 This compilation occurs automatically as part of the @command{gnatlink}
8757 processing.
8758
8759 Currently the GNAT run time requires a FPU using 80 bits mode
8760 precision. Under targets where this is not the default it is required to
8761 call GNAT.Float_Control.Reset before using floating point numbers (this
8762 include float computation, float input and output) in the Ada code. A
8763 side effect is that this could be the wrong mode for the foreign code
8764 where floating point computation could be broken after this call.
8765
8766 @node Binding Programs with No Main Subprogram
8767 @subsection Binding Programs with No Main Subprogram
8768
8769 @noindent
8770 It is possible to have an Ada program which does not have a main
8771 subprogram. This program will call the elaboration routines of all the
8772 packages, then the finalization routines.
8773
8774 The following switch is used to bind programs organized in this manner:
8775
8776 @table @option
8777 @item ^-z^/ZERO_MAIN^
8778 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8779 Normally the binder checks that the unit name given on the command line
8780 corresponds to a suitable main subprogram. When this switch is used,
8781 a list of ALI files can be given, and the execution of the program
8782 consists of elaboration of these units in an appropriate order. Note
8783 that the default wide character encoding method for standard Text_IO
8784 files is always set to Brackets if this switch is set (you can use
8785 the binder switch
8786 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8787 @end table
8788
8789 @node Command-Line Access
8790 @section Command-Line Access
8791
8792 @noindent
8793 The package @code{Ada.Command_Line} provides access to the command-line
8794 arguments and program name. In order for this interface to operate
8795 correctly, the two variables
8796
8797 @smallexample
8798 @group
8799 int gnat_argc;
8800 char **gnat_argv;
8801 @end group
8802 @end smallexample
8803
8804 @noindent
8805 @findex gnat_argv
8806 @findex gnat_argc
8807 are declared in one of the GNAT library routines. These variables must
8808 be set from the actual @code{argc} and @code{argv} values passed to the
8809 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8810 generates the C main program to automatically set these variables.
8811 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8812 set these variables. If they are not set, the procedures in
8813 @code{Ada.Command_Line} will not be available, and any attempt to use
8814 them will raise @code{Constraint_Error}. If command line access is
8815 required, your main program must set @code{gnat_argc} and
8816 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8817 it.
8818
8819 @node Search Paths for gnatbind
8820 @section Search Paths for @code{gnatbind}
8821
8822 @noindent
8823 The binder takes the name of an ALI file as its argument and needs to
8824 locate source files as well as other ALI files to verify object consistency.
8825
8826 For source files, it follows exactly the same search rules as @command{gcc}
8827 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8828 directories searched are:
8829
8830 @enumerate
8831 @item
8832 The directory containing the ALI file named in the command line, unless
8833 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8834
8835 @item
8836 All directories specified by @option{^-I^/SEARCH^}
8837 switches on the @code{gnatbind}
8838 command line, in the order given.
8839
8840 @item
8841 @findex ADA_PRJ_OBJECTS_FILE
8842 Each of the directories listed in the text file whose name is given
8843 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8844
8845 @noindent
8846 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8847 driver when project files are used. It should not normally be set
8848 by other means.
8849
8850 @item
8851 @findex ADA_OBJECTS_PATH
8852 Each of the directories listed in the value of the
8853 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8854 @ifset unw
8855 Construct this value
8856 exactly as the @env{PATH} environment variable: a list of directory
8857 names separated by colons (semicolons when working with the NT version
8858 of GNAT).
8859 @end ifset
8860 @ifset vms
8861 Normally, define this value as a logical name containing a comma separated
8862 list of directory names.
8863
8864 This variable can also be defined by means of an environment string
8865 (an argument to the HP C exec* set of functions).
8866
8867 Logical Name:
8868 @smallexample
8869 DEFINE ANOTHER_PATH FOO:[BAG]
8870 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8871 @end smallexample
8872
8873 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8874 first, followed by the standard Ada
8875 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8876 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8877 (Text_IO, Sequential_IO, etc)
8878 instead of the standard Ada packages. Thus, in order to get the standard Ada
8879 packages by default, ADA_OBJECTS_PATH must be redefined.
8880 @end ifset
8881
8882 @item
8883 The content of the @file{ada_object_path} file which is part of the GNAT
8884 installation tree and is used to store standard libraries such as the
8885 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8886 specified.
8887 @ifclear vms
8888 @ref{Installing a library}
8889 @end ifclear
8890 @end enumerate
8891
8892 @noindent
8893 In the binder the switch @option{^-I^/SEARCH^}
8894 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8895 is used to specify both source and
8896 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8897 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8898 instead if you want to specify
8899 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8900 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8901 if you want to specify library paths
8902 only. This means that for the binder
8903 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8904 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8905 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8906 The binder generates the bind file (a C language source file) in the
8907 current working directory.
8908
8909 @findex Ada
8910 @findex System
8911 @findex Interfaces
8912 @findex GNAT
8913 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8914 children make up the GNAT Run-Time Library, together with the package
8915 GNAT and its children, which contain a set of useful additional
8916 library functions provided by GNAT. The sources for these units are
8917 needed by the compiler and are kept together in one directory. The ALI
8918 files and object files generated by compiling the RTL are needed by the
8919 binder and the linker and are kept together in one directory, typically
8920 different from the directory containing the sources. In a normal
8921 installation, you need not specify these directory names when compiling
8922 or binding. Either the environment variables or the built-in defaults
8923 cause these files to be found.
8924
8925 Besides simplifying access to the RTL, a major use of search paths is
8926 in compiling sources from multiple directories. This can make
8927 development environments much more flexible.
8928
8929 @node Examples of gnatbind Usage
8930 @section Examples of @code{gnatbind} Usage
8931
8932 @noindent
8933 This section contains a number of examples of using the GNAT binding
8934 utility @code{gnatbind}.
8935
8936 @table @code
8937 @item gnatbind hello
8938 The main program @code{Hello} (source program in @file{hello.adb}) is
8939 bound using the standard switch settings. The generated main program is
8940 @file{b~hello.adb}. This is the normal, default use of the binder.
8941
8942 @ifclear vms
8943 @item gnatbind hello -o mainprog.adb
8944 @end ifclear
8945 @ifset vms
8946 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8947 @end ifset
8948 The main program @code{Hello} (source program in @file{hello.adb}) is
8949 bound using the standard switch settings. The generated main program is
8950 @file{mainprog.adb} with the associated spec in
8951 @file{mainprog.ads}. Note that you must specify the body here not the
8952 spec. Note that if this option is used, then linking must be done manually,
8953 since gnatlink will not be able to find the generated file.
8954 @end table
8955
8956 @c ------------------------------------
8957 @node Linking Using gnatlink
8958 @chapter Linking Using @command{gnatlink}
8959 @c ------------------------------------
8960 @findex gnatlink
8961
8962 @noindent
8963 This chapter discusses @command{gnatlink}, a tool that links
8964 an Ada program and builds an executable file. This utility
8965 invokes the system linker ^(via the @command{gcc} command)^^
8966 with a correct list of object files and library references.
8967 @command{gnatlink} automatically determines the list of files and
8968 references for the Ada part of a program. It uses the binder file
8969 generated by the @command{gnatbind} to determine this list.
8970
8971 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8972 driver (see @ref{The GNAT Driver and Project Files}).
8973
8974 @menu
8975 * Running gnatlink::
8976 * Switches for gnatlink::
8977 @end menu
8978
8979 @node Running gnatlink
8980 @section Running @command{gnatlink}
8981
8982 @noindent
8983 The form of the @command{gnatlink} command is
8984
8985 @smallexample
8986 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8987 @c            @ovar{non-Ada objects} @ovar{linker options}
8988 @c Expanding @ovar macro inline (explanation in macro def comments)
8989 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8990            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8991
8992 @end smallexample
8993
8994 @noindent
8995 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8996 non-Ada objects
8997 or linker options) may be in any order, provided that no non-Ada object may
8998 be mistaken for a main @file{ALI} file.
8999 Any file name @file{F} without the @file{.ali}
9000 extension will be taken as the main @file{ALI} file if a file exists
9001 whose name is the concatenation of @file{F} and @file{.ali}.
9002
9003 @noindent
9004 @file{@var{mainprog}.ali} references the ALI file of the main program.
9005 The @file{.ali} extension of this file can be omitted. From this
9006 reference, @command{gnatlink} locates the corresponding binder file
9007 @file{b~@var{mainprog}.adb} and, using the information in this file along
9008 with the list of non-Ada objects and linker options, constructs a
9009 linker command file to create the executable.
9010
9011 The arguments other than the @command{gnatlink} switches and the main
9012 @file{ALI} file are passed to the linker uninterpreted.
9013 They typically include the names of
9014 object files for units written in other languages than Ada and any library
9015 references required to resolve references in any of these foreign language
9016 units, or in @code{Import} pragmas in any Ada units.
9017
9018 @var{linker options} is an optional list of linker specific
9019 switches.
9020 The default linker called by gnatlink is @command{gcc} which in
9021 turn calls the appropriate system linker.
9022
9023 One useful option for the linker is @option{-s}: it reduces the size of the
9024 executable by removing all symbol table and relocation information from the
9025 executable.
9026
9027 Standard options for the linker such as @option{-lmy_lib} or
9028 @option{-Ldir} can be added as is.
9029 For options that are not recognized by
9030 @command{gcc} as linker options, use the @command{gcc} switches
9031 @option{-Xlinker} or @option{-Wl,}.
9032
9033 Refer to the GCC documentation for
9034 details.
9035
9036 Here is an example showing how to generate a linker map:
9037
9038 @smallexample
9039 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9040 @end smallexample
9041
9042 Using @var{linker options} it is possible to set the program stack and
9043 heap size.
9044 @ifset unw
9045 See @ref{Setting Stack Size from gnatlink} and
9046 @ref{Setting Heap Size from gnatlink}.
9047 @end ifset
9048
9049 @command{gnatlink} determines the list of objects required by the Ada
9050 program and prepends them to the list of objects passed to the linker.
9051 @command{gnatlink} also gathers any arguments set by the use of
9052 @code{pragma Linker_Options} and adds them to the list of arguments
9053 presented to the linker.
9054
9055 @ifset vms
9056 @command{gnatlink} accepts the following types of extra files on the command
9057 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9058 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9059 handled according to their extension.
9060 @end ifset
9061
9062 @node Switches for gnatlink
9063 @section Switches for @command{gnatlink}
9064
9065 @noindent
9066 The following switches are available with the @command{gnatlink} utility:
9067
9068 @table @option
9069 @c !sort!
9070
9071 @item --version
9072 @cindex @option{--version} @command{gnatlink}
9073 Display Copyright and version, then exit disregarding all other options.
9074
9075 @item --help
9076 @cindex @option{--help} @command{gnatlink}
9077 If @option{--version} was not used, display usage, then exit disregarding
9078 all other options.
9079
9080 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9081 @cindex Command line length
9082 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9083 On some targets, the command line length is limited, and @command{gnatlink}
9084 will generate a separate file for the linker if the list of object files
9085 is too long.
9086 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9087 to be generated even if
9088 the limit is not exceeded. This is useful in some cases to deal with
9089 special situations where the command line length is exceeded.
9090
9091 @item ^-g^/DEBUG^
9092 @cindex Debugging information, including
9093 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9094 The option to include debugging information causes the Ada bind file (in
9095 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9096 @option{^-g^/DEBUG^}.
9097 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9098 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9099 Without @option{^-g^/DEBUG^}, the binder removes these files by
9100 default. The same procedure apply if a C bind file was generated using
9101 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9102 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9103
9104 @item ^-n^/NOCOMPILE^
9105 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9106 Do not compile the file generated by the binder. This may be used when
9107 a link is rerun with different options, but there is no need to recompile
9108 the binder file.
9109
9110 @item ^-v^/VERBOSE^
9111 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9112 Causes additional information to be output, including a full list of the
9113 included object files. This switch option is most useful when you want
9114 to see what set of object files are being used in the link step.
9115
9116 @item ^-v -v^/VERBOSE/VERBOSE^
9117 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9118 Very verbose mode. Requests that the compiler operate in verbose mode when
9119 it compiles the binder file, and that the system linker run in verbose mode.
9120
9121 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9122 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9123 @var{exec-name} specifies an alternate name for the generated
9124 executable program. If this switch is omitted, the executable has the same
9125 name as the main unit. For example, @code{gnatlink try.ali} creates
9126 an executable called @file{^try^TRY.EXE^}.
9127
9128 @ifclear vms
9129 @item -b @var{target}
9130 @cindex @option{-b} (@command{gnatlink})
9131 Compile your program to run on @var{target}, which is the name of a
9132 system configuration. You must have a GNAT cross-compiler built if
9133 @var{target} is not the same as your host system.
9134
9135 @item -B@var{dir}
9136 @cindex @option{-B} (@command{gnatlink})
9137 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9138 from @var{dir} instead of the default location. Only use this switch
9139 when multiple versions of the GNAT compiler are available.
9140 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9141 for further details. You would normally use the @option{-b} or
9142 @option{-V} switch instead.
9143
9144 @item -M
9145 When linking an executable, create a map file. The name of the map file
9146 has the same name as the executable with extension ".map".
9147
9148 @item -M=mapfile
9149 When linking an executable, create a map file. The name of the map file is
9150 "mapfile".
9151
9152 @item --GCC=@var{compiler_name}
9153 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9154 Program used for compiling the binder file. The default is
9155 @command{gcc}. You need to use quotes around @var{compiler_name} if
9156 @code{compiler_name} contains spaces or other separator characters.
9157 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9158 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9159 inserted after your command name. Thus in the above example the compiler
9160 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9161 A limitation of this syntax is that the name and path name of the executable
9162 itself must not include any embedded spaces. If the compiler executable is
9163 different from the default one (gcc or <prefix>-gcc), then the back-end
9164 switches in the ALI file are not used to compile the binder generated source.
9165 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9166 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9167 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9168 is taken into account. However, all the additional switches are also taken
9169 into account. Thus,
9170 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9171 @option{--GCC="bar -x -y -z -t"}.
9172
9173 @item --LINK=@var{name}
9174 @cindex @option{--LINK=} (@command{gnatlink})
9175 @var{name} is the name of the linker to be invoked. This is especially
9176 useful in mixed language programs since languages such as C++ require
9177 their own linker to be used. When this switch is omitted, the default
9178 name for the linker is @command{gcc}. When this switch is used, the
9179 specified linker is called instead of @command{gcc} with exactly the same
9180 parameters that would have been passed to @command{gcc} so if the desired
9181 linker requires different parameters it is necessary to use a wrapper
9182 script that massages the parameters before invoking the real linker. It
9183 may be useful to control the exact invocation by using the verbose
9184 switch.
9185
9186 @end ifclear
9187
9188 @ifset vms
9189 @item /DEBUG=TRACEBACK
9190 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9191 This qualifier causes sufficient information to be included in the
9192 executable file to allow a traceback, but does not include the full
9193 symbol information needed by the debugger.
9194
9195 @item /IDENTIFICATION="<string>"
9196 @code{"<string>"} specifies the string to be stored in the image file
9197 identification field in the image header.
9198 It overrides any pragma @code{Ident} specified string.
9199
9200 @item /NOINHIBIT-EXEC
9201 Generate the executable file even if there are linker warnings.
9202
9203 @item /NOSTART_FILES
9204 Don't link in the object file containing the ``main'' transfer address.
9205 Used when linking with a foreign language main program compiled with an
9206 HP compiler.
9207
9208 @item /STATIC
9209 Prefer linking with object libraries over sharable images, even without
9210 /DEBUG.
9211 @end ifset
9212
9213 @end table
9214
9215 @node The GNAT Make Program gnatmake
9216 @chapter The GNAT Make Program @command{gnatmake}
9217 @findex gnatmake
9218
9219 @menu
9220 * Running gnatmake::
9221 * Switches for gnatmake::
9222 * Mode Switches for gnatmake::
9223 * Notes on the Command Line::
9224 * How gnatmake Works::
9225 * Examples of gnatmake Usage::
9226 @end menu
9227 @noindent
9228 A typical development cycle when working on an Ada program consists of
9229 the following steps:
9230
9231 @enumerate
9232 @item
9233 Edit some sources to fix bugs.
9234
9235 @item
9236 Add enhancements.
9237
9238 @item
9239 Compile all sources affected.
9240
9241 @item
9242 Rebind and relink.
9243
9244 @item
9245 Test.
9246 @end enumerate
9247
9248 @noindent
9249 The third step can be tricky, because not only do the modified files
9250 @cindex Dependency rules
9251 have to be compiled, but any files depending on these files must also be
9252 recompiled. The dependency rules in Ada can be quite complex, especially
9253 in the presence of overloading, @code{use} clauses, generics and inlined
9254 subprograms.
9255
9256 @command{gnatmake} automatically takes care of the third and fourth steps
9257 of this process. It determines which sources need to be compiled,
9258 compiles them, and binds and links the resulting object files.
9259
9260 Unlike some other Ada make programs, the dependencies are always
9261 accurately recomputed from the new sources. The source based approach of
9262 the GNAT compilation model makes this possible. This means that if
9263 changes to the source program cause corresponding changes in
9264 dependencies, they will always be tracked exactly correctly by
9265 @command{gnatmake}.
9266
9267 @node Running gnatmake
9268 @section Running @command{gnatmake}
9269
9270 @noindent
9271 The usual form of the @command{gnatmake} command is
9272
9273 @smallexample
9274 @c $ gnatmake @ovar{switches} @var{file_name}
9275 @c       @ovar{file_names} @ovar{mode_switches}
9276 @c Expanding @ovar macro inline (explanation in macro def comments)
9277 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9278       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9279 @end smallexample
9280
9281 @noindent
9282 The only required argument is one @var{file_name}, which specifies
9283 a compilation unit that is a main program. Several @var{file_names} can be
9284 specified: this will result in several executables being built.
9285 If @code{switches} are present, they can be placed before the first
9286 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9287 If @var{mode_switches} are present, they must always be placed after
9288 the last @var{file_name} and all @code{switches}.
9289
9290 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9291 extension may be omitted from the @var{file_name} arguments. However, if
9292 you are using non-standard extensions, then it is required that the
9293 extension be given. A relative or absolute directory path can be
9294 specified in a @var{file_name}, in which case, the input source file will
9295 be searched for in the specified directory only. Otherwise, the input
9296 source file will first be searched in the directory where
9297 @command{gnatmake} was invoked and if it is not found, it will be search on
9298 the source path of the compiler as described in
9299 @ref{Search Paths and the Run-Time Library (RTL)}.
9300
9301 All @command{gnatmake} output (except when you specify
9302 @option{^-M^/DEPENDENCIES_LIST^}) is to
9303 @file{stderr}. The output produced by the
9304 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9305 @file{stdout}.
9306
9307 @node Switches for gnatmake
9308 @section Switches for @command{gnatmake}
9309
9310 @noindent
9311 You may specify any of the following switches to @command{gnatmake}:
9312
9313 @table @option
9314 @c !sort!
9315
9316 @item --version
9317 @cindex @option{--version} @command{gnatmake}
9318 Display Copyright and version, then exit disregarding all other options.
9319
9320 @item --help
9321 @cindex @option{--help} @command{gnatmake}
9322 If @option{--version} was not used, display usage, then exit disregarding
9323 all other options.
9324
9325 @ifclear vms
9326 @item --GCC=@var{compiler_name}
9327 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9328 Program used for compiling. The default is `@command{gcc}'. You need to use
9329 quotes around @var{compiler_name} if @code{compiler_name} contains
9330 spaces or other separator characters. As an example @option{--GCC="foo -x
9331 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9332 compiler. A limitation of this syntax is that the name and path name of
9333 the executable itself must not include any embedded spaces. Note that
9334 switch @option{-c} is always inserted after your command name. Thus in the
9335 above example the compiler command that will be used by @command{gnatmake}
9336 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9337 used, only the last @var{compiler_name} is taken into account. However,
9338 all the additional switches are also taken into account. Thus,
9339 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9340 @option{--GCC="bar -x -y -z -t"}.
9341
9342 @item --GNATBIND=@var{binder_name}
9343 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9344 Program used for binding. The default is `@code{gnatbind}'. You need to
9345 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9346 or other separator characters. As an example @option{--GNATBIND="bar -x
9347 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9348 binder. Binder switches that are normally appended by @command{gnatmake}
9349 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9350 A limitation of this syntax is that the name and path name of the executable
9351 itself must not include any embedded spaces.
9352
9353 @item --GNATLINK=@var{linker_name}
9354 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9355 Program used for linking. The default is `@command{gnatlink}'. You need to
9356 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9357 or other separator characters. As an example @option{--GNATLINK="lan -x
9358 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9359 linker. Linker switches that are normally appended by @command{gnatmake} to
9360 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9361 A limitation of this syntax is that the name and path name of the executable
9362 itself must not include any embedded spaces.
9363
9364 @end ifclear
9365
9366 @item ^--subdirs^/SUBDIRS^=subdir
9367 Actual object directory of each project file is the subdirectory subdir of the
9368 object directory specified or defaulted in the project file.
9369
9370 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9371 Disallow simultaneous compilations in the same object directory when
9372 project files are used.
9373
9374 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9375 By default, shared library projects are not allowed to import static library
9376 projects. When this switch is used on the command line, this restriction is
9377 relaxed.
9378
9379 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9380 Specify a source info file. This switch is active only when project files
9381 are used. If the source info file is specified as a relative path, then it is
9382 relative to the object directory of the main project. If the source info file
9383 does not exist, then after the Project Manager has successfully parsed and
9384 processed the project files and found the sources, it creates the source info
9385 file. If the source info file already exists and can be read successfully,
9386 then the Project Manager will get all the needed information about the sources
9387 from the source info file and will not look for them. This reduces the time
9388 to process the project files, especially when looking for sources that take a
9389 long time. If the source info file exists but cannot be parsed successfully,
9390 the Project Manager will attempt to recreate it. If the Project Manager fails
9391 to create the source info file, a message is issued, but gnatmake does not
9392 fail. @command{gnatmake} "trusts" the source info file. This means that
9393 if the source files have changed (addition, deletion, moving to a different
9394 source directory), then the source info file need to be deleted and recreated.
9395
9396 @ifclear vms
9397 @item --create-map-file
9398 When linking an executable, create a map file. The name of the map file
9399 has the same name as the executable with extension ".map".
9400
9401 @item --create-map-file=mapfile
9402 When linking an executable, create a map file. The name of the map file is
9403 "mapfile".
9404
9405 @end ifclear
9406
9407 @item ^-a^/ALL_FILES^
9408 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9409 Consider all files in the make process, even the GNAT internal system
9410 files (for example, the predefined Ada library files), as well as any
9411 locked files. Locked files are files whose ALI file is write-protected.
9412 By default,
9413 @command{gnatmake} does not check these files,
9414 because the assumption is that the GNAT internal files are properly up
9415 to date, and also that any write protected ALI files have been properly
9416 installed. Note that if there is an installation problem, such that one
9417 of these files is not up to date, it will be properly caught by the
9418 binder.
9419 You may have to specify this switch if you are working on GNAT
9420 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9421 in conjunction with @option{^-f^/FORCE_COMPILE^}
9422 if you need to recompile an entire application,
9423 including run-time files, using special configuration pragmas,
9424 such as a @code{Normalize_Scalars} pragma.
9425
9426 By default
9427 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9428 internal files with
9429 @ifclear vms
9430 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9431 @end ifclear
9432 @ifset vms
9433 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9434 @end ifset
9435
9436 @item ^-b^/ACTIONS=BIND^
9437 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9438 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9439 compilation and binding, but no link.
9440 Can be combined with @option{^-l^/ACTIONS=LINK^}
9441 to do binding and linking. When not combined with
9442 @option{^-c^/ACTIONS=COMPILE^}
9443 all the units in the closure of the main program must have been previously
9444 compiled and must be up to date. The root unit specified by @var{file_name}
9445 may be given without extension, with the source extension or, if no GNAT
9446 Project File is specified, with the ALI file extension.
9447
9448 @item ^-c^/ACTIONS=COMPILE^
9449 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9450 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9451 is also specified. Do not perform linking, except if both
9452 @option{^-b^/ACTIONS=BIND^} and
9453 @option{^-l^/ACTIONS=LINK^} are also specified.
9454 If the root unit specified by @var{file_name} is not a main unit, this is the
9455 default. Otherwise @command{gnatmake} will attempt binding and linking
9456 unless all objects are up to date and the executable is more recent than
9457 the objects.
9458
9459 @item ^-C^/MAPPING^
9460 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9461 Use a temporary mapping file. A mapping file is a way to communicate
9462 to the compiler two mappings: from unit names to file names (without
9463 any directory information) and from file names to path names (with
9464 full directory information). A mapping file can make the compiler's
9465 file searches faster, especially if there are many source directories,
9466 or the sources are read over a slow network connection. If
9467 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9468 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9469 is initially populated based on the project file. If
9470 @option{^-C^/MAPPING^} is used without
9471 @option{^-P^/PROJECT_FILE^},
9472 the mapping file is initially empty. Each invocation of the compiler
9473 will add any newly accessed sources to the mapping file.
9474
9475 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9476 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9477 Use a specific mapping file. The file, specified as a path name (absolute or
9478 relative) by this switch, should already exist, otherwise the switch is
9479 ineffective. The specified mapping file will be communicated to the compiler.
9480 This switch is not compatible with a project file
9481 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9482 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9483
9484 @item ^-d^/DISPLAY_PROGRESS^
9485 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9486 Display progress for each source, up to date or not, as a single line
9487
9488 @smallexample
9489 completed x out of y (zz%)
9490 @end smallexample
9491
9492 If the file needs to be compiled this is displayed after the invocation of
9493 the compiler. These lines are displayed even in quiet output mode.
9494
9495 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9496 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9497 Put all object files and ALI file in directory @var{dir}.
9498 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9499 and ALI files go in the current working directory.
9500
9501 This switch cannot be used when using a project file.
9502
9503 @ifclear vms
9504 @item -eL
9505 @cindex @option{-eL} (@command{gnatmake})
9506 @cindex symbolic links
9507 Follow all symbolic links when processing project files.
9508 This should be used if your project uses symbolic links for files or
9509 directories, but is not needed in other cases.
9510
9511 @cindex naming scheme
9512 This also assumes that no directory matches the naming scheme for files (for
9513 instance that you do not have a directory called "sources.ads" when using the
9514 default GNAT naming scheme).
9515
9516 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9517 save a lot of system calls (several per source file and object file), which
9518 can result in a significant speed up to load and manipulate a project file,
9519 especially when using source files from a remote system.
9520
9521 @end ifclear
9522
9523 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9524 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9525 Output the commands for the compiler, the binder and the linker
9526 on ^standard output^SYS$OUTPUT^,
9527 instead of ^standard error^SYS$ERROR^.
9528
9529 @item ^-f^/FORCE_COMPILE^
9530 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9531 Force recompilations. Recompile all sources, even though some object
9532 files may be up to date, but don't recompile predefined or GNAT internal
9533 files or locked files (files with a write-protected ALI file),
9534 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9535
9536 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9537 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9538 When using project files, if some errors or warnings are detected during
9539 parsing and verbose mode is not in effect (no use of switch
9540 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9541 file, rather than its simple file name.
9542
9543 @item ^-g^/DEBUG^
9544 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9545 Enable debugging. This switch is simply passed to the compiler and to the
9546 linker.
9547
9548 @item ^-i^/IN_PLACE^
9549 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9550 In normal mode, @command{gnatmake} compiles all object files and ALI files
9551 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9552 then instead object files and ALI files that already exist are overwritten
9553 in place. This means that once a large project is organized into separate
9554 directories in the desired manner, then @command{gnatmake} will automatically
9555 maintain and update this organization. If no ALI files are found on the
9556 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9557 the new object and ALI files are created in the
9558 directory containing the source being compiled. If another organization
9559 is desired, where objects and sources are kept in different directories,
9560 a useful technique is to create dummy ALI files in the desired directories.
9561 When detecting such a dummy file, @command{gnatmake} will be forced to
9562 recompile the corresponding source file, and it will be put the resulting
9563 object and ALI files in the directory where it found the dummy file.
9564
9565 @item ^-j^/PROCESSES=^@var{n}
9566 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9567 @cindex Parallel make
9568 Use @var{n} processes to carry out the (re)compilations. On a
9569 multiprocessor machine compilations will occur in parallel. In the
9570 event of compilation errors, messages from various compilations might
9571 get interspersed (but @command{gnatmake} will give you the full ordered
9572 list of failing compiles at the end). If this is problematic, rerun
9573 the make process with n set to 1 to get a clean list of messages.
9574
9575 @item ^-k^/CONTINUE_ON_ERROR^
9576 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9577 Keep going. Continue as much as possible after a compilation error. To
9578 ease the programmer's task in case of compilation errors, the list of
9579 sources for which the compile fails is given when @command{gnatmake}
9580 terminates.
9581
9582 If @command{gnatmake} is invoked with several @file{file_names} and with this
9583 switch, if there are compilation errors when building an executable,
9584 @command{gnatmake} will not attempt to build the following executables.
9585
9586 @item ^-l^/ACTIONS=LINK^
9587 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9588 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9589 and linking. Linking will not be performed if combined with
9590 @option{^-c^/ACTIONS=COMPILE^}
9591 but not with @option{^-b^/ACTIONS=BIND^}.
9592 When not combined with @option{^-b^/ACTIONS=BIND^}
9593 all the units in the closure of the main program must have been previously
9594 compiled and must be up to date, and the main program needs to have been bound.
9595 The root unit specified by @var{file_name}
9596 may be given without extension, with the source extension or, if no GNAT
9597 Project File is specified, with the ALI file extension.
9598
9599 @item ^-m^/MINIMAL_RECOMPILATION^
9600 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9601 Specify that the minimum necessary amount of recompilations
9602 be performed. In this mode @command{gnatmake} ignores time
9603 stamp differences when the only
9604 modifications to a source file consist in adding/removing comments,
9605 empty lines, spaces or tabs. This means that if you have changed the
9606 comments in a source file or have simply reformatted it, using this
9607 switch will tell @command{gnatmake} not to recompile files that depend on it
9608 (provided other sources on which these files depend have undergone no
9609 semantic modifications). Note that the debugging information may be
9610 out of date with respect to the sources if the @option{-m} switch causes
9611 a compilation to be switched, so the use of this switch represents a
9612 trade-off between compilation time and accurate debugging information.
9613
9614 @item ^-M^/DEPENDENCIES_LIST^
9615 @cindex Dependencies, producing list
9616 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9617 Check if all objects are up to date. If they are, output the object
9618 dependences to @file{stdout} in a form that can be directly exploited in
9619 a @file{Makefile}. By default, each source file is prefixed with its
9620 (relative or absolute) directory name. This name is whatever you
9621 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9622 and @option{^-I^/SEARCH^} switches. If you use
9623 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9624 @option{^-q^/QUIET^}
9625 (see below), only the source file names,
9626 without relative paths, are output. If you just specify the
9627 @option{^-M^/DEPENDENCIES_LIST^}
9628 switch, dependencies of the GNAT internal system files are omitted. This
9629 is typically what you want. If you also specify
9630 the @option{^-a^/ALL_FILES^} switch,
9631 dependencies of the GNAT internal files are also listed. Note that
9632 dependencies of the objects in external Ada libraries (see switch
9633 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9634 are never reported.
9635
9636 @item ^-n^/DO_OBJECT_CHECK^
9637 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9638 Don't compile, bind, or link. Checks if all objects are up to date.
9639 If they are not, the full name of the first file that needs to be
9640 recompiled is printed.
9641 Repeated use of this option, followed by compiling the indicated source
9642 file, will eventually result in recompiling all required units.
9643
9644 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9645 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9646 Output executable name. The name of the final executable program will be
9647 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9648 name for the executable will be the name of the input file in appropriate form
9649 for an executable file on the host system.
9650
9651 This switch cannot be used when invoking @command{gnatmake} with several
9652 @file{file_names}.
9653
9654 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9655 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9656 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9657 automatically missing object directories, library directories and exec
9658 directories.
9659
9660 @item ^-P^/PROJECT_FILE=^@var{project}
9661 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9662 Use project file @var{project}. Only one such switch can be used.
9663 @xref{gnatmake and Project Files}.
9664
9665 @item ^-q^/QUIET^
9666 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9667 Quiet. When this flag is not set, the commands carried out by
9668 @command{gnatmake} are displayed.
9669
9670 @item ^-s^/SWITCH_CHECK/^
9671 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9672 Recompile if compiler switches have changed since last compilation.
9673 All compiler switches but -I and -o are taken into account in the
9674 following way:
9675 orders between different ``first letter'' switches are ignored, but
9676 orders between same switches are taken into account. For example,
9677 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9678 is equivalent to @option{-O -g}.
9679
9680 This switch is recommended when Integrated Preprocessing is used.
9681
9682 @item ^-u^/UNIQUE^
9683 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9684 Unique. Recompile at most the main files. It implies -c. Combined with
9685 -f, it is equivalent to calling the compiler directly. Note that using
9686 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9687 (@pxref{Project Files and Main Subprograms}).
9688
9689 @item ^-U^/ALL_PROJECTS^
9690 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9691 When used without a project file or with one or several mains on the command
9692 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9693 on the command line, all sources of all project files are checked and compiled
9694 if not up to date, and libraries are rebuilt, if necessary.
9695
9696 @item ^-v^/REASONS^
9697 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9698 Verbose. Display the reason for all recompilations @command{gnatmake}
9699 decides are necessary, with the highest verbosity level.
9700
9701 @item ^-vl^/LOW_VERBOSITY^
9702 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9703 Verbosity level Low. Display fewer lines than in verbosity Medium.
9704
9705 @item ^-vm^/MEDIUM_VERBOSITY^
9706 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9707 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9708
9709 @item ^-vh^/HIGH_VERBOSITY^
9710 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9711 Verbosity level High. Equivalent to ^-v^/REASONS^.
9712
9713 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9714 Indicate the verbosity of the parsing of GNAT project files.
9715 @xref{Switches Related to Project Files}.
9716
9717 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9718 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9719 Indicate that sources that are not part of any Project File may be compiled.
9720 Normally, when using Project Files, only sources that are part of a Project
9721 File may be compile. When this switch is used, a source outside of all Project
9722 Files may be compiled. The ALI file and the object file will be put in the
9723 object directory of the main Project. The compilation switches used will only
9724 be those specified on the command line. Even when
9725 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9726 command line need to be sources of a project file.
9727
9728 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9729 Indicate that external variable @var{name} has the value @var{value}.
9730 The Project Manager will use this value for occurrences of
9731 @code{external(name)} when parsing the project file.
9732 @xref{Switches Related to Project Files}.
9733
9734 @item ^-z^/NOMAIN^
9735 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9736 No main subprogram. Bind and link the program even if the unit name
9737 given on the command line is a package name. The resulting executable
9738 will execute the elaboration routines of the package and its closure,
9739 then the finalization routines.
9740
9741 @end table
9742
9743 @table @asis
9744 @item @command{gcc} @asis{switches}
9745 @ifclear vms
9746 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9747 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9748 @end ifclear
9749 @ifset vms
9750 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9751 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9752 automatically treated as a compiler switch, and passed on to all
9753 compilations that are carried out.
9754 @end ifset
9755 @end table
9756
9757 @noindent
9758 Source and library search path switches:
9759
9760 @table @option
9761 @c !sort!
9762 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9763 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9764 When looking for source files also look in directory @var{dir}.
9765 The order in which source files search is undertaken is
9766 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9767
9768 @item ^-aL^/SKIP_MISSING=^@var{dir}
9769 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9770 Consider @var{dir} as being an externally provided Ada library.
9771 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9772 files have been located in directory @var{dir}. This allows you to have
9773 missing bodies for the units in @var{dir} and to ignore out of date bodies
9774 for the same units. You still need to specify
9775 the location of the specs for these units by using the switches
9776 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9777 or @option{^-I^/SEARCH=^@var{dir}}.
9778 Note: this switch is provided for compatibility with previous versions
9779 of @command{gnatmake}. The easier method of causing standard libraries
9780 to be excluded from consideration is to write-protect the corresponding
9781 ALI files.
9782
9783 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9784 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9785 When searching for library and object files, look in directory
9786 @var{dir}. The order in which library files are searched is described in
9787 @ref{Search Paths for gnatbind}.
9788
9789 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9790 @cindex Search paths, for @command{gnatmake}
9791 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9792 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9793 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9794
9795 @item ^-I^/SEARCH=^@var{dir}
9796 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9797 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9798 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9799
9800 @item ^-I-^/NOCURRENT_DIRECTORY^
9801 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9802 @cindex Source files, suppressing search
9803 Do not look for source files in the directory containing the source
9804 file named in the command line.
9805 Do not look for ALI or object files in the directory
9806 where @command{gnatmake} was invoked.
9807
9808 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9809 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9810 @cindex Linker libraries
9811 Add directory @var{dir} to the list of directories in which the linker
9812 will search for libraries. This is equivalent to
9813 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9814 @ifclear vms
9815 Furthermore, under Windows, the sources pointed to by the libraries path
9816 set in the registry are not searched for.
9817 @end ifclear
9818
9819 @item -nostdinc
9820 @cindex @option{-nostdinc} (@command{gnatmake})
9821 Do not look for source files in the system default directory.
9822
9823 @item -nostdlib
9824 @cindex @option{-nostdlib} (@command{gnatmake})
9825 Do not look for library files in the system default directory.
9826
9827 @item --RTS=@var{rts-path}
9828 @cindex @option{--RTS} (@command{gnatmake})
9829 Specifies the default location of the runtime library. GNAT looks for the
9830 runtime
9831 in the following directories, and stops as soon as a valid runtime is found
9832 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9833 @file{ada_object_path} present):
9834
9835 @itemize @bullet
9836 @item <current directory>/$rts_path
9837
9838 @item <default-search-dir>/$rts_path
9839
9840 @item <default-search-dir>/rts-$rts_path
9841 @end itemize
9842
9843 @noindent
9844 The selected path is handled like a normal RTS path.
9845
9846 @end table
9847
9848 @node Mode Switches for gnatmake
9849 @section Mode Switches for @command{gnatmake}
9850
9851 @noindent
9852 The mode switches (referred to as @code{mode_switches}) allow the
9853 inclusion of switches that are to be passed to the compiler itself, the
9854 binder or the linker. The effect of a mode switch is to cause all
9855 subsequent switches up to the end of the switch list, or up to the next
9856 mode switch, to be interpreted as switches to be passed on to the
9857 designated component of GNAT.
9858
9859 @table @option
9860 @c !sort!
9861 @item -cargs @var{switches}
9862 @cindex @option{-cargs} (@command{gnatmake})
9863 Compiler switches. Here @var{switches} is a list of switches
9864 that are valid switches for @command{gcc}. They will be passed on to
9865 all compile steps performed by @command{gnatmake}.
9866
9867 @item -bargs @var{switches}
9868 @cindex @option{-bargs} (@command{gnatmake})
9869 Binder switches. Here @var{switches} is a list of switches
9870 that are valid switches for @code{gnatbind}. They will be passed on to
9871 all bind steps performed by @command{gnatmake}.
9872
9873 @item -largs @var{switches}
9874 @cindex @option{-largs} (@command{gnatmake})
9875 Linker switches. Here @var{switches} is a list of switches
9876 that are valid switches for @command{gnatlink}. They will be passed on to
9877 all link steps performed by @command{gnatmake}.
9878
9879 @item -margs @var{switches}
9880 @cindex @option{-margs} (@command{gnatmake})
9881 Make switches. The switches are directly interpreted by @command{gnatmake},
9882 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9883 or @option{-largs}.
9884 @end table
9885
9886 @node Notes on the Command Line
9887 @section Notes on the Command Line
9888
9889 @noindent
9890 This section contains some additional useful notes on the operation
9891 of the @command{gnatmake} command.
9892
9893 @itemize @bullet
9894 @item
9895 @cindex Recompilation, by @command{gnatmake}
9896 If @command{gnatmake} finds no ALI files, it recompiles the main program
9897 and all other units required by the main program.
9898 This means that @command{gnatmake}
9899 can be used for the initial compile, as well as during subsequent steps of
9900 the development cycle.
9901
9902 @item
9903 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9904 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9905 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9906 warning.
9907
9908 @item
9909 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9910 is used to specify both source and
9911 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9912 instead if you just want to specify
9913 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9914 if you want to specify library paths
9915 only.
9916
9917 @item
9918 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9919 This may conveniently be used to exclude standard libraries from
9920 consideration and in particular it means that the use of the
9921 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9922 unless @option{^-a^/ALL_FILES^} is also specified.
9923
9924 @item
9925 @command{gnatmake} has been designed to make the use of Ada libraries
9926 particularly convenient. Assume you have an Ada library organized
9927 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9928 of your Ada compilation units,
9929 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9930 specs of these units, but no bodies. Then to compile a unit
9931 stored in @code{main.adb}, which uses this Ada library you would just type
9932
9933 @smallexample
9934 @ifclear vms
9935 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9936 @end ifclear
9937 @ifset vms
9938 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9939            /SKIP_MISSING=@i{[OBJ_DIR]} main
9940 @end ifset
9941 @end smallexample
9942
9943 @item
9944 Using @command{gnatmake} along with the
9945 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9946 switch provides a mechanism for avoiding unnecessary recompilations. Using
9947 this switch,
9948 you can update the comments/format of your
9949 source files without having to recompile everything. Note, however, that
9950 adding or deleting lines in a source files may render its debugging
9951 info obsolete. If the file in question is a spec, the impact is rather
9952 limited, as that debugging info will only be useful during the
9953 elaboration phase of your program. For bodies the impact can be more
9954 significant. In all events, your debugger will warn you if a source file
9955 is more recent than the corresponding object, and alert you to the fact
9956 that the debugging information may be out of date.
9957 @end itemize
9958
9959 @node How gnatmake Works
9960 @section How @command{gnatmake} Works
9961
9962 @noindent
9963 Generally @command{gnatmake} automatically performs all necessary
9964 recompilations and you don't need to worry about how it works. However,
9965 it may be useful to have some basic understanding of the @command{gnatmake}
9966 approach and in particular to understand how it uses the results of
9967 previous compilations without incorrectly depending on them.
9968
9969 First a definition: an object file is considered @dfn{up to date} if the
9970 corresponding ALI file exists and if all the source files listed in the
9971 dependency section of this ALI file have time stamps matching those in
9972 the ALI file. This means that neither the source file itself nor any
9973 files that it depends on have been modified, and hence there is no need
9974 to recompile this file.
9975
9976 @command{gnatmake} works by first checking if the specified main unit is up
9977 to date. If so, no compilations are required for the main unit. If not,
9978 @command{gnatmake} compiles the main program to build a new ALI file that
9979 reflects the latest sources. Then the ALI file of the main unit is
9980 examined to find all the source files on which the main program depends,
9981 and @command{gnatmake} recursively applies the above procedure on all these
9982 files.
9983
9984 This process ensures that @command{gnatmake} only trusts the dependencies
9985 in an existing ALI file if they are known to be correct. Otherwise it
9986 always recompiles to determine a new, guaranteed accurate set of
9987 dependencies. As a result the program is compiled ``upside down'' from what may
9988 be more familiar as the required order of compilation in some other Ada
9989 systems. In particular, clients are compiled before the units on which
9990 they depend. The ability of GNAT to compile in any order is critical in
9991 allowing an order of compilation to be chosen that guarantees that
9992 @command{gnatmake} will recompute a correct set of new dependencies if
9993 necessary.
9994
9995 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9996 imported by several of the executables, it will be recompiled at most once.
9997
9998 Note: when using non-standard naming conventions
9999 (@pxref{Using Other File Names}), changing through a configuration pragmas
10000 file the version of a source and invoking @command{gnatmake} to recompile may
10001 have no effect, if the previous version of the source is still accessible
10002 by @command{gnatmake}. It may be necessary to use the switch
10003 ^-f^/FORCE_COMPILE^.
10004
10005 @node Examples of gnatmake Usage
10006 @section Examples of @command{gnatmake} Usage
10007
10008 @table @code
10009 @item gnatmake hello.adb
10010 Compile all files necessary to bind and link the main program
10011 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10012 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10013
10014 @item gnatmake main1 main2 main3
10015 Compile all files necessary to bind and link the main programs
10016 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10017 (containing unit @code{Main2}) and @file{main3.adb}
10018 (containing unit @code{Main3}) and bind and link the resulting object files
10019 to generate three executable files @file{^main1^MAIN1.EXE^},
10020 @file{^main2^MAIN2.EXE^}
10021 and @file{^main3^MAIN3.EXE^}.
10022
10023 @ifclear vms
10024 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10025 @end ifclear
10026
10027 @ifset vms
10028 @item gnatmake Main_Unit /QUIET
10029 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10030 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10031 @end ifset
10032 Compile all files necessary to bind and link the main program unit
10033 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10034 be done with optimization level 2 and the order of elaboration will be
10035 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10036 displaying commands it is executing.
10037 @end table
10038
10039 @c *************************
10040 @node Improving Performance
10041 @chapter Improving Performance
10042 @cindex Improving performance
10043
10044 @noindent
10045 This chapter presents several topics related to program performance.
10046 It first describes some of the tradeoffs that need to be considered
10047 and some of the techniques for making your program run faster.
10048 It then documents the @command{gnatelim} tool and unused subprogram/data
10049 elimination feature, which can reduce the size of program executables.
10050
10051 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10052 driver (see @ref{The GNAT Driver and Project Files}).
10053
10054 @ifnottex
10055 @menu
10056 * Performance Considerations::
10057 * Text_IO Suggestions::
10058 * Reducing Size of Ada Executables with gnatelim::
10059 * Reducing Size of Executables with unused subprogram/data elimination::
10060 @end menu
10061 @end ifnottex
10062
10063 @c *****************************
10064 @node Performance Considerations
10065 @section Performance Considerations
10066
10067 @noindent
10068 The GNAT system provides a number of options that allow a trade-off
10069 between
10070
10071 @itemize @bullet
10072 @item
10073 performance of the generated code
10074
10075 @item
10076 speed of compilation
10077
10078 @item
10079 minimization of dependences and recompilation
10080
10081 @item
10082 the degree of run-time checking.
10083 @end itemize
10084
10085 @noindent
10086 The defaults (if no options are selected) aim at improving the speed
10087 of compilation and minimizing dependences, at the expense of performance
10088 of the generated code:
10089
10090 @itemize @bullet
10091 @item
10092 no optimization
10093
10094 @item
10095 no inlining of subprogram calls
10096
10097 @item
10098 all run-time checks enabled except overflow and elaboration checks
10099 @end itemize
10100
10101 @noindent
10102 These options are suitable for most program development purposes. This
10103 chapter describes how you can modify these choices, and also provides
10104 some guidelines on debugging optimized code.
10105
10106 @menu
10107 * Controlling Run-Time Checks::
10108 * Use of Restrictions::
10109 * Optimization Levels::
10110 * Debugging Optimized Code::
10111 * Inlining of Subprograms::
10112 * Other Optimization Switches::
10113 * Optimization and Strict Aliasing::
10114
10115 @ifset vms
10116 * Coverage Analysis::
10117 @end ifset
10118 @end menu
10119
10120 @node Controlling Run-Time Checks
10121 @subsection Controlling Run-Time Checks
10122
10123 @noindent
10124 By default, GNAT generates all run-time checks, except integer overflow
10125 checks, stack overflow checks, and checks for access before elaboration on
10126 subprogram calls. The latter are not required in default mode, because all
10127 necessary checking is done at compile time.
10128 @cindex @option{-gnatp} (@command{gcc})
10129 @cindex @option{-gnato} (@command{gcc})
10130 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10131 be modified. @xref{Run-Time Checks}.
10132
10133 Our experience is that the default is suitable for most development
10134 purposes.
10135
10136 We treat integer overflow specially because these
10137 are quite expensive and in our experience are not as important as other
10138 run-time checks in the development process. Note that division by zero
10139 is not considered an overflow check, and divide by zero checks are
10140 generated where required by default.
10141
10142 Elaboration checks are off by default, and also not needed by default, since
10143 GNAT uses a static elaboration analysis approach that avoids the need for
10144 run-time checking. This manual contains a full chapter discussing the issue
10145 of elaboration checks, and if the default is not satisfactory for your use,
10146 you should read this chapter.
10147
10148 For validity checks, the minimal checks required by the Ada Reference
10149 Manual (for case statements and assignments to array elements) are on
10150 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10151 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10152 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10153 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10154 are also suppressed entirely if @option{-gnatp} is used.
10155
10156 @cindex Overflow checks
10157 @cindex Checks, overflow
10158 @findex Suppress
10159 @findex Unsuppress
10160 @cindex pragma Suppress
10161 @cindex pragma Unsuppress
10162 Note that the setting of the switches controls the default setting of
10163 the checks. They may be modified using either @code{pragma Suppress} (to
10164 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10165 checks) in the program source.
10166
10167 @node Use of Restrictions
10168 @subsection Use of Restrictions
10169
10170 @noindent
10171 The use of pragma Restrictions allows you to control which features are
10172 permitted in your program. Apart from the obvious point that if you avoid
10173 relatively expensive features like finalization (enforceable by the use
10174 of pragma Restrictions (No_Finalization), the use of this pragma does not
10175 affect the generated code in most cases.
10176
10177 One notable exception to this rule is that the possibility of task abort
10178 results in some distributed overhead, particularly if finalization or
10179 exception handlers are used. The reason is that certain sections of code
10180 have to be marked as non-abortable.
10181
10182 If you use neither the @code{abort} statement, nor asynchronous transfer
10183 of control (@code{select @dots{} then abort}), then this distributed overhead
10184 is removed, which may have a general positive effect in improving
10185 overall performance.  Especially code involving frequent use of tasking
10186 constructs and controlled types will show much improved performance.
10187 The relevant restrictions pragmas are
10188
10189 @smallexample @c ada
10190    pragma Restrictions (No_Abort_Statements);
10191    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10192 @end smallexample
10193
10194 @noindent
10195 It is recommended that these restriction pragmas be used if possible. Note
10196 that this also means that you can write code without worrying about the
10197 possibility of an immediate abort at any point.
10198
10199 @node Optimization Levels
10200 @subsection Optimization Levels
10201 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10202
10203 @noindent
10204 Without any optimization ^option,^qualifier,^
10205 the compiler's goal is to reduce the cost of
10206 compilation and to make debugging produce the expected results.
10207 Statements are independent: if you stop the program with a breakpoint between
10208 statements, you can then assign a new value to any variable or change
10209 the program counter to any other statement in the subprogram and get exactly
10210 the results you would expect from the source code.
10211
10212 Turning on optimization makes the compiler attempt to improve the
10213 performance and/or code size at the expense of compilation time and
10214 possibly the ability to debug the program.
10215
10216 If you use multiple
10217 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10218 the last such option is the one that is effective.
10219
10220 @noindent
10221 The default is optimization off. This results in the fastest compile
10222 times, but GNAT makes absolutely no attempt to optimize, and the
10223 generated programs are considerably larger and slower than when
10224 optimization is enabled. You can use the
10225 @ifclear vms
10226 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10227 @option{-O2}, @option{-O3}, and @option{-Os})
10228 @end ifclear
10229 @ifset vms
10230 @code{OPTIMIZE} qualifier
10231 @end ifset
10232 to @command{gcc} to control the optimization level:
10233
10234 @table @option
10235 @item ^-O0^/OPTIMIZE=NONE^
10236 No optimization (the default);
10237 generates unoptimized code but has
10238 the fastest compilation time.
10239
10240 Note that many other compilers do fairly extensive optimization
10241 even if ``no optimization'' is specified. With gcc, it is
10242 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10243 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10244 really does mean no optimization at all. This difference between
10245 gcc and other compilers should be kept in mind when doing
10246 performance comparisons.
10247
10248 @item ^-O1^/OPTIMIZE=SOME^
10249 Moderate optimization;
10250 optimizes reasonably well but does not
10251 degrade compilation time significantly.
10252
10253 @item ^-O2^/OPTIMIZE=ALL^
10254 @ifset vms
10255 @itemx /OPTIMIZE=DEVELOPMENT
10256 @end ifset
10257 Full optimization;
10258 generates highly optimized code and has
10259 the slowest compilation time.
10260
10261 @item ^-O3^/OPTIMIZE=INLINING^
10262 Full optimization as in @option{-O2};
10263 also uses more aggressive automatic inlining of subprograms within a unit
10264 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10265
10266 @item ^-Os^/OPTIMIZE=SPACE^
10267 Optimize space usage (code and data) of resulting program.
10268 @end table
10269
10270 @noindent
10271 Higher optimization levels perform more global transformations on the
10272 program and apply more expensive analysis algorithms in order to generate
10273 faster and more compact code. The price in compilation time, and the
10274 resulting improvement in execution time,
10275 both depend on the particular application and the hardware environment.
10276 You should experiment to find the best level for your application.
10277
10278 Since the precise set of optimizations done at each level will vary from
10279 release to release (and sometime from target to target), it is best to think
10280 of the optimization settings in general terms.
10281 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10282 the GNU Compiler Collection (GCC)}, for details about
10283 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10284 individually enable or disable specific optimizations.
10285
10286 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10287 been tested extensively at all optimization levels. There are some bugs
10288 which appear only with optimization turned on, but there have also been
10289 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10290 level of optimization does not improve the reliability of the code
10291 generator, which in practice is highly reliable at all optimization
10292 levels.
10293
10294 Note regarding the use of @option{-O3}: The use of this optimization level
10295 is generally discouraged with GNAT, since it often results in larger
10296 executables which may run more slowly. See further discussion of this point
10297 in @ref{Inlining of Subprograms}.
10298
10299 @node Debugging Optimized Code
10300 @subsection Debugging Optimized Code
10301 @cindex Debugging optimized code
10302 @cindex Optimization and debugging
10303
10304 @noindent
10305 Although it is possible to do a reasonable amount of debugging at
10306 @ifclear vms
10307 nonzero optimization levels,
10308 the higher the level the more likely that
10309 @end ifclear
10310 @ifset vms
10311 @option{/OPTIMIZE} settings other than @code{NONE},
10312 such settings will make it more likely that
10313 @end ifset
10314 source-level constructs will have been eliminated by optimization.
10315 For example, if a loop is strength-reduced, the loop
10316 control variable may be completely eliminated and thus cannot be
10317 displayed in the debugger.
10318 This can only happen at @option{-O2} or @option{-O3}.
10319 Explicit temporary variables that you code might be eliminated at
10320 ^level^setting^ @option{-O1} or higher.
10321
10322 The use of the @option{^-g^/DEBUG^} switch,
10323 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10324 which is needed for source-level debugging,
10325 affects the size of the program executable on disk,
10326 and indeed the debugging information can be quite large.
10327 However, it has no effect on the generated code (and thus does not
10328 degrade performance)
10329
10330 Since the compiler generates debugging tables for a compilation unit before
10331 it performs optimizations, the optimizing transformations may invalidate some
10332 of the debugging data.  You therefore need to anticipate certain
10333 anomalous situations that may arise while debugging optimized code.
10334 These are the most common cases:
10335
10336 @enumerate
10337 @item
10338 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10339 commands show
10340 the PC bouncing back and forth in the code.  This may result from any of
10341 the following optimizations:
10342
10343 @itemize @bullet
10344 @item
10345 @i{Common subexpression elimination:} using a single instance of code for a
10346 quantity that the source computes several times.  As a result you
10347 may not be able to stop on what looks like a statement.
10348
10349 @item
10350 @i{Invariant code motion:} moving an expression that does not change within a
10351 loop, to the beginning of the loop.
10352
10353 @item
10354 @i{Instruction scheduling:} moving instructions so as to
10355 overlap loads and stores (typically) with other code, or in
10356 general to move computations of values closer to their uses. Often
10357 this causes you to pass an assignment statement without the assignment
10358 happening and then later bounce back to the statement when the
10359 value is actually needed.  Placing a breakpoint on a line of code
10360 and then stepping over it may, therefore, not always cause all the
10361 expected side-effects.
10362 @end itemize
10363
10364 @item
10365 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10366 two identical pieces of code are merged and the program counter suddenly
10367 jumps to a statement that is not supposed to be executed, simply because
10368 it (and the code following) translates to the same thing as the code
10369 that @emph{was} supposed to be executed.  This effect is typically seen in
10370 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10371 a @code{break} in a C @code{^switch^switch^} statement.
10372
10373 @item
10374 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10375 There are various reasons for this effect:
10376
10377 @itemize @bullet
10378 @item
10379 In a subprogram prologue, a parameter may not yet have been moved to its
10380 ``home''.
10381
10382 @item
10383 A variable may be dead, and its register re-used.  This is
10384 probably the most common cause.
10385
10386 @item
10387 As mentioned above, the assignment of a value to a variable may
10388 have been moved.
10389
10390 @item
10391 A variable may be eliminated entirely by value propagation or
10392 other means.  In this case, GCC may incorrectly generate debugging
10393 information for the variable
10394 @end itemize
10395
10396 @noindent
10397 In general, when an unexpected value appears for a local variable or parameter
10398 you should first ascertain if that value was actually computed by
10399 your program, as opposed to being incorrectly reported by the debugger.
10400 Record fields or
10401 array elements in an object designated by an access value
10402 are generally less of a problem, once you have ascertained that the access
10403 value is sensible.
10404 Typically, this means checking variables in the preceding code and in the
10405 calling subprogram to verify that the value observed is explainable from other
10406 values (one must apply the procedure recursively to those
10407 other values); or re-running the code and stopping a little earlier
10408 (perhaps before the call) and stepping to better see how the variable obtained
10409 the value in question; or continuing to step @emph{from} the point of the
10410 strange value to see if code motion had simply moved the variable's
10411 assignments later.
10412 @end enumerate
10413
10414 @noindent
10415 In light of such anomalies, a recommended technique is to use @option{-O0}
10416 early in the software development cycle, when extensive debugging capabilities
10417 are most needed, and then move to @option{-O1} and later @option{-O2} as
10418 the debugger becomes less critical.
10419 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10420 a release management issue.
10421 @ifclear vms
10422 Note that if you use @option{-g} you can then use the @command{strip} program
10423 on the resulting executable,
10424 which removes both debugging information and global symbols.
10425 @end ifclear
10426
10427 @node Inlining of Subprograms
10428 @subsection Inlining of Subprograms
10429
10430 @noindent
10431 A call to a subprogram in the current unit is inlined if all the
10432 following conditions are met:
10433
10434 @itemize @bullet
10435 @item
10436 The optimization level is at least @option{-O1}.
10437
10438 @item
10439 The called subprogram is suitable for inlining: It must be small enough
10440 and not contain something that @command{gcc} cannot support in inlined
10441 subprograms.
10442
10443 @item
10444 @cindex pragma Inline
10445 @findex Inline
10446 Any one of the following applies: @code{pragma Inline} is applied to the
10447 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10448 subprogram is local to the unit and called once from within it; the
10449 subprogram is small and optimization level @option{-O2} is specified;
10450 optimization level @option{-O3}) is specified.
10451 @end itemize
10452
10453 @noindent
10454 Calls to subprograms in @code{with}'ed units are normally not inlined.
10455 To achieve actual inlining (that is, replacement of the call by the code
10456 in the body of the subprogram), the following conditions must all be true.
10457
10458 @itemize @bullet
10459 @item
10460 The optimization level is at least @option{-O1}.
10461
10462 @item
10463 The called subprogram is suitable for inlining: It must be small enough
10464 and not contain something that @command{gcc} cannot support in inlined
10465 subprograms.
10466
10467 @item
10468 The call appears in a body (not in a package spec).
10469
10470 @item
10471 There is a @code{pragma Inline} for the subprogram.
10472
10473 @item
10474 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10475 @end itemize
10476
10477 Even if all these conditions are met, it may not be possible for
10478 the compiler to inline the call, due to the length of the body,
10479 or features in the body that make it impossible for the compiler
10480 to do the inlining.
10481
10482 Note that specifying the @option{-gnatn} switch causes additional
10483 compilation dependencies. Consider the following:
10484
10485 @smallexample @c ada
10486 @cartouche
10487 package R is
10488    procedure Q;
10489    pragma Inline (Q);
10490 end R;
10491 package body R is
10492    @dots{}
10493 end R;
10494
10495 with R;
10496 procedure Main is
10497 begin
10498    @dots{}
10499    R.Q;
10500 end Main;
10501 @end cartouche
10502 @end smallexample
10503
10504 @noindent
10505 With the default behavior (no @option{-gnatn} switch specified), the
10506 compilation of the @code{Main} procedure depends only on its own source,
10507 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10508 means that editing the body of @code{R} does not require recompiling
10509 @code{Main}.
10510
10511 On the other hand, the call @code{R.Q} is not inlined under these
10512 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10513 is compiled, the call will be inlined if the body of @code{Q} is small
10514 enough, but now @code{Main} depends on the body of @code{R} in
10515 @file{r.adb} as well as on the spec. This means that if this body is edited,
10516 the main program must be recompiled. Note that this extra dependency
10517 occurs whether or not the call is in fact inlined by @command{gcc}.
10518
10519 The use of front end inlining with @option{-gnatN} generates similar
10520 additional dependencies.
10521
10522 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10523 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10524 can be used to prevent
10525 all inlining. This switch overrides all other conditions and ensures
10526 that no inlining occurs. The extra dependences resulting from
10527 @option{-gnatn} will still be active, even if
10528 this switch is used to suppress the resulting inlining actions.
10529
10530 @cindex @option{-fno-inline-functions} (@command{gcc})
10531 Note: The @option{-fno-inline-functions} switch can be used to prevent
10532 automatic inlining of subprograms if @option{-O3} is used.
10533
10534 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10535 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10536 automatic inlining of small subprograms if @option{-O2} is used.
10537
10538 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10539 Note: The @option{-fno-inline-functions-called-once} switch
10540 can be used to prevent inlining of subprograms local to the unit
10541 and called once from within it if @option{-O1} is used.
10542
10543 Note regarding the use of @option{-O3}: There is no difference in inlining
10544 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10545 pragma @code{Inline} assuming the use of @option{-gnatn}
10546 or @option{-gnatN} (the switches that activate inlining). If you have used
10547 pragma @code{Inline} in appropriate cases, then it is usually much better
10548 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10549 in this case only has the effect of inlining subprograms you did not
10550 think should be inlined. We often find that the use of @option{-O3} slows
10551 down code by performing excessive inlining, leading to increased instruction
10552 cache pressure from the increased code size. So the bottom line here is
10553 that you should not automatically assume that @option{-O3} is better than
10554 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10555 it actually improves performance.
10556
10557 @node Other Optimization Switches
10558 @subsection Other Optimization Switches
10559 @cindex Optimization Switches
10560
10561 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10562 @command{gcc} optimization switches are potentially usable. These switches
10563 have not been extensively tested with GNAT but can generally be expected
10564 to work. Examples of switches in this category are
10565 @option{-funroll-loops} and
10566 the various target-specific @option{-m} options (in particular, it has been
10567 observed that @option{-march=pentium4} can significantly improve performance
10568 on appropriate machines). For full details of these switches, see
10569 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10570 the GNU Compiler Collection (GCC)}.
10571
10572 @node Optimization and Strict Aliasing
10573 @subsection Optimization and Strict Aliasing
10574 @cindex Aliasing
10575 @cindex Strict Aliasing
10576 @cindex No_Strict_Aliasing
10577
10578 @noindent
10579 The strong typing capabilities of Ada allow an optimizer to generate
10580 efficient code in situations where other languages would be forced to
10581 make worst case assumptions preventing such optimizations. Consider
10582 the following example:
10583
10584 @smallexample @c ada
10585 @cartouche
10586 procedure R is
10587    type Int1 is new Integer;
10588    type Int2 is new Integer;
10589    type Int1A is access Int1;
10590    type Int2A is access Int2;
10591    Int1V : Int1A;
10592    Int2V : Int2A;
10593    @dots{}
10594
10595 begin
10596    @dots{}
10597    for J in Data'Range loop
10598       if Data (J) = Int1V.all then
10599          Int2V.all := Int2V.all + 1;
10600       end if;
10601    end loop;
10602    @dots{}
10603 end R;
10604 @end cartouche
10605 @end smallexample
10606
10607 @noindent
10608 In this example, since the variable @code{Int1V} can only access objects
10609 of type @code{Int1}, and @code{Int2V} can only access objects of type
10610 @code{Int2}, there is no possibility that the assignment to
10611 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10612 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10613 for all iterations of the loop and avoid the extra memory reference
10614 required to dereference it each time through the loop.
10615
10616 This kind of optimization, called strict aliasing analysis, is
10617 triggered by specifying an optimization level of @option{-O2} or
10618 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10619 when access values are involved.
10620
10621 However, although this optimization is always correct in terms of
10622 the formal semantics of the Ada Reference Manual, difficulties can
10623 arise if features like @code{Unchecked_Conversion} are used to break
10624 the typing system. Consider the following complete program example:
10625
10626 @smallexample @c ada
10627 @cartouche
10628 package p1 is
10629    type int1 is new integer;
10630    type int2 is new integer;
10631    type a1 is access int1;
10632    type a2 is access int2;
10633 end p1;
10634
10635 with p1; use p1;
10636 package p2 is
10637    function to_a2 (Input : a1) return a2;
10638 end p2;
10639
10640 with Unchecked_Conversion;
10641 package body p2 is
10642    function to_a2 (Input : a1) return a2 is
10643       function to_a2u is
10644         new Unchecked_Conversion (a1, a2);
10645    begin
10646       return to_a2u (Input);
10647    end to_a2;
10648 end p2;
10649
10650 with p2; use p2;
10651 with p1; use p1;
10652 with Text_IO; use Text_IO;
10653 procedure m is
10654    v1 : a1 := new int1;
10655    v2 : a2 := to_a2 (v1);
10656 begin
10657    v1.all := 1;
10658    v2.all := 0;
10659    put_line (int1'image (v1.all));
10660 end;
10661 @end cartouche
10662 @end smallexample
10663
10664 @noindent
10665 This program prints out 0 in @option{-O0} or @option{-O1}
10666 mode, but it prints out 1 in @option{-O2} mode. That's
10667 because in strict aliasing mode, the compiler can and
10668 does assume that the assignment to @code{v2.all} could not
10669 affect the value of @code{v1.all}, since different types
10670 are involved.
10671
10672 This behavior is not a case of non-conformance with the standard, since
10673 the Ada RM specifies that an unchecked conversion where the resulting
10674 bit pattern is not a correct value of the target type can result in an
10675 abnormal value and attempting to reference an abnormal value makes the
10676 execution of a program erroneous.  That's the case here since the result
10677 does not point to an object of type @code{int2}.  This means that the
10678 effect is entirely unpredictable.
10679
10680 However, although that explanation may satisfy a language
10681 lawyer, in practice an applications programmer expects an
10682 unchecked conversion involving pointers to create true
10683 aliases and the behavior of printing 1 seems plain wrong.
10684 In this case, the strict aliasing optimization is unwelcome.
10685
10686 Indeed the compiler recognizes this possibility, and the
10687 unchecked conversion generates a warning:
10688
10689 @smallexample
10690 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10691 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10692 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10693 @end smallexample
10694
10695 @noindent
10696 Unfortunately the problem is recognized when compiling the body of
10697 package @code{p2}, but the actual "bad" code is generated while
10698 compiling the body of @code{m} and this latter compilation does not see
10699 the suspicious @code{Unchecked_Conversion}.
10700
10701 As implied by the warning message, there are approaches you can use to
10702 avoid the unwanted strict aliasing optimization in a case like this.
10703
10704 One possibility is to simply avoid the use of @option{-O2}, but
10705 that is a bit drastic, since it throws away a number of useful
10706 optimizations that do not involve strict aliasing assumptions.
10707
10708 A less drastic approach is to compile the program using the
10709 option @option{-fno-strict-aliasing}. Actually it is only the
10710 unit containing the dereferencing of the suspicious pointer
10711 that needs to be compiled. So in this case, if we compile
10712 unit @code{m} with this switch, then we get the expected
10713 value of zero printed. Analyzing which units might need
10714 the switch can be painful, so a more reasonable approach
10715 is to compile the entire program with options @option{-O2}
10716 and @option{-fno-strict-aliasing}. If the performance is
10717 satisfactory with this combination of options, then the
10718 advantage is that the entire issue of possible "wrong"
10719 optimization due to strict aliasing is avoided.
10720
10721 To avoid the use of compiler switches, the configuration
10722 pragma @code{No_Strict_Aliasing} with no parameters may be
10723 used to specify that for all access types, the strict
10724 aliasing optimization should be suppressed.
10725
10726 However, these approaches are still overkill, in that they causes
10727 all manipulations of all access values to be deoptimized. A more
10728 refined approach is to concentrate attention on the specific
10729 access type identified as problematic.
10730
10731 First, if a careful analysis of uses of the pointer shows
10732 that there are no possible problematic references, then
10733 the warning can be suppressed by bracketing the
10734 instantiation of @code{Unchecked_Conversion} to turn
10735 the warning off:
10736
10737 @smallexample @c ada
10738    pragma Warnings (Off);
10739    function to_a2u is
10740      new Unchecked_Conversion (a1, a2);
10741    pragma Warnings (On);
10742 @end smallexample
10743
10744 @noindent
10745 Of course that approach is not appropriate for this particular
10746 example, since indeed there is a problematic reference. In this
10747 case we can take one of two other approaches.
10748
10749 The first possibility is to move the instantiation of unchecked
10750 conversion to the unit in which the type is declared. In
10751 this example, we would move the instantiation of
10752 @code{Unchecked_Conversion} from the body of package
10753 @code{p2} to the spec of package @code{p1}. Now the
10754 warning disappears. That's because any use of the
10755 access type knows there is a suspicious unchecked
10756 conversion, and the strict aliasing optimization
10757 is automatically suppressed for the type.
10758
10759 If it is not practical to move the unchecked conversion to the same unit
10760 in which the destination access type is declared (perhaps because the
10761 source type is not visible in that unit), you may use pragma
10762 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10763 same declarative sequence as the declaration of the access type:
10764
10765 @smallexample @c ada
10766    type a2 is access int2;
10767    pragma No_Strict_Aliasing (a2);
10768 @end smallexample
10769
10770 @noindent
10771 Here again, the compiler now knows that the strict aliasing optimization
10772 should be suppressed for any reference to type @code{a2} and the
10773 expected behavior is obtained.
10774
10775 Finally, note that although the compiler can generate warnings for
10776 simple cases of unchecked conversions, there are tricker and more
10777 indirect ways of creating type incorrect aliases which the compiler
10778 cannot detect. Examples are the use of address overlays and unchecked
10779 conversions involving composite types containing access types as
10780 components. In such cases, no warnings are generated, but there can
10781 still be aliasing problems. One safe coding practice is to forbid the
10782 use of address clauses for type overlaying, and to allow unchecked
10783 conversion only for primitive types. This is not really a significant
10784 restriction since any possible desired effect can be achieved by
10785 unchecked conversion of access values.
10786
10787 The aliasing analysis done in strict aliasing mode can certainly
10788 have significant benefits. We have seen cases of large scale
10789 application code where the time is increased by up to 5% by turning
10790 this optimization off. If you have code that includes significant
10791 usage of unchecked conversion, you might want to just stick with
10792 @option{-O1} and avoid the entire issue. If you get adequate
10793 performance at this level of optimization level, that's probably
10794 the safest approach. If tests show that you really need higher
10795 levels of optimization, then you can experiment with @option{-O2}
10796 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10797 has on size and speed of the code. If you really need to use
10798 @option{-O2} with strict aliasing in effect, then you should
10799 review any uses of unchecked conversion of access types,
10800 particularly if you are getting the warnings described above.
10801
10802 @ifset vms
10803 @node Coverage Analysis
10804 @subsection Coverage Analysis
10805
10806 @noindent
10807 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10808 the user to determine the distribution of execution time across a program,
10809 @pxref{Profiling} for details of usage.
10810 @end ifset
10811
10812
10813 @node Text_IO Suggestions
10814 @section @code{Text_IO} Suggestions
10815 @cindex @code{Text_IO} and performance
10816
10817 @noindent
10818 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10819 the requirement of maintaining page and line counts. If performance
10820 is critical, a recommendation is to use @code{Stream_IO} instead of
10821 @code{Text_IO} for volume output, since this package has less overhead.
10822
10823 If @code{Text_IO} must be used, note that by default output to the standard
10824 output and standard error files is unbuffered (this provides better
10825 behavior when output statements are used for debugging, or if the
10826 progress of a program is observed by tracking the output, e.g. by
10827 using the Unix @command{tail -f} command to watch redirected output.
10828
10829 If you are generating large volumes of output with @code{Text_IO} and
10830 performance is an important factor, use a designated file instead
10831 of the standard output file, or change the standard output file to
10832 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10833
10834
10835
10836 @node Reducing Size of Ada Executables with gnatelim
10837 @section Reducing Size of Ada Executables with @code{gnatelim}
10838 @findex gnatelim
10839
10840 @noindent
10841 This section describes @command{gnatelim}, a tool which detects unused
10842 subprograms and helps the compiler to create a smaller executable for your
10843 program.
10844
10845 @menu
10846 * About gnatelim::
10847 * Running gnatelim::
10848 * Processing Precompiled Libraries::
10849 * Correcting the List of Eliminate Pragmas::
10850 * Making Your Executables Smaller::
10851 * Summary of the gnatelim Usage Cycle::
10852 @end menu
10853
10854 @node About gnatelim
10855 @subsection About @code{gnatelim}
10856
10857 @noindent
10858 When a program shares a set of Ada
10859 packages with other programs, it may happen that this program uses
10860 only a fraction of the subprograms defined in these packages. The code
10861 created for these unused subprograms increases the size of the executable.
10862
10863 @code{gnatelim} tracks unused subprograms in an Ada program and
10864 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10865 subprograms that are declared but never called. By placing the list of
10866 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10867 recompiling your program, you may decrease the size of its executable,
10868 because the compiler will not generate the code for 'eliminated' subprograms.
10869 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10870 information about this pragma.
10871
10872 @code{gnatelim} needs as its input data the name of the main subprogram.
10873
10874 If a set of source files is specified as @code{gnatelim} arguments, it
10875 treats these files as a complete set of sources making up a program to
10876 analyse, and analyses only these sources.
10877
10878 After a full successful build of the main subprogram @code{gnatelim} can be
10879 called without  specifying sources to analyse, in this case it computes
10880 the source closure of the main unit from the @file{ALI} files.
10881
10882 The following command will create the set of @file{ALI} files needed for
10883 @code{gnatelim}:
10884
10885 @smallexample
10886 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10887 @end smallexample
10888
10889 Note that @code{gnatelim} does not need object files.
10890
10891 @node Running gnatelim
10892 @subsection Running @code{gnatelim}
10893
10894 @noindent
10895 @code{gnatelim} has the following command-line interface:
10896
10897 @smallexample
10898 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10899 @end smallexample
10900
10901 @noindent
10902 @var{main_unit_name} should be a name of a source file that contains the main
10903 subprogram of a program (partition).
10904
10905 Each @var{filename} is the name (including the extension) of a source
10906 file to process. ``Wildcards'' are allowed, and
10907 the file name may contain path information.
10908
10909 @samp{@var{gcc_switches}} is a list of switches for
10910 @command{gcc}. They will be passed on to all compiler invocations made by
10911 @command{gnatelim} to generate the ASIS trees. Here you can provide
10912 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10913 use the @option{-gnatec} switch to set the configuration file,
10914 use the @option{-gnat05} switch if sources should be compiled in
10915 Ada 2005 mode etc.
10916
10917 @code{gnatelim} has the following switches:
10918
10919 @table @option
10920 @c !sort!
10921 @item ^-files^/FILES^=@var{filename}
10922 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10923 Take the argument source files from the specified file. This file should be an
10924 ordinary text file containing file names separated by spaces or
10925 line breaks. You can use this switch more than once in the same call to
10926 @command{gnatelim}. You also can combine this switch with
10927 an explicit list of files.
10928
10929 @item ^-log^/LOG^
10930 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10931 Duplicate all the output sent to @file{stderr} into a log file. The log file
10932 is named @file{gnatelim.log} and is located in the current directory.
10933
10934 @item ^-log^/LOGFILE^=@var{filename}
10935 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10936 Duplicate all the output sent to @file{stderr} into a specified log file.
10937
10938 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10939 @item ^--no-elim-dispatch^/NO_DISPATCH^
10940 Do not generate pragmas for dispatching operations.
10941
10942 @item ^--ignore^/IGNORE^=@var{filename}
10943 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10944 Do not generate pragmas for subprograms declared in the sources
10945 listed in a specified file
10946
10947 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10948 @item ^-o^/OUTPUT^=@var{report_file}
10949 Put @command{gnatelim} output into a specified file. If this file already exists,
10950 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10951 into @file{stderr}
10952
10953 @item ^-q^/QUIET^
10954 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10955 Quiet mode: by default @code{gnatelim} outputs to the standard error
10956 stream the number of program units left to be processed. This option turns
10957 this trace off.
10958
10959 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10960 @item ^-t^/TIME^
10961 Print out execution time.
10962
10963 @item ^-v^/VERBOSE^
10964 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10965 Verbose mode: @code{gnatelim} version information is printed as Ada
10966 comments to the standard output stream. Also, in addition to the number of
10967 program units left @code{gnatelim} will output the name of the current unit
10968 being processed.
10969
10970 @item ^-wq^/WARNINGS=QUIET^
10971 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10972 Quiet warning mode - some warnings are suppressed. In particular warnings that
10973 indicate that the analysed set of sources is incomplete to make up a
10974 partition and that some subprogram bodies are missing are not generated.
10975 @end table
10976
10977 @node Processing Precompiled Libraries
10978 @subsection Processing Precompiled Libraries
10979
10980 @noindent
10981 If some program uses a precompiled Ada library, it can be processed by
10982 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10983 Eliminate pragma for a subprogram if the body of this subprogram has not
10984 been analysed, this is a typical case for subprograms from precompiled
10985 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10986 warnings about missing source files and non-analyzed subprogram bodies
10987 that can be generated when processing precompiled Ada libraries.
10988
10989 @node Correcting the List of Eliminate Pragmas
10990 @subsection Correcting the List of Eliminate Pragmas
10991
10992 @noindent
10993 In some rare cases @code{gnatelim} may try to eliminate
10994 subprograms that are actually called in the program. In this case, the
10995 compiler will generate an error message of the form:
10996
10997 @smallexample
10998 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10999 @end smallexample
11000
11001 @noindent
11002 You will need to manually remove the wrong @code{Eliminate} pragmas from
11003 the configuration file indicated in the error message. You should recompile
11004 your program from scratch after that, because you need a consistent
11005 configuration file(s) during the entire compilation.
11006
11007 @node Making Your Executables Smaller
11008 @subsection Making Your Executables Smaller
11009
11010 @noindent
11011 In order to get a smaller executable for your program you now have to
11012 recompile the program completely with the configuration file containing
11013 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11014 @file{gnat.adc} file located in your current directory, just do:
11015
11016 @smallexample
11017 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11018 @end smallexample
11019
11020 @noindent
11021 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11022 recompile everything
11023 with the set of pragmas @code{Eliminate} that you have obtained with
11024 @command{gnatelim}).
11025
11026 Be aware that the set of @code{Eliminate} pragmas is specific to each
11027 program. It is not recommended to merge sets of @code{Eliminate}
11028 pragmas created for different programs in one configuration file.
11029
11030 @node Summary of the gnatelim Usage Cycle
11031 @subsection Summary of the @code{gnatelim} Usage Cycle
11032
11033 @noindent
11034 Here is a quick summary of the steps to be taken in order to reduce
11035 the size of your executables with @code{gnatelim}. You may use
11036 other GNAT options to control the optimization level,
11037 to produce the debugging information, to set search path, etc.
11038
11039 @enumerate
11040 @item
11041 Create a complete set of @file{ALI} files (if the program has not been
11042 built already)
11043
11044 @smallexample
11045 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11046 @end smallexample
11047
11048 @item
11049 Generate a list of @code{Eliminate} pragmas in default configuration file
11050 @file{gnat.adc} in the current directory
11051 @smallexample
11052 @ifset vms
11053 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11054 @end ifset
11055 @ifclear vms
11056 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11057 @end ifclear
11058 @end smallexample
11059
11060 @item
11061 Recompile the application
11062
11063 @smallexample
11064 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11065 @end smallexample
11066
11067 @end enumerate
11068
11069 @node Reducing Size of Executables with unused subprogram/data elimination
11070 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11071 @findex unused subprogram/data elimination
11072
11073 @noindent
11074 This section describes how you can eliminate unused subprograms and data from
11075 your executable just by setting options at compilation time.
11076
11077 @menu
11078 * About unused subprogram/data elimination::
11079 * Compilation options::
11080 * Example of unused subprogram/data elimination::
11081 @end menu
11082
11083 @node About unused subprogram/data elimination
11084 @subsection About unused subprogram/data elimination
11085
11086 @noindent
11087 By default, an executable contains all code and data of its composing objects
11088 (directly linked or coming from statically linked libraries), even data or code
11089 never used by this executable.
11090
11091 This feature will allow you to eliminate such unused code from your
11092 executable, making it smaller (in disk and in memory).
11093
11094 This functionality is available on all Linux platforms except for the IA-64
11095 architecture and on all cross platforms using the ELF binary file format.
11096 In both cases GNU binutils version 2.16 or later are required to enable it.
11097
11098 @node Compilation options
11099 @subsection Compilation options
11100
11101 @noindent
11102 The operation of eliminating the unused code and data from the final executable
11103 is directly performed by the linker.
11104
11105 In order to do this, it has to work with objects compiled with the
11106 following options:
11107 @option{-ffunction-sections} @option{-fdata-sections}.
11108 @cindex @option{-ffunction-sections} (@command{gcc})
11109 @cindex @option{-fdata-sections} (@command{gcc})
11110 These options are usable with C and Ada files.
11111 They will place respectively each
11112 function or data in a separate section in the resulting object file.
11113
11114 Once the objects and static libraries are created with these options, the
11115 linker can perform the dead code elimination. You can do this by setting
11116 the @option{-Wl,--gc-sections} option to gcc command or in the
11117 @option{-largs} section of @command{gnatmake}. This will perform a
11118 garbage collection of code and data never referenced.
11119
11120 If the linker performs a partial link (@option{-r} ld linker option), then you
11121 will need to provide one or several entry point using the
11122 @option{-e} / @option{--entry} ld option.
11123
11124 Note that objects compiled without the @option{-ffunction-sections} and
11125 @option{-fdata-sections} options can still be linked with the executable.
11126 However, no dead code elimination will be performed on those objects (they will
11127 be linked as is).
11128
11129 The GNAT static library is now compiled with -ffunction-sections and
11130 -fdata-sections on some platforms. This allows you to eliminate the unused code
11131 and data of the GNAT library from your executable.
11132
11133 @node Example of unused subprogram/data elimination
11134 @subsection Example of unused subprogram/data elimination
11135
11136 @noindent
11137 Here is a simple example:
11138
11139 @smallexample @c ada
11140 with Aux;
11141
11142 procedure Test is
11143 begin
11144    Aux.Used (10);
11145 end Test;
11146
11147 package Aux is
11148    Used_Data   : Integer;
11149    Unused_Data : Integer;
11150
11151    procedure Used   (Data : Integer);
11152    procedure Unused (Data : Integer);
11153 end Aux;
11154
11155 package body Aux is
11156    procedure Used (Data : Integer) is
11157    begin
11158       Used_Data := Data;
11159    end Used;
11160
11161    procedure Unused (Data : Integer) is
11162    begin
11163       Unused_Data := Data;
11164    end Unused;
11165 end Aux;
11166 @end smallexample
11167
11168 @noindent
11169 @code{Unused} and @code{Unused_Data} are never referenced in this code
11170 excerpt, and hence they may be safely removed from the final executable.
11171
11172 @smallexample
11173 $ gnatmake test
11174
11175 $ nm test | grep used
11176 020015f0 T aux__unused
11177 02005d88 B aux__unused_data
11178 020015cc T aux__used
11179 02005d84 B aux__used_data
11180
11181 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11182      -largs -Wl,--gc-sections
11183
11184 $ nm test | grep used
11185 02005350 T aux__used
11186 0201ffe0 B aux__used_data
11187 @end smallexample
11188
11189 @noindent
11190 It can be observed that the procedure @code{Unused} and the object
11191 @code{Unused_Data} are removed by the linker when using the
11192 appropriate options.
11193
11194 @c ********************************
11195 @node Renaming Files Using gnatchop
11196 @chapter Renaming Files Using @code{gnatchop}
11197 @findex gnatchop
11198
11199 @noindent
11200 This chapter discusses how to handle files with multiple units by using
11201 the @code{gnatchop} utility. This utility is also useful in renaming
11202 files to meet the standard GNAT default file naming conventions.
11203
11204 @menu
11205 * Handling Files with Multiple Units::
11206 * Operating gnatchop in Compilation Mode::
11207 * Command Line for gnatchop::
11208 * Switches for gnatchop::
11209 * Examples of gnatchop Usage::
11210 @end menu
11211
11212 @node Handling Files with Multiple Units
11213 @section Handling Files with Multiple Units
11214
11215 @noindent
11216 The basic compilation model of GNAT requires that a file submitted to the
11217 compiler have only one unit and there be a strict correspondence
11218 between the file name and the unit name.
11219
11220 The @code{gnatchop} utility allows both of these rules to be relaxed,
11221 allowing GNAT to process files which contain multiple compilation units
11222 and files with arbitrary file names. @code{gnatchop}
11223 reads the specified file and generates one or more output files,
11224 containing one unit per file. The unit and the file name correspond,
11225 as required by GNAT.
11226
11227 If you want to permanently restructure a set of ``foreign'' files so that
11228 they match the GNAT rules, and do the remaining development using the
11229 GNAT structure, you can simply use @command{gnatchop} once, generate the
11230 new set of files and work with them from that point on.
11231
11232 Alternatively, if you want to keep your files in the ``foreign'' format,
11233 perhaps to maintain compatibility with some other Ada compilation
11234 system, you can set up a procedure where you use @command{gnatchop} each
11235 time you compile, regarding the source files that it writes as temporary
11236 files that you throw away.
11237
11238 Note that if your file containing multiple units starts with a byte order
11239 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11240 will each start with a copy of this BOM, meaning that they can be compiled
11241 automatically in UTF-8 mode without needing to specify an explicit encoding.
11242
11243 @node Operating gnatchop in Compilation Mode
11244 @section Operating gnatchop in Compilation Mode
11245
11246 @noindent
11247 The basic function of @code{gnatchop} is to take a file with multiple units
11248 and split it into separate files. The boundary between files is reasonably
11249 clear, except for the issue of comments and pragmas. In default mode, the
11250 rule is that any pragmas between units belong to the previous unit, except
11251 that configuration pragmas always belong to the following unit. Any comments
11252 belong to the following unit. These rules
11253 almost always result in the right choice of
11254 the split point without needing to mark it explicitly and most users will
11255 find this default to be what they want. In this default mode it is incorrect to
11256 submit a file containing only configuration pragmas, or one that ends in
11257 configuration pragmas, to @code{gnatchop}.
11258
11259 However, using a special option to activate ``compilation mode'',
11260 @code{gnatchop}
11261 can perform another function, which is to provide exactly the semantics
11262 required by the RM for handling of configuration pragmas in a compilation.
11263 In the absence of configuration pragmas (at the main file level), this
11264 option has no effect, but it causes such configuration pragmas to be handled
11265 in a quite different manner.
11266
11267 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11268 only configuration pragmas, then this file is appended to the
11269 @file{gnat.adc} file in the current directory. This behavior provides
11270 the required behavior described in the RM for the actions to be taken
11271 on submitting such a file to the compiler, namely that these pragmas
11272 should apply to all subsequent compilations in the same compilation
11273 environment. Using GNAT, the current directory, possibly containing a
11274 @file{gnat.adc} file is the representation
11275 of a compilation environment. For more information on the
11276 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11277
11278 Second, in compilation mode, if @code{gnatchop}
11279 is given a file that starts with
11280 configuration pragmas, and contains one or more units, then these
11281 configuration pragmas are prepended to each of the chopped files. This
11282 behavior provides the required behavior described in the RM for the
11283 actions to be taken on compiling such a file, namely that the pragmas
11284 apply to all units in the compilation, but not to subsequently compiled
11285 units.
11286
11287 Finally, if configuration pragmas appear between units, they are appended
11288 to the previous unit. This results in the previous unit being illegal,
11289 since the compiler does not accept configuration pragmas that follow
11290 a unit. This provides the required RM behavior that forbids configuration
11291 pragmas other than those preceding the first compilation unit of a
11292 compilation.
11293
11294 For most purposes, @code{gnatchop} will be used in default mode. The
11295 compilation mode described above is used only if you need exactly
11296 accurate behavior with respect to compilations, and you have files
11297 that contain multiple units and configuration pragmas. In this
11298 circumstance the use of @code{gnatchop} with the compilation mode
11299 switch provides the required behavior, and is for example the mode
11300 in which GNAT processes the ACVC tests.
11301
11302 @node Command Line for gnatchop
11303 @section Command Line for @code{gnatchop}
11304
11305 @noindent
11306 The @code{gnatchop} command has the form:
11307
11308 @smallexample
11309 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11310 @c      @ovar{directory}
11311 @c Expanding @ovar macro inline (explanation in macro def comments)
11312 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11313       @r{[}@var{directory}@r{]}
11314 @end smallexample
11315
11316 @noindent
11317 The only required argument is the file name of the file to be chopped.
11318 There are no restrictions on the form of this file name. The file itself
11319 contains one or more Ada units, in normal GNAT format, concatenated
11320 together. As shown, more than one file may be presented to be chopped.
11321
11322 When run in default mode, @code{gnatchop} generates one output file in
11323 the current directory for each unit in each of the files.
11324
11325 @var{directory}, if specified, gives the name of the directory to which
11326 the output files will be written. If it is not specified, all files are
11327 written to the current directory.
11328
11329 For example, given a
11330 file called @file{hellofiles} containing
11331
11332 @smallexample @c ada
11333 @group
11334 @cartouche
11335 procedure hello;
11336
11337 with Text_IO; use Text_IO;
11338 procedure hello is
11339 begin
11340    Put_Line ("Hello");
11341 end hello;
11342 @end cartouche
11343 @end group
11344 @end smallexample
11345
11346 @noindent
11347 the command
11348
11349 @smallexample
11350 $ gnatchop ^hellofiles^HELLOFILES.^
11351 @end smallexample
11352
11353 @noindent
11354 generates two files in the current directory, one called
11355 @file{hello.ads} containing the single line that is the procedure spec,
11356 and the other called @file{hello.adb} containing the remaining text. The
11357 original file is not affected. The generated files can be compiled in
11358 the normal manner.
11359
11360 @noindent
11361 When gnatchop is invoked on a file that is empty or that contains only empty
11362 lines and/or comments, gnatchop will not fail, but will not produce any
11363 new sources.
11364
11365 For example, given a
11366 file called @file{toto.txt} containing
11367
11368 @smallexample @c ada
11369 @group
11370 @cartouche
11371 --  Just a comment
11372 @end cartouche
11373 @end group
11374 @end smallexample
11375
11376 @noindent
11377 the command
11378
11379 @smallexample
11380 $ gnatchop ^toto.txt^TOT.TXT^
11381 @end smallexample
11382
11383 @noindent
11384 will not produce any new file and will result in the following warnings:
11385
11386 @smallexample
11387 toto.txt:1:01: warning: empty file, contains no compilation units
11388 no compilation units found
11389 no source files written
11390 @end smallexample
11391
11392 @node Switches for gnatchop
11393 @section Switches for @code{gnatchop}
11394
11395 @noindent
11396 @command{gnatchop} recognizes the following switches:
11397
11398 @table @option
11399 @c !sort!
11400
11401 @item --version
11402 @cindex @option{--version} @command{gnatchop}
11403 Display Copyright and version, then exit disregarding all other options.
11404
11405 @item --help
11406 @cindex @option{--help} @command{gnatchop}
11407 If @option{--version} was not used, display usage, then exit disregarding
11408 all other options.
11409
11410 @item ^-c^/COMPILATION^
11411 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11412 Causes @code{gnatchop} to operate in compilation mode, in which
11413 configuration pragmas are handled according to strict RM rules. See
11414 previous section for a full description of this mode.
11415
11416 @ifclear vms
11417 @item -gnat@var{xxx}
11418 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11419 used to parse the given file. Not all @var{xxx} options make sense,
11420 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11421 process a source file that uses Latin-2 coding for identifiers.
11422 @end ifclear
11423
11424 @item ^-h^/HELP^
11425 Causes @code{gnatchop} to generate a brief help summary to the standard
11426 output file showing usage information.
11427
11428 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11429 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11430 Limit generated file names to the specified number @code{mm}
11431 of characters.
11432 This is useful if the
11433 resulting set of files is required to be interoperable with systems
11434 which limit the length of file names.
11435 @ifset vms
11436 If no value is given, or
11437 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11438 a default of 39, suitable for OpenVMS Alpha
11439 Systems, is assumed
11440 @end ifset
11441 @ifclear vms
11442 No space is allowed between the @option{-k} and the numeric value. The numeric
11443 value may be omitted in which case a default of @option{-k8},
11444 suitable for use
11445 with DOS-like file systems, is used. If no @option{-k} switch
11446 is present then
11447 there is no limit on the length of file names.
11448 @end ifclear
11449
11450 @item ^-p^/PRESERVE^
11451 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11452 Causes the file ^modification^creation^ time stamp of the input file to be
11453 preserved and used for the time stamp of the output file(s). This may be
11454 useful for preserving coherency of time stamps in an environment where
11455 @code{gnatchop} is used as part of a standard build process.
11456
11457 @item ^-q^/QUIET^
11458 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11459 Causes output of informational messages indicating the set of generated
11460 files to be suppressed. Warnings and error messages are unaffected.
11461
11462 @item ^-r^/REFERENCE^
11463 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11464 @findex Source_Reference
11465 Generate @code{Source_Reference} pragmas. Use this switch if the output
11466 files are regarded as temporary and development is to be done in terms
11467 of the original unchopped file. This switch causes
11468 @code{Source_Reference} pragmas to be inserted into each of the
11469 generated files to refers back to the original file name and line number.
11470 The result is that all error messages refer back to the original
11471 unchopped file.
11472 In addition, the debugging information placed into the object file (when
11473 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11474 specified)
11475 also refers back to this original file so that tools like profilers and
11476 debuggers will give information in terms of the original unchopped file.
11477
11478 If the original file to be chopped itself contains
11479 a @code{Source_Reference}
11480 pragma referencing a third file, then gnatchop respects
11481 this pragma, and the generated @code{Source_Reference} pragmas
11482 in the chopped file refer to the original file, with appropriate
11483 line numbers. This is particularly useful when @code{gnatchop}
11484 is used in conjunction with @code{gnatprep} to compile files that
11485 contain preprocessing statements and multiple units.
11486
11487 @item ^-v^/VERBOSE^
11488 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11489 Causes @code{gnatchop} to operate in verbose mode. The version
11490 number and copyright notice are output, as well as exact copies of
11491 the gnat1 commands spawned to obtain the chop control information.
11492
11493 @item ^-w^/OVERWRITE^
11494 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11495 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11496 fatal error if there is already a file with the same name as a
11497 file it would otherwise output, in other words if the files to be
11498 chopped contain duplicated units. This switch bypasses this
11499 check, and causes all but the last instance of such duplicated
11500 units to be skipped.
11501
11502 @ifclear vms
11503 @item --GCC=@var{xxxx}
11504 @cindex @option{--GCC=} (@code{gnatchop})
11505 Specify the path of the GNAT parser to be used. When this switch is used,
11506 no attempt is made to add the prefix to the GNAT parser executable.
11507 @end ifclear
11508 @end table
11509
11510 @node Examples of gnatchop Usage
11511 @section Examples of @code{gnatchop} Usage
11512
11513 @table @code
11514 @ifset vms
11515 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11516 @end ifset
11517 @ifclear vms
11518 @item gnatchop -w hello_s.ada prerelease/files
11519 @end ifclear
11520
11521 Chops the source file @file{hello_s.ada}. The output files will be
11522 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11523 overwriting any
11524 files with matching names in that directory (no files in the current
11525 directory are modified).
11526
11527 @item gnatchop ^archive^ARCHIVE.^
11528 Chops the source file @file{^archive^ARCHIVE.^}
11529 into the current directory. One
11530 useful application of @code{gnatchop} is in sending sets of sources
11531 around, for example in email messages. The required sources are simply
11532 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11533 command), and then
11534 @command{gnatchop} is used at the other end to reconstitute the original
11535 file names.
11536
11537 @item gnatchop file1 file2 file3 direc
11538 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11539 the resulting files in the directory @file{direc}. Note that if any units
11540 occur more than once anywhere within this set of files, an error message
11541 is generated, and no files are written. To override this check, use the
11542 @option{^-w^/OVERWRITE^} switch,
11543 in which case the last occurrence in the last file will
11544 be the one that is output, and earlier duplicate occurrences for a given
11545 unit will be skipped.
11546 @end table
11547
11548 @node Configuration Pragmas
11549 @chapter Configuration Pragmas
11550 @cindex Configuration pragmas
11551 @cindex Pragmas, configuration
11552
11553 @noindent
11554 Configuration pragmas include those pragmas described as
11555 such in the Ada Reference Manual, as well as
11556 implementation-dependent pragmas that are configuration pragmas.
11557 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11558 for details on these additional GNAT-specific configuration pragmas.
11559 Most notably, the pragma @code{Source_File_Name}, which allows
11560 specifying non-default names for source files, is a configuration
11561 pragma. The following is a complete list of configuration pragmas
11562 recognized by GNAT:
11563
11564 @smallexample
11565    Ada_83
11566    Ada_95
11567    Ada_05
11568    Ada_2005
11569    Ada_12
11570    Ada_2012
11571    Assertion_Policy
11572    Assume_No_Invalid_Values
11573    C_Pass_By_Copy
11574    Check_Name
11575    Check_Policy
11576    Compile_Time_Error
11577    Compile_Time_Warning
11578    Compiler_Unit
11579    Component_Alignment
11580    Convention_Identifier
11581    Debug_Policy
11582    Detect_Blocking
11583    Default_Storage_Pool
11584    Discard_Names
11585    Elaboration_Checks
11586    Eliminate
11587    Extend_System
11588    Extensions_Allowed
11589    External_Name_Casing
11590    Fast_Math
11591    Favor_Top_Level
11592    Float_Representation
11593    Implicit_Packing
11594    Initialize_Scalars
11595    Interrupt_State
11596    License
11597    Locking_Policy
11598    Long_Float
11599    No_Run_Time
11600    No_Strict_Aliasing
11601    Normalize_Scalars
11602    Optimize_Alignment
11603    Persistent_BSS
11604    Polling
11605    Priority_Specific_Dispatching
11606    Profile
11607    Profile_Warnings
11608    Propagate_Exceptions
11609    Queuing_Policy
11610    Ravenscar
11611    Restricted_Run_Time
11612    Restrictions
11613    Restrictions_Warnings
11614    Reviewable
11615    Short_Circuit_And_Or
11616    Source_File_Name
11617    Source_File_Name_Project
11618    Style_Checks
11619    Suppress
11620    Suppress_Exception_Locations
11621    Task_Dispatching_Policy
11622    Universal_Data
11623    Unsuppress
11624    Use_VADS_Size
11625    Validity_Checks
11626    Warnings
11627    Wide_Character_Encoding
11628
11629 @end smallexample
11630
11631 @menu
11632 * Handling of Configuration Pragmas::
11633 * The Configuration Pragmas Files::
11634 @end menu
11635
11636 @node Handling of Configuration Pragmas
11637 @section Handling of Configuration Pragmas
11638
11639 Configuration pragmas may either appear at the start of a compilation
11640 unit, in which case they apply only to that unit, or they may apply to
11641 all compilations performed in a given compilation environment.
11642
11643 GNAT also provides the @code{gnatchop} utility to provide an automatic
11644 way to handle configuration pragmas following the semantics for
11645 compilations (that is, files with multiple units), described in the RM.
11646 See @ref{Operating gnatchop in Compilation Mode} for details.
11647 However, for most purposes, it will be more convenient to edit the
11648 @file{gnat.adc} file that contains configuration pragmas directly,
11649 as described in the following section.
11650
11651 @node The Configuration Pragmas Files
11652 @section The Configuration Pragmas Files
11653 @cindex @file{gnat.adc}
11654
11655 @noindent
11656 In GNAT a compilation environment is defined by the current
11657 directory at the time that a compile command is given. This current
11658 directory is searched for a file whose name is @file{gnat.adc}. If
11659 this file is present, it is expected to contain one or more
11660 configuration pragmas that will be applied to the current compilation.
11661 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11662 considered.
11663
11664 Configuration pragmas may be entered into the @file{gnat.adc} file
11665 either by running @code{gnatchop} on a source file that consists only of
11666 configuration pragmas, or more conveniently  by
11667 direct editing of the @file{gnat.adc} file, which is a standard format
11668 source file.
11669
11670 In addition to @file{gnat.adc}, additional files containing configuration
11671 pragmas may be applied to the current compilation using the switch
11672 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11673 contains only configuration pragmas. These configuration pragmas are
11674 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11675 is present and switch @option{-gnatA} is not used).
11676
11677 It is allowed to specify several switches @option{-gnatec}, all of which
11678 will be taken into account.
11679
11680 If you are using project file, a separate mechanism is provided using
11681 project attributes, see @ref{Specifying Configuration Pragmas} for more
11682 details.
11683
11684 @ifset vms
11685 Of special interest to GNAT OpenVMS Alpha is the following
11686 configuration pragma:
11687
11688 @smallexample @c ada
11689 @cartouche
11690 pragma Extend_System (Aux_DEC);
11691 @end cartouche
11692 @end smallexample
11693
11694 @noindent
11695 In the presence of this pragma, GNAT adds to the definition of the
11696 predefined package SYSTEM all the additional types and subprograms that are
11697 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11698 @end ifset
11699
11700 @node Handling Arbitrary File Naming Conventions Using gnatname
11701 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11702 @cindex Arbitrary File Naming Conventions
11703
11704 @menu
11705 * Arbitrary File Naming Conventions::
11706 * Running gnatname::
11707 * Switches for gnatname::
11708 * Examples of gnatname Usage::
11709 @end menu
11710
11711 @node Arbitrary File Naming Conventions
11712 @section Arbitrary File Naming Conventions
11713
11714 @noindent
11715 The GNAT compiler must be able to know the source file name of a compilation
11716 unit.  When using the standard GNAT default file naming conventions
11717 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11718 does not need additional information.
11719
11720 @noindent
11721 When the source file names do not follow the standard GNAT default file naming
11722 conventions, the GNAT compiler must be given additional information through
11723 a configuration pragmas file (@pxref{Configuration Pragmas})
11724 or a project file.
11725 When the non-standard file naming conventions are well-defined,
11726 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11727 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11728 if the file naming conventions are irregular or arbitrary, a number
11729 of pragma @code{Source_File_Name} for individual compilation units
11730 must be defined.
11731 To help maintain the correspondence between compilation unit names and
11732 source file names within the compiler,
11733 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11734 set of files.
11735
11736 @node Running gnatname
11737 @section Running @code{gnatname}
11738
11739 @noindent
11740 The usual form of the @code{gnatname} command is
11741
11742 @smallexample
11743 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11744 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11745 @c Expanding @ovar macro inline (explanation in macro def comments)
11746 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11747       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11748 @end smallexample
11749
11750 @noindent
11751 All of the arguments are optional. If invoked without any argument,
11752 @code{gnatname} will display its usage.
11753
11754 @noindent
11755 When used with at least one naming pattern, @code{gnatname} will attempt to
11756 find all the compilation units in files that follow at least one of the
11757 naming patterns. To find these compilation units,
11758 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11759 regular files.
11760
11761 @noindent
11762 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11763 Each Naming Pattern is enclosed between double quotes (or single
11764 quotes on Windows).
11765 A Naming Pattern is a regular expression similar to the wildcard patterns
11766 used in file names by the Unix shells or the DOS prompt.
11767
11768 @noindent
11769 @code{gnatname} may be called with several sections of directories/patterns.
11770 Sections are separated by switch @code{--and}. In each section, there must be
11771 at least one pattern. If no directory is specified in a section, the current
11772 directory (or the project directory is @code{-P} is used) is implied.
11773 The options other that the directory switches and the patterns apply globally
11774 even if they are in different sections.
11775
11776 @noindent
11777 Examples of Naming Patterns are
11778
11779 @smallexample
11780    "*.[12].ada"
11781    "*.ad[sb]*"
11782    "body_*"    "spec_*"
11783 @end smallexample
11784
11785 @noindent
11786 For a more complete description of the syntax of Naming Patterns,
11787 see the second kind of regular expressions described in @file{g-regexp.ads}
11788 (the ``Glob'' regular expressions).
11789
11790 @noindent
11791 When invoked with no switch @code{-P}, @code{gnatname} will create a
11792 configuration pragmas file @file{gnat.adc} in the current working directory,
11793 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11794 unit.
11795
11796 @node Switches for gnatname
11797 @section Switches for @code{gnatname}
11798
11799 @noindent
11800 Switches for @code{gnatname} must precede any specified Naming Pattern.
11801
11802 @noindent
11803 You may specify any of the following switches to @code{gnatname}:
11804
11805 @table @option
11806 @c !sort!
11807
11808 @item --version
11809 @cindex @option{--version} @command{gnatname}
11810 Display Copyright and version, then exit disregarding all other options.
11811
11812 @item --help
11813 @cindex @option{--help} @command{gnatname}
11814 If @option{--version} was not used, display usage, then exit disregarding
11815 all other options.
11816
11817 @item --and
11818 Start another section of directories/patterns.
11819
11820 @item ^-c^/CONFIG_FILE=^@file{file}
11821 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11822 Create a configuration pragmas file @file{file} (instead of the default
11823 @file{gnat.adc}).
11824 @ifclear vms
11825 There may be zero, one or more space between @option{-c} and
11826 @file{file}.
11827 @end ifclear
11828 @file{file} may include directory information. @file{file} must be
11829 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11830 When a switch @option{^-c^/CONFIG_FILE^} is
11831 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11832
11833 @item ^-d^/SOURCE_DIRS=^@file{dir}
11834 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11835 Look for source files in directory @file{dir}. There may be zero, one or more
11836 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11837 When a switch @option{^-d^/SOURCE_DIRS^}
11838 is specified, the current working directory will not be searched for source
11839 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11840 or @option{^-D^/DIR_FILES^} switch.
11841 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11842 If @file{dir} is a relative path, it is relative to the directory of
11843 the configuration pragmas file specified with switch
11844 @option{^-c^/CONFIG_FILE^},
11845 or to the directory of the project file specified with switch
11846 @option{^-P^/PROJECT_FILE^} or,
11847 if neither switch @option{^-c^/CONFIG_FILE^}
11848 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11849 current working directory. The directory
11850 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11851
11852 @item ^-D^/DIRS_FILE=^@file{file}
11853 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11854 Look for source files in all directories listed in text file @file{file}.
11855 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11856 and @file{file}.
11857 @file{file} must be an existing, readable text file.
11858 Each nonempty line in @file{file} must be a directory.
11859 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11860 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11861 @file{file}.
11862
11863 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11864 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11865 Foreign patterns. Using this switch, it is possible to add sources of languages
11866 other than Ada to the list of sources of a project file.
11867 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11868 For example,
11869 @smallexample
11870 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11871 @end smallexample
11872 @noindent
11873 will look for Ada units in all files with the @file{.ada} extension,
11874 and will add to the list of file for project @file{prj.gpr} the C files
11875 with extension @file{.^c^C^}.
11876
11877 @item ^-h^/HELP^
11878 @cindex @option{^-h^/HELP^} (@code{gnatname})
11879 Output usage (help) information. The output is written to @file{stdout}.
11880
11881 @item ^-P^/PROJECT_FILE=^@file{proj}
11882 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11883 Create or update project file @file{proj}. There may be zero, one or more space
11884 between @option{-P} and @file{proj}. @file{proj} may include directory
11885 information. @file{proj} must be writable.
11886 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11887 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11888 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11889
11890 @item ^-v^/VERBOSE^
11891 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11892 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11893 This includes name of the file written, the name of the directories to search
11894 and, for each file in those directories whose name matches at least one of
11895 the Naming Patterns, an indication of whether the file contains a unit,
11896 and if so the name of the unit.
11897
11898 @item ^-v -v^/VERBOSE /VERBOSE^
11899 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11900 Very Verbose mode. In addition to the output produced in verbose mode,
11901 for each file in the searched directories whose name matches none of
11902 the Naming Patterns, an indication is given that there is no match.
11903
11904 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11905 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11906 Excluded patterns. Using this switch, it is possible to exclude some files
11907 that would match the name patterns. For example,
11908 @smallexample
11909 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11910 @end smallexample
11911 @noindent
11912 will look for Ada units in all files with the @file{.ada} extension,
11913 except those whose names end with @file{_nt.ada}.
11914
11915 @end table
11916
11917 @node Examples of gnatname Usage
11918 @section Examples of @code{gnatname} Usage
11919
11920 @ifset vms
11921 @smallexample
11922 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11923 @end smallexample
11924 @end ifset
11925
11926 @ifclear vms
11927 @smallexample
11928 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11929 @end smallexample
11930 @end ifclear
11931
11932 @noindent
11933 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11934 and be writable. In addition, the directory
11935 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11936 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11937
11938 @ifclear vms
11939 Note the optional spaces after @option{-c} and @option{-d}.
11940 @end ifclear
11941
11942 @smallexample
11943 @ifclear vms
11944 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11945   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11946 @end ifclear
11947 @ifset vms
11948 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11949   /EXCLUDED_PATTERN=*_nt_body.ada
11950   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11951   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11952 @end ifset
11953 @end smallexample
11954
11955 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11956 even in conjunction with one or several switches
11957 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11958 are used in this example.
11959
11960 @c *****************************************
11961 @c * G N A T  P r o j e c t  M a n a g e r *
11962 @c *****************************************
11963
11964 @c ------ macros for projects.texi
11965 @c These macros are needed when building the gprbuild documentation, but
11966 @c should have no effect in the gnat user's guide
11967
11968 @macro CODESAMPLE{TXT}
11969 @smallexample
11970 @group
11971 \TXT\
11972 @end group
11973 @end smallexample
11974 @end macro
11975
11976 @macro PROJECTFILE{TXT}
11977 @CODESAMPLE{\TXT\}
11978 @end macro
11979
11980 @c simulates a newline when in a @CODESAMPLE
11981 @macro NL{}
11982 @end macro
11983
11984 @macro TIP{TXT}
11985 @quotation
11986 @noindent
11987 \TXT\
11988 @end quotation
11989 @end macro
11990
11991 @macro TIPHTML{TXT}
11992 \TXT\
11993 @end macro
11994
11995 @macro IMPORTANT{TXT}
11996 @quotation
11997 @noindent
11998 \TXT\
11999 @end quotation
12000
12001 @end macro
12002
12003 @macro NOTE{TXT}
12004 @quotation
12005 @noindent
12006 \TXT\
12007 @end quotation
12008 @end macro
12009
12010 @include projects.texi
12011
12012 @c *****************************************
12013 @c * Cross-referencing tools
12014 @c *****************************************
12015
12016 @node The Cross-Referencing Tools gnatxref and gnatfind
12017 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12018 @findex gnatxref
12019 @findex gnatfind
12020
12021 @noindent
12022 The compiler generates cross-referencing information (unless
12023 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12024 This information indicates where in the source each entity is declared and
12025 referenced. Note that entities in package Standard are not included, but
12026 entities in all other predefined units are included in the output.
12027
12028 Before using any of these two tools, you need to compile successfully your
12029 application, so that GNAT gets a chance to generate the cross-referencing
12030 information.
12031
12032 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12033 information to provide the user with the capability to easily locate the
12034 declaration and references to an entity. These tools are quite similar,
12035 the difference being that @code{gnatfind} is intended for locating
12036 definitions and/or references to a specified entity or entities, whereas
12037 @code{gnatxref} is oriented to generating a full report of all
12038 cross-references.
12039
12040 To use these tools, you must not compile your application using the
12041 @option{-gnatx} switch on the @command{gnatmake} command line
12042 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12043 information will not be generated.
12044
12045 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12046 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12047
12048 @menu
12049 * Switches for gnatxref::
12050 * Switches for gnatfind::
12051 * Project Files for gnatxref and gnatfind::
12052 * Regular Expressions in gnatfind and gnatxref::
12053 * Examples of gnatxref Usage::
12054 * Examples of gnatfind Usage::
12055 @end menu
12056
12057 @node Switches for gnatxref
12058 @section @code{gnatxref} Switches
12059
12060 @noindent
12061 The command invocation for @code{gnatxref} is:
12062 @smallexample
12063 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12064 @c Expanding @ovar macro inline (explanation in macro def comments)
12065 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12066 @end smallexample
12067
12068 @noindent
12069 where
12070
12071 @table @var
12072 @item sourcefile1
12073 @itemx sourcefile2
12074 identifies the source files for which a report is to be generated. The
12075 ``with''ed units will be processed too. You must provide at least one file.
12076
12077 These file names are considered to be regular expressions, so for instance
12078 specifying @file{source*.adb} is the same as giving every file in the current
12079 directory whose name starts with @file{source} and whose extension is
12080 @file{adb}.
12081
12082 You shouldn't specify any directory name, just base names. @command{gnatxref}
12083 and @command{gnatfind} will be able to locate these files by themselves using
12084 the source path. If you specify directories, no result is produced.
12085
12086 @end table
12087
12088 @noindent
12089 The switches can be:
12090 @table @option
12091 @c !sort!
12092 @item --version
12093 @cindex @option{--version} @command{gnatxref}
12094 Display Copyright and version, then exit disregarding all other options.
12095
12096 @item --help
12097 @cindex @option{--help} @command{gnatxref}
12098 If @option{--version} was not used, display usage, then exit disregarding
12099 all other options.
12100
12101 @item ^-a^/ALL_FILES^
12102 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12103 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12104 the read-only files found in the library search path. Otherwise, these files
12105 will be ignored. This option can be used to protect Gnat sources or your own
12106 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12107 much faster, and their output much smaller. Read-only here refers to access
12108 or permissions status in the file system for the current user.
12109
12110 @item -aIDIR
12111 @cindex @option{-aIDIR} (@command{gnatxref})
12112 When looking for source files also look in directory DIR. The order in which
12113 source file search is undertaken is the same as for @command{gnatmake}.
12114
12115 @item -aODIR
12116 @cindex @option{-aODIR} (@command{gnatxref})
12117 When searching for library and object files, look in directory
12118 DIR. The order in which library files are searched is the same as for
12119 @command{gnatmake}.
12120
12121 @item -nostdinc
12122 @cindex @option{-nostdinc} (@command{gnatxref})
12123 Do not look for sources in the system default directory.
12124
12125 @item -nostdlib
12126 @cindex @option{-nostdlib} (@command{gnatxref})
12127 Do not look for library files in the system default directory.
12128
12129 @item --ext=@var{extension}
12130 @cindex @option{--ext} (@command{gnatxref})
12131 Specify an alternate ali file extension. The default is @code{ali} and other
12132 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12133 switch. Note that if this switch overrides the default, which means that only
12134 the new extension will be considered.
12135
12136 @item --RTS=@var{rts-path}
12137 @cindex @option{--RTS} (@command{gnatxref})
12138 Specifies the default location of the runtime library. Same meaning as the
12139 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12140
12141 @item ^-d^/DERIVED_TYPES^
12142 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12143 If this switch is set @code{gnatxref} will output the parent type
12144 reference for each matching derived types.
12145
12146 @item ^-f^/FULL_PATHNAME^
12147 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12148 If this switch is set, the output file names will be preceded by their
12149 directory (if the file was found in the search path). If this switch is
12150 not set, the directory will not be printed.
12151
12152 @item ^-g^/IGNORE_LOCALS^
12153 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12154 If this switch is set, information is output only for library-level
12155 entities, ignoring local entities. The use of this switch may accelerate
12156 @code{gnatfind} and @code{gnatxref}.
12157
12158 @item -IDIR
12159 @cindex @option{-IDIR} (@command{gnatxref})
12160 Equivalent to @samp{-aODIR -aIDIR}.
12161
12162 @item -pFILE
12163 @cindex @option{-pFILE} (@command{gnatxref})
12164 Specify a project file to use @xref{GNAT Project Manager}.
12165 If you need to use the @file{.gpr}
12166 project files, you should use gnatxref through the GNAT driver
12167 (@command{gnat xref -Pproject}).
12168
12169 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12170 project file in the current directory.
12171
12172 If a project file is either specified or found by the tools, then the content
12173 of the source directory and object directory lines are added as if they
12174 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12175 and @samp{^-aO^OBJECT_SEARCH^}.
12176 @item ^-u^/UNUSED^
12177 Output only unused symbols. This may be really useful if you give your
12178 main compilation unit on the command line, as @code{gnatxref} will then
12179 display every unused entity and 'with'ed package.
12180
12181 @ifclear vms
12182 @item -v
12183 Instead of producing the default output, @code{gnatxref} will generate a
12184 @file{tags} file that can be used by vi. For examples how to use this
12185 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12186 to the standard output, thus you will have to redirect it to a file.
12187 @end ifclear
12188
12189 @end table
12190
12191 @noindent
12192 All these switches may be in any order on the command line, and may even
12193 appear after the file names. They need not be separated by spaces, thus
12194 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12195 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12196
12197 @node Switches for gnatfind
12198 @section @code{gnatfind} Switches
12199
12200 @noindent
12201 The command line for @code{gnatfind} is:
12202
12203 @smallexample
12204 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12205 @c       @r{[}@var{file1} @var{file2} @dots{}]
12206 @c Expanding @ovar macro inline (explanation in macro def comments)
12207 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12208       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12209 @end smallexample
12210
12211 @noindent
12212 where
12213
12214 @table @var
12215 @item pattern
12216 An entity will be output only if it matches the regular expression found
12217 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12218
12219 Omitting the pattern is equivalent to specifying @samp{*}, which
12220 will match any entity. Note that if you do not provide a pattern, you
12221 have to provide both a sourcefile and a line.
12222
12223 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12224 for matching purposes. At the current time there is no support for
12225 8-bit codes other than Latin-1, or for wide characters in identifiers.
12226
12227 @item sourcefile
12228 @code{gnatfind} will look for references, bodies or declarations
12229 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12230 and column @var{column}. See @ref{Examples of gnatfind Usage}
12231 for syntax examples.
12232
12233 @item line
12234 is a decimal integer identifying the line number containing
12235 the reference to the entity (or entities) to be located.
12236
12237 @item column
12238 is a decimal integer identifying the exact location on the
12239 line of the first character of the identifier for the
12240 entity reference. Columns are numbered from 1.
12241
12242 @item file1 file2 @dots{}
12243 The search will be restricted to these source files. If none are given, then
12244 the search will be done for every library file in the search path.
12245 These file must appear only after the pattern or sourcefile.
12246
12247 These file names are considered to be regular expressions, so for instance
12248 specifying @file{source*.adb} is the same as giving every file in the current
12249 directory whose name starts with @file{source} and whose extension is
12250 @file{adb}.
12251
12252 The location of the spec of the entity will always be displayed, even if it
12253 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12254 occurrences of the entity in the separate units of the ones given on the
12255 command line will also be displayed.
12256
12257 Note that if you specify at least one file in this part, @code{gnatfind} may
12258 sometimes not be able to find the body of the subprograms.
12259
12260 @end table
12261
12262 @noindent
12263 At least one of 'sourcefile' or 'pattern' has to be present on
12264 the command line.
12265
12266 The following switches are available:
12267 @table @option
12268 @c !sort!
12269
12270 @cindex @option{--version} @command{gnatfind}
12271 Display Copyright and version, then exit disregarding all other options.
12272
12273 @item --help
12274 @cindex @option{--help} @command{gnatfind}
12275 If @option{--version} was not used, display usage, then exit disregarding
12276 all other options.
12277
12278 @item ^-a^/ALL_FILES^
12279 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12280 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12281 the read-only files found in the library search path. Otherwise, these files
12282 will be ignored. This option can be used to protect Gnat sources or your own
12283 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12284 much faster, and their output much smaller. Read-only here refers to access
12285 or permission status in the file system for the current user.
12286
12287 @item -aIDIR
12288 @cindex @option{-aIDIR} (@command{gnatfind})
12289 When looking for source files also look in directory DIR. The order in which
12290 source file search is undertaken is the same as for @command{gnatmake}.
12291
12292 @item -aODIR
12293 @cindex @option{-aODIR} (@command{gnatfind})
12294 When searching for library and object files, look in directory
12295 DIR. The order in which library files are searched is the same as for
12296 @command{gnatmake}.
12297
12298 @item -nostdinc
12299 @cindex @option{-nostdinc} (@command{gnatfind})
12300 Do not look for sources in the system default directory.
12301
12302 @item -nostdlib
12303 @cindex @option{-nostdlib} (@command{gnatfind})
12304 Do not look for library files in the system default directory.
12305
12306 @item --ext=@var{extension}
12307 @cindex @option{--ext} (@command{gnatfind})
12308 Specify an alternate ali file extension. The default is @code{ali} and other
12309 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12310 switch. Note that if this switch overrides the default, which means that only
12311 the new extension will be considered.
12312
12313 @item --RTS=@var{rts-path}
12314 @cindex @option{--RTS} (@command{gnatfind})
12315 Specifies the default location of the runtime library. Same meaning as the
12316 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12317
12318 @item ^-d^/DERIVED_TYPE_INFORMATION^
12319 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12320 If this switch is set, then @code{gnatfind} will output the parent type
12321 reference for each matching derived types.
12322
12323 @item ^-e^/EXPRESSIONS^
12324 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12325 By default, @code{gnatfind} accept the simple regular expression set for
12326 @samp{pattern}. If this switch is set, then the pattern will be
12327 considered as full Unix-style regular expression.
12328
12329 @item ^-f^/FULL_PATHNAME^
12330 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12331 If this switch is set, the output file names will be preceded by their
12332 directory (if the file was found in the search path). If this switch is
12333 not set, the directory will not be printed.
12334
12335 @item ^-g^/IGNORE_LOCALS^
12336 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12337 If this switch is set, information is output only for library-level
12338 entities, ignoring local entities. The use of this switch may accelerate
12339 @code{gnatfind} and @code{gnatxref}.
12340
12341 @item -IDIR
12342 @cindex @option{-IDIR} (@command{gnatfind})
12343 Equivalent to @samp{-aODIR -aIDIR}.
12344
12345 @item -pFILE
12346 @cindex @option{-pFILE} (@command{gnatfind})
12347 Specify a project file (@pxref{GNAT Project Manager}) to use.
12348 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12349 project file in the current directory.
12350
12351 If a project file is either specified or found by the tools, then the content
12352 of the source directory and object directory lines are added as if they
12353 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12354 @samp{^-aO^/OBJECT_SEARCH^}.
12355
12356 @item ^-r^/REFERENCES^
12357 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12358 By default, @code{gnatfind} will output only the information about the
12359 declaration, body or type completion of the entities. If this switch is
12360 set, the @code{gnatfind} will locate every reference to the entities in
12361 the files specified on the command line (or in every file in the search
12362 path if no file is given on the command line).
12363
12364 @item ^-s^/PRINT_LINES^
12365 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12366 If this switch is set, then @code{gnatfind} will output the content
12367 of the Ada source file lines were the entity was found.
12368
12369 @item ^-t^/TYPE_HIERARCHY^
12370 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12371 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12372 the specified type. It act like -d option but recursively from parent
12373 type to parent type. When this switch is set it is not possible to
12374 specify more than one file.
12375
12376 @end table
12377
12378 @noindent
12379 All these switches may be in any order on the command line, and may even
12380 appear after the file names. They need not be separated by spaces, thus
12381 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12382 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12383
12384 As stated previously, gnatfind will search in every directory in the
12385 search path. You can force it to look only in the current directory if
12386 you specify @code{*} at the end of the command line.
12387
12388 @node Project Files for gnatxref and gnatfind
12389 @section Project Files for @command{gnatxref} and @command{gnatfind}
12390
12391 @noindent
12392 Project files allow a programmer to specify how to compile its
12393 application, where to find sources, etc.  These files are used
12394 @ifclear vms
12395 primarily by GPS, but they can also be used
12396 @end ifclear
12397 by the two tools
12398 @code{gnatxref} and @code{gnatfind}.
12399
12400 A project file name must end with @file{.gpr}. If a single one is
12401 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12402 extract the information from it. If multiple project files are found, none of
12403 them is read, and you have to use the @samp{-p} switch to specify the one
12404 you want to use.
12405
12406 The following lines can be included, even though most of them have default
12407 values which can be used in most cases.
12408 The lines can be entered in any order in the file.
12409 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12410 each line. If you have multiple instances, only the last one is taken into
12411 account.
12412
12413 @table @code
12414 @item src_dir=DIR
12415 [default: @code{"^./^[]^"}]
12416 specifies a directory where to look for source files. Multiple @code{src_dir}
12417 lines can be specified and they will be searched in the order they
12418 are specified.
12419
12420 @item obj_dir=DIR
12421 [default: @code{"^./^[]^"}]
12422 specifies a directory where to look for object and library files. Multiple
12423 @code{obj_dir} lines can be specified, and they will be searched in the order
12424 they are specified
12425
12426 @item comp_opt=SWITCHES
12427 [default: @code{""}]
12428 creates a variable which can be referred to subsequently by using
12429 the @code{$@{comp_opt@}} notation. This is intended to store the default
12430 switches given to @command{gnatmake} and @command{gcc}.
12431
12432 @item bind_opt=SWITCHES
12433 [default: @code{""}]
12434 creates a variable which can be referred to subsequently by using
12435 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12436 switches given to @command{gnatbind}.
12437
12438 @item link_opt=SWITCHES
12439 [default: @code{""}]
12440 creates a variable which can be referred to subsequently by using
12441 the @samp{$@{link_opt@}} notation. This is intended to store the default
12442 switches given to @command{gnatlink}.
12443
12444 @item main=EXECUTABLE
12445 [default: @code{""}]
12446 specifies the name of the executable for the application. This variable can
12447 be referred to in the following lines by using the @samp{$@{main@}} notation.
12448
12449 @ifset vms
12450 @item comp_cmd=COMMAND
12451 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12452 @end ifset
12453 @ifclear vms
12454 @item comp_cmd=COMMAND
12455 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12456 @end ifclear
12457 specifies the command used to compile a single file in the application.
12458
12459 @ifset vms
12460 @item make_cmd=COMMAND
12461 [default: @code{"GNAT MAKE $@{main@}
12462 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12463 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12464 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12465 @end ifset
12466 @ifclear vms
12467 @item make_cmd=COMMAND
12468 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12469 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12470 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12471 @end ifclear
12472 specifies the command used to recompile the whole application.
12473
12474 @item run_cmd=COMMAND
12475 [default: @code{"$@{main@}"}]
12476 specifies the command used to run the application.
12477
12478 @item debug_cmd=COMMAND
12479 [default: @code{"gdb $@{main@}"}]
12480 specifies the command used to debug the application
12481
12482 @end table
12483
12484 @noindent
12485 @command{gnatxref} and @command{gnatfind} only take into account the
12486 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12487
12488 @node Regular Expressions in gnatfind and gnatxref
12489 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12490
12491 @noindent
12492 As specified in the section about @command{gnatfind}, the pattern can be a
12493 regular expression. Actually, there are to set of regular expressions
12494 which are recognized by the program:
12495
12496 @table @code
12497 @item globbing patterns
12498 These are the most usual regular expression. They are the same that you
12499 generally used in a Unix shell command line, or in a DOS session.
12500
12501 Here is a more formal grammar:
12502 @smallexample
12503 @group
12504 @iftex
12505 @leftskip=.5cm
12506 @end iftex
12507 regexp ::= term
12508 term   ::= elmt            -- matches elmt
12509 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12510 term   ::= *               -- any string of 0 or more characters
12511 term   ::= ?               -- matches any character
12512 term   ::= [char @{char@}]   -- matches any character listed
12513 term   ::= [char - char]   -- matches any character in range
12514 @end group
12515 @end smallexample
12516
12517 @item full regular expression
12518 The second set of regular expressions is much more powerful. This is the
12519 type of regular expressions recognized by utilities such a @file{grep}.
12520
12521 The following is the form of a regular expression, expressed in Ada
12522 reference manual style BNF is as follows
12523
12524 @smallexample
12525 @iftex
12526 @leftskip=.5cm
12527 @end iftex
12528 @group
12529 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12530
12531 term ::= item @{item@}       -- concatenation (item then item)
12532
12533 item ::= elmt              -- match elmt
12534 item ::= elmt *            -- zero or more elmt's
12535 item ::= elmt +            -- one or more elmt's
12536 item ::= elmt ?            -- matches elmt or nothing
12537 @end group
12538 @group
12539 elmt ::= nschar            -- matches given character
12540 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12541 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12542 elmt ::= [char - char]     -- matches chars in given range
12543 elmt ::= \ char            -- matches given character
12544 elmt ::= .                 -- matches any single character
12545 elmt ::= ( regexp )        -- parens used for grouping
12546
12547 char ::= any character, including special characters
12548 nschar ::= any character except ()[].*+?^^^
12549 @end group
12550 @end smallexample
12551
12552 Following are a few examples:
12553
12554 @table @samp
12555 @item abcde|fghi
12556 will match any of the two strings @samp{abcde} and @samp{fghi},
12557
12558 @item abc*d
12559 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12560 @samp{abcccd}, and so on,
12561
12562 @item [a-z]+
12563 will match any string which has only lowercase characters in it (and at
12564 least one character.
12565
12566 @end table
12567 @end table
12568
12569 @node Examples of gnatxref Usage
12570 @section Examples of @code{gnatxref} Usage
12571
12572 @subsection General Usage
12573
12574 @noindent
12575 For the following examples, we will consider the following units:
12576
12577 @smallexample @c ada
12578 @group
12579 @cartouche
12580 main.ads:
12581 1: with Bar;
12582 2: package Main is
12583 3:     procedure Foo (B : in Integer);
12584 4:     C : Integer;
12585 5: private
12586 6:     D : Integer;
12587 7: end Main;
12588
12589 main.adb:
12590 1: package body Main is
12591 2:     procedure Foo (B : in Integer) is
12592 3:     begin
12593 4:        C := B;
12594 5:        D := B;
12595 6:        Bar.Print (B);
12596 7:        Bar.Print (C);
12597 8:     end Foo;
12598 9: end Main;
12599
12600 bar.ads:
12601 1: package Bar is
12602 2:     procedure Print (B : Integer);
12603 3: end bar;
12604 @end cartouche
12605 @end group
12606 @end smallexample
12607
12608 @table @code
12609
12610 @noindent
12611 The first thing to do is to recompile your application (for instance, in
12612 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12613 the cross-referencing information.
12614 You can then issue any of the following commands:
12615
12616 @item gnatxref main.adb
12617 @code{gnatxref} generates cross-reference information for main.adb
12618 and every unit 'with'ed by main.adb.
12619
12620 The output would be:
12621 @smallexample
12622 @iftex
12623 @leftskip=0cm
12624 @end iftex
12625 B                                                      Type: Integer
12626   Decl: bar.ads           2:22
12627 B                                                      Type: Integer
12628   Decl: main.ads          3:20
12629   Body: main.adb          2:20
12630   Ref:  main.adb          4:13     5:13     6:19
12631 Bar                                                    Type: Unit
12632   Decl: bar.ads           1:9
12633   Ref:  main.adb          6:8      7:8
12634        main.ads           1:6
12635 C                                                      Type: Integer
12636   Decl: main.ads          4:5
12637   Modi: main.adb          4:8
12638   Ref:  main.adb          7:19
12639 D                                                      Type: Integer
12640   Decl: main.ads          6:5
12641   Modi: main.adb          5:8
12642 Foo                                                    Type: Unit
12643   Decl: main.ads          3:15
12644   Body: main.adb          2:15
12645 Main                                                    Type: Unit
12646   Decl: main.ads          2:9
12647   Body: main.adb          1:14
12648 Print                                                   Type: Unit
12649   Decl: bar.ads           2:15
12650   Ref:  main.adb          6:12     7:12
12651 @end smallexample
12652
12653 @noindent
12654 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12655 its body is in main.adb, line 1, column 14 and is not referenced any where.
12656
12657 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12658 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12659
12660 @item gnatxref package1.adb package2.ads
12661 @code{gnatxref} will generates cross-reference information for
12662 package1.adb, package2.ads and any other package 'with'ed by any
12663 of these.
12664
12665 @end table
12666
12667 @ifclear vms
12668 @subsection Using gnatxref with vi
12669
12670 @code{gnatxref} can generate a tags file output, which can be used
12671 directly from @command{vi}. Note that the standard version of @command{vi}
12672 will not work properly with overloaded symbols. Consider using another
12673 free implementation of @command{vi}, such as @command{vim}.
12674
12675 @smallexample
12676 $ gnatxref -v gnatfind.adb > tags
12677 @end smallexample
12678
12679 @noindent
12680 will generate the tags file for @code{gnatfind} itself (if the sources
12681 are in the search path!).
12682
12683 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12684 (replacing @var{entity} by whatever you are looking for), and vi will
12685 display a new file with the corresponding declaration of entity.
12686 @end ifclear
12687
12688 @node Examples of gnatfind Usage
12689 @section Examples of @code{gnatfind} Usage
12690
12691 @table @code
12692
12693 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12694 Find declarations for all entities xyz referenced at least once in
12695 main.adb. The references are search in every library file in the search
12696 path.
12697
12698 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12699 switch is set)
12700
12701 The output will look like:
12702 @smallexample
12703 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12704 ^directory/^[directory]^main.adb:24:10: xyz <= body
12705 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12706 @end smallexample
12707
12708 @noindent
12709 that is to say, one of the entities xyz found in main.adb is declared at
12710 line 12 of main.ads (and its body is in main.adb), and another one is
12711 declared at line 45 of foo.ads
12712
12713 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12714 This is the same command as the previous one, instead @code{gnatfind} will
12715 display the content of the Ada source file lines.
12716
12717 The output will look like:
12718
12719 @smallexample
12720 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12721    procedure xyz;
12722 ^directory/^[directory]^main.adb:24:10: xyz <= body
12723    procedure xyz is
12724 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12725    xyz : Integer;
12726 @end smallexample
12727
12728 @noindent
12729 This can make it easier to find exactly the location your are looking
12730 for.
12731
12732 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12733 Find references to all entities containing an x that are
12734 referenced on line 123 of main.ads.
12735 The references will be searched only in main.ads and foo.adb.
12736
12737 @item gnatfind main.ads:123
12738 Find declarations and bodies for all entities that are referenced on
12739 line 123 of main.ads.
12740
12741 This is the same as @code{gnatfind "*":main.adb:123}.
12742
12743 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12744 Find the declaration for the entity referenced at column 45 in
12745 line 123 of file main.adb in directory mydir. Note that it
12746 is usual to omit the identifier name when the column is given,
12747 since the column position identifies a unique reference.
12748
12749 The column has to be the beginning of the identifier, and should not
12750 point to any character in the middle of the identifier.
12751
12752 @end table
12753
12754 @c *********************************
12755 @node The GNAT Pretty-Printer gnatpp
12756 @chapter The GNAT Pretty-Printer @command{gnatpp}
12757 @findex gnatpp
12758 @cindex Pretty-Printer
12759
12760 @noindent
12761 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12762 for source reformatting / pretty-printing.
12763 It takes an Ada source file as input and generates a reformatted
12764 version as output.
12765 You can specify various style directives via switches; e.g.,
12766 identifier case conventions, rules of indentation, and comment layout.
12767
12768 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12769 tree for the input source and thus requires the input to be syntactically and
12770 semantically legal.
12771 If this condition is not met, @command{gnatpp} will terminate with an
12772 error message; no output file will be generated.
12773
12774 If the source files presented to @command{gnatpp} contain
12775 preprocessing directives, then the output file will
12776 correspond to the generated source after all
12777 preprocessing is carried out. There is no way
12778 using @command{gnatpp} to obtain pretty printed files that
12779 include the preprocessing directives.
12780
12781 If the compilation unit
12782 contained in the input source depends semantically upon units located
12783 outside the current directory, you have to provide the source search path
12784 when invoking @command{gnatpp}, if these units are contained in files with
12785 names that do not follow the GNAT file naming rules, you have to provide
12786 the configuration file describing the corresponding naming scheme;
12787 see the description of the @command{gnatpp}
12788 switches below. Another possibility is to use a project file and to
12789 call @command{gnatpp} through the @command{gnat} driver
12790
12791 The @command{gnatpp} command has the form
12792
12793 @smallexample
12794 @c $ gnatpp @ovar{switches} @var{filename}
12795 @c Expanding @ovar macro inline (explanation in macro def comments)
12796 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12797 @end smallexample
12798
12799 @noindent
12800 where
12801 @itemize @bullet
12802 @item
12803 @var{switches} is an optional sequence of switches defining such properties as
12804 the formatting rules, the source search path, and the destination for the
12805 output source file
12806
12807 @item
12808 @var{filename} is the name (including the extension) of the source file to
12809 reformat; ``wildcards'' or several file names on the same gnatpp command are
12810 allowed.  The file name may contain path information; it does not have to
12811 follow the GNAT file naming rules
12812
12813 @item
12814 @samp{@var{gcc_switches}} is a list of switches for
12815 @command{gcc}. They will be passed on to all compiler invocations made by
12816 @command{gnatelim} to generate the ASIS trees. Here you can provide
12817 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12818 use the @option{-gnatec} switch to set the configuration file,
12819 use the @option{-gnat05} switch if sources should be compiled in
12820 Ada 2005 mode  etc.
12821 @end itemize
12822
12823 @menu
12824 * Switches for gnatpp::
12825 * Formatting Rules::
12826 @end menu
12827
12828 @node Switches for gnatpp
12829 @section Switches for @command{gnatpp}
12830
12831 @noindent
12832 The following subsections describe the various switches accepted by
12833 @command{gnatpp}, organized by category.
12834
12835 @ifclear vms
12836 You specify a switch by supplying a name and generally also a value.
12837 In many cases the values for a switch with a given name are incompatible with
12838 each other
12839 (for example the switch that controls the casing of a reserved word may have
12840 exactly one value: upper case, lower case, or
12841 mixed case) and thus exactly one such switch can be in effect for an
12842 invocation of @command{gnatpp}.
12843 If more than one is supplied, the last one is used.
12844 However, some values for the same switch are mutually compatible.
12845 You may supply several such switches to @command{gnatpp}, but then
12846 each must be specified in full, with both the name and the value.
12847 Abbreviated forms (the name appearing once, followed by each value) are
12848 not permitted.
12849 For example, to set
12850 the alignment of the assignment delimiter both in declarations and in
12851 assignment statements, you must write @option{-A2A3}
12852 (or @option{-A2 -A3}), but not @option{-A23}.
12853 @end ifclear
12854
12855 @ifset vms
12856 In many cases the set of options for a given qualifier are incompatible with
12857 each other (for example the qualifier that controls the casing of a reserved
12858 word may have exactly one option, which specifies either upper case, lower
12859 case, or mixed case), and thus exactly one such option can be in effect for
12860 an invocation of @command{gnatpp}.
12861 If more than one is supplied, the last one is used.
12862 However, some qualifiers have options that are mutually compatible,
12863 and then you may then supply several such options when invoking
12864 @command{gnatpp}.
12865 @end ifset
12866
12867 In most cases, it is obvious whether or not the
12868 ^values for a switch with a given name^options for a given qualifier^
12869 are compatible with each other.
12870 When the semantics might not be evident, the summaries below explicitly
12871 indicate the effect.
12872
12873 @menu
12874 * Alignment Control::
12875 * Casing Control::
12876 * Construct Layout Control::
12877 * General Text Layout Control::
12878 * Other Formatting Options::
12879 * Setting the Source Search Path::
12880 * Output File Control::
12881 * Other gnatpp Switches::
12882 @end menu
12883
12884 @node Alignment Control
12885 @subsection Alignment Control
12886 @cindex Alignment control in @command{gnatpp}
12887
12888 @noindent
12889 Programs can be easier to read if certain constructs are vertically aligned.
12890 By default all alignments are set ON.
12891 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12892 OFF, and then use one or more of the other
12893 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12894 to activate alignment for specific constructs.
12895
12896 @table @option
12897 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12898
12899 @ifset vms
12900 @item /ALIGN=ON
12901 Set all alignments to ON
12902 @end ifset
12903
12904 @item ^-A0^/ALIGN=OFF^
12905 Set all alignments to OFF
12906
12907 @item ^-A1^/ALIGN=COLONS^
12908 Align @code{:} in declarations
12909
12910 @item ^-A2^/ALIGN=DECLARATIONS^
12911 Align @code{:=} in initializations in declarations
12912
12913 @item ^-A3^/ALIGN=STATEMENTS^
12914 Align @code{:=} in assignment statements
12915
12916 @item ^-A4^/ALIGN=ARROWS^
12917 Align @code{=>} in associations
12918
12919 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12920 Align @code{at} keywords in the component clauses in record
12921 representation clauses
12922 @end table
12923
12924 @noindent
12925 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12926 is allowed.
12927
12928 @node Casing Control
12929 @subsection Casing Control
12930 @cindex Casing control in @command{gnatpp}
12931
12932 @noindent
12933 @command{gnatpp} allows you to specify the casing for reserved words,
12934 pragma names, attribute designators and identifiers.
12935 For identifiers you may define a
12936 general rule for name casing but also override this rule
12937 via a set of dictionary files.
12938
12939 Three types of casing are supported: lower case, upper case, and mixed case.
12940 Lower and upper case are self-explanatory (but since some letters in
12941 Latin1 and other GNAT-supported character sets
12942 exist only in lower-case form, an upper case conversion will have no
12943 effect on them.)
12944 ``Mixed case'' means that the first letter, and also each letter immediately
12945 following an underscore, are converted to their uppercase forms;
12946 all the other letters are converted to their lowercase forms.
12947
12948 @table @option
12949 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12950 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12951 Attribute designators are lower case
12952
12953 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12954 Attribute designators are upper case
12955
12956 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12957 Attribute designators are mixed case (this is the default)
12958
12959 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12960 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12961 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12962 lower case (this is the default)
12963
12964 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12965 Keywords are upper case
12966
12967 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12968 @item ^-nD^/NAME_CASING=AS_DECLARED^
12969 Name casing for defining occurrences are as they appear in the source file
12970 (this is the default)
12971
12972 @item ^-nU^/NAME_CASING=UPPER_CASE^
12973 Names are in upper case
12974
12975 @item ^-nL^/NAME_CASING=LOWER_CASE^
12976 Names are in lower case
12977
12978 @item ^-nM^/NAME_CASING=MIXED_CASE^
12979 Names are in mixed case
12980
12981 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12982 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12983 Pragma names are lower case
12984
12985 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12986 Pragma names are upper case
12987
12988 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12989 Pragma names are mixed case (this is the default)
12990
12991 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12992 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12993 Use @var{file} as a @emph{dictionary file} that defines
12994 the casing for a set of specified names,
12995 thereby overriding the effect on these names by
12996 any explicit or implicit
12997 ^-n^/NAME_CASING^ switch.
12998 To supply more than one dictionary file,
12999 use ^several @option{-D} switches^a list of files as options^.
13000
13001 @noindent
13002 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13003 to define the casing for the Ada predefined names and
13004 the names declared in the GNAT libraries.
13005
13006 @item ^-D-^/SPECIFIC_CASING^
13007 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13008 Do not use the default dictionary file;
13009 instead, use the casing
13010 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13011 dictionary file(s)
13012 @end table
13013
13014 @noindent
13015 The structure of a dictionary file, and details on the conventions
13016 used in the default dictionary file, are defined in @ref{Name Casing}.
13017
13018 The @option{^-D-^/SPECIFIC_CASING^} and
13019 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13020 compatible.
13021
13022 @node Construct Layout Control
13023 @subsection Construct Layout Control
13024 @cindex Layout control in @command{gnatpp}
13025
13026 @noindent
13027 This group of @command{gnatpp} switches controls the layout of comments and
13028 complex syntactic constructs.  See @ref{Formatting Comments} for details
13029 on their effect.
13030
13031 @table @option
13032 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13033 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13034 All the comments remain unchanged
13035
13036 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13037 GNAT-style comment line indentation (this is the default).
13038
13039 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13040 Reference-manual comment line indentation.
13041
13042 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13043 GNAT-style comment beginning
13044
13045 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13046 Reformat comment blocks
13047
13048 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13049 Keep unchanged special form comments
13050
13051 Reformat comment blocks
13052
13053 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13054 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13055 GNAT-style layout (this is the default)
13056
13057 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13058 Compact layout
13059
13060 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13061 Uncompact layout
13062
13063 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13064 @item ^-N^/NOTABS^
13065 All the VT characters are removed from the comment text. All the HT characters
13066 are expanded with the sequences of space characters to get to the next tab
13067 stops.
13068
13069 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13070 @item ^--no-separate-is^/NO_SEPARATE_IS^
13071 Do not place the keyword @code{is} on a separate line in a subprogram body in
13072 case if the spec occupies more then one line.
13073
13074 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13075 @item ^--separate-label^/SEPARATE_LABEL^
13076 Place statement label(s) on a separate line, with the following statement
13077 on the next line.
13078
13079 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13080 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13081 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13082 keyword @code{then} in IF statements on a separate line.
13083
13084 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13085 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13086 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13087 keyword @code{then} in IF statements on a separate line. This option is
13088 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13089
13090 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13091 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13092 Start each USE clause in a context clause from a separate line.
13093
13094 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13095 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13096 Use a separate line for a loop or block statement name, but do not use an extra
13097 indentation level for the statement itself.
13098
13099 @end table
13100
13101 @ifclear vms
13102 @noindent
13103 The @option{-c1} and @option{-c2} switches are incompatible.
13104 The @option{-c3} and @option{-c4} switches are compatible with each other and
13105 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13106 the other comment formatting switches.
13107
13108 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13109 @end ifclear
13110
13111 @ifset vms
13112 @noindent
13113 For the @option{/COMMENTS_LAYOUT} qualifier:
13114 @itemize @bullet
13115 @item
13116 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13117 @item
13118 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13119 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13120 @end itemize
13121
13122 @noindent
13123 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13124 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13125 @end ifset
13126
13127 @node General Text Layout Control
13128 @subsection General Text Layout Control
13129
13130 @noindent
13131 These switches allow control over line length and indentation.
13132
13133 @table @option
13134 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13135 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13136 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13137
13138 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13139 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13140 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13141
13142 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13143 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13144 Indentation level for continuation lines (relative to the line being
13145 continued), @var{nnn} from 1@dots{}9.
13146 The default
13147 value is one less then the (normal) indentation level, unless the
13148 indentation is set to 1 (in which case the default value for continuation
13149 line indentation is also 1)
13150 @end table
13151
13152 @node Other Formatting Options
13153 @subsection Other Formatting Options
13154
13155 @noindent
13156 These switches control the inclusion of missing end/exit labels, and
13157 the indentation level in @b{case} statements.
13158
13159 @table @option
13160 @item ^-e^/NO_MISSED_LABELS^
13161 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13162 Do not insert missing end/exit labels. An end label is the name of
13163 a construct that may optionally be repeated at the end of the
13164 construct's declaration;
13165 e.g., the names of packages, subprograms, and tasks.
13166 An exit label is the name of a loop that may appear as target
13167 of an exit statement within the loop.
13168 By default, @command{gnatpp} inserts these end/exit labels when
13169 they are absent from the original source. This option suppresses such
13170 insertion, so that the formatted source reflects the original.
13171
13172 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13173 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13174 Insert a Form Feed character after a pragma Page.
13175
13176 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13177 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13178 Do not use an additional indentation level for @b{case} alternatives
13179 and variants if there are @var{nnn} or more (the default
13180 value is 10).
13181 If @var{nnn} is 0, an additional indentation level is
13182 used for @b{case} alternatives and variants regardless of their number.
13183 @end table
13184
13185 @node Setting the Source Search Path
13186 @subsection Setting the Source Search Path
13187
13188 @noindent
13189 To define the search path for the input source file, @command{gnatpp}
13190 uses the same switches as the GNAT compiler, with the same effects.
13191
13192 @table @option
13193 @item ^-I^/SEARCH=^@var{dir}
13194 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13195 The same as the corresponding gcc switch
13196
13197 @item ^-I-^/NOCURRENT_DIRECTORY^
13198 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13199 The same as the corresponding gcc switch
13200
13201 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13202 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13203 The same as the corresponding gcc switch
13204
13205 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13206 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13207 The same as the corresponding gcc switch
13208
13209 @end table
13210
13211 @node Output File Control
13212 @subsection Output File Control
13213
13214 @noindent
13215 By default the output is sent to the file whose name is obtained by appending
13216 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13217 (if the file with this name already exists, it is unconditionally overwritten).
13218 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13219 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13220 as output file.
13221 The output may be redirected by the following switches:
13222
13223 @table @option
13224 @item ^-pipe^/STANDARD_OUTPUT^
13225 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13226 Send the output to @code{Standard_Output}
13227
13228 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13229 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13230 Write the output into @var{output_file}.
13231 If @var{output_file} already exists, @command{gnatpp} terminates without
13232 reading or processing the input file.
13233
13234 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13235 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13236 Write the output into @var{output_file}, overwriting the existing file
13237 (if one is present).
13238
13239 @item ^-r^/REPLACE^
13240 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13241 Replace the input source file with the reformatted output, and copy the
13242 original input source into the file whose name is obtained by appending the
13243 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13244 If a file with this name already exists, @command{gnatpp} terminates without
13245 reading or processing the input file.
13246
13247 @item ^-rf^/OVERRIDING_REPLACE^
13248 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13249 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13250 already exists, it is overwritten.
13251
13252 @item ^-rnb^/REPLACE_NO_BACKUP^
13253 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13254 Replace the input source file with the reformatted output without
13255 creating any backup copy of the input source.
13256
13257 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13258 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13259 Specifies the format of the reformatted output file. The @var{xxx}
13260 ^string specified with the switch^option^ may be either
13261 @itemize @bullet
13262 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13263 @item ``@option{^crlf^CRLF^}''
13264 the same as @option{^crlf^CRLF^}
13265 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13266 @item ``@option{^lf^LF^}''
13267 the same as @option{^unix^UNIX^}
13268 @end itemize
13269
13270 @item ^-W^/RESULT_ENCODING=^@var{e}
13271 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13272 Specify the wide character encoding method used to write the code in the
13273 result file
13274 @var{e} is one of the following:
13275
13276 @itemize @bullet
13277
13278 @item ^h^HEX^
13279 Hex encoding
13280
13281 @item ^u^UPPER^
13282 Upper half encoding
13283
13284 @item ^s^SHIFT_JIS^
13285 Shift/JIS encoding
13286
13287 @item ^e^EUC^
13288 EUC encoding
13289
13290 @item ^8^UTF8^
13291 UTF-8 encoding
13292
13293 @item ^b^BRACKETS^
13294 Brackets encoding (default value)
13295 @end itemize
13296
13297 @end table
13298
13299 @noindent
13300 Options @option{^-pipe^/STANDARD_OUTPUT^},
13301 @option{^-o^/OUTPUT^} and
13302 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13303 contains only one file to reformat.
13304 Option
13305 @option{^--eol^/END_OF_LINE^}
13306 and
13307 @option{^-W^/RESULT_ENCODING^}
13308 cannot be used together
13309 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13310
13311 @node Other gnatpp Switches
13312 @subsection Other @code{gnatpp} Switches
13313
13314 @noindent
13315 The additional @command{gnatpp} switches are defined in this subsection.
13316
13317 @table @option
13318 @item ^-files @var{filename}^/FILES=@var{filename}^
13319 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13320 Take the argument source files from the specified file. This file should be an
13321 ordinary text file containing file names separated by spaces or
13322 line breaks. You can use this switch more than once in the same call to
13323 @command{gnatpp}. You also can combine this switch with an explicit list of
13324 files.
13325
13326 @item ^-v^/VERBOSE^
13327 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13328 Verbose mode;
13329 @command{gnatpp} generates version information and then
13330 a trace of the actions it takes to produce or obtain the ASIS tree.
13331
13332 @item ^-w^/WARNINGS^
13333 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13334 Warning mode;
13335 @command{gnatpp} generates a warning whenever it cannot provide
13336 a required layout in the result source.
13337 @end table
13338
13339 @node Formatting Rules
13340 @section Formatting Rules
13341
13342 @noindent
13343 The following subsections show how @command{gnatpp} treats ``white space'',
13344 comments, program layout, and name casing.
13345 They provide the detailed descriptions of the switches shown above.
13346
13347 @menu
13348 * White Space and Empty Lines::
13349 * Formatting Comments::
13350 * Construct Layout::
13351 * Name Casing::
13352 @end menu
13353
13354 @node White Space and Empty Lines
13355 @subsection White Space and Empty Lines
13356
13357 @noindent
13358 @command{gnatpp} does not have an option to control space characters.
13359 It will add or remove spaces according to the style illustrated by the
13360 examples in the @cite{Ada Reference Manual}.
13361
13362 The only format effectors
13363 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13364 that will appear in the output file are platform-specific line breaks,
13365 and also format effectors within (but not at the end of) comments.
13366 In particular, each horizontal tab character that is not inside
13367 a comment will be treated as a space and thus will appear in the
13368 output file as zero or more spaces depending on
13369 the reformatting of the line in which it appears.
13370 The only exception is a Form Feed character, which is inserted after a
13371 pragma @code{Page} when @option{-ff} is set.
13372
13373 The output file will contain no lines with trailing ``white space'' (spaces,
13374 format effectors).
13375
13376 Empty lines in the original source are preserved
13377 only if they separate declarations or statements.
13378 In such contexts, a
13379 sequence of two or more empty lines is replaced by exactly one empty line.
13380 Note that a blank line will be removed if it separates two ``comment blocks''
13381 (a comment block is a sequence of whole-line comments).
13382 In order to preserve a visual separation between comment blocks, use an
13383 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13384 Likewise, if for some reason you wish to have a sequence of empty lines,
13385 use a sequence of empty comments instead.
13386
13387 @node Formatting Comments
13388 @subsection Formatting Comments
13389
13390 @noindent
13391 Comments in Ada code are of two kinds:
13392 @itemize @bullet
13393 @item
13394 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13395 ``white space'') on a line
13396
13397 @item
13398 an @emph{end-of-line comment}, which follows some other Ada lexical element
13399 on the same line.
13400 @end itemize
13401
13402 @noindent
13403 The indentation of a whole-line comment is that of either
13404 the preceding or following line in
13405 the formatted source, depending on switch settings as will be described below.
13406
13407 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13408 between the end of the preceding Ada lexical element and the beginning
13409 of the comment as appear in the original source,
13410 unless either the comment has to be split to
13411 satisfy the line length limitation, or else the next line contains a
13412 whole line comment that is considered a continuation of this end-of-line
13413 comment (because it starts at the same position).
13414 In the latter two
13415 cases, the start of the end-of-line comment is moved right to the nearest
13416 multiple of the indentation level.
13417 This may result in a ``line overflow'' (the right-shifted comment extending
13418 beyond the maximum line length), in which case the comment is split as
13419 described below.
13420
13421 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13422 (GNAT-style comment line indentation)
13423 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13424 (reference-manual comment line indentation).
13425 With reference-manual style, a whole-line comment is indented as if it
13426 were a declaration or statement at the same place
13427 (i.e., according to the indentation of the preceding line(s)).
13428 With GNAT style, a whole-line comment that is immediately followed by an
13429 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13430 word @b{begin}, is indented based on the construct that follows it.
13431
13432 For example:
13433 @smallexample @c ada
13434 @cartouche
13435 if A then
13436     null;
13437        -- some comment
13438 else
13439    null;
13440 end if;
13441 @end cartouche
13442 @end smallexample
13443
13444 @noindent
13445 Reference-manual indentation produces:
13446
13447 @smallexample @c ada
13448 @cartouche
13449 if A then
13450    null;
13451    --  some comment
13452 else
13453    null;
13454 end if;
13455 @end cartouche
13456 @end smallexample
13457
13458 @noindent
13459 while GNAT-style indentation produces:
13460
13461 @smallexample @c ada
13462 @cartouche
13463 if A then
13464    null;
13465 --  some comment
13466 else
13467    null;
13468 end if;
13469 @end cartouche
13470 @end smallexample
13471
13472 @noindent
13473 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13474 (GNAT style comment beginning) has the following
13475 effect:
13476
13477 @itemize @bullet
13478 @item
13479 For each whole-line comment that does not end with two hyphens,
13480 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13481 to ensure that there are at least two spaces between these hyphens and the
13482 first non-blank character of the comment.
13483 @end itemize
13484
13485 @noindent
13486 For an end-of-line comment, if in the original source the next line is a
13487 whole-line comment that starts at the same position
13488 as the end-of-line comment,
13489 then the whole-line comment (and all whole-line comments
13490 that follow it and that start at the same position)
13491 will start at this position in the output file.
13492
13493 @noindent
13494 That is, if in the original source we have:
13495
13496 @smallexample @c ada
13497 @cartouche
13498 begin
13499 A := B + C;            --  B must be in the range Low1..High1
13500                        --  C must be in the range Low2..High2
13501              --B+C will be in the range Low1+Low2..High1+High2
13502 X := X + 1;
13503 @end cartouche
13504 @end smallexample
13505
13506 @noindent
13507 Then in the formatted source we get
13508
13509 @smallexample @c ada
13510 @cartouche
13511 begin
13512    A := B + C;            --  B must be in the range Low1..High1
13513                           --  C must be in the range Low2..High2
13514    --  B+C will be in the range Low1+Low2..High1+High2
13515    X := X + 1;
13516 @end cartouche
13517 @end smallexample
13518
13519 @noindent
13520 A comment that exceeds the line length limit will be split.
13521 Unless switch
13522 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13523 the line belongs to a reformattable block, splitting the line generates a
13524 @command{gnatpp} warning.
13525 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13526 comments may be reformatted in typical
13527 word processor style (that is, moving words between lines and putting as
13528 many words in a line as possible).
13529
13530 @noindent
13531 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13532 that has a special format (that is, a character that is neither a letter nor digit
13533 not white space nor line break immediately following the leading @code{--} of
13534 the comment) should be without any change moved from the argument source
13535 into reformatted source. This switch allows to preserve comments that are used
13536 as a special marks in the code (e.g.@: SPARK annotation).
13537
13538 @node Construct Layout
13539 @subsection Construct Layout
13540
13541 @noindent
13542 In several cases the suggested layout in the Ada Reference Manual includes
13543 an extra level of indentation that many programmers prefer to avoid. The
13544 affected cases include:
13545
13546 @itemize @bullet
13547
13548 @item Record type declaration (RM 3.8)
13549
13550 @item Record representation clause (RM 13.5.1)
13551
13552 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13553
13554 @item Block statement in case if a block has a statement identifier (RM 5.6)
13555 @end itemize
13556
13557 @noindent
13558 In compact mode (when GNAT style layout or compact layout is set),
13559 the pretty printer uses one level of indentation instead
13560 of two. This is achieved in the record definition and record representation
13561 clause cases by putting the @code{record} keyword on the same line as the
13562 start of the declaration or representation clause, and in the block and loop
13563 case by putting the block or loop header on the same line as the statement
13564 identifier.
13565
13566 @noindent
13567 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13568 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13569 layout on the one hand, and uncompact layout
13570 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13571 can be illustrated by the following examples:
13572
13573 @iftex
13574 @cartouche
13575 @multitable @columnfractions .5 .5
13576 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13577
13578 @item
13579 @smallexample @c ada
13580 type q is record
13581    a : integer;
13582    b : integer;
13583 end record;
13584 @end smallexample
13585 @tab
13586 @smallexample @c ada
13587 type q is
13588    record
13589       a : integer;
13590       b : integer;
13591    end record;
13592 @end smallexample
13593
13594 @item
13595 @smallexample @c ada
13596 for q use record
13597    a at 0 range  0 .. 31;
13598    b at 4 range  0 .. 31;
13599 end record;
13600 @end smallexample
13601 @tab
13602 @smallexample @c ada
13603 for q use
13604    record
13605       a at 0 range  0 .. 31;
13606       b at 4 range  0 .. 31;
13607    end record;
13608 @end smallexample
13609
13610 @item
13611 @smallexample @c ada
13612 Block : declare
13613    A : Integer := 3;
13614 begin
13615    Proc (A, A);
13616 end Block;
13617 @end smallexample
13618 @tab
13619 @smallexample @c ada
13620 Block :
13621    declare
13622       A : Integer := 3;
13623    begin
13624       Proc (A, A);
13625    end Block;
13626 @end smallexample
13627
13628 @item
13629 @smallexample @c ada
13630 Clear : for J in 1 .. 10 loop
13631    A (J) := 0;
13632 end loop Clear;
13633 @end smallexample
13634 @tab
13635 @smallexample @c ada
13636 Clear :
13637    for J in 1 .. 10 loop
13638       A (J) := 0;
13639    end loop Clear;
13640 @end smallexample
13641 @end multitable
13642 @end cartouche
13643 @end iftex
13644
13645 @ifnottex
13646 @smallexample
13647 @cartouche
13648 GNAT style, compact layout              Uncompact layout
13649
13650 type q is record                        type q is
13651    a : integer;                            record
13652    b : integer;                               a : integer;
13653 end record;                                   b : integer;
13654                                            end record;
13655
13656 for q use record                        for q use
13657    a at 0 range  0 .. 31;                  record
13658    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13659 end record;                                   b at 4 range  0 .. 31;
13660                                            end record;
13661
13662 Block : declare                         Block :
13663    A : Integer := 3;                       declare
13664 begin                                         A : Integer := 3;
13665    Proc (A, A);                            begin
13666 end Block;                                    Proc (A, A);
13667                                            end Block;
13668
13669 Clear : for J in 1 .. 10 loop           Clear :
13670    A (J) := 0;                             for J in 1 .. 10 loop
13671 end loop Clear;                               A (J) := 0;
13672                                            end loop Clear;
13673 @end cartouche
13674 @end smallexample
13675 @end ifnottex
13676
13677 @noindent
13678 A further difference between GNAT style layout and compact layout is that
13679 GNAT style layout inserts empty lines as separation for
13680 compound statements, return statements and bodies.
13681
13682 Note that the layout specified by
13683 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13684 for named block and loop statements overrides the layout defined by these
13685 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13686 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13687 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13688
13689 @node Name Casing
13690 @subsection Name Casing
13691
13692 @noindent
13693 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13694 the same casing as the corresponding defining identifier.
13695
13696 You control the casing for defining occurrences via the
13697 @option{^-n^/NAME_CASING^} switch.
13698 @ifclear vms
13699 With @option{-nD} (``as declared'', which is the default),
13700 @end ifclear
13701 @ifset vms
13702 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13703 @end ifset
13704 defining occurrences appear exactly as in the source file
13705 where they are declared.
13706 The other ^values for this switch^options for this qualifier^ ---
13707 @option{^-nU^UPPER_CASE^},
13708 @option{^-nL^LOWER_CASE^},
13709 @option{^-nM^MIXED_CASE^} ---
13710 result in
13711 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13712 If @command{gnatpp} changes the casing of a defining
13713 occurrence, it analogously changes the casing of all the
13714 usage occurrences of this name.
13715
13716 If the defining occurrence of a name is not in the source compilation unit
13717 currently being processed by @command{gnatpp}, the casing of each reference to
13718 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13719 switch (subject to the dictionary file mechanism described below).
13720 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13721 had affected the
13722 casing for the defining occurrence of the name.
13723
13724 Some names may need to be spelled with casing conventions that are not
13725 covered by the upper-, lower-, and mixed-case transformations.
13726 You can arrange correct casing by placing such names in a
13727 @emph{dictionary file},
13728 and then supplying a @option{^-D^/DICTIONARY^} switch.
13729 The casing of names from dictionary files overrides
13730 any @option{^-n^/NAME_CASING^} switch.
13731
13732 To handle the casing of Ada predefined names and the names from GNAT libraries,
13733 @command{gnatpp} assumes a default dictionary file.
13734 The name of each predefined entity is spelled with the same casing as is used
13735 for the entity in the @cite{Ada Reference Manual}.
13736 The name of each entity in the GNAT libraries is spelled with the same casing
13737 as is used in the declaration of that entity.
13738
13739 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13740 default dictionary file.
13741 Instead, the casing for predefined and GNAT-defined names will be established
13742 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13743 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13744 will appear as just shown,
13745 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13746 To ensure that even such names are rendered in uppercase,
13747 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13748 (or else, less conveniently, place these names in upper case in a dictionary
13749 file).
13750
13751 A dictionary file is
13752 a plain text file; each line in this file can be either a blank line
13753 (containing only space characters and ASCII.HT characters), an Ada comment
13754 line, or the specification of exactly one @emph{casing schema}.
13755
13756 A casing schema is a string that has the following syntax:
13757
13758 @smallexample
13759 @cartouche
13760   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13761
13762   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13763 @end cartouche
13764 @end smallexample
13765
13766 @noindent
13767 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13768 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13769
13770 The casing schema string can be followed by white space and/or an Ada-style
13771 comment; any amount of white space is allowed before the string.
13772
13773 If a dictionary file is passed as
13774 @ifclear vms
13775 the value of a @option{-D@var{file}} switch
13776 @end ifclear
13777 @ifset vms
13778 an option to the @option{/DICTIONARY} qualifier
13779 @end ifset
13780 then for every
13781 simple name and every identifier, @command{gnatpp} checks if the dictionary
13782 defines the casing for the name or for some of its parts (the term ``subword''
13783 is used below to denote the part of a name which is delimited by ``_'' or by
13784 the beginning or end of the word and which does not contain any ``_'' inside):
13785
13786 @itemize @bullet
13787 @item
13788 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13789 the casing defined by the dictionary; no subwords are checked for this word
13790
13791 @item
13792 for every subword @command{gnatpp} checks if the dictionary contains the
13793 corresponding string of the form @code{*@var{simple_identifier}*},
13794 and if it does, the casing of this @var{simple_identifier} is used
13795 for this subword
13796
13797 @item
13798 if the whole name does not contain any ``_'' inside, and if for this name
13799 the dictionary contains two entries - one of the form @var{identifier},
13800 and another - of the form *@var{simple_identifier}*, then the first one
13801 is applied to define the casing of this name
13802
13803 @item
13804 if more than one dictionary file is passed as @command{gnatpp} switches, each
13805 dictionary adds new casing exceptions and overrides all the existing casing
13806 exceptions set by the previous dictionaries
13807
13808 @item
13809 when @command{gnatpp} checks if the word or subword is in the dictionary,
13810 this check is not case sensitive
13811 @end itemize
13812
13813 @noindent
13814 For example, suppose we have the following source to reformat:
13815
13816 @smallexample @c ada
13817 @cartouche
13818 procedure test is
13819    name1 : integer := 1;
13820    name4_name3_name2 : integer := 2;
13821    name2_name3_name4 : Boolean;
13822    name1_var : Float;
13823 begin
13824    name2_name3_name4 := name4_name3_name2 > name1;
13825 end;
13826 @end cartouche
13827 @end smallexample
13828
13829 @noindent
13830 And suppose we have two dictionaries:
13831
13832 @smallexample
13833 @cartouche
13834 @i{dict1:}
13835    NAME1
13836    *NaMe3*
13837    *Name1*
13838 @end cartouche
13839
13840 @cartouche
13841 @i{dict2:}
13842   *NAME3*
13843 @end cartouche
13844 @end smallexample
13845
13846 @noindent
13847 If @command{gnatpp} is called with the following switches:
13848
13849 @smallexample
13850 @ifclear vms
13851 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13852 @end ifclear
13853 @ifset vms
13854 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13855 @end ifset
13856 @end smallexample
13857
13858 @noindent
13859 then we will get the following name casing in the @command{gnatpp} output:
13860
13861 @smallexample @c ada
13862 @cartouche
13863 procedure Test is
13864    NAME1             : Integer := 1;
13865    Name4_NAME3_Name2 : Integer := 2;
13866    Name2_NAME3_Name4 : Boolean;
13867    Name1_Var         : Float;
13868 begin
13869    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13870 end Test;
13871 @end cartouche
13872 @end smallexample
13873
13874 @c *********************************
13875 @node The GNAT Metric Tool gnatmetric
13876 @chapter The GNAT Metric Tool @command{gnatmetric}
13877 @findex gnatmetric
13878 @cindex Metric tool
13879
13880 @noindent
13881 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13882 for computing various program metrics.
13883 It takes an Ada source file as input and generates a file containing the
13884 metrics data as output. Various switches control which
13885 metrics are computed and output.
13886
13887 @command{gnatmetric} generates and uses the ASIS
13888 tree for the input source and thus requires the input to be syntactically and
13889 semantically legal.
13890 If this condition is not met, @command{gnatmetric} will generate
13891 an error message; no metric information for this file will be
13892 computed and reported.
13893
13894 If the compilation unit contained in the input source depends semantically
13895 upon units in files located outside the current directory, you have to provide
13896 the source search path when invoking @command{gnatmetric}.
13897 If it depends semantically upon units that are contained
13898 in files with names that do not follow the GNAT file naming rules, you have to
13899 provide the configuration file describing the corresponding naming scheme (see
13900 the description of the @command{gnatmetric} switches below.)
13901 Alternatively, you may use a project file and invoke @command{gnatmetric}
13902 through the @command{gnat} driver.
13903
13904 The @command{gnatmetric} command has the form
13905
13906 @smallexample
13907 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13908 @c Expanding @ovar macro inline (explanation in macro def comments)
13909 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13910 @end smallexample
13911
13912 @noindent
13913 where
13914 @itemize @bullet
13915 @item
13916 @var{switches} specify the metrics to compute and define the destination for
13917 the output
13918
13919 @item
13920 Each @var{filename} is the name (including the extension) of a source
13921 file to process. ``Wildcards'' are allowed, and
13922 the file name may contain path information.
13923 If no @var{filename} is supplied, then the @var{switches} list must contain
13924 at least one
13925 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13926 Including both a @option{-files} switch and one or more
13927 @var{filename} arguments is permitted.
13928
13929 @item
13930 @samp{@var{gcc_switches}} is a list of switches for
13931 @command{gcc}. They will be passed on to all compiler invocations made by
13932 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13933 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13934 and use the @option{-gnatec} switch to set the configuration file,
13935 use the @option{-gnat05} switch if sources should be compiled in
13936 Ada 2005 mode etc.
13937 @end itemize
13938
13939 @menu
13940 * Switches for gnatmetric::
13941 @end menu
13942
13943 @node Switches for gnatmetric
13944 @section Switches for @command{gnatmetric}
13945
13946 @noindent
13947 The following subsections describe the various switches accepted by
13948 @command{gnatmetric}, organized by category.
13949
13950 @menu
13951 * Output Files Control::
13952 * Disable Metrics For Local Units::
13953 * Specifying a set of metrics to compute::
13954 * Other gnatmetric Switches::
13955 * Generate project-wide metrics::
13956 @end menu
13957
13958 @node Output Files Control
13959 @subsection Output File Control
13960 @cindex Output file control in @command{gnatmetric}
13961
13962 @noindent
13963 @command{gnatmetric} has two output formats. It can generate a
13964 textual (human-readable) form, and also XML. By default only textual
13965 output is generated.
13966
13967 When generating the output in textual form, @command{gnatmetric} creates
13968 for each Ada source file a corresponding text file
13969 containing the computed metrics, except for the case when the set of metrics
13970 specified by gnatmetric parameters consists only of metrics that are computed
13971 for the whole set of analyzed sources, but not for each Ada source.
13972 By default, this file is placed in the same directory as where the source
13973 file is located, and its name is obtained
13974 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13975 input file.
13976
13977 All the output information generated in XML format is placed in a single
13978 file. By default this file is placed in the current directory and has the
13979 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13980
13981 Some of the computed metrics are summed over the units passed to
13982 @command{gnatmetric}; for example, the total number of lines of code.
13983 By default this information is sent to @file{stdout}, but a file
13984 can be specified with the @option{-og} switch.
13985
13986 The following switches control the @command{gnatmetric} output:
13987
13988 @table @option
13989 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13990 @item ^-x^/XML^
13991 Generate the XML output
13992
13993 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13994 @item ^-xs^/XSD^
13995 Generate the XML output and the XML schema file that describes the structure
13996 of the XML metric report, this schema is assigned to the XML file. The schema
13997 file has the same name as the XML output file with @file{.xml} suffix replaced
13998 with @file{.xsd}
13999
14000 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14001 @item ^-nt^/NO_TEXT^
14002 Do not generate the output in text form (implies @option{^-x^/XML^})
14003
14004 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14005 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14006 Put text files with detailed metrics into @var{output_dir}
14007
14008 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14009 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14010 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14011 in the name of the output file.
14012
14013 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14014 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14015 Put global metrics into @var{file_name}
14016
14017 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14018 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14019 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14020
14021 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14022 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14023 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14024 output includes the name(s) of the Ada source file(s) from which the metrics
14025 are computed.  By default each name includes the absolute path. The
14026 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14027 to exclude all directory information from the file names that are output.)
14028
14029 @end table
14030
14031 @node Disable Metrics For Local Units
14032 @subsection Disable Metrics For Local Units
14033 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14034
14035 @noindent
14036 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14037 one compilation
14038 unit per one source file. It computes line metrics for the whole source
14039 file, and it also computes syntax
14040 and complexity metrics for the file's outermost unit.
14041
14042 By default, @command{gnatmetric} will also compute all metrics for certain
14043 kinds of locally declared program units:
14044
14045 @itemize @bullet
14046 @item
14047 subprogram (and generic subprogram) bodies;
14048
14049 @item
14050 package (and generic package) specs and bodies;
14051
14052 @item
14053 task object and type specifications and bodies;
14054
14055 @item
14056 protected object and type specifications and bodies.
14057 @end itemize
14058
14059 @noindent
14060 These kinds of entities will be referred to as
14061 @emph{eligible local program units}, or simply @emph{eligible local units},
14062 @cindex Eligible local unit (for @command{gnatmetric})
14063 in the discussion below.
14064
14065 Note that a subprogram declaration, generic instantiation,
14066 or renaming declaration only receives metrics
14067 computation when it appear as the outermost entity
14068 in a source file.
14069
14070 Suppression of metrics computation for eligible local units can be
14071 obtained via the following switch:
14072
14073 @table @option
14074 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14075 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14076 Do not compute detailed metrics for eligible local program units
14077
14078 @end table
14079
14080 @node Specifying a set of metrics to compute
14081 @subsection Specifying a set of metrics to compute
14082
14083 @noindent
14084 By default all the metrics are computed and reported. The switches
14085 described in this subsection allow you to control, on an individual
14086 basis, whether metrics are computed and
14087 reported. If at least one positive metric
14088 switch is specified (that is, a switch that defines that a given
14089 metric or set of metrics is to be computed), then only
14090 explicitly specified metrics are reported.
14091
14092 @menu
14093 * Line Metrics Control::
14094 * Syntax Metrics Control::
14095 * Complexity Metrics Control::
14096 * Object-Oriented Metrics Control::
14097 @end menu
14098
14099 @node Line Metrics Control
14100 @subsubsection Line Metrics Control
14101 @cindex Line metrics control in @command{gnatmetric}
14102
14103 @noindent
14104 For any (legal) source file, and for each of its
14105 eligible local program units, @command{gnatmetric} computes the following
14106 metrics:
14107
14108 @itemize @bullet
14109 @item
14110 the total number of lines;
14111
14112 @item
14113 the total number of code lines (i.e., non-blank lines that are not comments)
14114
14115 @item
14116 the number of comment lines
14117
14118 @item
14119 the number of code lines containing end-of-line comments;
14120
14121 @item
14122 the comment percentage: the ratio between the number of lines that contain
14123 comments and the number of all non-blank lines, expressed as a percentage;
14124
14125 @item
14126 the number of empty lines and lines containing only space characters and/or
14127 format effectors (blank lines)
14128
14129 @item
14130 the average number of code lines in subprogram bodies, task bodies, entry
14131 bodies and statement sequences in package bodies (this metric is only computed
14132 across the whole set of the analyzed units)
14133
14134 @end itemize
14135
14136 @noindent
14137 @command{gnatmetric} sums the values of the line metrics for all the
14138 files being processed and then generates the cumulative results. The tool
14139 also computes for all the files being processed the average number of code
14140 lines in bodies.
14141
14142 You can use the following switches to select the specific line metrics
14143 to be computed and reported.
14144
14145 @table @option
14146 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14147
14148 @ifclear vms
14149 @cindex @option{--no-lines@var{x}}
14150 @end ifclear
14151
14152 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14153 Report all the line metrics
14154
14155 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14156 Do not report any of line metrics
14157
14158 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14159 Report the number of all lines
14160
14161 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14162 Do not report the number of all lines
14163
14164 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14165 Report the number of code lines
14166
14167 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14168 Do not report the number of code lines
14169
14170 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14171 Report the number of comment lines
14172
14173 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14174 Do not report the number of comment lines
14175
14176 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14177 Report the number of code lines containing
14178 end-of-line comments
14179
14180 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14181 Do not report the number of code lines containing
14182 end-of-line comments
14183
14184 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14185 Report the comment percentage in the program text
14186
14187 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14188 Do not report the comment percentage in the program text
14189
14190 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14191 Report the number of blank lines
14192
14193 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14194 Do not report the number of blank lines
14195
14196 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14197 Report the average number of code lines in subprogram bodies, task bodies,
14198 entry bodies and statement sequences in package bodies. The metric is computed
14199 and reported for the whole set of processed Ada sources only.
14200
14201 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14202 Do not report the average number of code lines in subprogram bodies,
14203 task bodies, entry bodies and statement sequences in package bodies.
14204
14205 @end table
14206
14207 @node Syntax Metrics Control
14208 @subsubsection Syntax Metrics Control
14209 @cindex Syntax metrics control in @command{gnatmetric}
14210
14211 @noindent
14212 @command{gnatmetric} computes various syntactic metrics for the
14213 outermost unit and for each eligible local unit:
14214
14215 @table @emph
14216 @item LSLOC (``Logical Source Lines Of Code'')
14217 The total number of declarations and the total number of statements
14218
14219 @item Maximal static nesting level of inner program units
14220 According to
14221 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14222 package, a task unit, a protected unit, a
14223 protected entry, a generic unit, or an explicitly declared subprogram other
14224 than an enumeration literal.''
14225
14226 @item Maximal nesting level of composite syntactic constructs
14227 This corresponds to the notion of the
14228 maximum nesting level in the GNAT built-in style checks
14229 (@pxref{Style Checking})
14230 @end table
14231
14232 @noindent
14233 For the outermost unit in the file, @command{gnatmetric} additionally computes
14234 the following metrics:
14235
14236 @table @emph
14237 @item Public subprograms
14238 This metric is computed for package specs. It is the
14239 number of subprograms and generic subprograms declared in the visible
14240 part (including the visible part of nested packages, protected objects, and
14241 protected types).
14242
14243 @item All subprograms
14244 This metric is computed for bodies and subunits. The
14245 metric is equal to a total number of subprogram bodies in the compilation
14246 unit.
14247 Neither generic instantiations nor renamings-as-a-body nor body stubs
14248 are counted. Any subprogram body is counted, independently of its nesting
14249 level and enclosing constructs. Generic bodies and bodies of protected
14250 subprograms are counted in the same way as ``usual'' subprogram bodies.
14251
14252 @item Public types
14253 This metric is computed for package specs and
14254 generic package declarations. It is the total number of types
14255 that can be referenced from outside this compilation unit, plus the
14256 number of types from all the visible parts of all the visible generic
14257 packages. Generic formal types are not counted.  Only types, not subtypes,
14258 are included.
14259
14260 @noindent
14261 Along with the total number of public types, the following
14262 types are counted and reported separately:
14263
14264 @itemize @bullet
14265 @item
14266 Abstract types
14267
14268 @item
14269 Root tagged types (abstract, non-abstract, private, non-private). Type
14270 extensions are @emph{not} counted
14271
14272 @item
14273 Private types (including private extensions)
14274
14275 @item
14276 Task types
14277
14278 @item
14279 Protected types
14280
14281 @end itemize
14282
14283 @item All types
14284 This metric is computed for any compilation unit. It is equal to the total
14285 number of the declarations of different types given in the compilation unit.
14286 The private and the corresponding full type declaration are counted as one
14287 type declaration. Incomplete type declarations and generic formal types
14288 are not counted.
14289 No distinction is made among different kinds of types (abstract,
14290 private etc.); the total number of types is computed and reported.
14291
14292 @end table
14293
14294 @noindent
14295 By default, all the syntax metrics are computed and reported. You can use the
14296 following switches to select specific syntax metrics.
14297
14298 @table @option
14299
14300 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14301
14302 @ifclear vms
14303 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14304 @end ifclear
14305
14306 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14307 Report all the syntax metrics
14308
14309 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14310 Do not report any of syntax metrics
14311
14312 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14313 Report the total number of declarations
14314
14315 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14316 Do not report the total number of declarations
14317
14318 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14319 Report the total number of statements
14320
14321 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14322 Do not report the total number of statements
14323
14324 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14325 Report the number of public subprograms in a compilation unit
14326
14327 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14328 Do not report the number of public subprograms in a compilation unit
14329
14330 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14331 Report the number of all the subprograms in a compilation unit
14332
14333 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14334 Do not report the number of all the subprograms in a compilation unit
14335
14336 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14337 Report the number of public types in a compilation unit
14338
14339 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14340 Do not report the number of public types in a compilation unit
14341
14342 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14343 Report the number of all the types in a compilation unit
14344
14345 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14346 Do not report the number of all the types in a compilation unit
14347
14348 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14349 Report the maximal program unit nesting level
14350
14351 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14352 Do not report the maximal program unit nesting level
14353
14354 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14355 Report the maximal construct nesting level
14356
14357 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14358 Do not report the maximal construct nesting level
14359
14360 @end table
14361
14362 @node Complexity Metrics Control
14363 @subsubsection Complexity Metrics Control
14364 @cindex Complexity metrics control in @command{gnatmetric}
14365
14366 @noindent
14367 For a program unit that is an executable body (a subprogram body (including
14368 generic bodies), task body, entry body or a package body containing
14369 its own statement sequence) @command{gnatmetric} computes the following
14370 complexity metrics:
14371
14372 @itemize @bullet
14373 @item
14374 McCabe cyclomatic complexity;
14375
14376 @item
14377 McCabe essential complexity;
14378
14379 @item
14380 maximal loop nesting level;
14381
14382 @item
14383 extra exit points (for subprograms);
14384 @end itemize
14385
14386 @noindent
14387 The McCabe cyclomatic complexity metric is defined
14388 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14389
14390 According to McCabe, both control statements and short-circuit control forms
14391 should be taken into account when computing cyclomatic complexity. For each
14392 body, we compute three metric values:
14393
14394 @itemize @bullet
14395 @item
14396 the complexity introduced by control
14397 statements only, without taking into account short-circuit forms,
14398
14399 @item
14400 the complexity introduced by short-circuit control forms only, and
14401
14402 @item
14403 the total
14404 cyclomatic complexity, which is the sum of these two values.
14405 @end itemize
14406
14407 @noindent
14408
14409 The origin of cyclomatic complexity metric is the need to estimate the number
14410 of independent paths in the control flow graph that in turn gives the number
14411 of tests needed to satisfy paths coverage testing completeness criterion.
14412 Considered from the testing point of view, a static Ada @code{loop} (that is,
14413 the @code{loop} statement having static subtype in loop parameter
14414 specification) does not add to cyclomatic complexity. By providing
14415 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14416 may specify that such loops should not be counted when computing the
14417 cyclomatic complexity metric
14418
14419 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14420 counted for the code that is reduced by excluding all the pure structural Ada
14421 control statements. An compound statement is considered as a non-structural
14422 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14423 or if it contains a @code{goto} statement that transfers the control outside
14424 the operator. A selective accept statement with @code{terminate} alternative
14425 is considered as non-structural statement. When computing this metric,
14426 @code{exit} statements are treated in the same way as @code{goto}
14427 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14428
14429 The Ada essential complexity metric defined here is intended to quantify
14430 the extent to which the software is unstructured. It is adapted from
14431 the McCabe essential complexity metric defined in
14432 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14433 suitable for typical Ada usage. For example, short circuit forms
14434 are not penalized as unstructured in the Ada essential complexity metric.
14435
14436 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14437 the code in the exception handlers and in all the nested program units.
14438
14439 By default, all the complexity metrics are computed and reported.
14440 For more fine-grained control you can use
14441 the following switches:
14442
14443 @table @option
14444 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14445
14446 @ifclear vms
14447 @cindex @option{--no-complexity@var{x}}
14448 @end ifclear
14449
14450 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14451 Report all the complexity metrics
14452
14453 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14454 Do not report any of complexity metrics
14455
14456 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14457 Report the McCabe Cyclomatic Complexity
14458
14459 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14460 Do not report the McCabe Cyclomatic Complexity
14461
14462 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14463 Report the Essential Complexity
14464
14465 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14466 Do not report the Essential Complexity
14467
14468 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14469 Report maximal loop nesting level
14470
14471 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14472 Do not report maximal loop nesting level
14473
14474 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14475 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14476 task bodies, entry bodies and statement sequences in package bodies.
14477 The metric is computed and reported for whole set of processed Ada sources
14478 only.
14479
14480 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14481 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14482 bodies, task bodies, entry bodies and statement sequences in package bodies
14483
14484 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14485 @item ^-ne^/NO_EXITS_AS_GOTOS^
14486 Do not consider @code{exit} statements as @code{goto}s when
14487 computing Essential Complexity
14488
14489 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14490 @item ^--no-static-loop^/NO_STATIC_LOOP^
14491 Do not consider static loops when computing cyclomatic complexity
14492
14493 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14494 Report the extra exit points for subprogram bodies. As an exit point, this
14495 metric counts @code{return} statements and raise statements in case when the
14496 raised exception is not handled in the same body. In case of a function this
14497 metric subtracts 1 from the number of exit points, because a function body
14498 must contain at least one @code{return} statement.
14499
14500 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14501 Do not report the extra exit points for subprogram bodies
14502 @end table
14503
14504
14505 @node Object-Oriented Metrics Control
14506 @subsubsection Object-Oriented Metrics Control
14507 @cindex Object-Oriented metrics control in @command{gnatmetric}
14508
14509 @noindent
14510 @cindex Coupling metrics (in in @command{gnatmetric})
14511 Coupling metrics are object-oriented metrics that measure the
14512 dependencies between a given class (or a group of classes) and the
14513 ``external world'' (that is, the other classes in the program). In this
14514 subsection the term ``class'' is used in its
14515 traditional object-oriented programming sense
14516 (an instantiable module that contains data and/or method members).
14517 A @emph{category} (of classes)
14518 is a group of closely related classes that are reused and/or
14519 modified together.
14520
14521 A class @code{K}'s @emph{efferent coupling} is the number of classes
14522 that @code{K} depends upon.
14523 A category's efferent coupling is the number of classes outside the
14524 category that the classes inside the category depend upon.
14525
14526 A class @code{K}'s @emph{afferent coupling} is the number of classes
14527 that depend upon @code{K}.
14528 A category's afferent coupling is the number of classes outside the
14529 category that depend on classes belonging to the category.
14530
14531 Ada's implementation of the object-oriented paradigm does not use the
14532 traditional class notion, so the definition of the coupling
14533 metrics for Ada maps the class and class category notions
14534 onto Ada constructs.
14535
14536 For the coupling metrics, several kinds of modules -- a library package,
14537 a library generic package, and a library generic package instantiation --
14538 that define a tagged type or an interface type are
14539 considered to be a class. A category consists of a library package (or
14540 a library generic package) that defines a tagged or an interface type,
14541 together with all its descendant (generic) packages that define tagged
14542 or interface types. For any package counted as a class,
14543 its body and subunits (if any) are considered
14544 together with its spec when counting the dependencies, and coupling
14545 metrics are reported for spec units only. For dependencies
14546 between classes, the Ada semantic dependencies are considered.
14547 For coupling metrics, only dependencies on units that are considered as
14548 classes, are considered.
14549
14550 When computing coupling metrics, @command{gnatmetric} counts only
14551 dependencies between units that are arguments of the gnatmetric call.
14552 Coupling metrics are program-wide (or project-wide) metrics, so to
14553 get a valid result, you should call @command{gnatmetric} for
14554 the whole set of sources that make up your program. It can be done
14555 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14556 option (see See @ref{The GNAT Driver and Project Files} for details.
14557
14558 By default, all the coupling metrics are disabled. You can use the following
14559 switches to specify the coupling metrics to be computed and reported:
14560
14561 @table @option
14562
14563 @ifclear vms
14564 @cindex @option{--package@var{x}} (@command{gnatmetric})
14565 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14566 @cindex @option{--category@var{x}} (@command{gnatmetric})
14567 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14568 @end ifclear
14569
14570 @ifset vms
14571 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14572 @end ifset
14573
14574 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14575 Report all the coupling metrics
14576
14577 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14578 Do not report any of  metrics
14579
14580 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14581 Report package efferent coupling
14582
14583 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14584 Do not report package efferent coupling
14585
14586 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14587 Report package afferent coupling
14588
14589 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14590 Do not report package afferent coupling
14591
14592 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14593 Report category efferent coupling
14594
14595 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14596 Do not report category efferent coupling
14597
14598 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14599 Report category afferent coupling
14600
14601 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14602 Do not report category afferent coupling
14603
14604 @end table
14605
14606 @node Other gnatmetric Switches
14607 @subsection Other @code{gnatmetric} Switches
14608
14609 @noindent
14610 Additional @command{gnatmetric} switches are as follows:
14611
14612 @table @option
14613 @item ^-files @var{filename}^/FILES=@var{filename}^
14614 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14615 Take the argument source files from the specified file. This file should be an
14616 ordinary text file containing file names separated by spaces or
14617 line breaks. You can use this switch more than once in the same call to
14618 @command{gnatmetric}. You also can combine this switch with
14619 an explicit list of files.
14620
14621 @item ^-v^/VERBOSE^
14622 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14623 Verbose mode;
14624 @command{gnatmetric} generates version information and then
14625 a trace of sources being processed.
14626
14627 @item ^-q^/QUIET^
14628 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14629 Quiet mode.
14630 @end table
14631
14632 @node Generate project-wide metrics
14633 @subsection Generate project-wide metrics
14634
14635 In order to compute metrics on all units of a given project, you can use
14636 the @command{gnat} driver along with the @option{-P} option:
14637 @smallexample
14638    gnat metric -Pproj
14639 @end smallexample
14640
14641 @noindent
14642 If the project @code{proj} depends upon other projects, you can compute
14643 the metrics on the project closure using the @option{-U} option:
14644 @smallexample
14645    gnat metric -Pproj -U
14646 @end smallexample
14647
14648 @noindent
14649 Finally, if not all the units are relevant to a particular main
14650 program in the project closure, you can generate metrics for the set
14651 of units needed to create a given main program (unit closure) using
14652 the @option{-U} option followed by the name of the main unit:
14653 @smallexample
14654    gnat metric -Pproj -U main
14655 @end smallexample
14656
14657
14658 @c ***********************************
14659 @node File Name Krunching Using gnatkr
14660 @chapter File Name Krunching Using @code{gnatkr}
14661 @findex gnatkr
14662
14663 @noindent
14664 This chapter discusses the method used by the compiler to shorten
14665 the default file names chosen for Ada units so that they do not
14666 exceed the maximum length permitted. It also describes the
14667 @code{gnatkr} utility that can be used to determine the result of
14668 applying this shortening.
14669 @menu
14670 * About gnatkr::
14671 * Using gnatkr::
14672 * Krunching Method::
14673 * Examples of gnatkr Usage::
14674 @end menu
14675
14676 @node About gnatkr
14677 @section About @code{gnatkr}
14678
14679 @noindent
14680 The default file naming rule in GNAT
14681 is that the file name must be derived from
14682 the unit name. The exact default rule is as follows:
14683 @itemize @bullet
14684 @item
14685 Take the unit name and replace all dots by hyphens.
14686 @item
14687 If such a replacement occurs in the
14688 second character position of a name, and the first character is
14689 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14690 then replace the dot by the character
14691 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14692 instead of a minus.
14693 @end itemize
14694 The reason for this exception is to avoid clashes
14695 with the standard names for children of System, Ada, Interfaces,
14696 and GNAT, which use the prefixes
14697 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14698 respectively.
14699
14700 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14701 switch of the compiler activates a ``krunching''
14702 circuit that limits file names to nn characters (where nn is a decimal
14703 integer). For example, using OpenVMS,
14704 where the maximum file name length is
14705 39, the value of nn is usually set to 39, but if you want to generate
14706 a set of files that would be usable if ported to a system with some
14707 different maximum file length, then a different value can be specified.
14708 The default value of 39 for OpenVMS need not be specified.
14709
14710 The @code{gnatkr} utility can be used to determine the krunched name for
14711 a given file, when krunched to a specified maximum length.
14712
14713 @node Using gnatkr
14714 @section Using @code{gnatkr}
14715
14716 @noindent
14717 The @code{gnatkr} command has the form
14718
14719 @ifclear vms
14720 @smallexample
14721 @c $ gnatkr @var{name} @ovar{length}
14722 @c Expanding @ovar macro inline (explanation in macro def comments)
14723 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14724 @end smallexample
14725 @end ifclear
14726
14727 @ifset vms
14728 @smallexample
14729 $ gnatkr @var{name} /COUNT=nn
14730 @end smallexample
14731 @end ifset
14732
14733 @noindent
14734 @var{name} is the uncrunched file name, derived from the name of the unit
14735 in the standard manner described in the previous section (i.e., in particular
14736 all dots are replaced by hyphens). The file name may or may not have an
14737 extension (defined as a suffix of the form period followed by arbitrary
14738 characters other than period). If an extension is present then it will
14739 be preserved in the output. For example, when krunching @file{hellofile.ads}
14740 to eight characters, the result will be hellofil.ads.
14741
14742 Note: for compatibility with previous versions of @code{gnatkr} dots may
14743 appear in the name instead of hyphens, but the last dot will always be
14744 taken as the start of an extension. So if @code{gnatkr} is given an argument
14745 such as @file{Hello.World.adb} it will be treated exactly as if the first
14746 period had been a hyphen, and for example krunching to eight characters
14747 gives the result @file{hellworl.adb}.
14748
14749 Note that the result is always all lower case (except on OpenVMS where it is
14750 all upper case). Characters of the other case are folded as required.
14751
14752 @var{length} represents the length of the krunched name. The default
14753 when no argument is given is ^8^39^ characters. A length of zero stands for
14754 unlimited, in other words do not chop except for system files where the
14755 implied crunching length is always eight characters.
14756
14757 @noindent
14758 The output is the krunched name. The output has an extension only if the
14759 original argument was a file name with an extension.
14760
14761 @node Krunching Method
14762 @section Krunching Method
14763
14764 @noindent
14765 The initial file name is determined by the name of the unit that the file
14766 contains. The name is formed by taking the full expanded name of the
14767 unit and replacing the separating dots with hyphens and
14768 using ^lowercase^uppercase^
14769 for all letters, except that a hyphen in the second character position is
14770 replaced by a ^tilde^dollar sign^ if the first character is
14771 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14772 The extension is @code{.ads} for a
14773 spec and @code{.adb} for a body.
14774 Krunching does not affect the extension, but the file name is shortened to
14775 the specified length by following these rules:
14776
14777 @itemize @bullet
14778 @item
14779 The name is divided into segments separated by hyphens, tildes or
14780 underscores and all hyphens, tildes, and underscores are
14781 eliminated. If this leaves the name short enough, we are done.
14782
14783 @item
14784 If the name is too long, the longest segment is located (left-most
14785 if there are two of equal length), and shortened by dropping
14786 its last character. This is repeated until the name is short enough.
14787
14788 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14789 to fit the name into 8 characters as required by some operating systems.
14790
14791 @smallexample
14792 our-strings-wide_fixed 22
14793 our strings wide fixed 19
14794 our string  wide fixed 18
14795 our strin   wide fixed 17
14796 our stri    wide fixed 16
14797 our stri    wide fixe  15
14798 our str     wide fixe  14
14799 our str     wid  fixe  13
14800 our str     wid  fix   12
14801 ou  str     wid  fix   11
14802 ou  st      wid  fix   10
14803 ou  st      wi   fix   9
14804 ou  st      wi   fi    8
14805 Final file name: oustwifi.adb
14806 @end smallexample
14807
14808 @item
14809 The file names for all predefined units are always krunched to eight
14810 characters. The krunching of these predefined units uses the following
14811 special prefix replacements:
14812
14813 @table @file
14814 @item ada-
14815 replaced by @file{^a^A^-}
14816
14817 @item gnat-
14818 replaced by @file{^g^G^-}
14819
14820 @item interfaces-
14821 replaced by @file{^i^I^-}
14822
14823 @item system-
14824 replaced by @file{^s^S^-}
14825 @end table
14826
14827 These system files have a hyphen in the second character position. That
14828 is why normal user files replace such a character with a
14829 ^tilde^dollar sign^, to
14830 avoid confusion with system file names.
14831
14832 As an example of this special rule, consider
14833 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14834
14835 @smallexample
14836 ada-strings-wide_fixed 22
14837 a-  strings wide fixed 18
14838 a-  string  wide fixed 17
14839 a-  strin   wide fixed 16
14840 a-  stri    wide fixed 15
14841 a-  stri    wide fixe  14
14842 a-  str     wide fixe  13
14843 a-  str     wid  fixe  12
14844 a-  str     wid  fix   11
14845 a-  st      wid  fix   10
14846 a-  st      wi   fix   9
14847 a-  st      wi   fi    8
14848 Final file name: a-stwifi.adb
14849 @end smallexample
14850 @end itemize
14851
14852 Of course no file shortening algorithm can guarantee uniqueness over all
14853 possible unit names, and if file name krunching is used then it is your
14854 responsibility to ensure that no name clashes occur. The utility
14855 program @code{gnatkr} is supplied for conveniently determining the
14856 krunched name of a file.
14857
14858 @node Examples of gnatkr Usage
14859 @section Examples of @code{gnatkr} Usage
14860
14861 @smallexample
14862 @iftex
14863 @leftskip=0cm
14864 @end iftex
14865 @ifclear vms
14866 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14867 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14868 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14869 $ gnatkr grandparent-parent-child     --> grparchi
14870 @end ifclear
14871 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14872 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14873 @end smallexample
14874
14875 @node Preprocessing Using gnatprep
14876 @chapter Preprocessing Using @code{gnatprep}
14877 @findex gnatprep
14878
14879 @noindent
14880 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14881 preprocessing.
14882 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14883 special GNAT features.
14884 For further discussion of conditional compilation in general, see
14885 @ref{Conditional Compilation}.
14886
14887 @menu
14888 * Preprocessing Symbols::
14889 * Using gnatprep::
14890 * Switches for gnatprep::
14891 * Form of Definitions File::
14892 * Form of Input Text for gnatprep::
14893 @end menu
14894
14895 @node Preprocessing Symbols
14896 @section Preprocessing Symbols
14897
14898 @noindent
14899 Preprocessing symbols are defined in definition files and referred to in
14900 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14901 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14902 all characters need to be in the ASCII set (no accented letters).
14903
14904 @node Using gnatprep
14905 @section Using @code{gnatprep}
14906
14907 @noindent
14908 To call @code{gnatprep} use
14909
14910 @smallexample
14911 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14912 @c Expanding @ovar macro inline (explanation in macro def comments)
14913 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14914 @end smallexample
14915
14916 @noindent
14917 where
14918 @table @var
14919 @item switches
14920 is an optional sequence of switches as described in the next section.
14921
14922 @item infile
14923 is the full name of the input file, which is an Ada source
14924 file containing preprocessor directives.
14925
14926 @item outfile
14927 is the full name of the output file, which is an Ada source
14928 in standard Ada form. When used with GNAT, this file name will
14929 normally have an ads or adb suffix.
14930
14931 @item deffile
14932 is the full name of a text file containing definitions of
14933 preprocessing symbols to be referenced by the preprocessor. This argument is
14934 optional, and can be replaced by the use of the @option{-D} switch.
14935
14936 @end table
14937
14938 @node Switches for gnatprep
14939 @section Switches for @code{gnatprep}
14940
14941 @table @option
14942 @c !sort!
14943
14944 @item ^-b^/BLANK_LINES^
14945 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14946 Causes both preprocessor lines and the lines deleted by
14947 preprocessing to be replaced by blank lines in the output source file,
14948 preserving line numbers in the output file.
14949
14950 @item ^-c^/COMMENTS^
14951 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14952 Causes both preprocessor lines and the lines deleted
14953 by preprocessing to be retained in the output source as comments marked
14954 with the special string @code{"--! "}. This option will result in line numbers
14955 being preserved in the output file.
14956
14957 @item ^-C^/REPLACE_IN_COMMENTS^
14958 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14959 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14960 If this option is specified, then comments are scanned and any $symbol
14961 substitutions performed as in program text. This is particularly useful
14962 when structured comments are used (e.g., when writing programs in the
14963 SPARK dialect of Ada). Note that this switch is not available when
14964 doing integrated preprocessing (it would be useless in this context
14965 since comments are ignored by the compiler in any case).
14966
14967 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14968 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14969 Defines a new preprocessing symbol, associated with value. If no value is given
14970 on the command line, then symbol is considered to be @code{True}. This switch
14971 can be used in place of a definition file.
14972
14973 @ifset vms
14974 @item /REMOVE
14975 @cindex @option{/REMOVE} (@command{gnatprep})
14976 This is the default setting which causes lines deleted by preprocessing
14977 to be entirely removed from the output file.
14978 @end ifset
14979
14980 @item ^-r^/REFERENCE^
14981 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14982 Causes a @code{Source_Reference} pragma to be generated that
14983 references the original input file, so that error messages will use
14984 the file name of this original file. The use of this switch implies
14985 that preprocessor lines are not to be removed from the file, so its
14986 use will force @option{^-b^/BLANK_LINES^} mode if
14987 @option{^-c^/COMMENTS^}
14988 has not been specified explicitly.
14989
14990 Note that if the file to be preprocessed contains multiple units, then
14991 it will be necessary to @code{gnatchop} the output file from
14992 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14993 in the preprocessed file, it will be respected by
14994 @code{gnatchop ^-r^/REFERENCE^}
14995 so that the final chopped files will correctly refer to the original
14996 input source file for @code{gnatprep}.
14997
14998 @item ^-s^/SYMBOLS^
14999 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15000 Causes a sorted list of symbol names and values to be
15001 listed on the standard output file.
15002
15003 @item ^-u^/UNDEFINED^
15004 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15005 Causes undefined symbols to be treated as having the value FALSE in the context
15006 of a preprocessor test. In the absence of this option, an undefined symbol in
15007 a @code{#if} or @code{#elsif} test will be treated as an error.
15008
15009 @end table
15010
15011 @ifclear vms
15012 @noindent
15013 Note: if neither @option{-b} nor @option{-c} is present,
15014 then preprocessor lines and
15015 deleted lines are completely removed from the output, unless -r is
15016 specified, in which case -b is assumed.
15017 @end ifclear
15018
15019 @node Form of Definitions File
15020 @section Form of Definitions File
15021
15022 @noindent
15023 The definitions file contains lines of the form
15024
15025 @smallexample
15026 symbol := value
15027 @end smallexample
15028
15029 @noindent
15030 where symbol is a preprocessing symbol, and value is one of the following:
15031
15032 @itemize @bullet
15033 @item
15034 Empty, corresponding to a null substitution
15035 @item
15036 A string literal using normal Ada syntax
15037 @item
15038 Any sequence of characters from the set
15039 (letters, digits, period, underline).
15040 @end itemize
15041
15042 @noindent
15043 Comment lines may also appear in the definitions file, starting with
15044 the usual @code{--},
15045 and comments may be added to the definitions lines.
15046
15047 @node Form of Input Text for gnatprep
15048 @section Form of Input Text for @code{gnatprep}
15049
15050 @noindent
15051 The input text may contain preprocessor conditional inclusion lines,
15052 as well as general symbol substitution sequences.
15053
15054 The preprocessor conditional inclusion commands have the form
15055
15056 @smallexample
15057 @group
15058 @cartouche
15059 #if @i{expression} @r{[}then@r{]}
15060    lines
15061 #elsif @i{expression} @r{[}then@r{]}
15062    lines
15063 #elsif @i{expression} @r{[}then@r{]}
15064    lines
15065 @dots{}
15066 #else
15067    lines
15068 #end if;
15069 @end cartouche
15070 @end group
15071 @end smallexample
15072
15073 @noindent
15074 In this example, @i{expression} is defined by the following grammar:
15075 @smallexample
15076 @i{expression} ::=  <symbol>
15077 @i{expression} ::=  <symbol> = "<value>"
15078 @i{expression} ::=  <symbol> = <symbol>
15079 @i{expression} ::=  <symbol> 'Defined
15080 @i{expression} ::=  not @i{expression}
15081 @i{expression} ::=  @i{expression} and @i{expression}
15082 @i{expression} ::=  @i{expression} or @i{expression}
15083 @i{expression} ::=  @i{expression} and then @i{expression}
15084 @i{expression} ::=  @i{expression} or else @i{expression}
15085 @i{expression} ::=  ( @i{expression} )
15086 @end smallexample
15087
15088 The following restriction exists: it is not allowed to have "and" or "or"
15089 following "not" in the same expression without parentheses. For example, this
15090 is not allowed:
15091
15092 @smallexample
15093    not X or Y
15094 @end smallexample
15095
15096 This should be one of the following:
15097
15098 @smallexample
15099    (not X) or Y
15100    not (X or Y)
15101 @end smallexample
15102
15103 @noindent
15104 For the first test (@i{expression} ::= <symbol>) the symbol must have
15105 either the value true or false, that is to say the right-hand of the
15106 symbol definition must be one of the (case-insensitive) literals
15107 @code{True} or @code{False}. If the value is true, then the
15108 corresponding lines are included, and if the value is false, they are
15109 excluded.
15110
15111 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15112 the symbol has been defined in the definition file or by a @option{-D}
15113 switch on the command line. Otherwise, the test is false.
15114
15115 The equality tests are case insensitive, as are all the preprocessor lines.
15116
15117 If the symbol referenced is not defined in the symbol definitions file,
15118 then the effect depends on whether or not switch @option{-u}
15119 is specified. If so, then the symbol is treated as if it had the value
15120 false and the test fails. If this switch is not specified, then
15121 it is an error to reference an undefined symbol. It is also an error to
15122 reference a symbol that is defined with a value other than @code{True}
15123 or @code{False}.
15124
15125 The use of the @code{not} operator inverts the sense of this logical test.
15126 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15127 operators, without parentheses. For example, "if not X or Y then" is not
15128 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15129
15130 The @code{then} keyword is optional as shown
15131
15132 The @code{#} must be the first non-blank character on a line, but
15133 otherwise the format is free form. Spaces or tabs may appear between
15134 the @code{#} and the keyword. The keywords and the symbols are case
15135 insensitive as in normal Ada code. Comments may be used on a
15136 preprocessor line, but other than that, no other tokens may appear on a
15137 preprocessor line. Any number of @code{elsif} clauses can be present,
15138 including none at all. The @code{else} is optional, as in Ada.
15139
15140 The @code{#} marking the start of a preprocessor line must be the first
15141 non-blank character on the line, i.e., it must be preceded only by
15142 spaces or horizontal tabs.
15143
15144 Symbol substitution outside of preprocessor lines is obtained by using
15145 the sequence
15146
15147 @smallexample
15148 $symbol
15149 @end smallexample
15150
15151 @noindent
15152 anywhere within a source line, except in a comment or within a
15153 string literal. The identifier
15154 following the @code{$} must match one of the symbols defined in the symbol
15155 definition file, and the result is to substitute the value of the
15156 symbol in place of @code{$symbol} in the output file.
15157
15158 Note that although the substitution of strings within a string literal
15159 is not possible, it is possible to have a symbol whose defined value is
15160 a string literal. So instead of setting XYZ to @code{hello} and writing:
15161
15162 @smallexample
15163 Header : String := "$XYZ";
15164 @end smallexample
15165
15166 @noindent
15167 you should set XYZ to @code{"hello"} and write:
15168
15169 @smallexample
15170 Header : String := $XYZ;
15171 @end smallexample
15172
15173 @noindent
15174 and then the substitution will occur as desired.
15175
15176 @node The GNAT Library Browser gnatls
15177 @chapter The GNAT Library Browser @code{gnatls}
15178 @findex gnatls
15179 @cindex Library browser
15180
15181 @noindent
15182 @code{gnatls} is a tool that outputs information about compiled
15183 units. It gives the relationship between objects, unit names and source
15184 files. It can also be used to check the source dependencies of a unit
15185 as well as various characteristics.
15186
15187 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15188 driver (see @ref{The GNAT Driver and Project Files}).
15189
15190 @menu
15191 * Running gnatls::
15192 * Switches for gnatls::
15193 * Examples of gnatls Usage::
15194 @end menu
15195
15196 @node Running gnatls
15197 @section Running @code{gnatls}
15198
15199 @noindent
15200 The @code{gnatls} command has the form
15201
15202 @smallexample
15203 $ gnatls switches @var{object_or_ali_file}
15204 @end smallexample
15205
15206 @noindent
15207 The main argument is the list of object or @file{ali} files
15208 (@pxref{The Ada Library Information Files})
15209 for which information is requested.
15210
15211 In normal mode, without additional option, @code{gnatls} produces a
15212 four-column listing. Each line represents information for a specific
15213 object. The first column gives the full path of the object, the second
15214 column gives the name of the principal unit in this object, the third
15215 column gives the status of the source and the fourth column gives the
15216 full path of the source representing this unit.
15217 Here is a simple example of use:
15218
15219 @smallexample
15220 $ gnatls *.o
15221 ^./^[]^demo1.o            demo1            DIF demo1.adb
15222 ^./^[]^demo2.o            demo2             OK demo2.adb
15223 ^./^[]^hello.o            h1                OK hello.adb
15224 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15225 ^./^[]^instr.o            instr             OK instr.adb
15226 ^./^[]^tef.o              tef              DIF tef.adb
15227 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15228 ^./^[]^tgef.o             tgef             DIF tgef.adb
15229 @end smallexample
15230
15231 @noindent
15232 The first line can be interpreted as follows: the main unit which is
15233 contained in
15234 object file @file{demo1.o} is demo1, whose main source is in
15235 @file{demo1.adb}. Furthermore, the version of the source used for the
15236 compilation of demo1 has been modified (DIF). Each source file has a status
15237 qualifier which can be:
15238
15239 @table @code
15240 @item OK (unchanged)
15241 The version of the source file used for the compilation of the
15242 specified unit corresponds exactly to the actual source file.
15243
15244 @item MOK (slightly modified)
15245 The version of the source file used for the compilation of the
15246 specified unit differs from the actual source file but not enough to
15247 require recompilation. If you use gnatmake with the qualifier
15248 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15249 MOK will not be recompiled.
15250
15251 @item DIF (modified)
15252 No version of the source found on the path corresponds to the source
15253 used to build this object.
15254
15255 @item ??? (file not found)
15256 No source file was found for this unit.
15257
15258 @item HID (hidden,  unchanged version not first on PATH)
15259 The version of the source that corresponds exactly to the source used
15260 for compilation has been found on the path but it is hidden by another
15261 version of the same source that has been modified.
15262
15263 @end table
15264
15265 @node Switches for gnatls
15266 @section Switches for @code{gnatls}
15267
15268 @noindent
15269 @code{gnatls} recognizes the following switches:
15270
15271 @table @option
15272 @c !sort!
15273 @cindex @option{--version} @command{gnatls}
15274 Display Copyright and version, then exit disregarding all other options.
15275
15276 @item --help
15277 @cindex @option{--help} @command{gnatls}
15278 If @option{--version} was not used, display usage, then exit disregarding
15279 all other options.
15280
15281 @item ^-a^/ALL_UNITS^
15282 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15283 Consider all units, including those of the predefined Ada library.
15284 Especially useful with @option{^-d^/DEPENDENCIES^}.
15285
15286 @item ^-d^/DEPENDENCIES^
15287 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15288 List sources from which specified units depend on.
15289
15290 @item ^-h^/OUTPUT=OPTIONS^
15291 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15292 Output the list of options.
15293
15294 @item ^-o^/OUTPUT=OBJECTS^
15295 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15296 Only output information about object files.
15297
15298 @item ^-s^/OUTPUT=SOURCES^
15299 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15300 Only output information about source files.
15301
15302 @item ^-u^/OUTPUT=UNITS^
15303 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15304 Only output information about compilation units.
15305
15306 @item ^-files^/FILES^=@var{file}
15307 @cindex @option{^-files^/FILES^} (@code{gnatls})
15308 Take as arguments the files listed in text file @var{file}.
15309 Text file @var{file} may contain empty lines that are ignored.
15310 Each nonempty line should contain the name of an existing file.
15311 Several such switches may be specified simultaneously.
15312
15313 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15314 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15315 @itemx ^-I^/SEARCH=^@var{dir}
15316 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15317 @itemx -nostdinc
15318 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15319 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15320 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15321 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15322 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15323 flags (@pxref{Switches for gnatmake}).
15324
15325 @item --RTS=@var{rts-path}
15326 @cindex @option{--RTS} (@code{gnatls})
15327 Specifies the default location of the runtime library. Same meaning as the
15328 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15329
15330 @item ^-v^/OUTPUT=VERBOSE^
15331 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15332 Verbose mode. Output the complete source, object and project paths. Do not use
15333 the default column layout but instead use long format giving as much as
15334 information possible on each requested units, including special
15335 characteristics such as:
15336
15337 @table @code
15338 @item  Preelaborable
15339 The unit is preelaborable in the Ada sense.
15340
15341 @item No_Elab_Code
15342 No elaboration code has been produced by the compiler for this unit.
15343
15344 @item Pure
15345 The unit is pure in the Ada sense.
15346
15347 @item Elaborate_Body
15348 The unit contains a pragma Elaborate_Body.
15349
15350 @item Remote_Types
15351 The unit contains a pragma Remote_Types.
15352
15353 @item Shared_Passive
15354 The unit contains a pragma Shared_Passive.
15355
15356 @item Predefined
15357 This unit is part of the predefined environment and cannot be modified
15358 by the user.
15359
15360 @item Remote_Call_Interface
15361 The unit contains a pragma Remote_Call_Interface.
15362
15363 @end table
15364
15365 @end table
15366
15367 @node Examples of gnatls Usage
15368 @section Example of @code{gnatls} Usage
15369 @ifclear vms
15370
15371 @noindent
15372 Example of using the verbose switch. Note how the source and
15373 object paths are affected by the -I switch.
15374
15375 @smallexample
15376 $ gnatls -v -I.. demo1.o
15377
15378 GNATLS 5.03w (20041123-34)
15379 Copyright 1997-2004 Free Software Foundation, Inc.
15380
15381 Source Search Path:
15382    <Current_Directory>
15383    ../
15384    /home/comar/local/adainclude/
15385
15386 Object Search Path:
15387    <Current_Directory>
15388    ../
15389    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15390
15391 Project Search Path:
15392    <Current_Directory>
15393    /home/comar/local/lib/gnat/
15394
15395 ./demo1.o
15396    Unit =>
15397      Name   => demo1
15398      Kind   => subprogram body
15399      Flags  => No_Elab_Code
15400      Source => demo1.adb    modified
15401 @end smallexample
15402
15403 @noindent
15404 The following is an example of use of the dependency list.
15405 Note the use of the -s switch
15406 which gives a straight list of source files. This can be useful for
15407 building specialized scripts.
15408
15409 @smallexample
15410 $ gnatls -d demo2.o
15411 ./demo2.o   demo2        OK demo2.adb
15412                          OK gen_list.ads
15413                          OK gen_list.adb
15414                          OK instr.ads
15415                          OK instr-child.ads
15416
15417 $ gnatls -d -s -a demo1.o
15418 demo1.adb
15419 /home/comar/local/adainclude/ada.ads
15420 /home/comar/local/adainclude/a-finali.ads
15421 /home/comar/local/adainclude/a-filico.ads
15422 /home/comar/local/adainclude/a-stream.ads
15423 /home/comar/local/adainclude/a-tags.ads
15424 gen_list.ads
15425 gen_list.adb
15426 /home/comar/local/adainclude/gnat.ads
15427 /home/comar/local/adainclude/g-io.ads
15428 instr.ads
15429 /home/comar/local/adainclude/system.ads
15430 /home/comar/local/adainclude/s-exctab.ads
15431 /home/comar/local/adainclude/s-finimp.ads
15432 /home/comar/local/adainclude/s-finroo.ads
15433 /home/comar/local/adainclude/s-secsta.ads
15434 /home/comar/local/adainclude/s-stalib.ads
15435 /home/comar/local/adainclude/s-stoele.ads
15436 /home/comar/local/adainclude/s-stratt.ads
15437 /home/comar/local/adainclude/s-tasoli.ads
15438 /home/comar/local/adainclude/s-unstyp.ads
15439 /home/comar/local/adainclude/unchconv.ads
15440 @end smallexample
15441 @end ifclear
15442
15443 @ifset vms
15444 @smallexample
15445 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15446
15447 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15448 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15449 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15450 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15451 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15452 demo1.adb
15453 gen_list.ads
15454 gen_list.adb
15455 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15456 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15457 instr.ads
15458 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15459 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15460 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15461 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15462 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15463 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15464 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15465 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15466 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15467 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15468 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15469 @end smallexample
15470 @end ifset
15471
15472 @node Cleaning Up Using gnatclean
15473 @chapter Cleaning Up Using @code{gnatclean}
15474 @findex gnatclean
15475 @cindex Cleaning tool
15476
15477 @noindent
15478 @code{gnatclean} is a tool that allows the deletion of files produced by the
15479 compiler, binder and linker, including ALI files, object files, tree files,
15480 expanded source files, library files, interface copy source files, binder
15481 generated files and executable files.
15482
15483 @menu
15484 * Running gnatclean::
15485 * Switches for gnatclean::
15486 @c * Examples of gnatclean Usage::
15487 @end menu
15488
15489 @node Running gnatclean
15490 @section Running @code{gnatclean}
15491
15492 @noindent
15493 The @code{gnatclean} command has the form:
15494
15495 @smallexample
15496 $ gnatclean switches @var{names}
15497 @end smallexample
15498
15499 @noindent
15500 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15501 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15502 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15503
15504 @noindent
15505 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15506 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15507 the linker. In informative-only mode, specified by switch
15508 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15509 normal mode is listed, but no file is actually deleted.
15510
15511 @node Switches for gnatclean
15512 @section Switches for @code{gnatclean}
15513
15514 @noindent
15515 @code{gnatclean} recognizes the following switches:
15516
15517 @table @option
15518 @c !sort!
15519 @cindex @option{--version} @command{gnatclean}
15520 Display Copyright and version, then exit disregarding all other options.
15521
15522 @item --help
15523 @cindex @option{--help} @command{gnatclean}
15524 If @option{--version} was not used, display usage, then exit disregarding
15525 all other options.
15526
15527 @item ^--subdirs^/SUBDIRS^=subdir
15528 Actual object directory of each project file is the subdirectory subdir of the
15529 object directory specified or defaulted in the project file.
15530
15531 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15532 By default, shared library projects are not allowed to import static library
15533 projects. When this switch is used on the command line, this restriction is
15534 relaxed.
15535
15536 @item ^-c^/COMPILER_FILES_ONLY^
15537 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15538 Only attempt to delete the files produced by the compiler, not those produced
15539 by the binder or the linker. The files that are not to be deleted are library
15540 files, interface copy files, binder generated files and executable files.
15541
15542 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15543 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15544 Indicate that ALI and object files should normally be found in directory
15545 @var{dir}.
15546
15547 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15548 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15549 When using project files, if some errors or warnings are detected during
15550 parsing and verbose mode is not in effect (no use of switch
15551 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15552 file, rather than its simple file name.
15553
15554 @item ^-h^/HELP^
15555 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15556 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15557
15558 @item ^-n^/NODELETE^
15559 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15560 Informative-only mode. Do not delete any files. Output the list of the files
15561 that would have been deleted if this switch was not specified.
15562
15563 @item ^-P^/PROJECT_FILE=^@var{project}
15564 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15565 Use project file @var{project}. Only one such switch can be used.
15566 When cleaning a project file, the files produced by the compilation of the
15567 immediate sources or inherited sources of the project files are to be
15568 deleted. This is not depending on the presence or not of executable names
15569 on the command line.
15570
15571 @item ^-q^/QUIET^
15572 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15573 Quiet output. If there are no errors, do not output anything, except in
15574 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15575 (switch ^-n^/NODELETE^).
15576
15577 @item ^-r^/RECURSIVE^
15578 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15579 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15580 clean all imported and extended project files, recursively. If this switch
15581 is not specified, only the files related to the main project file are to be
15582 deleted. This switch has no effect if no project file is specified.
15583
15584 @item ^-v^/VERBOSE^
15585 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15586 Verbose mode.
15587
15588 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15589 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15590 Indicates the verbosity of the parsing of GNAT project files.
15591 @xref{Switches Related to Project Files}.
15592
15593 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15594 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15595 Indicates that external variable @var{name} has the value @var{value}.
15596 The Project Manager will use this value for occurrences of
15597 @code{external(name)} when parsing the project file.
15598 @xref{Switches Related to Project Files}.
15599
15600 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15601 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15602 When searching for ALI and object files, look in directory
15603 @var{dir}.
15604
15605 @item ^-I^/SEARCH=^@var{dir}
15606 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15607 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15608
15609 @item ^-I-^/NOCURRENT_DIRECTORY^
15610 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15611 @cindex Source files, suppressing search
15612 Do not look for ALI or object files in the directory
15613 where @code{gnatclean} was invoked.
15614
15615 @end table
15616
15617 @c @node Examples of gnatclean Usage
15618 @c @section Examples of @code{gnatclean} Usage
15619
15620 @ifclear vms
15621 @node GNAT and Libraries
15622 @chapter GNAT and Libraries
15623 @cindex Library, building, installing, using
15624
15625 @noindent
15626 This chapter describes how to build and use libraries with GNAT, and also shows
15627 how to recompile the GNAT run-time library. You should be familiar with the
15628 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15629 chapter.
15630
15631 @menu
15632 * Introduction to Libraries in GNAT::
15633 * General Ada Libraries::
15634 * Stand-alone Ada Libraries::
15635 * Rebuilding the GNAT Run-Time Library::
15636 @end menu
15637
15638 @node Introduction to Libraries in GNAT
15639 @section Introduction to Libraries in GNAT
15640
15641 @noindent
15642 A library is, conceptually, a collection of objects which does not have its
15643 own main thread of execution, but rather provides certain services to the
15644 applications that use it. A library can be either statically linked with the
15645 application, in which case its code is directly included in the application,
15646 or, on platforms that support it, be dynamically linked, in which case
15647 its code is shared by all applications making use of this library.
15648
15649 GNAT supports both types of libraries.
15650 In the static case, the compiled code can be provided in different ways. The
15651 simplest approach is to provide directly the set of objects resulting from
15652 compilation of the library source files. Alternatively, you can group the
15653 objects into an archive using whatever commands are provided by the operating
15654 system. For the latter case, the objects are grouped into a shared library.
15655
15656 In the GNAT environment, a library has three types of components:
15657 @itemize @bullet
15658 @item
15659 Source files.
15660 @item
15661 @file{ALI} files.
15662 @xref{The Ada Library Information Files}.
15663 @item
15664 Object files, an archive or a shared library.
15665 @end itemize
15666
15667 @noindent
15668 A GNAT library may expose all its source files, which is useful for
15669 documentation purposes. Alternatively, it may expose only the units needed by
15670 an external user to make use of the library. That is to say, the specs
15671 reflecting the library services along with all the units needed to compile
15672 those specs, which can include generic bodies or any body implementing an
15673 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15674 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15675
15676 All compilation units comprising an application, including those in a library,
15677 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15678 computes the elaboration order from the @file{ALI} files and this is why they
15679 constitute a mandatory part of GNAT libraries.
15680 @emph{Stand-alone libraries} are the exception to this rule because a specific
15681 library elaboration routine is produced independently of the application(s)
15682 using the library.
15683
15684 @node General Ada Libraries
15685 @section General Ada Libraries
15686
15687 @menu
15688 * Building a library::
15689 * Installing a library::
15690 * Using a library::
15691 @end menu
15692
15693 @node Building a library
15694 @subsection Building a library
15695
15696 @noindent
15697 The easiest way to build a library is to use the Project Manager,
15698 which supports a special type of project called a @emph{Library Project}
15699 (@pxref{Library Projects}).
15700
15701 A project is considered a library project, when two project-level attributes
15702 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15703 control different aspects of library configuration, additional optional
15704 project-level attributes can be specified:
15705 @table @code
15706 @item Library_Kind
15707 This attribute controls whether the library is to be static or dynamic
15708
15709 @item Library_Version
15710 This attribute specifies the library version; this value is used
15711 during dynamic linking of shared libraries to determine if the currently
15712 installed versions of the binaries are compatible.
15713
15714 @item Library_Options
15715 @item Library_GCC
15716 These attributes specify additional low-level options to be used during
15717 library generation, and redefine the actual application used to generate
15718 library.
15719 @end table
15720
15721 @noindent
15722 The GNAT Project Manager takes full care of the library maintenance task,
15723 including recompilation of the source files for which objects do not exist
15724 or are not up to date, assembly of the library archive, and installation of
15725 the library (i.e., copying associated source, object and @file{ALI} files
15726 to the specified location).
15727
15728 Here is a simple library project file:
15729 @smallexample @c ada
15730 project My_Lib is
15731    for Source_Dirs use ("src1", "src2");
15732    for Object_Dir use "obj";
15733    for Library_Name use "mylib";
15734    for Library_Dir use "lib";
15735    for Library_Kind use "dynamic";
15736 end My_lib;
15737 @end smallexample
15738
15739 @noindent
15740 and the compilation command to build and install the library:
15741
15742 @smallexample @c ada
15743   $ gnatmake -Pmy_lib
15744 @end smallexample
15745
15746 @noindent
15747 It is not entirely trivial to perform manually all the steps required to
15748 produce a library. We recommend that you use the GNAT Project Manager
15749 for this task. In special cases where this is not desired, the necessary
15750 steps are discussed below.
15751
15752 There are various possibilities for compiling the units that make up the
15753 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15754 with a conventional script. For simple libraries, it is also possible to create
15755 a dummy main program which depends upon all the packages that comprise the
15756 interface of the library. This dummy main program can then be given to
15757 @command{gnatmake}, which will ensure that all necessary objects are built.
15758
15759 After this task is accomplished, you should follow the standard procedure
15760 of the underlying operating system to produce the static or shared library.
15761
15762 Here is an example of such a dummy program:
15763 @smallexample @c ada
15764 @group
15765 with My_Lib.Service1;
15766 with My_Lib.Service2;
15767 with My_Lib.Service3;
15768 procedure My_Lib_Dummy is
15769 begin
15770    null;
15771 end;
15772 @end group
15773 @end smallexample
15774
15775 @noindent
15776 Here are the generic commands that will build an archive or a shared library.
15777
15778 @smallexample
15779 # compiling the library
15780 $ gnatmake -c my_lib_dummy.adb
15781
15782 # we don't need the dummy object itself
15783 $ rm my_lib_dummy.o my_lib_dummy.ali
15784
15785 # create an archive with the remaining objects
15786 $ ar rc libmy_lib.a *.o
15787 # some systems may require "ranlib" to be run as well
15788
15789 # or create a shared library
15790 $ gcc -shared -o libmy_lib.so *.o
15791 # some systems may require the code to have been compiled with -fPIC
15792
15793 # remove the object files that are now in the library
15794 $ rm *.o
15795
15796 # Make the ALI files read-only so that gnatmake will not try to
15797 # regenerate the objects that are in the library
15798 $ chmod -w *.ali
15799 @end smallexample
15800
15801 @noindent
15802 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15803 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15804 be accessed by the directive @option{-l@var{xxx}} at link time.
15805
15806 @node Installing a library
15807 @subsection Installing a library
15808 @cindex @code{ADA_PROJECT_PATH}
15809 @cindex @code{GPR_PROJECT_PATH}
15810
15811 @noindent
15812 If you use project files, library installation is part of the library build
15813 process (@pxref{Installing a library with project files}).
15814
15815 When project files are not an option, it is also possible, but not recommended,
15816 to install the library so that the sources needed to use the library are on the
15817 Ada source path and the ALI files & libraries be on the Ada Object path (see
15818 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15819 administrator can place general-purpose libraries in the default compiler
15820 paths, by specifying the libraries' location in the configuration files
15821 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15822 must be located in the GNAT installation tree at the same place as the gcc spec
15823 file. The location of the gcc spec file can be determined as follows:
15824 @smallexample
15825 $ gcc -v
15826 @end smallexample
15827
15828 @noindent
15829 The configuration files mentioned above have a simple format: each line
15830 must contain one unique directory name.
15831 Those names are added to the corresponding path
15832 in their order of appearance in the file. The names can be either absolute
15833 or relative; in the latter case, they are relative to where theses files
15834 are located.
15835
15836 The files @file{ada_source_path} and @file{ada_object_path} might not be
15837 present in a
15838 GNAT installation, in which case, GNAT will look for its run-time library in
15839 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15840 objects and @file{ALI} files). When the files exist, the compiler does not
15841 look in @file{adainclude} and @file{adalib}, and thus the
15842 @file{ada_source_path} file
15843 must contain the location for the GNAT run-time sources (which can simply
15844 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15845 contain the location for the GNAT run-time objects (which can simply
15846 be @file{adalib}).
15847
15848 You can also specify a new default path to the run-time library at compilation
15849 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15850 the run-time library you want your program to be compiled with. This switch is
15851 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15852 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15853
15854 It is possible to install a library before or after the standard GNAT
15855 library, by reordering the lines in the configuration files. In general, a
15856 library must be installed before the GNAT library if it redefines
15857 any part of it.
15858
15859 @node Using a library
15860 @subsection Using a library
15861
15862 @noindent Once again, the project facility greatly simplifies the use of
15863 libraries. In this context, using a library is just a matter of adding a
15864 @code{with} clause in the user project. For instance, to make use of the
15865 library @code{My_Lib} shown in examples in earlier sections, you can
15866 write:
15867
15868 @smallexample @c projectfile
15869 with "my_lib";
15870 project My_Proj is
15871   @dots{}
15872 end My_Proj;
15873 @end smallexample
15874
15875 Even if you have a third-party, non-Ada library, you can still use GNAT's
15876 Project Manager facility to provide a wrapper for it. For example, the
15877 following project, when @code{with}ed by your main project, will link with the
15878 third-party library @file{liba.a}:
15879
15880 @smallexample @c projectfile
15881 @group
15882 project Liba is
15883    for Externally_Built use "true";
15884    for Source_Files use ();
15885    for Library_Dir use "lib";
15886    for Library_Name use "a";
15887    for Library_Kind use "static";
15888 end Liba;
15889 @end group
15890 @end smallexample
15891 This is an alternative to the use of @code{pragma Linker_Options}. It is
15892 especially interesting in the context of systems with several interdependent
15893 static libraries where finding a proper linker order is not easy and best be
15894 left to the tools having visibility over project dependence information.
15895
15896 @noindent
15897 In order to use an Ada library manually, you need to make sure that this
15898 library is on both your source and object path
15899 (see @ref{Search Paths and the Run-Time Library (RTL)}
15900 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15901 in an archive or a shared library, you need to specify the desired
15902 library at link time.
15903
15904 For example, you can use the library @file{mylib} installed in
15905 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15906
15907 @smallexample
15908 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15909   -largs -lmy_lib
15910 @end smallexample
15911
15912 @noindent
15913 This can be expressed more simply:
15914 @smallexample
15915 $ gnatmake my_appl
15916 @end smallexample
15917 @noindent
15918 when the following conditions are met:
15919 @itemize @bullet
15920 @item
15921 @file{/dir/my_lib_src} has been added by the user to the environment
15922 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15923 @file{ada_source_path}
15924 @item
15925 @file{/dir/my_lib_obj} has been added by the user to the environment
15926 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15927 @file{ada_object_path}
15928 @item
15929 a pragma @code{Linker_Options} has been added to one of the sources.
15930 For example:
15931
15932 @smallexample @c ada
15933 pragma Linker_Options ("-lmy_lib");
15934 @end smallexample
15935 @end itemize
15936
15937 @node Stand-alone Ada Libraries
15938 @section Stand-alone Ada Libraries
15939 @cindex Stand-alone library, building, using
15940
15941 @menu
15942 * Introduction to Stand-alone Libraries::
15943 * Building a Stand-alone Library::
15944 * Creating a Stand-alone Library to be used in a non-Ada context::
15945 * Restrictions in Stand-alone Libraries::
15946 @end menu
15947
15948 @node Introduction to Stand-alone Libraries
15949 @subsection Introduction to Stand-alone Libraries
15950
15951 @noindent
15952 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15953 necessary code to
15954 elaborate the Ada units that are included in the library. In contrast with
15955 an ordinary library, which consists of all sources, objects and @file{ALI}
15956 files of the
15957 library, a SAL may specify a restricted subset of compilation units
15958 to serve as a library interface. In this case, the fully
15959 self-sufficient set of files will normally consist of an objects
15960 archive, the sources of interface units' specs, and the @file{ALI}
15961 files of interface units.
15962 If an interface spec contains a generic unit or an inlined subprogram,
15963 the body's
15964 source must also be provided; if the units that must be provided in the source
15965 form depend on other units, the source and @file{ALI} files of those must
15966 also be provided.
15967
15968 The main purpose of a SAL is to minimize the recompilation overhead of client
15969 applications when a new version of the library is installed. Specifically,
15970 if the interface sources have not changed, client applications do not need to
15971 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15972 version, controlled by @code{Library_Version} attribute, is not changed,
15973 then the clients do not need to be relinked.
15974
15975 SALs also allow the library providers to minimize the amount of library source
15976 text exposed to the clients.  Such ``information hiding'' might be useful or
15977 necessary for various reasons.
15978
15979 Stand-alone libraries are also well suited to be used in an executable whose
15980 main routine is not written in Ada.
15981
15982 @node Building a Stand-alone Library
15983 @subsection Building a Stand-alone Library
15984
15985 @noindent
15986 GNAT's Project facility provides a simple way of building and installing
15987 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15988 To be a Stand-alone Library Project, in addition to the two attributes
15989 that make a project a Library Project (@code{Library_Name} and
15990 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15991 @code{Library_Interface} must be defined.  For example:
15992
15993 @smallexample @c projectfile
15994 @group
15995    for Library_Dir use "lib_dir";
15996    for Library_Name use "dummy";
15997    for Library_Interface use ("int1", "int1.child");
15998 @end group
15999 @end smallexample
16000
16001 @noindent
16002 Attribute @code{Library_Interface} has a non-empty string list value,
16003 each string in the list designating a unit contained in an immediate source
16004 of the project file.
16005
16006 When a Stand-alone Library is built, first the binder is invoked to build
16007 a package whose name depends on the library name
16008 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16009 This binder-generated package includes initialization and
16010 finalization procedures whose
16011 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16012 in the example
16013 above). The object corresponding to this package is included in the library.
16014
16015 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16016 calling of these procedures if a static SAL is built, or if a shared SAL
16017 is built
16018 with the project-level attribute @code{Library_Auto_Init} set to
16019 @code{"false"}.
16020
16021 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16022 (those that are listed in attribute @code{Library_Interface}) are copied to
16023 the Library Directory. As a consequence, only the Interface Units may be
16024 imported from Ada units outside of the library. If other units are imported,
16025 the binding phase will fail.
16026
16027 The attribute @code{Library_Src_Dir} may be specified for a
16028 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16029 single string value. Its value must be the path (absolute or relative to the
16030 project directory) of an existing directory. This directory cannot be the
16031 object directory or one of the source directories, but it can be the same as
16032 the library directory. The sources of the Interface
16033 Units of the library that are needed by an Ada client of the library will be
16034 copied to the designated directory, called the Interface Copy directory.
16035 These sources include the specs of the Interface Units, but they may also
16036 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16037 are used, or when there is a generic unit in the spec. Before the sources
16038 are copied to the Interface Copy directory, an attempt is made to delete all
16039 files in the Interface Copy directory.
16040
16041 Building stand-alone libraries by hand is somewhat tedious, but for those
16042 occasions when it is necessary here are the steps that you need to perform:
16043 @itemize @bullet
16044 @item
16045 Compile all library sources.
16046
16047 @item
16048 Invoke the binder with the switch @option{-n} (No Ada main program),
16049 with all the @file{ALI} files of the interfaces, and
16050 with the switch @option{-L} to give specific names to the @code{init}
16051 and @code{final} procedures.  For example:
16052 @smallexample
16053   gnatbind -n int1.ali int2.ali -Lsal1
16054 @end smallexample
16055
16056 @item
16057 Compile the binder generated file:
16058 @smallexample
16059   gcc -c b~int2.adb
16060 @end smallexample
16061
16062 @item
16063 Link the dynamic library with all the necessary object files,
16064 indicating to the linker the names of the @code{init} (and possibly
16065 @code{final}) procedures for automatic initialization (and finalization).
16066 The built library should be placed in a directory different from
16067 the object directory.
16068
16069 @item
16070 Copy the @code{ALI} files of the interface to the library directory,
16071 add in this copy an indication that it is an interface to a SAL
16072 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16073 with letter ``P'') and make the modified copy of the @file{ALI} file
16074 read-only.
16075 @end itemize
16076
16077 @noindent
16078 Using SALs is not different from using other libraries
16079 (see @ref{Using a library}).
16080
16081 @node Creating a Stand-alone Library to be used in a non-Ada context
16082 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16083
16084 @noindent
16085 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16086 a non-Ada context.
16087
16088 The only extra step required is to ensure that library interface subprograms
16089 are compatible with the main program, by means of @code{pragma Export}
16090 or @code{pragma Convention}.
16091
16092 Here is an example of simple library interface for use with C main program:
16093
16094 @smallexample @c ada
16095 package My_Package is
16096
16097    procedure Do_Something;
16098    pragma Export (C, Do_Something, "do_something");
16099
16100    procedure Do_Something_Else;
16101    pragma Export (C, Do_Something_Else, "do_something_else");
16102
16103 end My_Package;
16104 @end smallexample
16105
16106 @noindent
16107 On the foreign language side, you must provide a ``foreign'' view of the
16108 library interface; remember that it should contain elaboration routines in
16109 addition to interface subprograms.
16110
16111 The example below shows the content of @code{mylib_interface.h} (note
16112 that there is no rule for the naming of this file, any name can be used)
16113 @smallexample
16114 /* the library elaboration procedure */
16115 extern void mylibinit (void);
16116
16117 /* the library finalization procedure */
16118 extern void mylibfinal (void);
16119
16120 /* the interface exported by the library */
16121 extern void do_something (void);
16122 extern void do_something_else (void);
16123 @end smallexample
16124
16125 @noindent
16126 Libraries built as explained above can be used from any program, provided
16127 that the elaboration procedures (named @code{mylibinit} in the previous
16128 example) are called before the library services are used. Any number of
16129 libraries can be used simultaneously, as long as the elaboration
16130 procedure of each library is called.
16131
16132 Below is an example of a C program that uses the @code{mylib} library.
16133
16134 @smallexample
16135 #include "mylib_interface.h"
16136
16137 int
16138 main (void)
16139 @{
16140    /* First, elaborate the library before using it */
16141    mylibinit ();
16142
16143    /* Main program, using the library exported entities */
16144    do_something ();
16145    do_something_else ();
16146
16147    /* Library finalization at the end of the program */
16148    mylibfinal ();
16149    return 0;
16150 @}
16151 @end smallexample
16152
16153 @noindent
16154 Note that invoking any library finalization procedure generated by
16155 @code{gnatbind} shuts down the Ada run-time environment.
16156 Consequently, the
16157 finalization of all Ada libraries must be performed at the end of the program.
16158 No call to these libraries or to the Ada run-time library should be made
16159 after the finalization phase.
16160
16161 @node Restrictions in Stand-alone Libraries
16162 @subsection Restrictions in Stand-alone Libraries
16163
16164 @noindent
16165 The pragmas listed below should be used with caution inside libraries,
16166 as they can create incompatibilities with other Ada libraries:
16167 @itemize @bullet
16168 @item pragma @code{Locking_Policy}
16169 @item pragma @code{Queuing_Policy}
16170 @item pragma @code{Task_Dispatching_Policy}
16171 @item pragma @code{Unreserve_All_Interrupts}
16172 @end itemize
16173
16174 @noindent
16175 When using a library that contains such pragmas, the user must make sure
16176 that all libraries use the same pragmas with the same values. Otherwise,
16177 @code{Program_Error} will
16178 be raised during the elaboration of the conflicting
16179 libraries. The usage of these pragmas and its consequences for the user
16180 should therefore be well documented.
16181
16182 Similarly, the traceback in the exception occurrence mechanism should be
16183 enabled or disabled in a consistent manner across all libraries.
16184 Otherwise, Program_Error will be raised during the elaboration of the
16185 conflicting libraries.
16186
16187 If the @code{Version} or @code{Body_Version}
16188 attributes are used inside a library, then you need to
16189 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16190 libraries, so that version identifiers can be properly computed.
16191 In practice these attributes are rarely used, so this is unlikely
16192 to be a consideration.
16193
16194 @node  Rebuilding the GNAT Run-Time Library
16195 @section Rebuilding the GNAT Run-Time Library
16196 @cindex GNAT Run-Time Library, rebuilding
16197 @cindex Building the GNAT Run-Time Library
16198 @cindex Rebuilding the GNAT Run-Time Library
16199 @cindex Run-Time Library, rebuilding
16200
16201 @noindent
16202 It may be useful to recompile the GNAT library in various contexts, the
16203 most important one being the use of partition-wide configuration pragmas
16204 such as @code{Normalize_Scalars}. A special Makefile called
16205 @code{Makefile.adalib} is provided to that effect and can be found in
16206 the directory containing the GNAT library. The location of this
16207 directory depends on the way the GNAT environment has been installed and can
16208 be determined by means of the command:
16209
16210 @smallexample
16211 $ gnatls -v
16212 @end smallexample
16213
16214 @noindent
16215 The last entry in the object search path usually contains the
16216 gnat library. This Makefile contains its own documentation and in
16217 particular the set of instructions needed to rebuild a new library and
16218 to use it.
16219
16220 @node Using the GNU make Utility
16221 @chapter Using the GNU @code{make} Utility
16222 @findex make
16223
16224 @noindent
16225 This chapter offers some examples of makefiles that solve specific
16226 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16227 make, make, GNU @code{make}}), nor does it try to replace the
16228 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16229
16230 All the examples in this section are specific to the GNU version of
16231 make. Although @command{make} is a standard utility, and the basic language
16232 is the same, these examples use some advanced features found only in
16233 @code{GNU make}.
16234
16235 @menu
16236 * Using gnatmake in a Makefile::
16237 * Automatically Creating a List of Directories::
16238 * Generating the Command Line Switches::
16239 * Overcoming Command Line Length Limits::
16240 @end menu
16241
16242 @node Using gnatmake in a Makefile
16243 @section Using gnatmake in a Makefile
16244 @findex makefile
16245 @cindex GNU make
16246
16247 @noindent
16248 Complex project organizations can be handled in a very powerful way by
16249 using GNU make combined with gnatmake. For instance, here is a Makefile
16250 which allows you to build each subsystem of a big project into a separate
16251 shared library. Such a makefile allows you to significantly reduce the link
16252 time of very big applications while maintaining full coherence at
16253 each step of the build process.
16254
16255 The list of dependencies are handled automatically by
16256 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16257 the appropriate directories.
16258
16259 Note that you should also read the example on how to automatically
16260 create the list of directories
16261 (@pxref{Automatically Creating a List of Directories})
16262 which might help you in case your project has a lot of subdirectories.
16263
16264 @smallexample
16265 @iftex
16266 @leftskip=0cm
16267 @font@heightrm=cmr8
16268 @heightrm
16269 @end iftex
16270 ## This Makefile is intended to be used with the following directory
16271 ## configuration:
16272 ##  - The sources are split into a series of csc (computer software components)
16273 ##    Each of these csc is put in its own directory.
16274 ##    Their name are referenced by the directory names.
16275 ##    They will be compiled into shared library (although this would also work
16276 ##    with static libraries
16277 ##  - The main program (and possibly other packages that do not belong to any
16278 ##    csc is put in the top level directory (where the Makefile is).
16279 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16280 ##                    \_ second_csc (sources) __ lib (will contain the library)
16281 ##                    \_ @dots{}
16282 ## Although this Makefile is build for shared library, it is easy to modify
16283 ## to build partial link objects instead (modify the lines with -shared and
16284 ## gnatlink below)
16285 ##
16286 ## With this makefile, you can change any file in the system or add any new
16287 ## file, and everything will be recompiled correctly (only the relevant shared
16288 ## objects will be recompiled, and the main program will be re-linked).
16289
16290 # The list of computer software component for your project. This might be
16291 # generated automatically.
16292 CSC_LIST=aa bb cc
16293
16294 # Name of the main program (no extension)
16295 MAIN=main
16296
16297 # If we need to build objects with -fPIC, uncomment the following line
16298 #NEED_FPIC=-fPIC
16299
16300 # The following variable should give the directory containing libgnat.so
16301 # You can get this directory through 'gnatls -v'. This is usually the last
16302 # directory in the Object_Path.
16303 GLIB=@dots{}
16304
16305 # The directories for the libraries
16306 # (This macro expands the list of CSC to the list of shared libraries, you
16307 # could simply use the expanded form:
16308 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16309 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16310
16311 $@{MAIN@}: objects $@{LIB_DIR@}
16312     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16313     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16314
16315 objects::
16316     # recompile the sources
16317     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16318
16319 # Note: In a future version of GNAT, the following commands will be simplified
16320 # by a new tool, gnatmlib
16321 $@{LIB_DIR@}:
16322     mkdir -p $@{dir $@@ @}
16323     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16324     cd $@{dir $@@ @} && cp -f ../*.ali .
16325
16326 # The dependencies for the modules
16327 # Note that we have to force the expansion of *.o, since in some cases
16328 # make won't be able to do it itself.
16329 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16330 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16331 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16332
16333 # Make sure all of the shared libraries are in the path before starting the
16334 # program
16335 run::
16336     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16337
16338 clean::
16339     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16340     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16341     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16342     $@{RM@} *.o *.ali $@{MAIN@}
16343 @end smallexample
16344
16345 @node Automatically Creating a List of Directories
16346 @section Automatically Creating a List of Directories
16347
16348 @noindent
16349 In most makefiles, you will have to specify a list of directories, and
16350 store it in a variable. For small projects, it is often easier to
16351 specify each of them by hand, since you then have full control over what
16352 is the proper order for these directories, which ones should be
16353 included.
16354
16355 However, in larger projects, which might involve hundreds of
16356 subdirectories, it might be more convenient to generate this list
16357 automatically.
16358
16359 The example below presents two methods. The first one, although less
16360 general, gives you more control over the list. It involves wildcard
16361 characters, that are automatically expanded by @command{make}. Its
16362 shortcoming is that you need to explicitly specify some of the
16363 organization of your project, such as for instance the directory tree
16364 depth, whether some directories are found in a separate tree, @enddots{}
16365
16366 The second method is the most general one. It requires an external
16367 program, called @command{find}, which is standard on all Unix systems. All
16368 the directories found under a given root directory will be added to the
16369 list.
16370
16371 @smallexample
16372 @iftex
16373 @leftskip=0cm
16374 @font@heightrm=cmr8
16375 @heightrm
16376 @end iftex
16377 # The examples below are based on the following directory hierarchy:
16378 # All the directories can contain any number of files
16379 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16380 #                       ->  ab
16381 #                       ->  ac
16382 #                ->  b  ->  ba  ->  baa
16383 #                       ->  bb
16384 #                       ->  bc
16385 # This Makefile creates a variable called DIRS, that can be reused any time
16386 # you need this list (see the other examples in this section)
16387
16388 # The root of your project's directory hierarchy
16389 ROOT_DIRECTORY=.
16390
16391 ####
16392 # First method: specify explicitly the list of directories
16393 # This allows you to specify any subset of all the directories you need.
16394 ####
16395
16396 DIRS := a/aa/ a/ab/ b/ba/
16397
16398 ####
16399 # Second method: use wildcards
16400 # Note that the argument(s) to wildcard below should end with a '/'.
16401 # Since wildcards also return file names, we have to filter them out
16402 # to avoid duplicate directory names.
16403 # We thus use make's @code{dir} and @code{sort} functions.
16404 # It sets DIRs to the following value (note that the directories aaa and baa
16405 # are not given, unless you change the arguments to wildcard).
16406 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16407 ####
16408
16409 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16410                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16411
16412 ####
16413 # Third method: use an external program
16414 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16415 # This is the most complete command: it sets DIRs to the following value:
16416 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16417 ####
16418
16419 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16420
16421 @end smallexample
16422
16423 @node Generating the Command Line Switches
16424 @section Generating the Command Line Switches
16425
16426 @noindent
16427 Once you have created the list of directories as explained in the
16428 previous section (@pxref{Automatically Creating a List of Directories}),
16429 you can easily generate the command line arguments to pass to gnatmake.
16430
16431 For the sake of completeness, this example assumes that the source path
16432 is not the same as the object path, and that you have two separate lists
16433 of directories.
16434
16435 @smallexample
16436 # see "Automatically creating a list of directories" to create
16437 # these variables
16438 SOURCE_DIRS=
16439 OBJECT_DIRS=
16440
16441 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16442 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16443
16444 all:
16445         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16446 @end smallexample
16447
16448 @node Overcoming Command Line Length Limits
16449 @section Overcoming Command Line Length Limits
16450
16451 @noindent
16452 One problem that might be encountered on big projects is that many
16453 operating systems limit the length of the command line. It is thus hard to give
16454 gnatmake the list of source and object directories.
16455
16456 This example shows how you can set up environment variables, which will
16457 make @command{gnatmake} behave exactly as if the directories had been
16458 specified on the command line, but have a much higher length limit (or
16459 even none on most systems).
16460
16461 It assumes that you have created a list of directories in your Makefile,
16462 using one of the methods presented in
16463 @ref{Automatically Creating a List of Directories}.
16464 For the sake of completeness, we assume that the object
16465 path (where the ALI files are found) is different from the sources patch.
16466
16467 Note a small trick in the Makefile below: for efficiency reasons, we
16468 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16469 expanded immediately by @code{make}. This way we overcome the standard
16470 make behavior which is to expand the variables only when they are
16471 actually used.
16472
16473 On Windows, if you are using the standard Windows command shell, you must
16474 replace colons with semicolons in the assignments to these variables.
16475
16476 @smallexample
16477 @iftex
16478 @leftskip=0cm
16479 @font@heightrm=cmr8
16480 @heightrm
16481 @end iftex
16482 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16483 # This is the same thing as putting the -I arguments on the command line.
16484 # (the equivalent of using -aI on the command line would be to define
16485 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16486 # You can of course have different values for these variables.
16487 #
16488 # Note also that we need to keep the previous values of these variables, since
16489 # they might have been set before running 'make' to specify where the GNAT
16490 # library is installed.
16491
16492 # see "Automatically creating a list of directories" to create these
16493 # variables
16494 SOURCE_DIRS=
16495 OBJECT_DIRS=
16496
16497 empty:=
16498 space:=$@{empty@} $@{empty@}
16499 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16500 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16501 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16502 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16503 export ADA_INCLUDE_PATH
16504 export ADA_OBJECTS_PATH
16505
16506 all:
16507         gnatmake main_unit
16508 @end smallexample
16509 @end ifclear
16510
16511 @node Memory Management Issues
16512 @chapter Memory Management Issues
16513
16514 @noindent
16515 This chapter describes some useful memory pools provided in the GNAT library
16516 and in particular the GNAT Debug Pool facility, which can be used to detect
16517 incorrect uses of access values (including ``dangling references'').
16518 @ifclear vms
16519 It also describes the @command{gnatmem} tool, which can be used to track down
16520 ``memory leaks''.
16521 @end ifclear
16522
16523 @menu
16524 * Some Useful Memory Pools::
16525 * The GNAT Debug Pool Facility::
16526 @ifclear vms
16527 * The gnatmem Tool::
16528 @end ifclear
16529 @end menu
16530
16531 @node Some Useful Memory Pools
16532 @section Some Useful Memory Pools
16533 @findex Memory Pool
16534 @cindex storage, pool
16535
16536 @noindent
16537 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16538 storage pool. Allocations use the standard system call @code{malloc} while
16539 deallocations use the standard system call @code{free}. No reclamation is
16540 performed when the pool goes out of scope. For performance reasons, the
16541 standard default Ada allocators/deallocators do not use any explicit storage
16542 pools but if they did, they could use this storage pool without any change in
16543 behavior. That is why this storage pool is used  when the user
16544 manages to make the default implicit allocator explicit as in this example:
16545 @smallexample @c ada
16546    type T1 is access Something;
16547     -- no Storage pool is defined for T2
16548    type T2 is access Something_Else;
16549    for T2'Storage_Pool use T1'Storage_Pool;
16550    -- the above is equivalent to
16551    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16552 @end smallexample
16553
16554 @noindent
16555 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16556 pool. The allocation strategy is similar to @code{Pool_Local}'s
16557 except that the all
16558 storage allocated with this pool is reclaimed when the pool object goes out of
16559 scope. This pool provides a explicit mechanism similar to the implicit one
16560 provided by several Ada 83 compilers for allocations performed through a local
16561 access type and whose purpose was to reclaim memory when exiting the
16562 scope of a given local access. As an example, the following program does not
16563 leak memory even though it does not perform explicit deallocation:
16564
16565 @smallexample @c ada
16566 with System.Pool_Local;
16567 procedure Pooloc1 is
16568    procedure Internal is
16569       type A is access Integer;
16570       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16571       for A'Storage_Pool use X;
16572       v : A;
16573    begin
16574       for I in  1 .. 50 loop
16575          v := new Integer;
16576       end loop;
16577    end Internal;
16578 begin
16579    for I in  1 .. 100 loop
16580       Internal;
16581    end loop;
16582 end Pooloc1;
16583 @end smallexample
16584
16585 @noindent
16586 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16587 @code{Storage_Size} is specified for an access type.
16588 The whole storage for the pool is
16589 allocated at once, usually on the stack at the point where the access type is
16590 elaborated. It is automatically reclaimed when exiting the scope where the
16591 access type is defined. This package is not intended to be used directly by the
16592 user and it is implicitly used for each such declaration:
16593
16594 @smallexample @c ada
16595    type T1 is access Something;
16596    for T1'Storage_Size use 10_000;
16597 @end smallexample
16598
16599 @node The GNAT Debug Pool Facility
16600 @section The GNAT Debug Pool Facility
16601 @findex Debug Pool
16602 @cindex storage, pool, memory corruption
16603
16604 @noindent
16605 The use of unchecked deallocation and unchecked conversion can easily
16606 lead to incorrect memory references. The problems generated by such
16607 references are usually difficult to tackle because the symptoms can be
16608 very remote from the origin of the problem. In such cases, it is
16609 very helpful to detect the problem as early as possible. This is the
16610 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16611
16612 In order to use the GNAT specific debugging pool, the user must
16613 associate a debug pool object with each of the access types that may be
16614 related to suspected memory problems. See Ada Reference Manual 13.11.
16615 @smallexample @c ada
16616 type Ptr is access Some_Type;
16617 Pool : GNAT.Debug_Pools.Debug_Pool;
16618 for Ptr'Storage_Pool use Pool;
16619 @end smallexample
16620
16621 @noindent
16622 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16623 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16624 allow the user to redefine allocation and deallocation strategies. They
16625 also provide a checkpoint for each dereference, through the use of
16626 the primitive operation @code{Dereference} which is implicitly called at
16627 each dereference of an access value.
16628
16629 Once an access type has been associated with a debug pool, operations on
16630 values of the type may raise four distinct exceptions,
16631 which correspond to four potential kinds of memory corruption:
16632 @itemize @bullet
16633 @item
16634 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16635 @item
16636 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16637 @item
16638 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16639 @item
16640 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16641 @end itemize
16642
16643 @noindent
16644 For types associated with a Debug_Pool, dynamic allocation is performed using
16645 the standard GNAT allocation routine. References to all allocated chunks of
16646 memory are kept in an internal dictionary. Several deallocation strategies are
16647 provided, whereupon the user can choose to release the memory to the system,
16648 keep it allocated for further invalid access checks, or fill it with an easily
16649 recognizable pattern for debug sessions. The memory pattern is the old IBM
16650 hexadecimal convention: @code{16#DEADBEEF#}.
16651
16652 See the documentation in the file g-debpoo.ads for more information on the
16653 various strategies.
16654
16655 Upon each dereference, a check is made that the access value denotes a
16656 properly allocated memory location. Here is a complete example of use of
16657 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16658 @smallexample @c ada
16659 @iftex
16660 @leftskip=0cm
16661 @end iftex
16662 with Gnat.Io; use Gnat.Io;
16663 with Unchecked_Deallocation;
16664 with Unchecked_Conversion;
16665 with GNAT.Debug_Pools;
16666 with System.Storage_Elements;
16667 with Ada.Exceptions; use Ada.Exceptions;
16668 procedure Debug_Pool_Test is
16669
16670    type T is access Integer;
16671    type U is access all T;
16672
16673    P : GNAT.Debug_Pools.Debug_Pool;
16674    for T'Storage_Pool use P;
16675
16676    procedure Free is new Unchecked_Deallocation (Integer, T);
16677    function UC is new Unchecked_Conversion (U, T);
16678    A, B : aliased T;
16679
16680    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16681
16682 begin
16683    Info (P);
16684    A := new Integer;
16685    B := new Integer;
16686    B := A;
16687    Info (P);
16688    Free (A);
16689    begin
16690       Put_Line (Integer'Image(B.all));
16691    exception
16692       when E : others => Put_Line ("raised: " & Exception_Name (E));
16693    end;
16694    begin
16695       Free (B);
16696    exception
16697       when E : others => Put_Line ("raised: " & Exception_Name (E));
16698    end;
16699    B := UC(A'Access);
16700    begin
16701       Put_Line (Integer'Image(B.all));
16702    exception
16703       when E : others => Put_Line ("raised: " & Exception_Name (E));
16704    end;
16705    begin
16706       Free (B);
16707    exception
16708       when E : others => Put_Line ("raised: " & Exception_Name (E));
16709    end;
16710    Info (P);
16711 end Debug_Pool_Test;
16712 @end smallexample
16713
16714 @noindent
16715 The debug pool mechanism provides the following precise diagnostics on the
16716 execution of this erroneous program:
16717 @smallexample
16718 Debug Pool info:
16719   Total allocated bytes :  0
16720   Total deallocated bytes :  0
16721   Current Water Mark:  0
16722   High Water Mark:  0
16723
16724 Debug Pool info:
16725   Total allocated bytes :  8
16726   Total deallocated bytes :  0
16727   Current Water Mark:  8
16728   High Water Mark:  8
16729
16730 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16731 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16732 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16733 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16734 Debug Pool info:
16735   Total allocated bytes :  8
16736   Total deallocated bytes :  4
16737   Current Water Mark:  4
16738   High Water Mark:  8
16739 @end smallexample
16740
16741 @ifclear vms
16742 @node The gnatmem Tool
16743 @section The @command{gnatmem} Tool
16744 @findex gnatmem
16745
16746 @noindent
16747 The @code{gnatmem} utility monitors dynamic allocation and
16748 deallocation activity in a program, and displays information about
16749 incorrect deallocations and possible sources of memory leaks.
16750 It is designed to work in association with a static runtime library
16751 only and in this context provides three types of information:
16752 @itemize @bullet
16753 @item
16754 General information concerning memory management, such as the total
16755 number of allocations and deallocations, the amount of allocated
16756 memory and the high water mark, i.e.@: the largest amount of allocated
16757 memory in the course of program execution.
16758
16759 @item
16760 Backtraces for all incorrect deallocations, that is to say deallocations
16761 which do not correspond to a valid allocation.
16762
16763 @item
16764 Information on each allocation that is potentially the origin of a memory
16765 leak.
16766 @end itemize
16767
16768 @menu
16769 * Running gnatmem::
16770 * Switches for gnatmem::
16771 * Example of gnatmem Usage::
16772 @end menu
16773
16774 @node Running gnatmem
16775 @subsection Running @code{gnatmem}
16776
16777 @noindent
16778 @code{gnatmem} makes use of the output created by the special version of
16779 allocation and deallocation routines that record call information. This
16780 allows to obtain accurate dynamic memory usage history at a minimal cost to
16781 the execution speed. Note however, that @code{gnatmem} is not supported on
16782 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16783 Solaris and Windows NT/2000/XP (x86).
16784
16785 @noindent
16786 The @code{gnatmem} command has the form
16787
16788 @smallexample
16789 @c    $ gnatmem @ovar{switches} user_program
16790 @c Expanding @ovar macro inline (explanation in macro def comments)
16791       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16792 @end smallexample
16793
16794 @noindent
16795 The program must have been linked with the instrumented version of the
16796 allocation and deallocation routines. This is done by linking with the
16797 @file{libgmem.a} library. For correct symbolic backtrace information,
16798 the user program should be compiled with debugging options
16799 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16800
16801 @smallexample
16802 $ gnatmake -g my_program -largs -lgmem
16803 @end smallexample
16804
16805 @noindent
16806 As library @file{libgmem.a} contains an alternate body for package
16807 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16808 when an executable is linked with library @file{libgmem.a}. It is then not
16809 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16810
16811 @noindent
16812 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16813 This file contains information about all allocations and deallocations
16814 performed by the program. It is produced by the instrumented allocations and
16815 deallocations routines and will be used by @code{gnatmem}.
16816
16817 In order to produce symbolic backtrace information for allocations and
16818 deallocations performed by the GNAT run-time library, you need to use a
16819 version of that library that has been compiled with the @option{-g} switch
16820 (see @ref{Rebuilding the GNAT Run-Time Library}).
16821
16822 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16823 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16824 @option{-i} switch, gnatmem will assume that this file can be found in the
16825 current directory. For example, after you have executed @file{my_program},
16826 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16827
16828 @smallexample
16829 $ gnatmem my_program
16830 @end smallexample
16831
16832 @noindent
16833 This will produce the output with the following format:
16834
16835 *************** debut cc
16836 @smallexample
16837 $ gnatmem my_program
16838
16839 Global information
16840 ------------------
16841    Total number of allocations        :  45
16842    Total number of deallocations      :   6
16843    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16844    High Water Mark                    :  11.40 Kilobytes
16845
16846 .
16847 .
16848 .
16849 Allocation Root # 2
16850 -------------------
16851  Number of non freed allocations    :  11
16852  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16853  High Water Mark                    :   1.27 Kilobytes
16854  Backtrace                          :
16855    my_program.adb:23 my_program.alloc
16856 .
16857 .
16858 .
16859 @end smallexample
16860
16861 The first block of output gives general information. In this case, the
16862 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16863 Unchecked_Deallocation routine occurred.
16864
16865 @noindent
16866 Subsequent paragraphs display  information on all allocation roots.
16867 An allocation root is a specific point in the execution of the program
16868 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16869 construct. This root is represented by an execution backtrace (or subprogram
16870 call stack). By default the backtrace depth for allocations roots is 1, so
16871 that a root corresponds exactly to a source location. The backtrace can
16872 be made deeper, to make the root more specific.
16873
16874 @node Switches for gnatmem
16875 @subsection Switches for @code{gnatmem}
16876
16877 @noindent
16878 @code{gnatmem} recognizes the following switches:
16879
16880 @table @option
16881
16882 @item -q
16883 @cindex @option{-q} (@code{gnatmem})
16884 Quiet. Gives the minimum output needed to identify the origin of the
16885 memory leaks. Omits statistical information.
16886
16887 @item @var{N}
16888 @cindex @var{N} (@code{gnatmem})
16889 N is an integer literal (usually between 1 and 10) which controls the
16890 depth of the backtraces defining allocation root. The default value for
16891 N is 1. The deeper the backtrace, the more precise the localization of
16892 the root. Note that the total number of roots can depend on this
16893 parameter. This parameter must be specified @emph{before} the name of the
16894 executable to be analyzed, to avoid ambiguity.
16895
16896 @item -b n
16897 @cindex @option{-b} (@code{gnatmem})
16898 This switch has the same effect as just depth parameter.
16899
16900 @item -i @var{file}
16901 @cindex @option{-i} (@code{gnatmem})
16902 Do the @code{gnatmem} processing starting from @file{file}, rather than
16903 @file{gmem.out} in the current directory.
16904
16905 @item -m n
16906 @cindex @option{-m} (@code{gnatmem})
16907 This switch causes @code{gnatmem} to mask the allocation roots that have less
16908 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16909 examine even the roots that didn't result in leaks.
16910
16911 @item -s order
16912 @cindex @option{-s} (@code{gnatmem})
16913 This switch causes @code{gnatmem} to sort the allocation roots according to the
16914 specified order of sort criteria, each identified by a single letter. The
16915 currently supported criteria are @code{n, h, w} standing respectively for
16916 number of unfreed allocations, high watermark, and final watermark
16917 corresponding to a specific root. The default order is @code{nwh}.
16918
16919 @end table
16920
16921 @node Example of gnatmem Usage
16922 @subsection Example of @code{gnatmem} Usage
16923
16924 @noindent
16925 The following example shows the use of @code{gnatmem}
16926 on a simple memory-leaking program.
16927 Suppose that we have the following Ada program:
16928
16929 @smallexample @c ada
16930 @group
16931 @cartouche
16932 with Unchecked_Deallocation;
16933 procedure Test_Gm is
16934
16935    type T is array (1..1000) of Integer;
16936    type Ptr is access T;
16937    procedure Free is new Unchecked_Deallocation (T, Ptr);
16938    A : Ptr;
16939
16940    procedure My_Alloc is
16941    begin
16942       A := new T;
16943    end My_Alloc;
16944
16945    procedure My_DeAlloc is
16946       B : Ptr := A;
16947    begin
16948       Free (B);
16949    end My_DeAlloc;
16950
16951 begin
16952    My_Alloc;
16953    for I in 1 .. 5 loop
16954       for J in I .. 5 loop
16955          My_Alloc;
16956       end loop;
16957       My_Dealloc;
16958    end loop;
16959 end;
16960 @end cartouche
16961 @end group
16962 @end smallexample
16963
16964 @noindent
16965 The program needs to be compiled with debugging option and linked with
16966 @code{gmem} library:
16967
16968 @smallexample
16969 $ gnatmake -g test_gm -largs -lgmem
16970 @end smallexample
16971
16972 @noindent
16973 Then we execute the program as usual:
16974
16975 @smallexample
16976 $ test_gm
16977 @end smallexample
16978
16979 @noindent
16980 Then @code{gnatmem} is invoked simply with
16981 @smallexample
16982 $ gnatmem test_gm
16983 @end smallexample
16984
16985 @noindent
16986 which produces the following output (result may vary on different platforms):
16987
16988 @smallexample
16989 Global information
16990 ------------------
16991    Total number of allocations        :  18
16992    Total number of deallocations      :   5
16993    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16994    High Water Mark                    :  56.90 Kilobytes
16995
16996 Allocation Root # 1
16997 -------------------
16998  Number of non freed allocations    :  11
16999  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17000  High Water Mark                    :  46.88 Kilobytes
17001  Backtrace                          :
17002    test_gm.adb:11 test_gm.my_alloc
17003
17004 Allocation Root # 2
17005 -------------------
17006  Number of non freed allocations    :   1
17007  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17008  High Water Mark                    :  10.02 Kilobytes
17009  Backtrace                          :
17010    s-secsta.adb:81 system.secondary_stack.ss_init
17011
17012 Allocation Root # 3
17013 -------------------
17014  Number of non freed allocations    :   1
17015  Final Water Mark (non freed mem)   :  12 Bytes
17016  High Water Mark                    :  12 Bytes
17017  Backtrace                          :
17018    s-secsta.adb:181 system.secondary_stack.ss_init
17019 @end smallexample
17020
17021 @noindent
17022 Note that the GNAT run time contains itself a certain number of
17023 allocations that have no  corresponding deallocation,
17024 as shown here for root #2 and root
17025 #3. This is a normal behavior when the number of non-freed allocations
17026 is one, it allocates dynamic data structures that the run time needs for
17027 the complete lifetime of the program. Note also that there is only one
17028 allocation root in the user program with a single line back trace:
17029 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17030 program shows that 'My_Alloc' is called at 2 different points in the
17031 source (line 21 and line 24). If those two allocation roots need to be
17032 distinguished, the backtrace depth parameter can be used:
17033
17034 @smallexample
17035 $ gnatmem 3 test_gm
17036 @end smallexample
17037
17038 @noindent
17039 which will give the following output:
17040
17041 @smallexample
17042 Global information
17043 ------------------
17044    Total number of allocations        :  18
17045    Total number of deallocations      :   5
17046    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17047    High Water Mark                    :  56.90 Kilobytes
17048
17049 Allocation Root # 1
17050 -------------------
17051  Number of non freed allocations    :  10
17052  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17053  High Water Mark                    :  42.97 Kilobytes
17054  Backtrace                          :
17055    test_gm.adb:11 test_gm.my_alloc
17056    test_gm.adb:24 test_gm
17057    b_test_gm.c:52 main
17058
17059 Allocation Root # 2
17060 -------------------
17061  Number of non freed allocations    :   1
17062  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17063  High Water Mark                    :  10.02 Kilobytes
17064  Backtrace                          :
17065    s-secsta.adb:81  system.secondary_stack.ss_init
17066    s-secsta.adb:283 <system__secondary_stack___elabb>
17067    b_test_gm.c:33   adainit
17068
17069 Allocation Root # 3
17070 -------------------
17071  Number of non freed allocations    :   1
17072  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17073  High Water Mark                    :   3.91 Kilobytes
17074  Backtrace                          :
17075    test_gm.adb:11 test_gm.my_alloc
17076    test_gm.adb:21 test_gm
17077    b_test_gm.c:52 main
17078
17079 Allocation Root # 4
17080 -------------------
17081  Number of non freed allocations    :   1
17082  Final Water Mark (non freed mem)   :  12 Bytes
17083  High Water Mark                    :  12 Bytes
17084  Backtrace                          :
17085    s-secsta.adb:181 system.secondary_stack.ss_init
17086    s-secsta.adb:283 <system__secondary_stack___elabb>
17087    b_test_gm.c:33   adainit
17088 @end smallexample
17089
17090 @noindent
17091 The allocation root #1 of the first example has been split in 2 roots #1
17092 and #3 thanks to the more precise associated backtrace.
17093
17094 @end ifclear
17095
17096 @node Stack Related Facilities
17097 @chapter Stack Related Facilities
17098
17099 @noindent
17100 This chapter describes some useful tools associated with stack
17101 checking and analysis. In
17102 particular, it deals with dynamic and static stack usage measurements.
17103
17104 @menu
17105 * Stack Overflow Checking::
17106 * Static Stack Usage Analysis::
17107 * Dynamic Stack Usage Analysis::
17108 @end menu
17109
17110 @node Stack Overflow Checking
17111 @section Stack Overflow Checking
17112 @cindex Stack Overflow Checking
17113 @cindex -fstack-check
17114
17115 @noindent
17116 For most operating systems, @command{gcc} does not perform stack overflow
17117 checking by default. This means that if the main environment task or
17118 some other task exceeds the available stack space, then unpredictable
17119 behavior will occur. Most native systems offer some level of protection by
17120 adding a guard page at the end of each task stack. This mechanism is usually
17121 not enough for dealing properly with stack overflow situations because
17122 a large local variable could ``jump'' above the guard page.
17123 Furthermore, when the
17124 guard page is hit, there may not be any space left on the stack for executing
17125 the exception propagation code. Enabling stack checking avoids
17126 such situations.
17127
17128 To activate stack checking, compile all units with the gcc option
17129 @option{-fstack-check}. For example:
17130
17131 @smallexample
17132 gcc -c -fstack-check package1.adb
17133 @end smallexample
17134
17135 @noindent
17136 Units compiled with this option will generate extra instructions to check
17137 that any use of the stack (for procedure calls or for declaring local
17138 variables in declare blocks) does not exceed the available stack space.
17139 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17140
17141 For declared tasks, the stack size is controlled by the size
17142 given in an applicable @code{Storage_Size} pragma or by the value specified
17143 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17144 the default size as defined in the GNAT runtime otherwise.
17145
17146 For the environment task, the stack size depends on
17147 system defaults and is unknown to the compiler. Stack checking
17148 may still work correctly if a fixed
17149 size stack is allocated, but this cannot be guaranteed.
17150 @ifclear vms
17151 To ensure that a clean exception is signalled for stack
17152 overflow, set the environment variable
17153 @env{GNAT_STACK_LIMIT} to indicate the maximum
17154 stack area that can be used, as in:
17155 @cindex GNAT_STACK_LIMIT
17156
17157 @smallexample
17158 SET GNAT_STACK_LIMIT 1600
17159 @end smallexample
17160
17161 @noindent
17162 The limit is given in kilobytes, so the above declaration would
17163 set the stack limit of the environment task to 1.6 megabytes.
17164 Note that the only purpose of this usage is to limit the amount
17165 of stack used by the environment task. If it is necessary to
17166 increase the amount of stack for the environment task, then this
17167 is an operating systems issue, and must be addressed with the
17168 appropriate operating systems commands.
17169 @end ifclear
17170 @ifset vms
17171 To have a fixed size stack in the environment task, the stack must be put
17172 in the P0 address space and its size specified.  Use these switches to
17173 create a p0 image:
17174
17175 @smallexample
17176 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17177 @end smallexample
17178
17179 @noindent
17180 The quotes are required to keep case.  The number after @samp{STACK=} is the
17181 size of the environmental task stack in pagelets (512 bytes).  In this example
17182 the stack size is about 2 megabytes.
17183
17184 @noindent
17185 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17186 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17187 more details about the @option{/p0image} qualifier and the @option{stack}
17188 option.
17189 @end ifset
17190
17191 @node Static Stack Usage Analysis
17192 @section Static Stack Usage Analysis
17193 @cindex Static Stack Usage Analysis
17194 @cindex -fstack-usage
17195
17196 @noindent
17197 A unit compiled with @option{-fstack-usage} will generate an extra file
17198 that specifies
17199 the maximum amount of stack used, on a per-function basis.
17200 The file has the same
17201 basename as the target object file with a @file{.su} extension.
17202 Each line of this file is made up of three fields:
17203
17204 @itemize
17205 @item
17206 The name of the function.
17207 @item
17208 A number of bytes.
17209 @item
17210 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17211 @end itemize
17212
17213 The second field corresponds to the size of the known part of the function
17214 frame.
17215
17216 The qualifier @code{static} means that the function frame size
17217 is purely static.
17218 It usually means that all local variables have a static size.
17219 In this case, the second field is a reliable measure of the function stack
17220 utilization.
17221
17222 The qualifier @code{dynamic} means that the function frame size is not static.
17223 It happens mainly when some local variables have a dynamic size. When this
17224 qualifier appears alone, the second field is not a reliable measure
17225 of the function stack analysis. When it is qualified with  @code{bounded}, it
17226 means that the second field is a reliable maximum of the function stack
17227 utilization.
17228
17229 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17230 subprogram whose stack usage might be larger than the specified amount of
17231 bytes.  The wording is in keeping with the qualifier documented above.
17232
17233 @node Dynamic Stack Usage Analysis
17234 @section Dynamic Stack Usage Analysis
17235
17236 @noindent
17237 It is possible to measure the maximum amount of stack used by a task, by
17238 adding a switch to @command{gnatbind}, as:
17239
17240 @smallexample
17241 $ gnatbind -u0 file
17242 @end smallexample
17243
17244 @noindent
17245 With this option, at each task termination, its stack usage is  output on
17246 @file{stderr}.
17247 It is not always convenient to output the stack usage when the program
17248 is still running. Hence, it is possible to delay this output until program
17249 termination. for a given number of tasks specified as the argument of the
17250 @option{-u} option. For instance:
17251
17252 @smallexample
17253 $ gnatbind -u100 file
17254 @end smallexample
17255
17256 @noindent
17257 will buffer the stack usage information of the first 100 tasks to terminate and
17258 output this info at program termination. Results are displayed in four
17259 columns:
17260
17261 @noindent
17262 Index | Task Name | Stack Size | Stack Usage
17263
17264 @noindent
17265 where:
17266
17267 @table @emph
17268 @item Index
17269 is a number associated with each task.
17270
17271 @item Task Name
17272 is the name of the task analyzed.
17273
17274 @item Stack Size
17275 is the maximum size for the stack.
17276
17277 @item Stack Usage
17278 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17279 is not entirely analyzed, and it's not possible to know exactly how
17280 much has actually been used.
17281
17282 @end table
17283
17284 @noindent
17285 The environment task stack, e.g., the stack that contains the main unit, is
17286 only processed when the environment variable GNAT_STACK_LIMIT is set.
17287
17288 @noindent
17289 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17290 stack usage reports at run-time. See its body for the details.
17291
17292 @c *********************************
17293 @c *            GNATCHECK          *
17294 @c *********************************
17295 @node Verifying Properties Using gnatcheck
17296 @chapter Verifying Properties Using @command{gnatcheck}
17297 @findex gnatcheck
17298 @cindex @command{gnatcheck}
17299
17300 @noindent
17301 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17302 of Ada source files according to a given set of semantic rules.
17303 @cindex ASIS
17304
17305 In order to check compliance with a given rule, @command{gnatcheck} has to
17306 semantically analyze the Ada sources.
17307 Therefore, checks can only be performed on
17308 legal Ada units. Moreover, when a unit depends semantically upon units located
17309 outside the current directory, the source search path has to be provided when
17310 calling @command{gnatcheck}, either through a specified project file or
17311 through @command{gnatcheck} switches.
17312
17313 For full details, refer to @cite{GNATcheck Reference Manual} document.
17314
17315
17316 @c *********************************
17317 @node Creating Sample Bodies Using gnatstub
17318 @chapter Creating Sample Bodies Using @command{gnatstub}
17319 @findex gnatstub
17320
17321 @noindent
17322 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17323 for library unit declarations.
17324
17325 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17326 driver (see @ref{The GNAT Driver and Project Files}).
17327
17328 To create a body stub, @command{gnatstub} has to compile the library
17329 unit declaration. Therefore, bodies can be created only for legal
17330 library units. Moreover, if a library unit depends semantically upon
17331 units located outside the current directory, you have to provide
17332 the source search path when calling @command{gnatstub}, see the description
17333 of @command{gnatstub} switches below.
17334
17335 By default, all the program unit body stubs generated by @code{gnatstub}
17336 raise the predefined @code{Program_Error} exception, which will catch
17337 accidental calls of generated stubs. This behavior can be changed with
17338 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17339
17340 @menu
17341 * Running gnatstub::
17342 * Switches for gnatstub::
17343 @end menu
17344
17345 @node Running gnatstub
17346 @section Running @command{gnatstub}
17347
17348 @noindent
17349 @command{gnatstub} has the command-line interface of the form
17350
17351 @smallexample
17352 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17353 @c Expanding @ovar macro inline (explanation in macro def comments)
17354 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17355 @end smallexample
17356
17357 @noindent
17358 where
17359 @table @var
17360 @item filename
17361 is the name of the source file that contains a library unit declaration
17362 for which a body must be created. The file name may contain the path
17363 information.
17364 The file name does not have to follow the GNAT file name conventions. If the
17365 name
17366 does not follow GNAT file naming conventions, the name of the body file must
17367 be provided
17368 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17369 If the file name follows the GNAT file naming
17370 conventions and the name of the body file is not provided,
17371 @command{gnatstub}
17372 creates the name
17373 of the body file from the argument file name by replacing the @file{.ads}
17374 suffix
17375 with the @file{.adb} suffix.
17376
17377 @item directory
17378 indicates the directory in which the body stub is to be placed (the default
17379 is the
17380 current directory)
17381
17382 @item @samp{@var{gcc_switches}} is a list of switches for
17383 @command{gcc}. They will be passed on to all compiler invocations made by
17384 @command{gnatelim} to generate the ASIS trees. Here you can provide
17385 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17386 use the @option{-gnatec} switch to set the configuration file,
17387 use the @option{-gnat05} switch if sources should be compiled in
17388 Ada 2005 mode etc.
17389
17390 @item switches
17391 is an optional sequence of switches as described in the next section
17392 @end table
17393
17394 @node Switches for gnatstub
17395 @section Switches for @command{gnatstub}
17396
17397 @table @option
17398 @c !sort!
17399
17400 @item ^-f^/FULL^
17401 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17402 If the destination directory already contains a file with the name of the
17403 body file
17404 for the argument spec file, replace it with the generated body stub.
17405
17406 @item ^-hs^/HEADER=SPEC^
17407 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17408 Put the comment header (i.e., all the comments preceding the
17409 compilation unit) from the source of the library unit declaration
17410 into the body stub.
17411
17412 @item ^-hg^/HEADER=GENERAL^
17413 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17414 Put a sample comment header into the body stub.
17415
17416 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17417 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17418 Use the content of the file as the comment header for a generated body stub.
17419
17420 @ifclear vms
17421 @item -IDIR
17422 @cindex @option{-IDIR} (@command{gnatstub})
17423 @itemx -I-
17424 @cindex @option{-I-} (@command{gnatstub})
17425 @end ifclear
17426 @ifset vms
17427 @item /NOCURRENT_DIRECTORY
17428 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17429 @end ifset
17430 ^These switches have ^This switch has^ the same meaning as in calls to
17431 @command{gcc}.
17432 ^They define ^It defines ^ the source search path in the call to
17433 @command{gcc} issued
17434 by @command{gnatstub} to compile an argument source file.
17435
17436 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17437 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17438 This switch has the same meaning as in calls to @command{gcc}.
17439 It defines the additional configuration file to be passed to the call to
17440 @command{gcc} issued
17441 by @command{gnatstub} to compile an argument source file.
17442
17443 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17444 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17445 (@var{n} is a non-negative integer). Set the maximum line length in the
17446 body stub to @var{n}; the default is 79. The maximum value that can be
17447 specified is 32767. Note that in the special case of configuration
17448 pragma files, the maximum is always 32767 regardless of whether or
17449 not this switch appears.
17450
17451 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17452 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17453 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17454 the generated body sample to @var{n}.
17455 The default indentation is 3.
17456
17457 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17458 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17459 Order local bodies alphabetically. (By default local bodies are ordered
17460 in the same way as the corresponding local specs in the argument spec file.)
17461
17462 @item ^-i^/INDENTATION=^@var{n}
17463 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17464 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17465
17466 @item ^-k^/TREE_FILE=SAVE^
17467 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17468 Do not remove the tree file (i.e., the snapshot of the compiler internal
17469 structures used by @command{gnatstub}) after creating the body stub.
17470
17471 @item ^-l^/LINE_LENGTH=^@var{n}
17472 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17473 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17474
17475 @item ^--no-exception^/NO_EXCEPTION^
17476 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17477 void raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17478 This is not always possible for function stubs.
17479
17480 @item ^--no-local-header^/NO_LOCAL_HEADER^
17481 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17482 Do not place local comment header with unit name before body stub for a
17483 unit.
17484
17485 @item ^-o ^/BODY=^@var{body-name}
17486 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17487 Body file name.  This should be set if the argument file name does not
17488 follow
17489 the GNAT file naming
17490 conventions. If this switch is omitted the default name for the body will be
17491 obtained
17492 from the argument file name according to the GNAT file naming conventions.
17493
17494 @item ^-q^/QUIET^
17495 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17496 Quiet mode: do not generate a confirmation when a body is
17497 successfully created, and do not generate a message when a body is not
17498 required for an
17499 argument unit.
17500
17501 @item ^-r^/TREE_FILE=REUSE^
17502 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17503 Reuse the tree file (if it exists) instead of creating it.  Instead of
17504 creating the tree file for the library unit declaration, @command{gnatstub}
17505 tries to find it in the current directory and use it for creating
17506 a body. If the tree file is not found, no body is created. This option
17507 also implies @option{^-k^/SAVE^}, whether or not
17508 the latter is set explicitly.
17509
17510 @item ^-t^/TREE_FILE=OVERWRITE^
17511 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17512 Overwrite the existing tree file.  If the current directory already
17513 contains the file which, according to the GNAT file naming rules should
17514 be considered as a tree file for the argument source file,
17515 @command{gnatstub}
17516 will refuse to create the tree file needed to create a sample body
17517 unless this option is set.
17518
17519 @item ^-v^/VERBOSE^
17520 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17521 Verbose mode: generate version information.
17522
17523 @end table
17524
17525 @c *********************************
17526 @node Generating Ada Bindings for C and C++ headers
17527 @chapter Generating Ada Bindings for C and C++ headers
17528 @findex binding
17529
17530 @noindent
17531 GNAT now comes with a binding generator for C and C++ headers which is
17532 intended to do 95% of the tedious work of generating Ada specs from C
17533 or C++ header files.
17534
17535 Note that this capability is not intended to generate 100% correct Ada specs,
17536 and will is some cases require manual adjustments, although it can often
17537 be used out of the box in practice.
17538
17539 Some of the known limitations include:
17540
17541 @itemize @bullet
17542 @item only very simple character constant macros are translated into Ada
17543 constants. Function macros (macros with arguments) are partially translated
17544 as comments, to be completed manually if needed.
17545 @item some extensions (e.g. vector types) are not supported
17546 @item pointers to pointers or complex structures are mapped to System.Address
17547 @item identifiers with identical name (except casing) will generate compilation
17548       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
17549 @end itemize
17550
17551 The code generated is using the Ada 2005 syntax, which makes it
17552 easier to interface with other languages than previous versions of Ada.
17553
17554 @menu
17555 * Running the binding generator::
17556 * Generating bindings for C++ headers::
17557 * Switches::
17558 @end menu
17559
17560 @node Running the binding generator
17561 @section Running the binding generator
17562
17563 @noindent
17564 The binding generator is part of the @command{gcc} compiler and can be
17565 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
17566 spec files for the header files specified on the command line, and all
17567 header files needed by these files transitively. For example:
17568
17569 @smallexample
17570 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
17571 $ gcc -c -gnat05 *.ads
17572 @end smallexample
17573
17574 will generate, under GNU/Linux, the following files: @file{time_h.ads},
17575 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
17576 correspond to the files @file{/usr/include/time.h},
17577 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
17578 mode these Ada specs.
17579
17580 The @code{-C} switch tells @command{gcc} to extract comments from headers,
17581 and will attempt to generate corresponding Ada comments.
17582
17583 If you want to generate a single Ada file and not the transitive closure, you
17584 can use instead the @option{-fdump-ada-spec-slim} switch.
17585
17586 Note that we recommend when possible to use the @command{g++} driver to
17587 generate bindings, even for most C headers, since this will in general
17588 generate better Ada specs. For generating bindings for C++ headers, it is
17589 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
17590 is equivalent in this case. If @command{g++} cannot work on your C headers
17591 because of incompatibilities between C and C++, then you can fallback to
17592 @command{gcc} instead.
17593
17594 For an example of better bindings generated from the C++ front-end,
17595 the name of the parameters (when available) are actually ignored by the C
17596 front-end. Consider the following C header:
17597
17598 @smallexample
17599 extern void foo (int variable);
17600 @end smallexample
17601
17602 with the C front-end, @code{variable} is ignored, and the above is handled as:
17603
17604 @smallexample
17605 extern void foo (int);
17606 @end smallexample
17607
17608 generating a generic:
17609
17610 @smallexample
17611 procedure foo (param1 : int);
17612 @end smallexample
17613
17614 with the C++ front-end, the name is available, and we generate:
17615
17616 @smallexample
17617 procedure foo (variable : int);
17618 @end smallexample
17619
17620 In some cases, the generated bindings will be more complete or more meaningful
17621 when defining some macros, which you can do via the @option{-D} switch. This
17622 is for example the case with @file{Xlib.h} under GNU/Linux:
17623
17624 @smallexample
17625 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
17626 @end smallexample
17627
17628 The above will generate more complete bindings than a straight call without
17629 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
17630
17631 In other cases, it is not possible to parse a header file in a stand alone
17632 manner, because other include files need to be included first. In this
17633 case, the solution is to create a small header file including the needed
17634 @code{#include} and possible @code{#define} directives. For example, to
17635 generate Ada bindings for @file{readline/readline.h}, you need to first
17636 include @file{stdio.h}, so you can create a file with the following two
17637 lines in e.g. @file{readline1.h}:
17638
17639 @smallexample
17640 #include <stdio.h>
17641 #include <readline/readline.h>
17642 @end smallexample
17643
17644 and then generate Ada bindings from this file:
17645
17646 @smallexample
17647 $ g++ -c -fdump-ada-spec readline1.h
17648 @end smallexample
17649
17650 @node Generating bindings for C++ headers
17651 @section Generating bindings for C++ headers
17652
17653 @noindent
17654 Generating bindings for C++ headers is done using the same options, always
17655 with the @command{g++} compiler.
17656
17657 In this mode, C++ classes will be mapped to Ada tagged types, constructors
17658 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
17659 multiple inheritance of abstract classes will be mapped to Ada interfaces
17660 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
17661 information on interfacing to C++).
17662
17663 For example, given the following C++ header file:
17664
17665 @smallexample
17666 @group
17667 @cartouche
17668 class Carnivore @{
17669 public:
17670    virtual int Number_Of_Teeth () = 0;
17671 @};
17672
17673 class Domestic @{
17674 public:
17675    virtual void Set_Owner (char* Name) = 0;
17676 @};
17677
17678 class Animal @{
17679 public:
17680   int Age_Count;
17681   virtual void Set_Age (int New_Age);
17682 @};
17683
17684 class Dog : Animal, Carnivore, Domestic @{
17685  public:
17686   int  Tooth_Count;
17687   char *Owner;
17688
17689   virtual int  Number_Of_Teeth ();
17690   virtual void Set_Owner (char* Name);
17691
17692   Dog();
17693 @};
17694 @end cartouche
17695 @end group
17696 @end smallexample
17697
17698 The corresponding Ada code is generated:
17699
17700 @smallexample @c ada
17701 @group
17702 @cartouche
17703   package Class_Carnivore is
17704     type Carnivore is limited interface;
17705     pragma Import (CPP, Carnivore);
17706
17707     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
17708   end;
17709   use Class_Carnivore;
17710
17711   package Class_Domestic is
17712     type Domestic is limited interface;
17713     pragma Import (CPP, Domestic);
17714
17715     procedure Set_Owner
17716       (this : access Domestic;
17717        Name : Interfaces.C.Strings.chars_ptr) is abstract;
17718   end;
17719   use Class_Domestic;
17720
17721   package Class_Animal is
17722     type Animal is tagged limited record
17723       Age_Count : aliased int;
17724     end record;
17725     pragma Import (CPP, Animal);
17726
17727     procedure Set_Age (this : access Animal; New_Age : int);
17728     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
17729   end;
17730   use Class_Animal;
17731
17732   package Class_Dog is
17733     type Dog is new Animal and Carnivore and Domestic with record
17734       Tooth_Count : aliased int;
17735       Owner : Interfaces.C.Strings.chars_ptr;
17736     end record;
17737     pragma Import (CPP, Dog);
17738
17739     function Number_Of_Teeth (this : access Dog) return int;
17740     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
17741
17742     procedure Set_Owner
17743       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
17744     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
17745
17746     function New_Dog return Dog;
17747     pragma CPP_Constructor (New_Dog);
17748     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
17749   end;
17750   use Class_Dog;
17751 @end cartouche
17752 @end group
17753 @end smallexample
17754
17755 @node Switches
17756 @section Switches
17757
17758 @table @option
17759 @item -fdump-ada-spec
17760 @cindex @option{-fdump-ada-spec} (@command{gcc})
17761 Generate Ada spec files for the given header files transitively (including
17762 all header files that these headers depend upon).
17763
17764 @item -fdump-ada-spec-slim
17765 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
17766 Generate Ada spec files for the header files specified on the command line
17767 only.
17768
17769 @item -C
17770 @cindex @option{-C} (@command{gcc})
17771 Extract comments from headers and generate Ada comments in the Ada spec files.
17772 @end table
17773
17774 @node Other Utility Programs
17775 @chapter Other Utility Programs
17776
17777 @noindent
17778 This chapter discusses some other utility programs available in the Ada
17779 environment.
17780
17781 @menu
17782 * Using Other Utility Programs with GNAT::
17783 * The External Symbol Naming Scheme of GNAT::
17784 * Converting Ada Files to html with gnathtml::
17785 * Installing gnathtml::
17786 @ifset vms
17787 * LSE::
17788 * Profiling::
17789 @end ifset
17790 @end menu
17791
17792 @node Using Other Utility Programs with GNAT
17793 @section Using Other Utility Programs with GNAT
17794
17795 @noindent
17796 The object files generated by GNAT are in standard system format and in
17797 particular the debugging information uses this format. This means
17798 programs generated by GNAT can be used with existing utilities that
17799 depend on these formats.
17800
17801 @ifclear vms
17802 In general, any utility program that works with C will also often work with
17803 Ada programs generated by GNAT. This includes software utilities such as
17804 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17805 as Purify.
17806 @end ifclear
17807
17808 @node The External Symbol Naming Scheme of GNAT
17809 @section The External Symbol Naming Scheme of GNAT
17810
17811 @noindent
17812 In order to interpret the output from GNAT, when using tools that are
17813 originally intended for use with other languages, it is useful to
17814 understand the conventions used to generate link names from the Ada
17815 entity names.
17816
17817 All link names are in all lowercase letters. With the exception of library
17818 procedure names, the mechanism used is simply to use the full expanded
17819 Ada name with dots replaced by double underscores. For example, suppose
17820 we have the following package spec:
17821
17822 @smallexample @c ada
17823 @group
17824 @cartouche
17825 package QRS is
17826    MN : Integer;
17827 end QRS;
17828 @end cartouche
17829 @end group
17830 @end smallexample
17831
17832 @noindent
17833 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17834 the corresponding link name is @code{qrs__mn}.
17835 @findex Export
17836 Of course if a @code{pragma Export} is used this may be overridden:
17837
17838 @smallexample @c ada
17839 @group
17840 @cartouche
17841 package Exports is
17842    Var1 : Integer;
17843    pragma Export (Var1, C, External_Name => "var1_name");
17844    Var2 : Integer;
17845    pragma Export (Var2, C, Link_Name => "var2_link_name");
17846 end Exports;
17847 @end cartouche
17848 @end group
17849 @end smallexample
17850
17851 @noindent
17852 In this case, the link name for @var{Var1} is whatever link name the
17853 C compiler would assign for the C function @var{var1_name}. This typically
17854 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17855 system conventions, but other possibilities exist. The link name for
17856 @var{Var2} is @var{var2_link_name}, and this is not operating system
17857 dependent.
17858
17859 @findex _main
17860 One exception occurs for library level procedures. A potential ambiguity
17861 arises between the required name @code{_main} for the C main program,
17862 and the name we would otherwise assign to an Ada library level procedure
17863 called @code{Main} (which might well not be the main program).
17864
17865 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17866 names. So if we have a library level procedure such as
17867
17868 @smallexample @c ada
17869 @group
17870 @cartouche
17871 procedure Hello (S : String);
17872 @end cartouche
17873 @end group
17874 @end smallexample
17875
17876 @noindent
17877 the external name of this procedure will be @var{_ada_hello}.
17878
17879
17880 @node Converting Ada Files to html with gnathtml
17881 @section Converting Ada Files to HTML with @code{gnathtml}
17882
17883 @noindent
17884 This @code{Perl} script allows Ada source files to be browsed using
17885 standard Web browsers. For installation procedure, see the section
17886 @xref{Installing gnathtml}.
17887
17888 Ada reserved keywords are highlighted in a bold font and Ada comments in
17889 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17890 switch to suppress the generation of cross-referencing information, user
17891 defined variables and types will appear in a different color; you will
17892 be able to click on any identifier and go to its declaration.
17893
17894 The command line is as follow:
17895 @smallexample
17896 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
17897 @c Expanding @ovar macro inline (explanation in macro def comments)
17898 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
17899 @end smallexample
17900
17901 @noindent
17902 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17903 an html file for every ada file, and a global file called @file{index.htm}.
17904 This file is an index of every identifier defined in the files.
17905
17906 The available ^switches^options^ are the following ones:
17907
17908 @table @option
17909 @item -83
17910 @cindex @option{-83} (@code{gnathtml})
17911 Only the Ada 83 subset of keywords will be highlighted.
17912
17913 @item -cc @var{color}
17914 @cindex @option{-cc} (@code{gnathtml})
17915 This option allows you to change the color used for comments. The default
17916 value is green. The color argument can be any name accepted by html.
17917
17918 @item -d
17919 @cindex @option{-d} (@code{gnathtml})
17920 If the Ada files depend on some other files (for instance through
17921 @code{with} clauses, the latter files will also be converted to html.
17922 Only the files in the user project will be converted to html, not the files
17923 in the run-time library itself.
17924
17925 @item -D
17926 @cindex @option{-D} (@code{gnathtml})
17927 This command is the same as @option{-d} above, but @command{gnathtml} will
17928 also look for files in the run-time library, and generate html files for them.
17929
17930 @item -ext @var{extension}
17931 @cindex @option{-ext} (@code{gnathtml})
17932 This option allows you to change the extension of the generated HTML files.
17933 If you do not specify an extension, it will default to @file{htm}.
17934
17935 @item -f
17936 @cindex @option{-f} (@code{gnathtml})
17937 By default, gnathtml will generate html links only for global entities
17938 ('with'ed units, global variables and types,@dots{}).  If you specify
17939 @option{-f} on the command line, then links will be generated for local
17940 entities too.
17941
17942 @item -l @var{number}
17943 @cindex @option{-l} (@code{gnathtml})
17944 If this ^switch^option^ is provided and @var{number} is not 0, then
17945 @code{gnathtml} will number the html files every @var{number} line.
17946
17947 @item -I @var{dir}
17948 @cindex @option{-I} (@code{gnathtml})
17949 Specify a directory to search for library files (@file{.ALI} files) and
17950 source files. You can provide several -I switches on the command line,
17951 and the directories will be parsed in the order of the command line.
17952
17953 @item -o @var{dir}
17954 @cindex @option{-o} (@code{gnathtml})
17955 Specify the output directory for html files. By default, gnathtml will
17956 saved the generated html files in a subdirectory named @file{html/}.
17957
17958 @item -p @var{file}
17959 @cindex @option{-p} (@code{gnathtml})
17960 If you are using Emacs and the most recent Emacs Ada mode, which provides
17961 a full Integrated Development Environment for compiling, checking,
17962 running and debugging applications, you may use @file{.gpr} files
17963 to give the directories where Emacs can find sources and object files.
17964
17965 Using this ^switch^option^, you can tell gnathtml to use these files.
17966 This allows you to get an html version of your application, even if it
17967 is spread over multiple directories.
17968
17969 @item -sc @var{color}
17970 @cindex @option{-sc} (@code{gnathtml})
17971 This ^switch^option^ allows you to change the color used for symbol
17972 definitions.
17973 The default value is red. The color argument can be any name accepted by html.
17974
17975 @item -t @var{file}
17976 @cindex @option{-t} (@code{gnathtml})
17977 This ^switch^option^ provides the name of a file. This file contains a list of
17978 file names to be converted, and the effect is exactly as though they had
17979 appeared explicitly on the command line. This
17980 is the recommended way to work around the command line length limit on some
17981 systems.
17982
17983 @end table
17984
17985 @node Installing gnathtml
17986 @section Installing @code{gnathtml}
17987
17988 @noindent
17989 @code{Perl} needs to be installed on your machine to run this script.
17990 @code{Perl} is freely available for almost every architecture and
17991 Operating System via the Internet.
17992
17993 On Unix systems, you  may want to modify  the  first line of  the script
17994 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17995 is. The syntax of this line is:
17996 @smallexample
17997 #!full_path_name_to_perl
17998 @end smallexample
17999
18000 @noindent
18001 Alternatively, you may run the script using the following command line:
18002
18003 @smallexample
18004 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18005 @c Expanding @ovar macro inline (explanation in macro def comments)
18006 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18007 @end smallexample
18008
18009 @ifset vms
18010 @node LSE
18011 @section LSE
18012 @findex LSE
18013
18014 @noindent
18015 The GNAT distribution provides an Ada 95 template for the HP Language
18016 Sensitive Editor (LSE), a component of DECset. In order to
18017 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18018
18019 @node Profiling
18020 @section Profiling
18021 @findex PCA
18022
18023 @noindent
18024 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18025 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18026 the collection phase with the /DEBUG qualifier.
18027
18028 @smallexample
18029 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18030 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18031 $ RUN/DEBUG <PROGRAM_NAME>
18032 @end smallexample
18033 @noindent
18034 @end ifset
18035
18036 @ifclear vms
18037 @c ******************************
18038 @node Code Coverage and Profiling
18039 @chapter Code Coverage and Profiling
18040 @cindex Code Coverage
18041 @cindex Profiling
18042
18043 @noindent
18044 This chapter describes how to use @code{gcov} - coverage testing tool - and
18045 @code{gprof} - profiler tool - on your Ada programs.
18046
18047 @menu
18048 * Code Coverage of Ada Programs using gcov::
18049 * Profiling an Ada Program using gprof::
18050 @end menu
18051
18052 @node Code Coverage of Ada Programs using gcov
18053 @section Code Coverage of Ada Programs using gcov
18054 @cindex gcov
18055 @cindex -fprofile-arcs
18056 @cindex -ftest-coverage
18057 @cindex -coverage
18058 @cindex Code Coverage
18059
18060 @noindent
18061 @code{gcov} is a test coverage program: it analyzes the execution of a given
18062 program on selected tests, to help you determine the portions of the program
18063 that are still untested.
18064
18065 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18066 User's Guide. You can refer to this documentation for a more complete
18067 description.
18068
18069 This chapter provides a quick startup guide, and
18070 details some Gnat-specific features.
18071
18072 @menu
18073 * Quick startup guide::
18074 * Gnat specifics::
18075 @end menu
18076
18077 @node Quick startup guide
18078 @subsection Quick startup guide
18079
18080 In order to perform coverage analysis of a program using @code{gcov}, 3
18081 steps are needed:
18082
18083 @itemize @bullet
18084 @item
18085 Code instrumentation during the compilation process
18086 @item
18087 Execution of the instrumented program
18088 @item
18089 Execution of the @code{gcov} tool to generate the result.
18090 @end itemize
18091
18092 The code instrumentation needed by gcov is created at the object level:
18093 The source code is not modified in any way, because the instrumentation code is
18094 inserted by gcc during the compilation process. To compile your code with code
18095 coverage activated, you need to recompile your whole project using the
18096 switches
18097 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18098 @code{-fprofile-arcs}.
18099
18100 @smallexample
18101 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18102    -largs -fprofile-arcs
18103 @end smallexample
18104
18105 This compilation process will create @file{.gcno} files together with
18106 the usual object files.
18107
18108 Once the program is compiled with coverage instrumentation, you can
18109 run it as many times as needed - on portions of a test suite for
18110 example. The first execution will produce @file{.gcda} files at the
18111 same location as the @file{.gcno} files.  The following executions
18112 will update those files, so that a cumulative result of the covered
18113 portions of the program is generated.
18114
18115 Finally, you need to call the @code{gcov} tool. The different options of
18116 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18117
18118 This will create annotated source files with a @file{.gcov} extension:
18119 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18120
18121 @node Gnat specifics
18122 @subsection Gnat specifics
18123
18124 Because Ada semantics, portions of the source code may be shared among
18125 several object files. This is the case for example when generics are
18126 involved, when inlining is active  or when declarations generate  initialisation
18127 calls. In order to take
18128 into account this shared code, you need to call @code{gcov} on all
18129 source files of the tested program at once.
18130
18131 The list of source files might exceed the system's maximum command line
18132 length. In order to bypass this limitation, a new mechanism has been
18133 implemented in @code{gcov}: you can now list all your project's files into a
18134 text file, and provide this file to gcov as a parameter,  preceded by a @@
18135 (e.g. @samp{gcov @@mysrclist.txt}).
18136
18137 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18138 not supported as there can be unresolved symbols during the final link.
18139
18140 @node Profiling an Ada Program using gprof
18141 @section Profiling an Ada Program using gprof
18142 @cindex gprof
18143 @cindex -pg
18144 @cindex Profiling
18145
18146 @noindent
18147 This section is not meant to be an exhaustive documentation of @code{gprof}.
18148 Full documentation for it can be found in the GNU Profiler User's Guide
18149 documentation that is part of this GNAT distribution.
18150
18151 Profiling a program helps determine the parts of a program that are executed
18152 most often, and are therefore the most time-consuming.
18153
18154 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18155 better handle Ada programs and multitasking.
18156 It is currently supported on the following platforms
18157 @itemize @bullet
18158 @item
18159 linux x86/x86_64
18160 @item
18161 solaris sparc/sparc64/x86
18162 @item
18163 windows x86
18164 @end itemize
18165
18166 @noindent
18167 In order to profile a program using @code{gprof}, 3 steps are needed:
18168
18169 @itemize @bullet
18170 @item
18171 Code instrumentation, requiring a full recompilation of the project with the
18172 proper switches.
18173 @item
18174 Execution of the program under the analysis conditions, i.e. with the desired
18175 input.
18176 @item
18177 Analysis of the results using the @code{gprof} tool.
18178 @end itemize
18179
18180 @noindent
18181 The following sections detail the different steps, and indicate how
18182 to interpret the results:
18183 @menu
18184 * Compilation for profiling::
18185 * Program execution::
18186 * Running gprof::
18187 * Interpretation of profiling results::
18188 @end menu
18189
18190 @node Compilation for profiling
18191 @subsection Compilation for profiling
18192 @cindex -pg
18193 @cindex Profiling
18194
18195 In order to profile a program the first step is to tell the compiler
18196 to generate the necessary profiling information. The compiler switch to be used
18197 is @code{-pg}, which must be added to other compilation switches. This
18198 switch needs to be specified both during compilation and link stages, and can
18199 be specified once when using gnatmake:
18200
18201 @smallexample
18202 gnatmake -f -pg -P my_project
18203 @end smallexample
18204
18205 @noindent
18206 Note that only the objects that were compiled with the @samp{-pg} switch will
18207 be profiled; if you need to profile your whole project, use the @samp{-f}
18208 gnatmake switch to force full recompilation.
18209
18210 @node Program execution
18211 @subsection Program execution
18212
18213 @noindent
18214 Once the program has been compiled for profiling, you can run it as usual.
18215
18216 The only constraint imposed by profiling is that the program must terminate
18217 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18218 properly analyzed.
18219
18220 Once the program completes execution, a data file called @file{gmon.out} is
18221 generated in the directory where the program was launched from. If this file
18222 already exists, it will be overwritten.
18223
18224 @node Running gprof
18225 @subsection Running gprof
18226
18227 @noindent
18228 The @code{gprof} tool is called as follow:
18229
18230 @smallexample
18231 gprof my_prog gmon.out
18232 @end smallexample
18233
18234 @noindent
18235 or simpler:
18236
18237 @smallexample
18238 gprof my_prog
18239 @end smallexample
18240
18241 @noindent
18242 The complete form of the gprof command line is the following:
18243
18244 @smallexample
18245 gprof [^switches^options^] [executable [data-file]]
18246 @end smallexample
18247
18248 @noindent
18249 @code{gprof} supports numerous ^switch^options^. The order of these
18250 ^switch^options^ does not matter. The full list of options can be found in
18251 the GNU Profiler User's Guide documentation that comes with this documentation.
18252
18253 The following is the subset of those switches that is most relevant:
18254
18255 @table @option
18256
18257 @item --demangle[=@var{style}]
18258 @itemx --no-demangle
18259 @cindex @option{--demangle} (@code{gprof})
18260 These options control whether symbol names should be demangled when
18261 printing output.  The default is to demangle C++ symbols.  The
18262 @code{--no-demangle} option may be used to turn off demangling. Different
18263 compilers have different mangling styles.  The optional demangling style
18264 argument can be used to choose an appropriate demangling style for your
18265 compiler, in particular Ada symbols generated by GNAT can be demangled using
18266 @code{--demangle=gnat}.
18267
18268 @item -e @var{function_name}
18269 @cindex @option{-e} (@code{gprof})
18270 The @samp{-e @var{function}} option tells @code{gprof} not to print
18271 information about the function @var{function_name} (and its
18272 children@dots{}) in the call graph.  The function will still be listed
18273 as a child of any functions that call it, but its index number will be
18274 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18275 given; only one @var{function_name} may be indicated with each @samp{-e}
18276 option.
18277
18278 @item -E @var{function_name}
18279 @cindex @option{-E} (@code{gprof})
18280 The @code{-E @var{function}} option works like the @code{-e} option, but
18281 execution time spent in the function (and children who were not called from
18282 anywhere else), will not be used to compute the percentages-of-time for
18283 the call graph.  More than one @samp{-E} option may be given; only one
18284 @var{function_name} may be indicated with each @samp{-E} option.
18285
18286 @item -f @var{function_name}
18287 @cindex @option{-f} (@code{gprof})
18288 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18289 call graph to the function @var{function_name} and its children (and
18290 their children@dots{}).  More than one @samp{-f} option may be given;
18291 only one @var{function_name} may be indicated with each @samp{-f}
18292 option.
18293
18294 @item -F @var{function_name}
18295 @cindex @option{-F} (@code{gprof})
18296 The @samp{-F @var{function}} option works like the @code{-f} option, but
18297 only time spent in the function and its children (and their
18298 children@dots{}) will be used to determine total-time and
18299 percentages-of-time for the call graph.  More than one @samp{-F} option
18300 may be given; only one @var{function_name} may be indicated with each
18301 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18302
18303 @end table
18304
18305 @node Interpretation of profiling results
18306 @subsection Interpretation of profiling results
18307
18308 @noindent
18309
18310 The results of the profiling analysis are represented by two arrays: the
18311 'flat profile' and the 'call graph'. Full documentation of those outputs
18312 can be found in the GNU Profiler User's Guide.
18313
18314 The flat profile shows the time spent in each function of the program, and how
18315 many time it has been called. This allows you to locate easily the most
18316 time-consuming functions.
18317
18318 The call graph shows, for each subprogram, the subprograms that call it,
18319 and the subprograms that it calls. It also provides an estimate of the time
18320 spent in each of those callers/called subprograms.
18321 @end ifclear
18322
18323 @c ******************************
18324 @node Running and Debugging Ada Programs
18325 @chapter Running and Debugging Ada Programs
18326 @cindex Debugging
18327
18328 @noindent
18329 This chapter discusses how to debug Ada programs.
18330 @ifset vms
18331 It applies to GNAT on the Alpha OpenVMS platform;
18332 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18333 since HP has implemented Ada support in the OpenVMS debugger on I64.
18334 @end ifset
18335
18336 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18337
18338 @enumerate
18339 @item
18340 The illegality may be a violation of the static semantics of Ada. In
18341 that case GNAT diagnoses the constructs in the program that are illegal.
18342 It is then a straightforward matter for the user to modify those parts of
18343 the program.
18344
18345 @item
18346 The illegality may be a violation of the dynamic semantics of Ada. In
18347 that case the program compiles and executes, but may generate incorrect
18348 results, or may terminate abnormally with some exception.
18349
18350 @item
18351 When presented with a program that contains convoluted errors, GNAT
18352 itself may terminate abnormally without providing full diagnostics on
18353 the incorrect user program.
18354 @end enumerate
18355
18356 @menu
18357 * The GNAT Debugger GDB::
18358 * Running GDB::
18359 * Introduction to GDB Commands::
18360 * Using Ada Expressions::
18361 * Calling User-Defined Subprograms::
18362 * Using the Next Command in a Function::
18363 * Ada Exceptions::
18364 * Ada Tasks::
18365 * Debugging Generic Units::
18366 * Remote Debugging using gdbserver::
18367 * GNAT Abnormal Termination or Failure to Terminate::
18368 * Naming Conventions for GNAT Source Files::
18369 * Getting Internal Debugging Information::
18370 * Stack Traceback::
18371 @end menu
18372
18373 @cindex Debugger
18374 @findex gdb
18375
18376 @node The GNAT Debugger GDB
18377 @section The GNAT Debugger GDB
18378
18379 @noindent
18380 @code{GDB} is a general purpose, platform-independent debugger that
18381 can be used to debug mixed-language programs compiled with @command{gcc},
18382 and in particular is capable of debugging Ada programs compiled with
18383 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18384 complex Ada data structures.
18385
18386 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18387 @ifset vms
18388 located in the GNU:[DOCS] directory,
18389 @end ifset
18390 for full details on the usage of @code{GDB}, including a section on
18391 its usage on programs. This manual should be consulted for full
18392 details. The section that follows is a brief introduction to the
18393 philosophy and use of @code{GDB}.
18394
18395 When GNAT programs are compiled, the compiler optionally writes debugging
18396 information into the generated object file, including information on
18397 line numbers, and on declared types and variables. This information is
18398 separate from the generated code. It makes the object files considerably
18399 larger, but it does not add to the size of the actual executable that
18400 will be loaded into memory, and has no impact on run-time performance. The
18401 generation of debug information is triggered by the use of the
18402 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18403 used to carry out the compilations. It is important to emphasize that
18404 the use of these options does not change the generated code.
18405
18406 The debugging information is written in standard system formats that
18407 are used by many tools, including debuggers and profilers. The format
18408 of the information is typically designed to describe C types and
18409 semantics, but GNAT implements a translation scheme which allows full
18410 details about Ada types and variables to be encoded into these
18411 standard C formats. Details of this encoding scheme may be found in
18412 the file exp_dbug.ads in the GNAT source distribution. However, the
18413 details of this encoding are, in general, of no interest to a user,
18414 since @code{GDB} automatically performs the necessary decoding.
18415
18416 When a program is bound and linked, the debugging information is
18417 collected from the object files, and stored in the executable image of
18418 the program. Again, this process significantly increases the size of
18419 the generated executable file, but it does not increase the size of
18420 the executable program itself. Furthermore, if this program is run in
18421 the normal manner, it runs exactly as if the debug information were
18422 not present, and takes no more actual memory.
18423
18424 However, if the program is run under control of @code{GDB}, the
18425 debugger is activated.  The image of the program is loaded, at which
18426 point it is ready to run.  If a run command is given, then the program
18427 will run exactly as it would have if @code{GDB} were not present. This
18428 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18429 entirely non-intrusive until a breakpoint is encountered.  If no
18430 breakpoint is ever hit, the program will run exactly as it would if no
18431 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18432 the debugging information and can respond to user commands to inspect
18433 variables, and more generally to report on the state of execution.
18434
18435 @c **************
18436 @node Running GDB
18437 @section Running GDB
18438
18439 @noindent
18440 This section describes how to initiate the debugger.
18441 @c The above sentence is really just filler, but it was otherwise
18442 @c clumsy to get the first paragraph nonindented given the conditional
18443 @c nature of the description
18444
18445 @ifclear vms
18446 The debugger can be launched from a @code{GPS} menu or
18447 directly from the command line. The description below covers the latter use.
18448 All the commands shown can be used in the @code{GPS} debug console window,
18449 but there are usually more GUI-based ways to achieve the same effect.
18450 @end ifclear
18451
18452 The command to run @code{GDB} is
18453
18454 @smallexample
18455 $ ^gdb program^GDB PROGRAM^
18456 @end smallexample
18457
18458 @noindent
18459 where @code{^program^PROGRAM^} is the name of the executable file. This
18460 activates the debugger and results in a prompt for debugger commands.
18461 The simplest command is simply @code{run}, which causes the program to run
18462 exactly as if the debugger were not present. The following section
18463 describes some of the additional commands that can be given to @code{GDB}.
18464
18465 @c *******************************
18466 @node Introduction to GDB Commands
18467 @section Introduction to GDB Commands
18468
18469 @noindent
18470 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18471 Debugging with GDB, gdb, Debugging with GDB},
18472 @ifset vms
18473 located in the GNU:[DOCS] directory,
18474 @end ifset
18475 for extensive documentation on the use
18476 of these commands, together with examples of their use. Furthermore,
18477 the command @command{help} invoked from within GDB activates a simple help
18478 facility which summarizes the available commands and their options.
18479 In this section we summarize a few of the most commonly
18480 used commands to give an idea of what @code{GDB} is about. You should create
18481 a simple program with debugging information and experiment with the use of
18482 these @code{GDB} commands on the program as you read through the
18483 following section.
18484
18485 @table @code
18486 @item set args @var{arguments}
18487 The @var{arguments} list above is a list of arguments to be passed to
18488 the program on a subsequent run command, just as though the arguments
18489 had been entered on a normal invocation of the program. The @code{set args}
18490 command is not needed if the program does not require arguments.
18491
18492 @item run
18493 The @code{run} command causes execution of the program to start from
18494 the beginning. If the program is already running, that is to say if
18495 you are currently positioned at a breakpoint, then a prompt will ask
18496 for confirmation that you want to abandon the current execution and
18497 restart.
18498
18499 @item breakpoint @var{location}
18500 The breakpoint command sets a breakpoint, that is to say a point at which
18501 execution will halt and @code{GDB} will await further
18502 commands. @var{location} is
18503 either a line number within a file, given in the format @code{file:linenumber},
18504 or it is the name of a subprogram. If you request that a breakpoint be set on
18505 a subprogram that is overloaded, a prompt will ask you to specify on which of
18506 those subprograms you want to breakpoint. You can also
18507 specify that all of them should be breakpointed. If the program is run
18508 and execution encounters the breakpoint, then the program
18509 stops and @code{GDB} signals that the breakpoint was encountered by
18510 printing the line of code before which the program is halted.
18511
18512 @item catch exception @var{name}
18513 This command causes the program execution to stop whenever exception
18514 @var{name} is raised.  If @var{name} is omitted, then the execution is
18515 suspended when any exception is raised.
18516
18517 @item print @var{expression}
18518 This will print the value of the given expression. Most simple
18519 Ada expression formats are properly handled by @code{GDB}, so the expression
18520 can contain function calls, variables, operators, and attribute references.
18521
18522 @item continue
18523 Continues execution following a breakpoint, until the next breakpoint or the
18524 termination of the program.
18525
18526 @item step
18527 Executes a single line after a breakpoint. If the next statement
18528 is a subprogram call, execution continues into (the first statement of)
18529 the called subprogram.
18530
18531 @item next
18532 Executes a single line. If this line is a subprogram call, executes and
18533 returns from the call.
18534
18535 @item list
18536 Lists a few lines around the current source location. In practice, it
18537 is usually more convenient to have a separate edit window open with the
18538 relevant source file displayed. Successive applications of this command
18539 print subsequent lines. The command can be given an argument which is a
18540 line number, in which case it displays a few lines around the specified one.
18541
18542 @item backtrace
18543 Displays a backtrace of the call chain. This command is typically
18544 used after a breakpoint has occurred, to examine the sequence of calls that
18545 leads to the current breakpoint. The display includes one line for each
18546 activation record (frame) corresponding to an active subprogram.
18547
18548 @item up
18549 At a breakpoint, @code{GDB} can display the values of variables local
18550 to the current frame. The command @code{up} can be used to
18551 examine the contents of other active frames, by moving the focus up
18552 the stack, that is to say from callee to caller, one frame at a time.
18553
18554 @item down
18555 Moves the focus of @code{GDB} down from the frame currently being
18556 examined to the frame of its callee (the reverse of the previous command),
18557
18558 @item frame @var{n}
18559 Inspect the frame with the given number. The value 0 denotes the frame
18560 of the current breakpoint, that is to say the top of the call stack.
18561
18562 @end table
18563
18564 @noindent
18565 The above list is a very short introduction to the commands that
18566 @code{GDB} provides. Important additional capabilities, including conditional
18567 breakpoints, the ability to execute command sequences on a breakpoint,
18568 the ability to debug at the machine instruction level and many other
18569 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
18570 Debugging with GDB}.  Note that most commands can be abbreviated
18571 (for example, c for continue, bt for backtrace).
18572
18573 @node Using Ada Expressions
18574 @section Using Ada Expressions
18575 @cindex Ada expressions
18576
18577 @noindent
18578 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18579 extensions. The philosophy behind the design of this subset is
18580
18581 @itemize @bullet
18582 @item
18583 That @code{GDB} should provide basic literals and access to operations for
18584 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18585 leaving more sophisticated computations to subprograms written into the
18586 program (which therefore may be called from @code{GDB}).
18587
18588 @item
18589 That type safety and strict adherence to Ada language restrictions
18590 are not particularly important to the @code{GDB} user.
18591
18592 @item
18593 That brevity is important to the @code{GDB} user.
18594 @end itemize
18595
18596 @noindent
18597 Thus, for brevity, the debugger acts as if there were
18598 implicit @code{with} and @code{use} clauses in effect for all user-written
18599 packages, thus making it unnecessary to fully qualify most names with
18600 their packages, regardless of context. Where this causes ambiguity,
18601 @code{GDB} asks the user's intent.
18602
18603 For details on the supported Ada syntax, see @ref{Top,, Debugging with
18604 GDB, gdb, Debugging with GDB}.
18605
18606 @node Calling User-Defined Subprograms
18607 @section Calling User-Defined Subprograms
18608
18609 @noindent
18610 An important capability of @code{GDB} is the ability to call user-defined
18611 subprograms while debugging. This is achieved simply by entering
18612 a subprogram call statement in the form:
18613
18614 @smallexample
18615 call subprogram-name (parameters)
18616 @end smallexample
18617
18618 @noindent
18619 The keyword @code{call} can be omitted in the normal case where the
18620 @code{subprogram-name} does not coincide with any of the predefined
18621 @code{GDB} commands.
18622
18623 The effect is to invoke the given subprogram, passing it the
18624 list of parameters that is supplied. The parameters can be expressions and
18625 can include variables from the program being debugged. The
18626 subprogram must be defined
18627 at the library level within your program, and @code{GDB} will call the
18628 subprogram within the environment of your program execution (which
18629 means that the subprogram is free to access or even modify variables
18630 within your program).
18631
18632 The most important use of this facility is in allowing the inclusion of
18633 debugging routines that are tailored to particular data structures
18634 in your program. Such debugging routines can be written to provide a suitably
18635 high-level description of an abstract type, rather than a low-level dump
18636 of its physical layout. After all, the standard
18637 @code{GDB print} command only knows the physical layout of your
18638 types, not their abstract meaning. Debugging routines can provide information
18639 at the desired semantic level and are thus enormously useful.
18640
18641 For example, when debugging GNAT itself, it is crucial to have access to
18642 the contents of the tree nodes used to represent the program internally.
18643 But tree nodes are represented simply by an integer value (which in turn
18644 is an index into a table of nodes).
18645 Using the @code{print} command on a tree node would simply print this integer
18646 value, which is not very useful. But the PN routine (defined in file
18647 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18648 a useful high level representation of the tree node, which includes the
18649 syntactic category of the node, its position in the source, the integers
18650 that denote descendant nodes and parent node, as well as varied
18651 semantic information. To study this example in more detail, you might want to
18652 look at the body of the PN procedure in the stated file.
18653
18654 @node Using the Next Command in a Function
18655 @section Using the Next Command in a Function
18656
18657 @noindent
18658 When you use the @code{next} command in a function, the current source
18659 location will advance to the next statement as usual. A special case
18660 arises in the case of a @code{return} statement.
18661
18662 Part of the code for a return statement is the ``epilog'' of the function.
18663 This is the code that returns to the caller. There is only one copy of
18664 this epilog code, and it is typically associated with the last return
18665 statement in the function if there is more than one return. In some
18666 implementations, this epilog is associated with the first statement
18667 of the function.
18668
18669 The result is that if you use the @code{next} command from a return
18670 statement that is not the last return statement of the function you
18671 may see a strange apparent jump to the last return statement or to
18672 the start of the function. You should simply ignore this odd jump.
18673 The value returned is always that from the first return statement
18674 that was stepped through.
18675
18676 @node Ada Exceptions
18677 @section Stopping when Ada Exceptions are Raised
18678 @cindex Exceptions
18679
18680 @noindent
18681 You can set catchpoints that stop the program execution when your program
18682 raises selected exceptions.
18683
18684 @table @code
18685 @item catch exception
18686 Set a catchpoint that stops execution whenever (any task in the) program
18687 raises any exception.
18688
18689 @item catch exception @var{name}
18690 Set a catchpoint that stops execution whenever (any task in the) program
18691 raises the exception @var{name}.
18692
18693 @item catch exception unhandled
18694 Set a catchpoint that stops executing whenever (any task in the) program
18695 raises an exception for which there is no handler.
18696
18697 @item info exceptions
18698 @itemx info exceptions @var{regexp}
18699 The @code{info exceptions} command permits the user to examine all defined
18700 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18701 argument, prints out only those exceptions whose name matches @var{regexp}.
18702 @end table
18703
18704 @node Ada Tasks
18705 @section Ada Tasks
18706 @cindex Tasks
18707
18708 @noindent
18709 @code{GDB} allows the following task-related commands:
18710
18711 @table @code
18712 @item info tasks
18713 This command shows a list of current Ada tasks, as in the following example:
18714
18715 @smallexample
18716 @iftex
18717 @leftskip=0cm
18718 @end iftex
18719 (gdb) info tasks
18720   ID       TID P-ID   Thread Pri State                 Name
18721    1   8088000   0   807e000  15 Child Activation Wait main_task
18722    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18723    3   809a800   1   80a4800  15 Child Activation Wait a
18724 *  4   80ae800   3   80b8000  15 Running               c
18725 @end smallexample
18726
18727 @noindent
18728 In this listing, the asterisk before the first task indicates it to be the
18729 currently running task. The first column lists the task ID that is used
18730 to refer to tasks in the following commands.
18731
18732 @item break @var{linespec} task @var{taskid}
18733 @itemx break @var{linespec} task @var{taskid} if @dots{}
18734 @cindex Breakpoints and tasks
18735 These commands are like the @code{break @dots{} thread @dots{}}.
18736 @var{linespec} specifies source lines.
18737
18738 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18739 to specify that you only want @code{GDB} to stop the program when a
18740 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18741 numeric task identifiers assigned by @code{GDB}, shown in the first
18742 column of the @samp{info tasks} display.
18743
18744 If you do not specify @samp{task @var{taskid}} when you set a
18745 breakpoint, the breakpoint applies to @emph{all} tasks of your
18746 program.
18747
18748 You can use the @code{task} qualifier on conditional breakpoints as
18749 well; in this case, place @samp{task @var{taskid}} before the
18750 breakpoint condition (before the @code{if}).
18751
18752 @item task @var{taskno}
18753 @cindex Task switching
18754
18755 This command allows to switch to the task referred by @var{taskno}. In
18756 particular, This allows to browse the backtrace of the specified
18757 task. It is advised to switch back to the original task before
18758 continuing execution otherwise the scheduling of the program may be
18759 perturbed.
18760 @end table
18761
18762 @noindent
18763 For more detailed information on the tasking support,
18764 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
18765
18766 @node Debugging Generic Units
18767 @section Debugging Generic Units
18768 @cindex Debugging Generic Units
18769 @cindex Generics
18770
18771 @noindent
18772 GNAT always uses code expansion for generic instantiation. This means that
18773 each time an instantiation occurs, a complete copy of the original code is
18774 made, with appropriate substitutions of formals by actuals.
18775
18776 It is not possible to refer to the original generic entities in
18777 @code{GDB}, but it is always possible to debug a particular instance of
18778 a generic, by using the appropriate expanded names. For example, if we have
18779
18780 @smallexample @c ada
18781 @group
18782 @cartouche
18783 procedure g is
18784
18785    generic package k is
18786       procedure kp (v1 : in out integer);
18787    end k;
18788
18789    package body k is
18790       procedure kp (v1 : in out integer) is
18791       begin
18792          v1 := v1 + 1;
18793       end kp;
18794    end k;
18795
18796    package k1 is new k;
18797    package k2 is new k;
18798
18799    var : integer := 1;
18800
18801 begin
18802    k1.kp (var);
18803    k2.kp (var);
18804    k1.kp (var);
18805    k2.kp (var);
18806 end;
18807 @end cartouche
18808 @end group
18809 @end smallexample
18810
18811 @noindent
18812 Then to break on a call to procedure kp in the k2 instance, simply
18813 use the command:
18814
18815 @smallexample
18816 (gdb) break g.k2.kp
18817 @end smallexample
18818
18819 @noindent
18820 When the breakpoint occurs, you can step through the code of the
18821 instance in the normal manner and examine the values of local variables, as for
18822 other units.
18823
18824 @node Remote Debugging using gdbserver
18825 @section Remote Debugging using gdbserver
18826 @cindex Remote Debugging using gdbserver
18827
18828 @noindent
18829 On platforms where gdbserver is supported, it is possible to use this tool
18830 to debug your application remotely.  This can be useful in situations
18831 where the program needs to be run on a target host that is different
18832 from the host used for development, particularly when the target has
18833 a limited amount of resources (either CPU and/or memory).
18834
18835 To do so, start your program using gdbserver on the target machine.
18836 gdbserver then automatically suspends the execution of your program
18837 at its entry point, waiting for a debugger to connect to it.  The
18838 following commands starts an application and tells gdbserver to
18839 wait for a connection with the debugger on localhost port 4444.
18840
18841 @smallexample
18842 $ gdbserver localhost:4444 program
18843 Process program created; pid = 5685
18844 Listening on port 4444
18845 @end smallexample
18846
18847 Once gdbserver has started listening, we can tell the debugger to establish
18848 a connection with this gdbserver, and then start the same debugging session
18849 as if the program was being debugged on the same host, directly under
18850 the control of GDB.
18851
18852 @smallexample
18853 $ gdb program
18854 (gdb) target remote targethost:4444
18855 Remote debugging using targethost:4444
18856 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18857 (gdb) b foo.adb:3
18858 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18859 (gdb) continue
18860 Continuing.
18861
18862 Breakpoint 1, foo () at foo.adb:4
18863 4       end foo;
18864 @end smallexample
18865
18866 It is also possible to use gdbserver to attach to an already running
18867 program, in which case the execution of that program is simply suspended
18868 until the connection between the debugger and gdbserver is established.
18869
18870 For more information on how to use gdbserver, @ref{Top, Server, Using
18871 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
18872 for gdbserver on x86-linux, x86-windows and x86_64-linux.
18873
18874 @node GNAT Abnormal Termination or Failure to Terminate
18875 @section GNAT Abnormal Termination or Failure to Terminate
18876 @cindex GNAT Abnormal Termination or Failure to Terminate
18877
18878 @noindent
18879 When presented with programs that contain serious errors in syntax
18880 or semantics,
18881 GNAT may on rare occasions  experience problems in operation, such
18882 as aborting with a
18883 segmentation fault or illegal memory access, raising an internal
18884 exception, terminating abnormally, or failing to terminate at all.
18885 In such cases, you can activate
18886 various features of GNAT that can help you pinpoint the construct in your
18887 program that is the likely source of the problem.
18888
18889 The following strategies are presented in increasing order of
18890 difficulty, corresponding to your experience in using GNAT and your
18891 familiarity with compiler internals.
18892
18893 @enumerate
18894 @item
18895 Run @command{gcc} with the @option{-gnatf}. This first
18896 switch causes all errors on a given line to be reported. In its absence,
18897 only the first error on a line is displayed.
18898
18899 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18900 are encountered, rather than after compilation is terminated. If GNAT
18901 terminates prematurely or goes into an infinite loop, the last error
18902 message displayed may help to pinpoint the culprit.
18903
18904 @item
18905 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
18906 mode, @command{gcc} produces ongoing information about the progress of the
18907 compilation and provides the name of each procedure as code is
18908 generated. This switch allows you to find which Ada procedure was being
18909 compiled when it encountered a code generation problem.
18910
18911 @item
18912 @cindex @option{-gnatdc} switch
18913 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18914 switch that does for the front-end what @option{^-v^VERBOSE^} does
18915 for the back end. The system prints the name of each unit,
18916 either a compilation unit or nested unit, as it is being analyzed.
18917 @item
18918 Finally, you can start
18919 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18920 front-end of GNAT, and can be run independently (normally it is just
18921 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
18922 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18923 @code{where} command is the first line of attack; the variable
18924 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18925 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
18926 which the execution stopped, and @code{input_file name} indicates the name of
18927 the source file.
18928 @end enumerate
18929
18930 @node Naming Conventions for GNAT Source Files
18931 @section Naming Conventions for GNAT Source Files
18932
18933 @noindent
18934 In order to examine the workings of the GNAT system, the following
18935 brief description of its organization may be helpful:
18936
18937 @itemize @bullet
18938 @item
18939 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18940
18941 @item
18942 All files prefixed with @file{^par^PAR^} are components of the parser. The
18943 numbers correspond to chapters of the Ada Reference Manual. For example,
18944 parsing of select statements can be found in @file{par-ch9.adb}.
18945
18946 @item
18947 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18948 numbers correspond to chapters of the Ada standard. For example, all
18949 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18950 addition, some features of the language require sufficient special processing
18951 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18952 dynamic dispatching, etc.
18953
18954 @item
18955 All files prefixed with @file{^exp^EXP^} perform normalization and
18956 expansion of the intermediate representation (abstract syntax tree, or AST).
18957 these files use the same numbering scheme as the parser and semantics files.
18958 For example, the construction of record initialization procedures is done in
18959 @file{exp_ch3.adb}.
18960
18961 @item
18962 The files prefixed with @file{^bind^BIND^} implement the binder, which
18963 verifies the consistency of the compilation, determines an order of
18964 elaboration, and generates the bind file.
18965
18966 @item
18967 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18968 data structures used by the front-end.
18969
18970 @item
18971 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18972 the abstract syntax tree as produced by the parser.
18973
18974 @item
18975 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18976 all entities, computed during semantic analysis.
18977
18978 @item
18979 Library management issues are dealt with in files with prefix
18980 @file{^lib^LIB^}.
18981
18982 @item
18983 @findex Ada
18984 @cindex Annex A
18985 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18986 defined in Annex A.
18987
18988 @item
18989 @findex Interfaces
18990 @cindex Annex B
18991 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18992 defined in Annex B.
18993
18994 @item
18995 @findex System
18996 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18997 both language-defined children and GNAT run-time routines.
18998
18999 @item
19000 @findex GNAT
19001 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19002 general-purpose packages, fully documented in their specs. All
19003 the other @file{.c} files are modifications of common @command{gcc} files.
19004 @end itemize
19005
19006 @node Getting Internal Debugging Information
19007 @section Getting Internal Debugging Information
19008
19009 @noindent
19010 Most compilers have internal debugging switches and modes. GNAT
19011 does also, except GNAT internal debugging switches and modes are not
19012 secret. A summary and full description of all the compiler and binder
19013 debug flags are in the file @file{debug.adb}. You must obtain the
19014 sources of the compiler to see the full detailed effects of these flags.
19015
19016 The switches that print the source of the program (reconstructed from
19017 the internal tree) are of general interest for user programs, as are the
19018 options to print
19019 the full internal tree, and the entity table (the symbol table
19020 information). The reconstructed source provides a readable version of the
19021 program after the front-end has completed analysis and  expansion,
19022 and is useful when studying the performance of specific constructs.
19023 For example, constraint checks are indicated, complex aggregates
19024 are replaced with loops and assignments, and tasking primitives
19025 are replaced with run-time calls.
19026
19027 @node Stack Traceback
19028 @section Stack Traceback
19029 @cindex traceback
19030 @cindex stack traceback
19031 @cindex stack unwinding
19032
19033 @noindent
19034 Traceback is a mechanism to display the sequence of subprogram calls that
19035 leads to a specified execution point in a program. Often (but not always)
19036 the execution point is an instruction at which an exception has been raised.
19037 This mechanism is also known as @i{stack unwinding} because it obtains
19038 its information by scanning the run-time stack and recovering the activation
19039 records of all active subprograms. Stack unwinding is one of the most
19040 important tools for program debugging.
19041
19042 The first entry stored in traceback corresponds to the deepest calling level,
19043 that is to say the subprogram currently executing the instruction
19044 from which we want to obtain the traceback.
19045
19046 Note that there is no runtime performance penalty when stack traceback
19047 is enabled, and no exception is raised during program execution.
19048
19049 @menu
19050 * Non-Symbolic Traceback::
19051 * Symbolic Traceback::
19052 @end menu
19053
19054 @node Non-Symbolic Traceback
19055 @subsection Non-Symbolic Traceback
19056 @cindex traceback, non-symbolic
19057
19058 @noindent
19059 Note: this feature is not supported on all platforms. See
19060 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19061 platforms.
19062
19063 @menu
19064 * Tracebacks From an Unhandled Exception::
19065 * Tracebacks From Exception Occurrences (non-symbolic)::
19066 * Tracebacks From Anywhere in a Program (non-symbolic)::
19067 @end menu
19068
19069 @node Tracebacks From an Unhandled Exception
19070 @subsubsection Tracebacks From an Unhandled Exception
19071
19072 @noindent
19073 A runtime non-symbolic traceback is a list of addresses of call instructions.
19074 To enable this feature you must use the @option{-E}
19075 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19076 of exception information. You can retrieve this information using the
19077 @code{addr2line} tool.
19078
19079 Here is a simple example:
19080
19081 @smallexample @c ada
19082 @cartouche
19083 procedure STB is
19084
19085    procedure P1 is
19086    begin
19087       raise Constraint_Error;
19088    end P1;
19089
19090    procedure P2 is
19091    begin
19092       P1;
19093    end P2;
19094
19095 begin
19096    P2;
19097 end STB;
19098 @end cartouche
19099 @end smallexample
19100
19101 @smallexample
19102 $ gnatmake stb -bargs -E
19103 $ stb
19104
19105 Execution terminated by unhandled exception
19106 Exception name: CONSTRAINT_ERROR
19107 Message: stb.adb:5
19108 Call stack traceback locations:
19109 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19110 @end smallexample
19111
19112 @noindent
19113 As we see the traceback lists a sequence of addresses for the unhandled
19114 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19115 guess that this exception come from procedure P1. To translate these
19116 addresses into the source lines where the calls appear, the
19117 @code{addr2line} tool, described below, is invaluable. The use of this tool
19118 requires the program to be compiled with debug information.
19119
19120 @smallexample
19121 $ gnatmake -g stb -bargs -E
19122 $ stb
19123
19124 Execution terminated by unhandled exception
19125 Exception name: CONSTRAINT_ERROR
19126 Message: stb.adb:5
19127 Call stack traceback locations:
19128 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19129
19130 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19131    0x4011f1 0x77e892a4
19132
19133 00401373 at d:/stb/stb.adb:5
19134 0040138B at d:/stb/stb.adb:10
19135 0040139C at d:/stb/stb.adb:14
19136 00401335 at d:/stb/b~stb.adb:104
19137 004011C4 at /build/@dots{}/crt1.c:200
19138 004011F1 at /build/@dots{}/crt1.c:222
19139 77E892A4 in ?? at ??:0
19140 @end smallexample
19141
19142 @noindent
19143 The @code{addr2line} tool has several other useful options:
19144
19145 @table @code
19146 @item --functions
19147 to get the function name corresponding to any location
19148
19149 @item --demangle=gnat
19150 to use the gnat decoding mode for the function names. Note that
19151 for binutils version 2.9.x the option is simply @option{--demangle}.
19152 @end table
19153
19154 @smallexample
19155 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19156    0x40139c 0x401335 0x4011c4 0x4011f1
19157
19158 00401373 in stb.p1 at d:/stb/stb.adb:5
19159 0040138B in stb.p2 at d:/stb/stb.adb:10
19160 0040139C in stb at d:/stb/stb.adb:14
19161 00401335 in main at d:/stb/b~stb.adb:104
19162 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19163 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19164 @end smallexample
19165
19166 @noindent
19167 From this traceback we can see that the exception was raised in
19168 @file{stb.adb} at line 5, which was reached from a procedure call in
19169 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19170 which contains the call to the main program.
19171 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19172 and the output will vary from platform to platform.
19173
19174 It is also possible to use @code{GDB} with these traceback addresses to debug
19175 the program. For example, we can break at a given code location, as reported
19176 in the stack traceback:
19177
19178 @smallexample
19179 $ gdb -nw stb
19180 @ifclear vms
19181 @noindent
19182 Furthermore, this feature is not implemented inside Windows DLL. Only
19183 the non-symbolic traceback is reported in this case.
19184 @end ifclear
19185
19186 (gdb) break *0x401373
19187 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19188 @end smallexample
19189
19190 @noindent
19191 It is important to note that the stack traceback addresses
19192 do not change when debug information is included. This is particularly useful
19193 because it makes it possible to release software without debug information (to
19194 minimize object size), get a field report that includes a stack traceback
19195 whenever an internal bug occurs, and then be able to retrieve the sequence
19196 of calls with the same program compiled with debug information.
19197
19198 @node Tracebacks From Exception Occurrences (non-symbolic)
19199 @subsubsection Tracebacks From Exception Occurrences
19200
19201 @noindent
19202 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19203 The stack traceback is attached to the exception information string, and can
19204 be retrieved in an exception handler within the Ada program, by means of the
19205 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19206
19207 @smallexample @c ada
19208 with Ada.Text_IO;
19209 with Ada.Exceptions;
19210
19211 procedure STB is
19212
19213    use Ada;
19214    use Ada.Exceptions;
19215
19216    procedure P1 is
19217       K : Positive := 1;
19218    begin
19219       K := K - 1;
19220    exception
19221       when E : others =>
19222          Text_IO.Put_Line (Exception_Information (E));
19223    end P1;
19224
19225    procedure P2 is
19226    begin
19227       P1;
19228    end P2;
19229
19230 begin
19231    P2;
19232 end STB;
19233 @end smallexample
19234
19235 @noindent
19236 This program will output:
19237
19238 @smallexample
19239 $ stb
19240
19241 Exception name: CONSTRAINT_ERROR
19242 Message: stb.adb:12
19243 Call stack traceback locations:
19244 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19245 @end smallexample
19246
19247 @node Tracebacks From Anywhere in a Program (non-symbolic)
19248 @subsubsection Tracebacks From Anywhere in a Program
19249
19250 @noindent
19251 It is also possible to retrieve a stack traceback from anywhere in a
19252 program. For this you need to
19253 use the @code{GNAT.Traceback} API. This package includes a procedure called
19254 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19255 display procedures described below. It is not necessary to use the
19256 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19257 is invoked explicitly.
19258
19259 @noindent
19260 In the following example we compute a traceback at a specific location in
19261 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19262 convert addresses to strings:
19263
19264 @smallexample @c ada
19265 with Ada.Text_IO;
19266 with GNAT.Traceback;
19267 with GNAT.Debug_Utilities;
19268
19269 procedure STB is
19270
19271    use Ada;
19272    use GNAT;
19273    use GNAT.Traceback;
19274
19275    procedure P1 is
19276       TB  : Tracebacks_Array (1 .. 10);
19277       --  We are asking for a maximum of 10 stack frames.
19278       Len : Natural;
19279       --  Len will receive the actual number of stack frames returned.
19280    begin
19281       Call_Chain (TB, Len);
19282
19283       Text_IO.Put ("In STB.P1 : ");
19284
19285       for K in 1 .. Len loop
19286          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19287          Text_IO.Put (' ');
19288       end loop;
19289
19290       Text_IO.New_Line;
19291    end P1;
19292
19293    procedure P2 is
19294    begin
19295       P1;
19296    end P2;
19297
19298 begin
19299    P2;
19300 end STB;
19301 @end smallexample
19302
19303 @smallexample
19304 $ gnatmake -g stb
19305 $ stb
19306
19307 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19308 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19309 @end smallexample
19310
19311 @noindent
19312 You can then get further information by invoking the @code{addr2line}
19313 tool as described earlier (note that the hexadecimal addresses
19314 need to be specified in C format, with a leading ``0x'').
19315
19316 @node Symbolic Traceback
19317 @subsection Symbolic Traceback
19318 @cindex traceback, symbolic
19319
19320 @noindent
19321 A symbolic traceback is a stack traceback in which procedure names are
19322 associated with each code location.
19323
19324 @noindent
19325 Note that this feature is not supported on all platforms. See
19326 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19327 list of currently supported platforms.
19328
19329 @noindent
19330 Note that the symbolic traceback requires that the program be compiled
19331 with debug information. If it is not compiled with debug information
19332 only the non-symbolic information will be valid.
19333
19334 @menu
19335 * Tracebacks From Exception Occurrences (symbolic)::
19336 * Tracebacks From Anywhere in a Program (symbolic)::
19337 @end menu
19338
19339 @node Tracebacks From Exception Occurrences (symbolic)
19340 @subsubsection Tracebacks From Exception Occurrences
19341
19342 @smallexample @c ada
19343 with Ada.Text_IO;
19344 with GNAT.Traceback.Symbolic;
19345
19346 procedure STB is
19347
19348    procedure P1 is
19349    begin
19350       raise Constraint_Error;
19351    end P1;
19352
19353    procedure P2 is
19354    begin
19355       P1;
19356    end P2;
19357
19358    procedure P3 is
19359    begin
19360       P2;
19361    end P3;
19362
19363 begin
19364    P3;
19365 exception
19366    when E : others =>
19367       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19368 end STB;
19369 @end smallexample
19370
19371 @smallexample
19372 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19373 $ stb
19374
19375 0040149F in stb.p1 at stb.adb:8
19376 004014B7 in stb.p2 at stb.adb:13
19377 004014CF in stb.p3 at stb.adb:18
19378 004015DD in ada.stb at stb.adb:22
19379 00401461 in main at b~stb.adb:168
19380 004011C4 in __mingw_CRTStartup at crt1.c:200
19381 004011F1 in mainCRTStartup at crt1.c:222
19382 77E892A4 in ?? at ??:0
19383 @end smallexample
19384
19385 @noindent
19386 In the above example the ``.\'' syntax in the @command{gnatmake} command
19387 is currently required by @command{addr2line} for files that are in
19388 the current working directory.
19389 Moreover, the exact sequence of linker options may vary from platform
19390 to platform.
19391 The above @option{-largs} section is for Windows platforms. By contrast,
19392 under Unix there is no need for the @option{-largs} section.
19393 Differences across platforms are due to details of linker implementation.
19394
19395 @node Tracebacks From Anywhere in a Program (symbolic)
19396 @subsubsection Tracebacks From Anywhere in a Program
19397
19398 @noindent
19399 It is possible to get a symbolic stack traceback
19400 from anywhere in a program, just as for non-symbolic tracebacks.
19401 The first step is to obtain a non-symbolic
19402 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19403 information. Here is an example:
19404
19405 @smallexample @c ada
19406 with Ada.Text_IO;
19407 with GNAT.Traceback;
19408 with GNAT.Traceback.Symbolic;
19409
19410 procedure STB is
19411
19412    use Ada;
19413    use GNAT.Traceback;
19414    use GNAT.Traceback.Symbolic;
19415
19416    procedure P1 is
19417       TB  : Tracebacks_Array (1 .. 10);
19418       --  We are asking for a maximum of 10 stack frames.
19419       Len : Natural;
19420       --  Len will receive the actual number of stack frames returned.
19421    begin
19422       Call_Chain (TB, Len);
19423       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19424    end P1;
19425
19426    procedure P2 is
19427    begin
19428       P1;
19429    end P2;
19430
19431 begin
19432    P2;
19433 end STB;
19434 @end smallexample
19435
19436 @c ******************************
19437 @ifset vms
19438 @node Compatibility with HP Ada
19439 @chapter Compatibility with HP Ada
19440 @cindex Compatibility
19441
19442 @noindent
19443 @cindex DEC Ada
19444 @cindex HP Ada
19445 @cindex Compatibility between GNAT and HP Ada
19446 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19447 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19448 GNAT is highly compatible
19449 with HP Ada, and it should generally be straightforward to port code
19450 from the HP Ada environment to GNAT. However, there are a few language
19451 and implementation differences of which the user must be aware. These
19452 differences are discussed in this chapter. In
19453 addition, the operating environment and command structure for the
19454 compiler are different, and these differences are also discussed.
19455
19456 For further details on these and other compatibility issues,
19457 see Appendix E of the HP publication
19458 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19459
19460 Except where otherwise indicated, the description of GNAT for OpenVMS
19461 applies to both the Alpha and I64 platforms.
19462
19463 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19464 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19465
19466 The discussion in this chapter addresses specifically the implementation
19467 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19468 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19469 GNAT always follows the Alpha implementation.
19470
19471 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19472 attributes are recognized, although only a subset of them can sensibly
19473 be implemented.  The description of pragmas in
19474 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19475 indicates whether or not they are applicable to non-VMS systems.
19476
19477 @menu
19478 * Ada Language Compatibility::
19479 * Differences in the Definition of Package System::
19480 * Language-Related Features::
19481 * The Package STANDARD::
19482 * The Package SYSTEM::
19483 * Tasking and Task-Related Features::
19484 * Pragmas and Pragma-Related Features::
19485 * Library of Predefined Units::
19486 * Bindings::
19487 * Main Program Definition::
19488 * Implementation-Defined Attributes::
19489 * Compiler and Run-Time Interfacing::
19490 * Program Compilation and Library Management::
19491 * Input-Output::
19492 * Implementation Limits::
19493 * Tools and Utilities::
19494 @end menu
19495
19496 @node Ada Language Compatibility
19497 @section Ada Language Compatibility
19498
19499 @noindent
19500 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19501 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19502 with Ada 83, and therefore Ada 83 programs will compile
19503 and run under GNAT with
19504 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19505 provides details on specific incompatibilities.
19506
19507 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19508 as well as the pragma @code{ADA_83}, to force the compiler to
19509 operate in Ada 83 mode. This mode does not guarantee complete
19510 conformance to Ada 83, but in practice is sufficient to
19511 eliminate most sources of incompatibilities.
19512 In particular, it eliminates the recognition of the
19513 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19514 in Ada 83 programs is legal, and handles the cases of packages
19515 with optional bodies, and generics that instantiate unconstrained
19516 types without the use of @code{(<>)}.
19517
19518 @node Differences in the Definition of Package System
19519 @section Differences in the Definition of Package @code{System}
19520
19521 @noindent
19522 An Ada compiler is allowed to add
19523 implementation-dependent declarations to package @code{System}.
19524 In normal mode,
19525 GNAT does not take advantage of this permission, and the version of
19526 @code{System} provided by GNAT exactly matches that defined in the Ada
19527 Reference Manual.
19528
19529 However, HP Ada adds an extensive set of declarations to package
19530 @code{System},
19531 as fully documented in the HP Ada manuals. To minimize changes required
19532 for programs that make use of these extensions, GNAT provides the pragma
19533 @code{Extend_System} for extending the definition of package System. By using:
19534 @cindex pragma @code{Extend_System}
19535 @cindex @code{Extend_System} pragma
19536
19537 @smallexample @c ada
19538 @group
19539 @cartouche
19540 pragma Extend_System (Aux_DEC);
19541 @end cartouche
19542 @end group
19543 @end smallexample
19544
19545 @noindent
19546 the set of definitions in @code{System} is extended to include those in
19547 package @code{System.Aux_DEC}.
19548 @cindex @code{System.Aux_DEC} package
19549 @cindex @code{Aux_DEC} package (child of @code{System})
19550 These definitions are incorporated directly into package @code{System},
19551 as though they had been declared there. For a
19552 list of the declarations added, see the spec of this package,
19553 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19554 @cindex @file{s-auxdec.ads} file
19555 The pragma @code{Extend_System} is a configuration pragma, which means that
19556 it can be placed in the file @file{gnat.adc}, so that it will automatically
19557 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19558 for further details.
19559
19560 An alternative approach that avoids the use of the non-standard
19561 @code{Extend_System} pragma is to add a context clause to the unit that
19562 references these facilities:
19563
19564 @smallexample @c ada
19565 @cartouche
19566 with System.Aux_DEC;
19567 use  System.Aux_DEC;
19568 @end cartouche
19569 @end smallexample
19570
19571 @noindent
19572 The effect is not quite semantically identical to incorporating
19573 the declarations directly into package @code{System},
19574 but most programs will not notice a difference
19575 unless they use prefix notation (e.g.@: @code{System.Integer_8})
19576 to reference the entities directly in package @code{System}.
19577 For units containing such references,
19578 the prefixes must either be removed, or the pragma @code{Extend_System}
19579 must be used.
19580
19581 @node Language-Related Features
19582 @section Language-Related Features
19583
19584 @noindent
19585 The following sections highlight differences in types,
19586 representations of types, operations, alignment, and
19587 related topics.
19588
19589 @menu
19590 * Integer Types and Representations::
19591 * Floating-Point Types and Representations::
19592 * Pragmas Float_Representation and Long_Float::
19593 * Fixed-Point Types and Representations::
19594 * Record and Array Component Alignment::
19595 * Address Clauses::
19596 * Other Representation Clauses::
19597 @end menu
19598
19599 @node Integer Types and Representations
19600 @subsection Integer Types and Representations
19601
19602 @noindent
19603 The set of predefined integer types is identical in HP Ada and GNAT.
19604 Furthermore the representation of these integer types is also identical,
19605 including the capability of size clauses forcing biased representation.
19606
19607 In addition,
19608 HP Ada for OpenVMS Alpha systems has defined the
19609 following additional integer types in package @code{System}:
19610
19611 @itemize @bullet
19612
19613 @item
19614 @code{INTEGER_8}
19615
19616 @item
19617 @code{INTEGER_16}
19618
19619 @item
19620 @code{INTEGER_32}
19621
19622 @item
19623 @code{INTEGER_64}
19624
19625 @item
19626 @code{LARGEST_INTEGER}
19627 @end itemize
19628
19629 @noindent
19630 In GNAT, the first four of these types may be obtained from the
19631 standard Ada package @code{Interfaces}.
19632 Alternatively, by use of the pragma @code{Extend_System}, identical
19633 declarations can be referenced directly in package @code{System}.
19634 On both GNAT and HP Ada, the maximum integer size is 64 bits.
19635
19636 @node Floating-Point Types and Representations
19637 @subsection Floating-Point Types and Representations
19638 @cindex Floating-Point types
19639
19640 @noindent
19641 The set of predefined floating-point types is identical in HP Ada and GNAT.
19642 Furthermore the representation of these floating-point
19643 types is also identical. One important difference is that the default
19644 representation for HP Ada is @code{VAX_Float}, but the default representation
19645 for GNAT is IEEE.
19646
19647 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
19648 pragma @code{Float_Representation} as described in the HP Ada
19649 documentation.
19650 For example, the declarations:
19651
19652 @smallexample @c ada
19653 @cartouche
19654 type F_Float is digits 6;
19655 pragma Float_Representation (VAX_Float, F_Float);
19656 @end cartouche
19657 @end smallexample
19658
19659 @noindent
19660 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
19661 format.
19662 This set of declarations actually appears in @code{System.Aux_DEC},
19663 which contains
19664 the full set of additional floating-point declarations provided in
19665 the HP Ada version of package @code{System}.
19666 This and similar declarations may be accessed in a user program
19667 by using pragma @code{Extend_System}. The use of this
19668 pragma, and the related pragma @code{Long_Float} is described in further
19669 detail in the following section.
19670
19671 @node Pragmas Float_Representation and Long_Float
19672 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
19673
19674 @noindent
19675 HP Ada provides the pragma @code{Float_Representation}, which
19676 acts as a program library switch to allow control over
19677 the internal representation chosen for the predefined
19678 floating-point types declared in the package @code{Standard}.
19679 The format of this pragma is as follows:
19680
19681 @smallexample @c ada
19682 @cartouche
19683 pragma Float_Representation(VAX_Float | IEEE_Float);
19684 @end cartouche
19685 @end smallexample
19686
19687 @noindent
19688 This pragma controls the representation of floating-point
19689 types as follows:
19690
19691 @itemize @bullet
19692 @item
19693 @code{VAX_Float} specifies that floating-point
19694 types are represented by default with the VAX system hardware types
19695 @code{F-floating}, @code{D-floating}, @code{G-floating}.
19696 Note that the @code{H-floating}
19697 type was available only on VAX systems, and is not available
19698 in either HP Ada or GNAT.
19699
19700 @item
19701 @code{IEEE_Float} specifies that floating-point
19702 types are represented by default with the IEEE single and
19703 double floating-point types.
19704 @end itemize
19705
19706 @noindent
19707 GNAT provides an identical implementation of the pragma
19708 @code{Float_Representation}, except that it functions as a
19709 configuration pragma. Note that the
19710 notion of configuration pragma corresponds closely to the
19711 HP Ada notion of a program library switch.
19712
19713 When no pragma is used in GNAT, the default is @code{IEEE_Float},
19714 which is different
19715 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
19716 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
19717 advisable to change the format of numbers passed to standard library
19718 routines, and if necessary explicit type conversions may be needed.
19719
19720 The use of @code{IEEE_Float} is recommended in GNAT since it is more
19721 efficient, and (given that it conforms to an international standard)
19722 potentially more portable.
19723 The situation in which @code{VAX_Float} may be useful is in interfacing
19724 to existing code and data that expect the use of @code{VAX_Float}.
19725 In such a situation use the predefined @code{VAX_Float}
19726 types in package @code{System}, as extended by
19727 @code{Extend_System}. For example, use @code{System.F_Float}
19728 to specify the 32-bit @code{F-Float} format.
19729
19730 @noindent
19731 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
19732 to allow control over the internal representation chosen
19733 for the predefined type @code{Long_Float} and for floating-point
19734 type declarations with digits specified in the range 7 .. 15.
19735 The format of this pragma is as follows:
19736
19737 @smallexample @c ada
19738 @cartouche
19739 pragma Long_Float (D_FLOAT | G_FLOAT);
19740 @end cartouche
19741 @end smallexample
19742
19743 @node Fixed-Point Types and Representations
19744 @subsection Fixed-Point Types and Representations
19745
19746 @noindent
19747 On HP Ada for OpenVMS Alpha systems, rounding is
19748 away from zero for both positive and negative numbers.
19749 Therefore, @code{+0.5} rounds to @code{1},
19750 and @code{-0.5} rounds to @code{-1}.
19751
19752 On GNAT the results of operations
19753 on fixed-point types are in accordance with the Ada
19754 rules. In particular, results of operations on decimal
19755 fixed-point types are truncated.
19756
19757 @node Record and Array Component Alignment
19758 @subsection Record and Array Component Alignment
19759
19760 @noindent
19761 On HP Ada for OpenVMS Alpha, all non-composite components
19762 are aligned on natural boundaries. For example, 1-byte
19763 components are aligned on byte boundaries, 2-byte
19764 components on 2-byte boundaries, 4-byte components on 4-byte
19765 byte boundaries, and so on. The OpenVMS Alpha hardware
19766 runs more efficiently with naturally aligned data.
19767
19768 On GNAT, alignment rules are compatible
19769 with HP Ada for OpenVMS Alpha.
19770
19771 @node Address Clauses
19772 @subsection Address Clauses
19773
19774 @noindent
19775 In HP Ada and GNAT, address clauses are supported for
19776 objects and imported subprograms.
19777 The predefined type @code{System.Address} is a private type
19778 in both compilers on Alpha OpenVMS, with the same representation
19779 (it is simply a machine pointer). Addition, subtraction, and comparison
19780 operations are available in the standard Ada package
19781 @code{System.Storage_Elements}, or in package @code{System}
19782 if it is extended to include @code{System.Aux_DEC} using a
19783 pragma @code{Extend_System} as previously described.
19784
19785 Note that code that @code{with}'s both this extended package @code{System}
19786 and the package @code{System.Storage_Elements} should not @code{use}
19787 both packages, or ambiguities will result. In general it is better
19788 not to mix these two sets of facilities. The Ada package was
19789 designed specifically to provide the kind of features that HP Ada
19790 adds directly to package @code{System}.
19791
19792 The type @code{System.Address} is a 64-bit integer type in GNAT for
19793 I64 OpenVMS.  For more information,
19794 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19795
19796 GNAT is compatible with HP Ada in its handling of address
19797 clauses, except for some limitations in
19798 the form of address clauses for composite objects with
19799 initialization. Such address clauses are easily replaced
19800 by the use of an explicitly-defined constant as described
19801 in the Ada Reference Manual (13.1(22)). For example, the sequence
19802 of declarations:
19803
19804 @smallexample @c ada
19805 @cartouche
19806 X, Y : Integer := Init_Func;
19807 Q : String (X .. Y) := "abc";
19808 @dots{}
19809 for Q'Address use Compute_Address;
19810 @end cartouche
19811 @end smallexample
19812
19813 @noindent
19814 will be rejected by GNAT, since the address cannot be computed at the time
19815 that @code{Q} is declared. To achieve the intended effect, write instead:
19816
19817 @smallexample @c ada
19818 @group
19819 @cartouche
19820 X, Y : Integer := Init_Func;
19821 Q_Address : constant Address := Compute_Address;
19822 Q : String (X .. Y) := "abc";
19823 @dots{}
19824 for Q'Address use Q_Address;
19825 @end cartouche
19826 @end group
19827 @end smallexample
19828
19829 @noindent
19830 which will be accepted by GNAT (and other Ada compilers), and is also
19831 compatible with Ada 83. A fuller description of the restrictions
19832 on address specifications is found in @ref{Top, GNAT Reference Manual,
19833 About This Guide, gnat_rm, GNAT Reference Manual}.
19834
19835 @node Other Representation Clauses
19836 @subsection Other Representation Clauses
19837
19838 @noindent
19839 GNAT implements in a compatible manner all the representation
19840 clauses supported by HP Ada. In addition, GNAT
19841 implements the representation clause forms that were introduced in Ada 95,
19842 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
19843
19844 @node The Package STANDARD
19845 @section The Package @code{STANDARD}
19846
19847 @noindent
19848 The package @code{STANDARD}, as implemented by HP Ada, is fully
19849 described in the @cite{Ada Reference Manual} and in the
19850 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
19851 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
19852
19853 In addition, HP Ada supports the Latin-1 character set in
19854 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
19855 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
19856 the type @code{WIDE_CHARACTER}.
19857
19858 The floating-point types supported by GNAT are those
19859 supported by HP Ada, but the defaults are different, and are controlled by
19860 pragmas. See @ref{Floating-Point Types and Representations}, for details.
19861
19862 @node The Package SYSTEM
19863 @section The Package @code{SYSTEM}
19864
19865 @noindent
19866 HP Ada provides a specific version of the package
19867 @code{SYSTEM} for each platform on which the language is implemented.
19868 For the complete spec of the package @code{SYSTEM}, see
19869 Appendix F of the @cite{HP Ada Language Reference Manual}.
19870
19871 On HP Ada, the package @code{SYSTEM} includes the following conversion
19872 functions:
19873 @itemize @bullet
19874 @item @code{TO_ADDRESS(INTEGER)}
19875
19876 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
19877
19878 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
19879
19880 @item @code{TO_INTEGER(ADDRESS)}
19881
19882 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
19883
19884 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
19885 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
19886 @end itemize
19887
19888 @noindent
19889 By default, GNAT supplies a version of @code{SYSTEM} that matches
19890 the definition given in the @cite{Ada Reference Manual}.
19891 This
19892 is a subset of the HP system definitions, which is as
19893 close as possible to the original definitions. The only difference
19894 is that the definition of @code{SYSTEM_NAME} is different:
19895
19896 @smallexample @c ada
19897 @cartouche
19898 type Name is (SYSTEM_NAME_GNAT);
19899 System_Name : constant Name := SYSTEM_NAME_GNAT;
19900 @end cartouche
19901 @end smallexample
19902
19903 @noindent
19904 Also, GNAT adds the Ada declarations for
19905 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
19906
19907 However, the use of the following pragma causes GNAT
19908 to extend the definition of package @code{SYSTEM} so that it
19909 encompasses the full set of HP-specific extensions,
19910 including the functions listed above:
19911
19912 @smallexample @c ada
19913 @cartouche
19914 pragma Extend_System (Aux_DEC);
19915 @end cartouche
19916 @end smallexample
19917
19918 @noindent
19919 The pragma @code{Extend_System} is a configuration pragma that
19920 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
19921 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
19922
19923 HP Ada does not allow the recompilation of the package
19924 @code{SYSTEM}. Instead HP Ada provides several pragmas
19925 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
19926 to modify values in the package @code{SYSTEM}.
19927 On OpenVMS Alpha systems, the pragma
19928 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
19929 its single argument.
19930
19931 GNAT does permit the recompilation of package @code{SYSTEM} using
19932 the special switch @option{-gnatg}, and this switch can be used if
19933 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
19934 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
19935 or @code{MEMORY_SIZE} by any other means.
19936
19937 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
19938 enumeration literal @code{SYSTEM_NAME_GNAT}.
19939
19940 The definitions provided by the use of
19941
19942 @smallexample @c ada
19943 pragma Extend_System (AUX_Dec);
19944 @end smallexample
19945
19946 @noindent
19947 are virtually identical to those provided by the HP Ada 83 package
19948 @code{SYSTEM}. One important difference is that the name of the
19949 @code{TO_ADDRESS}
19950 function for type @code{UNSIGNED_LONGWORD} is changed to
19951 @code{TO_ADDRESS_LONG}.
19952 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
19953 discussion of why this change was necessary.
19954
19955 @noindent
19956 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
19957 is in fact
19958 an extension to Ada 83 not strictly compatible with the reference manual.
19959 GNAT, in order to be exactly compatible with the standard,
19960 does not provide this capability. In HP Ada 83, the
19961 point of this definition is to deal with a call like:
19962
19963 @smallexample @c ada
19964 TO_ADDRESS (16#12777#);
19965 @end smallexample
19966
19967 @noindent
19968 Normally, according to Ada 83 semantics, one would expect this to be
19969 ambiguous, since it matches both the @code{INTEGER} and
19970 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
19971 However, in HP Ada 83, there is no ambiguity, since the
19972 definition using @i{universal_integer} takes precedence.
19973
19974 In GNAT, since the version with @i{universal_integer} cannot be supplied,
19975 it is
19976 not possible to be 100% compatible. Since there are many programs using
19977 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
19978 GNAT was
19979 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
19980 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
19981
19982 @smallexample @c ada
19983 function To_Address (X : Integer) return Address;
19984 pragma Pure_Function (To_Address);
19985
19986 function To_Address_Long (X : Unsigned_Longword) return Address;
19987 pragma Pure_Function (To_Address_Long);
19988 @end smallexample
19989
19990 @noindent
19991 This means that programs using @code{TO_ADDRESS} for
19992 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
19993
19994 @node Tasking and Task-Related Features
19995 @section Tasking and Task-Related Features
19996
19997 @noindent
19998 This section compares the treatment of tasking in GNAT
19999 and in HP Ada for OpenVMS Alpha.
20000 The GNAT description applies to both Alpha and I64 OpenVMS.
20001 For detailed information on tasking in
20002 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20003 relevant run-time reference manual.
20004
20005 @menu
20006 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20007 * Assigning Task IDs::
20008 * Task IDs and Delays::
20009 * Task-Related Pragmas::
20010 * Scheduling and Task Priority::
20011 * The Task Stack::
20012 * External Interrupts::
20013 @end menu
20014
20015 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20016 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20017
20018 @noindent
20019 On OpenVMS Alpha systems, each Ada task (except a passive
20020 task) is implemented as a single stream of execution
20021 that is created and managed by the kernel. On these
20022 systems, HP Ada tasking support is based on DECthreads,
20023 an implementation of the POSIX standard for threads.
20024
20025 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20026 code that calls DECthreads routines can be used together.
20027 The interaction between Ada tasks and DECthreads routines
20028 can have some benefits. For example when on OpenVMS Alpha,
20029 HP Ada can call C code that is already threaded.
20030
20031 GNAT uses the facilities of DECthreads,
20032 and Ada tasks are mapped to threads.
20033
20034 @node Assigning Task IDs
20035 @subsection Assigning Task IDs
20036
20037 @noindent
20038 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20039 the environment task that executes the main program. On
20040 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20041 that have been created but are not yet activated.
20042
20043 On OpenVMS Alpha systems, task IDs are assigned at
20044 activation. On GNAT systems, task IDs are also assigned at
20045 task creation but do not have the same form or values as
20046 task ID values in HP Ada. There is no null task, and the
20047 environment task does not have a specific task ID value.
20048
20049 @node Task IDs and Delays
20050 @subsection Task IDs and Delays
20051
20052 @noindent
20053 On OpenVMS Alpha systems, tasking delays are implemented
20054 using Timer System Services. The Task ID is used for the
20055 identification of the timer request (the @code{REQIDT} parameter).
20056 If Timers are used in the application take care not to use
20057 @code{0} for the identification, because cancelling such a timer
20058 will cancel all timers and may lead to unpredictable results.
20059
20060 @node Task-Related Pragmas
20061 @subsection Task-Related Pragmas
20062
20063 @noindent
20064 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20065 specification of the size of the guard area for a task
20066 stack. (The guard area forms an area of memory that has no
20067 read or write access and thus helps in the detection of
20068 stack overflow.) On OpenVMS Alpha systems, if the pragma
20069 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20070 area is created. In the absence of a pragma @code{TASK_STORAGE},
20071 a default guard area is created.
20072
20073 GNAT supplies the following task-related pragmas:
20074
20075 @itemize @bullet
20076 @item  @code{TASK_INFO}
20077
20078 This pragma appears within a task definition and
20079 applies to the task in which it appears. The argument
20080 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20081
20082 @item  @code{TASK_STORAGE}
20083
20084 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20085 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20086 @code{SUPPRESS}, and @code{VOLATILE}.
20087 @end itemize
20088 @node Scheduling and Task Priority
20089 @subsection Scheduling and Task Priority
20090
20091 @noindent
20092 HP Ada implements the Ada language requirement that
20093 when two tasks are eligible for execution and they have
20094 different priorities, the lower priority task does not
20095 execute while the higher priority task is waiting. The HP
20096 Ada Run-Time Library keeps a task running until either the
20097 task is suspended or a higher priority task becomes ready.
20098
20099 On OpenVMS Alpha systems, the default strategy is round-
20100 robin with preemption. Tasks of equal priority take turns
20101 at the processor. A task is run for a certain period of
20102 time and then placed at the tail of the ready queue for
20103 its priority level.
20104
20105 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20106 which can be used to enable or disable round-robin
20107 scheduling of tasks with the same priority.
20108 See the relevant HP Ada run-time reference manual for
20109 information on using the pragmas to control HP Ada task
20110 scheduling.
20111
20112 GNAT follows the scheduling rules of Annex D (Real-Time
20113 Annex) of the @cite{Ada Reference Manual}. In general, this
20114 scheduling strategy is fully compatible with HP Ada
20115 although it provides some additional constraints (as
20116 fully documented in Annex D).
20117 GNAT implements time slicing control in a manner compatible with
20118 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20119 are identical to the HP Ada 83 pragma of the same name.
20120 Note that it is not possible to mix GNAT tasking and
20121 HP Ada 83 tasking in the same program, since the two run-time
20122 libraries are not compatible.
20123
20124 @node The Task Stack
20125 @subsection The Task Stack
20126
20127 @noindent
20128 In HP Ada, a task stack is allocated each time a
20129 non-passive task is activated. As soon as the task is
20130 terminated, the storage for the task stack is deallocated.
20131 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20132 a default stack size is used. Also, regardless of the size
20133 specified, some additional space is allocated for task
20134 management purposes. On OpenVMS Alpha systems, at least
20135 one page is allocated.
20136
20137 GNAT handles task stacks in a similar manner. In accordance with
20138 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20139 an alternative method for controlling the task stack size.
20140 The specification of the attribute @code{T'STORAGE_SIZE} is also
20141 supported in a manner compatible with HP Ada.
20142
20143 @node External Interrupts
20144 @subsection External Interrupts
20145
20146 @noindent
20147 On HP Ada, external interrupts can be associated with task entries.
20148 GNAT is compatible with HP Ada in its handling of external interrupts.
20149
20150 @node Pragmas and Pragma-Related Features
20151 @section Pragmas and Pragma-Related Features
20152
20153 @noindent
20154 Both HP Ada and GNAT supply all language-defined pragmas
20155 as specified by the Ada 83 standard. GNAT also supplies all
20156 language-defined pragmas introduced by Ada 95 and Ada 2005.
20157 In addition, GNAT implements the implementation-defined pragmas
20158 from HP Ada 83.
20159
20160 @itemize @bullet
20161 @item  @code{AST_ENTRY}
20162
20163 @item  @code{COMMON_OBJECT}
20164
20165 @item  @code{COMPONENT_ALIGNMENT}
20166
20167 @item  @code{EXPORT_EXCEPTION}
20168
20169 @item  @code{EXPORT_FUNCTION}
20170
20171 @item  @code{EXPORT_OBJECT}
20172
20173 @item  @code{EXPORT_PROCEDURE}
20174
20175 @item  @code{EXPORT_VALUED_PROCEDURE}
20176
20177 @item  @code{FLOAT_REPRESENTATION}
20178
20179 @item  @code{IDENT}
20180
20181 @item  @code{IMPORT_EXCEPTION}
20182
20183 @item  @code{IMPORT_FUNCTION}
20184
20185 @item  @code{IMPORT_OBJECT}
20186
20187 @item  @code{IMPORT_PROCEDURE}
20188
20189 @item  @code{IMPORT_VALUED_PROCEDURE}
20190
20191 @item  @code{INLINE_GENERIC}
20192
20193 @item  @code{INTERFACE_NAME}
20194
20195 @item  @code{LONG_FLOAT}
20196
20197 @item  @code{MAIN_STORAGE}
20198
20199 @item  @code{PASSIVE}
20200
20201 @item  @code{PSECT_OBJECT}
20202
20203 @item  @code{SHARE_GENERIC}
20204
20205 @item  @code{SUPPRESS_ALL}
20206
20207 @item  @code{TASK_STORAGE}
20208
20209 @item  @code{TIME_SLICE}
20210
20211 @item  @code{TITLE}
20212 @end itemize
20213
20214 @noindent
20215 These pragmas are all fully implemented, with the exception of @code{TITLE},
20216 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20217 recognized, but which have no
20218 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20219 use of Ada protected objects. In GNAT, all generics are inlined.
20220
20221 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20222 a separate subprogram specification which must appear before the
20223 subprogram body.
20224
20225 GNAT also supplies a number of implementation-defined pragmas including the
20226 following:
20227
20228 @itemize @bullet
20229 @item  @code{ABORT_DEFER}
20230
20231 @item  @code{ADA_83}
20232
20233 @item  @code{ADA_95}
20234
20235 @item  @code{ADA_05}
20236
20237 @item  @code{Ada_2005}
20238
20239 @item  @code{Ada_12}
20240
20241 @item  @code{Ada_2012}
20242
20243 @item  @code{ANNOTATE}
20244
20245 @item  @code{ASSERT}
20246
20247 @item  @code{C_PASS_BY_COPY}
20248
20249 @item  @code{CPP_CLASS}
20250
20251 @item  @code{CPP_CONSTRUCTOR}
20252
20253 @item  @code{CPP_DESTRUCTOR}
20254
20255 @item  @code{DEBUG}
20256
20257 @item  @code{EXTEND_SYSTEM}
20258
20259 @item  @code{LINKER_ALIAS}
20260
20261 @item  @code{LINKER_SECTION}
20262
20263 @item  @code{MACHINE_ATTRIBUTE}
20264
20265 @item  @code{NO_RETURN}
20266
20267 @item  @code{PURE_FUNCTION}
20268
20269 @item  @code{SOURCE_FILE_NAME}
20270
20271 @item  @code{SOURCE_REFERENCE}
20272
20273 @item  @code{TASK_INFO}
20274
20275 @item  @code{UNCHECKED_UNION}
20276
20277 @item  @code{UNIMPLEMENTED_UNIT}
20278
20279 @item  @code{UNIVERSAL_DATA}
20280
20281 @item  @code{UNSUPPRESS}
20282
20283 @item  @code{WARNINGS}
20284
20285 @item  @code{WEAK_EXTERNAL}
20286 @end itemize
20287
20288 @noindent
20289 For full details on these and other GNAT implementation-defined pragmas,
20290 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20291 Manual}.
20292
20293 @menu
20294 * Restrictions on the Pragma INLINE::
20295 * Restrictions on the Pragma INTERFACE::
20296 * Restrictions on the Pragma SYSTEM_NAME::
20297 @end menu
20298
20299 @node Restrictions on the Pragma INLINE
20300 @subsection Restrictions on Pragma @code{INLINE}
20301
20302 @noindent
20303 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20304 @itemize @bullet
20305 @item  Parameters cannot have a task type.
20306
20307 @item  Function results cannot be task types, unconstrained
20308 array types, or unconstrained types with discriminants.
20309
20310 @item  Bodies cannot declare the following:
20311 @itemize @bullet
20312 @item  Subprogram body or stub (imported subprogram is allowed)
20313
20314 @item  Tasks
20315
20316 @item  Generic declarations
20317
20318 @item  Instantiations
20319
20320 @item  Exceptions
20321
20322 @item  Access types (types derived from access types allowed)
20323
20324 @item  Array or record types
20325
20326 @item  Dependent tasks
20327
20328 @item  Direct recursive calls of subprogram or containing
20329 subprogram, directly or via a renaming
20330
20331 @end itemize
20332 @end itemize
20333
20334 @noindent
20335 In GNAT, the only restriction on pragma @code{INLINE} is that the
20336 body must occur before the call if both are in the same
20337 unit, and the size must be appropriately small. There are
20338 no other specific restrictions which cause subprograms to
20339 be incapable of being inlined.
20340
20341 @node  Restrictions on the Pragma INTERFACE
20342 @subsection  Restrictions on Pragma @code{INTERFACE}
20343
20344 @noindent
20345 The following restrictions on pragma @code{INTERFACE}
20346 are enforced by both HP Ada and GNAT:
20347 @itemize @bullet
20348 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20349 Default is the default on OpenVMS Alpha systems.
20350
20351 @item  Parameter passing: Language specifies default
20352 mechanisms but can be overridden with an @code{EXPORT} pragma.
20353
20354 @itemize @bullet
20355 @item  Ada: Use internal Ada rules.
20356
20357 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20358 record or task type. Result cannot be a string, an
20359 array, or a record.
20360
20361 @item  Fortran: Parameters cannot have a task type. Result cannot
20362 be a string, an array, or a record.
20363 @end itemize
20364 @end itemize
20365
20366 @noindent
20367 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20368 record parameters for all languages.
20369
20370 @node  Restrictions on the Pragma SYSTEM_NAME
20371 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20372
20373 @noindent
20374 For HP Ada for OpenVMS Alpha, the enumeration literal
20375 for the type @code{NAME} is @code{OPENVMS_AXP}.
20376 In GNAT, the enumeration
20377 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20378
20379 @node  Library of Predefined Units
20380 @section  Library of Predefined Units
20381
20382 @noindent
20383 A library of predefined units is provided as part of the
20384 HP Ada and GNAT implementations. HP Ada does not provide
20385 the package @code{MACHINE_CODE} but instead recommends importing
20386 assembler code.
20387
20388 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20389 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20390 version.
20391 The HP Ada Predefined Library units are modified to remove post-Ada 83
20392 incompatibilities and to make them interoperable with GNAT
20393 (@pxref{Changes to DECLIB}, for details).
20394 The units are located in the @file{DECLIB} directory.
20395
20396 The GNAT RTL is contained in
20397 the @file{ADALIB} directory, and
20398 the default search path is set up to find @code{DECLIB} units in preference
20399 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20400 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20401
20402 @menu
20403 * Changes to DECLIB::
20404 @end menu
20405
20406 @node Changes to DECLIB
20407 @subsection Changes to @code{DECLIB}
20408
20409 @noindent
20410 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20411 compatibility are minor and include the following:
20412
20413 @itemize @bullet
20414 @item  Adjusting the location of pragmas and record representation
20415 clauses to obey Ada 95 (and thus Ada 2005) rules
20416
20417 @item  Adding the proper notation to generic formal parameters
20418 that take unconstrained types in instantiation
20419
20420 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20421 that have package bodies not otherwise allowed
20422
20423 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20424 ``@code{PROTECTD}''.
20425 Currently these are found only in the @code{STARLET} package spec.
20426
20427 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20428 where the address size is constrained to 32 bits.
20429 @end itemize
20430
20431 @noindent
20432 None of the above changes is visible to users.
20433
20434 @node Bindings
20435 @section Bindings
20436
20437 @noindent
20438 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20439 @itemize @bullet
20440
20441 @item  Command Language Interpreter (CLI interface)
20442
20443 @item  DECtalk Run-Time Library (DTK interface)
20444
20445 @item  Librarian utility routines (LBR interface)
20446
20447 @item  General Purpose Run-Time Library (LIB interface)
20448
20449 @item  Math Run-Time Library (MTH interface)
20450
20451 @item  National Character Set Run-Time Library (NCS interface)
20452
20453 @item  Compiled Code Support Run-Time Library (OTS interface)
20454
20455 @item  Parallel Processing Run-Time Library (PPL interface)
20456
20457 @item  Screen Management Run-Time Library (SMG interface)
20458
20459 @item  Sort Run-Time Library (SOR interface)
20460
20461 @item  String Run-Time Library (STR interface)
20462
20463 @item STARLET System Library
20464 @findex Starlet
20465
20466 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20467
20468 @item  X Windows Toolkit (XT interface)
20469
20470 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20471 @end itemize
20472
20473 @noindent
20474 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20475 directory, on both the Alpha and I64 OpenVMS platforms.
20476
20477 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20478 in the
20479 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20480 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20481 @code{Xt}, and @code{X_Lib}
20482 causing the default X/Motif sharable image libraries to be linked in. This
20483 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20484 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20485
20486 It may be necessary to edit these options files to update or correct the
20487 library names if, for example, the newer X/Motif bindings from
20488 @file{ADA$EXAMPLES}
20489 had been (previous to installing GNAT) copied and renamed to supersede the
20490 default @file{ADA$PREDEFINED} versions.
20491
20492 @menu
20493 * Shared Libraries and Options Files::
20494 * Interfaces to C::
20495 @end menu
20496
20497 @node Shared Libraries and Options Files
20498 @subsection Shared Libraries and Options Files
20499
20500 @noindent
20501 When using the HP Ada
20502 predefined X and Motif bindings, the linking with their sharable images is
20503 done automatically by @command{GNAT LINK}.
20504 When using other X and Motif bindings, you need
20505 to add the corresponding sharable images to the command line for
20506 @code{GNAT LINK}. When linking with shared libraries, or with
20507 @file{.OPT} files, you must
20508 also add them to the command line for @command{GNAT LINK}.
20509
20510 A shared library to be used with GNAT is built in the same way as other
20511 libraries under VMS. The VMS Link command can be used in standard fashion.
20512
20513 @node Interfaces to C
20514 @subsection Interfaces to C
20515
20516 @noindent
20517 HP Ada
20518 provides the following Ada types and operations:
20519
20520 @itemize @bullet
20521 @item C types package (@code{C_TYPES})
20522
20523 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20524
20525 @item Other_types (@code{SHORT_INT})
20526 @end itemize
20527
20528 @noindent
20529 Interfacing to C with GNAT, you can use the above approach
20530 described for HP Ada or the facilities of Annex B of
20531 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20532 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20533 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20534
20535 The @option{-gnatF} qualifier forces default and explicit
20536 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20537 to be uppercased for compatibility with the default behavior
20538 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20539
20540 @node Main Program Definition
20541 @section Main Program Definition
20542
20543 @noindent
20544 The following section discusses differences in the
20545 definition of main programs on HP Ada and GNAT.
20546 On HP Ada, main programs are defined to meet the
20547 following conditions:
20548 @itemize @bullet
20549 @item  Procedure with no formal parameters (returns @code{0} upon
20550 normal completion)
20551
20552 @item  Procedure with no formal parameters (returns @code{42} when
20553 an unhandled exception is raised)
20554
20555 @item  Function with no formal parameters whose returned value
20556 is of a discrete type
20557
20558 @item  Procedure with one @code{out} formal of a discrete type for
20559 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20560
20561 @end itemize
20562
20563 @noindent
20564 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
20565 a main function or main procedure returns a discrete
20566 value whose size is less than 64 bits (32 on VAX systems),
20567 the value is zero- or sign-extended as appropriate.
20568 On GNAT, main programs are defined as follows:
20569 @itemize @bullet
20570 @item  Must be a non-generic, parameterless subprogram that
20571 is either a procedure or function returning an Ada
20572 @code{STANDARD.INTEGER} (the predefined type)
20573
20574 @item  Cannot be a generic subprogram or an instantiation of a
20575 generic subprogram
20576 @end itemize
20577
20578 @node Implementation-Defined Attributes
20579 @section Implementation-Defined Attributes
20580
20581 @noindent
20582 GNAT provides all HP Ada implementation-defined
20583 attributes.
20584
20585 @node Compiler and Run-Time Interfacing
20586 @section Compiler and Run-Time Interfacing
20587
20588 @noindent
20589 HP Ada provides the following qualifiers to pass options to the linker
20590 (ACS LINK):
20591 @itemize @bullet
20592 @item  @option{/WAIT} and @option{/SUBMIT}
20593
20594 @item  @option{/COMMAND}
20595
20596 @item  @option{/@r{[}NO@r{]}MAP}
20597
20598 @item  @option{/OUTPUT=@var{file-spec}}
20599
20600 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20601 @end itemize
20602
20603 @noindent
20604 To pass options to the linker, GNAT provides the following
20605 switches:
20606
20607 @itemize @bullet
20608 @item   @option{/EXECUTABLE=@var{exec-name}}
20609
20610 @item   @option{/VERBOSE}
20611
20612 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20613 @end itemize
20614
20615 @noindent
20616 For more information on these switches, see
20617 @ref{Switches for gnatlink}.
20618 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
20619 to control optimization. HP Ada also supplies the
20620 following pragmas:
20621 @itemize @bullet
20622 @item  @code{OPTIMIZE}
20623
20624 @item  @code{INLINE}
20625
20626 @item  @code{INLINE_GENERIC}
20627
20628 @item  @code{SUPPRESS_ALL}
20629
20630 @item  @code{PASSIVE}
20631 @end itemize
20632
20633 @noindent
20634 In GNAT, optimization is controlled strictly by command
20635 line parameters, as described in the corresponding section of this guide.
20636 The HP pragmas for control of optimization are
20637 recognized but ignored.
20638
20639 Note that in GNAT, the default is optimization off, whereas in HP Ada
20640 the default is that optimization is turned on.
20641
20642 @node Program Compilation and Library Management
20643 @section Program Compilation and Library Management
20644
20645 @noindent
20646 HP Ada and GNAT provide a comparable set of commands to
20647 build programs. HP Ada also provides a program library,
20648 which is a concept that does not exist on GNAT. Instead,
20649 GNAT provides directories of sources that are compiled as
20650 needed.
20651
20652 The following table summarizes
20653 the HP Ada commands and provides
20654 equivalent GNAT commands. In this table, some GNAT
20655 equivalents reflect the fact that GNAT does not use the
20656 concept of a program library. Instead, it uses a model
20657 in which collections of source and object files are used
20658 in a manner consistent with other languages like C and
20659 Fortran. Therefore, standard system file commands are used
20660 to manipulate these elements. Those GNAT commands are marked with
20661 an asterisk.
20662 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
20663
20664 @need 1500
20665 @multitable @columnfractions .35 .65
20666
20667 @item @emph{HP Ada Command}
20668 @tab @emph{GNAT Equivalent / Description}
20669
20670 @item @command{ADA}
20671 @tab @command{GNAT COMPILE}@*
20672 Invokes the compiler to compile one or more Ada source files.
20673
20674 @item @command{ACS ATTACH}@*
20675 @tab [No equivalent]@*
20676 Switches control of terminal from current process running the program
20677 library manager.
20678
20679 @item @command{ACS CHECK}
20680 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20681 Forms the execution closure of one
20682 or more compiled units and checks completeness and currency.
20683
20684 @item @command{ACS COMPILE}
20685 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20686 Forms the execution closure of one or
20687 more specified units, checks completeness and currency,
20688 identifies units that have revised source files, compiles same,
20689 and recompiles units that are or will become obsolete.
20690 Also completes incomplete generic instantiations.
20691
20692 @item @command{ACS COPY FOREIGN}
20693 @tab Copy (*)@*
20694 Copies a foreign object file into the program library as a
20695 library unit body.
20696
20697 @item @command{ACS COPY UNIT}
20698 @tab Copy (*)@*
20699 Copies a compiled unit from one program library to another.
20700
20701 @item @command{ACS CREATE LIBRARY}
20702 @tab Create /directory (*)@*
20703 Creates a program library.
20704
20705 @item @command{ACS CREATE SUBLIBRARY}
20706 @tab Create /directory (*)@*
20707 Creates a program sublibrary.
20708
20709 @item @command{ACS DELETE LIBRARY}
20710 @tab @*
20711 Deletes a program library and its contents.
20712
20713 @item @command{ACS DELETE SUBLIBRARY}
20714 @tab @*
20715 Deletes a program sublibrary and its contents.
20716
20717 @item @command{ACS DELETE UNIT}
20718 @tab Delete file (*)@*
20719 On OpenVMS systems, deletes one or more compiled units from
20720 the current program library.
20721
20722 @item @command{ACS DIRECTORY}
20723 @tab Directory (*)@*
20724 On OpenVMS systems, lists units contained in the current
20725 program library.
20726
20727 @item @command{ACS ENTER FOREIGN}
20728 @tab Copy (*)@*
20729 Allows the import of a foreign body as an Ada library
20730 spec and enters a reference to a pointer.
20731
20732 @item @command{ACS ENTER UNIT}
20733 @tab Copy (*)@*
20734 Enters a reference (pointer) from the current program library to
20735 a unit compiled into another program library.
20736
20737 @item @command{ACS EXIT}
20738 @tab [No equivalent]@*
20739 Exits from the program library manager.
20740
20741 @item @command{ACS EXPORT}
20742 @tab Copy (*)@*
20743 Creates an object file that contains system-specific object code
20744 for one or more units. With GNAT, object files can simply be copied
20745 into the desired directory.
20746
20747 @item @command{ACS EXTRACT SOURCE}
20748 @tab Copy (*)@*
20749 Allows access to the copied source file for each Ada compilation unit
20750
20751 @item @command{ACS HELP}
20752 @tab @command{HELP GNAT}@*
20753 Provides online help.
20754
20755 @item @command{ACS LINK}
20756 @tab @command{GNAT LINK}@*
20757 Links an object file containing Ada units into an executable file.
20758
20759 @item @command{ACS LOAD}
20760 @tab Copy (*)@*
20761 Loads (partially compiles) Ada units into the program library.
20762 Allows loading a program from a collection of files into a library
20763 without knowing the relationship among units.
20764
20765 @item @command{ACS MERGE}
20766 @tab Copy (*)@*
20767 Merges into the current program library, one or more units from
20768 another library where they were modified.
20769
20770 @item @command{ACS RECOMPILE}
20771 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20772 Recompiles from   external or copied source files any obsolete
20773 unit in the closure. Also, completes any incomplete generic
20774 instantiations.
20775
20776 @item @command{ACS REENTER}
20777 @tab @command{GNAT MAKE}@*
20778 Reenters current references to units compiled after last entered
20779 with the @command{ACS ENTER UNIT} command.
20780
20781 @item @command{ACS SET LIBRARY}
20782 @tab Set default (*)@*
20783 Defines a program library to be the compilation context as well
20784 as the target library for compiler output and commands in general.
20785
20786 @item @command{ACS SET PRAGMA}
20787 @tab Edit @file{gnat.adc} (*)@*
20788 Redefines specified  values of the library characteristics
20789 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20790 and @code{Float_Representation}.
20791
20792 @item @command{ACS SET SOURCE}
20793 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20794 Defines the source file search list for the @command{ACS COMPILE} command.
20795
20796 @item @command{ACS SHOW LIBRARY}
20797 @tab Directory (*)@*
20798 Lists information about one or more program libraries.
20799
20800 @item @command{ACS SHOW PROGRAM}
20801 @tab [No equivalent]@*
20802 Lists information about the execution closure of one or
20803 more units in the program library.
20804
20805 @item @command{ACS SHOW SOURCE}
20806 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20807 Shows the source file search used when compiling units.
20808
20809 @item @command{ACS SHOW VERSION}
20810 @tab Compile with @option{VERBOSE} option
20811 Displays the version number of the compiler and program library
20812 manager used.
20813
20814 @item @command{ACS SPAWN}
20815 @tab [No equivalent]@*
20816 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20817 command).
20818
20819 @item @command{ACS VERIFY}
20820 @tab [No equivalent]@*
20821 Performs a series of consistency checks on a program library to
20822 determine whether the library structure and library files are in
20823 valid form.
20824 @end multitable
20825
20826 @noindent
20827
20828 @node Input-Output
20829 @section Input-Output
20830
20831 @noindent
20832 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
20833 Management Services (RMS) to perform operations on
20834 external files.
20835
20836 @noindent
20837 HP Ada and GNAT predefine an identical set of input-
20838 output packages. To make the use of the
20839 generic @code{TEXT_IO} operations more convenient, HP Ada
20840 provides predefined library packages that instantiate the
20841 integer and floating-point operations for the predefined
20842 integer and floating-point types as shown in the following table.
20843
20844 @multitable @columnfractions .45 .55
20845 @item @emph{Package Name} @tab Instantiation
20846
20847 @item @code{INTEGER_TEXT_IO}
20848 @tab @code{INTEGER_IO(INTEGER)}
20849
20850 @item @code{SHORT_INTEGER_TEXT_IO}
20851 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20852
20853 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20854 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20855
20856 @item @code{FLOAT_TEXT_IO}
20857 @tab @code{FLOAT_IO(FLOAT)}
20858
20859 @item @code{LONG_FLOAT_TEXT_IO}
20860 @tab @code{FLOAT_IO(LONG_FLOAT)}
20861 @end multitable
20862
20863 @noindent
20864 The HP Ada predefined packages and their operations
20865 are implemented using OpenVMS Alpha files and input-output
20866 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
20867 Familiarity with the following is recommended:
20868 @itemize @bullet
20869 @item  RMS file organizations and access methods
20870
20871 @item  OpenVMS file specifications and directories
20872
20873 @item  OpenVMS File Definition Language (FDL)
20874 @end itemize
20875
20876 @noindent
20877 GNAT provides I/O facilities that are completely
20878 compatible with HP Ada. The distribution includes the
20879 standard HP Ada versions of all I/O packages, operating
20880 in a manner compatible with HP Ada. In particular, the
20881 following packages are by default the HP Ada (Ada 83)
20882 versions of these packages rather than the renamings
20883 suggested in Annex J of the Ada Reference Manual:
20884 @itemize @bullet
20885 @item  @code{TEXT_IO}
20886
20887 @item  @code{SEQUENTIAL_IO}
20888
20889 @item  @code{DIRECT_IO}
20890 @end itemize
20891
20892 @noindent
20893 The use of the standard child package syntax (for
20894 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
20895 packages.
20896 GNAT provides HP-compatible predefined instantiations
20897 of the @code{TEXT_IO} packages, and also
20898 provides the standard predefined instantiations required
20899 by the @cite{Ada Reference Manual}.
20900
20901 For further information on how GNAT interfaces to the file
20902 system or how I/O is implemented in programs written in
20903 mixed languages, see @ref{Implementation of the Standard I/O,,,
20904 gnat_rm, GNAT Reference Manual}.
20905 This chapter covers the following:
20906 @itemize @bullet
20907 @item  Standard I/O packages
20908
20909 @item  @code{FORM} strings
20910
20911 @item  @code{ADA.DIRECT_IO}
20912
20913 @item  @code{ADA.SEQUENTIAL_IO}
20914
20915 @item  @code{ADA.TEXT_IO}
20916
20917 @item  Stream pointer positioning
20918
20919 @item  Reading and writing non-regular files
20920
20921 @item  @code{GET_IMMEDIATE}
20922
20923 @item  Treating @code{TEXT_IO} files as streams
20924
20925 @item  Shared files
20926
20927 @item  Open modes
20928 @end itemize
20929
20930 @node Implementation Limits
20931 @section Implementation Limits
20932
20933 @noindent
20934 The following table lists implementation limits for HP Ada
20935 and GNAT systems.
20936 @multitable @columnfractions .60 .20 .20
20937 @sp 1
20938 @item  @emph{Compilation Parameter}
20939 @tab   @emph{HP Ada}
20940 @tab   @emph{GNAT}
20941 @sp 1
20942
20943 @item  In a subprogram or entry  declaration, maximum number of
20944 formal parameters that are of an unconstrained record type
20945 @tab   32
20946 @tab   No set limit
20947 @sp 1
20948
20949 @item  Maximum identifier length (number of characters)
20950 @tab   255
20951 @tab   32766
20952 @sp 1
20953
20954 @item  Maximum number of characters in a source line
20955 @tab   255
20956 @tab   32766
20957 @sp 1
20958
20959 @item  Maximum collection size   (number of bytes)
20960 @tab   2**31-1
20961 @tab   2**31-1
20962 @sp 1
20963
20964 @item  Maximum number of discriminants for a record type
20965 @tab   245
20966 @tab   No set limit
20967 @sp 1
20968
20969 @item  Maximum number of formal parameters in an entry or
20970 subprogram declaration
20971 @tab   246
20972 @tab    No set limit
20973 @sp 1
20974
20975 @item  Maximum number of dimensions in an array type
20976 @tab   255
20977 @tab   No set limit
20978 @sp 1
20979
20980 @item  Maximum number of library  units and subunits in a compilation.
20981 @tab   4095
20982 @tab   No set limit
20983 @sp 1
20984
20985 @item  Maximum number of library units and subunits in an execution.
20986 @tab   16383
20987 @tab   No set limit
20988 @sp 1
20989
20990 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20991 or @code{PSECT_OBJECT}
20992 @tab   32757
20993 @tab   No set limit
20994 @sp 1
20995
20996 @item  Maximum number of enumeration literals in an enumeration type
20997 definition
20998 @tab   65535
20999 @tab   No set limit
21000 @sp 1
21001
21002 @item  Maximum number of lines in a source file
21003 @tab   65534
21004 @tab   No set limit
21005 @sp 1
21006
21007 @item  Maximum number of bits in any object
21008 @tab   2**31-1
21009 @tab   2**31-1
21010 @sp 1
21011
21012 @item  Maximum size of the static portion of a stack frame (approximate)
21013 @tab   2**31-1
21014 @tab   2**31-1
21015 @end multitable
21016
21017 @node Tools and Utilities
21018 @section Tools and Utilities
21019
21020 @noindent
21021 The following table lists some of the OpenVMS development tools
21022 available for HP Ada, and the corresponding tools for
21023 use with @value{EDITION} on Alpha and I64 platforms.
21024 Aside from the debugger, all the OpenVMS tools identified are part
21025 of the DECset package.
21026
21027 @iftex
21028 @c Specify table in TeX since Texinfo does a poor job
21029 @tex
21030 \smallskip
21031 \smallskip
21032 \settabs\+Language-Sensitive Editor\quad
21033    &Product with HP Ada\quad
21034    &\cr
21035 \+\it Tool
21036    &\it Product with HP Ada
21037    & \it Product with GNAT Pro\cr
21038 \smallskip
21039 \+Code Management System
21040    &HP CMS
21041    & HP CMS\cr
21042 \smallskip
21043 \+Language-Sensitive Editor
21044    &HP LSE
21045    & emacs or HP LSE (Alpha)\cr
21046 \+
21047    &
21048    & HP LSE (I64)\cr
21049 \smallskip
21050 \+Debugger
21051    &OpenVMS Debug
21052    & gdb (Alpha),\cr
21053 \+
21054    &
21055    & OpenVMS Debug (I64)\cr
21056 \smallskip
21057 \+Source Code Analyzer /
21058    &HP SCA
21059    & GNAT XREF\cr
21060 \+Cross Referencer
21061    &
21062    &\cr
21063 \smallskip
21064 \+Test Manager
21065    &HP Digital Test
21066    & HP DTM\cr
21067 \+
21068    &Manager (DTM)
21069    &\cr
21070 \smallskip
21071 \+Performance and
21072    & HP PCA
21073    & HP PCA\cr
21074 \+Coverage Analyzer
21075    &
21076    &\cr
21077 \smallskip
21078 \+Module Management
21079    & HP MMS
21080    & Not applicable\cr
21081 \+ System
21082    &
21083    &\cr
21084 \smallskip
21085 \smallskip
21086 @end tex
21087 @end iftex
21088
21089 @ifnottex
21090 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21091 @c the TeX version above for the printed version
21092 @flushleft
21093 @c @multitable @columnfractions .3 .4 .4
21094 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21095 @item @i{Tool}
21096 @tab @i{Tool with HP Ada}
21097 @tab @i{Tool with @value{EDITION}}
21098 @item Code Management@*System
21099 @tab HP CMS
21100 @tab HP CMS
21101 @item Language-Sensitive@*Editor
21102 @tab HP LSE
21103 @tab emacs or HP LSE (Alpha)
21104 @item
21105 @tab
21106 @tab HP LSE (I64)
21107 @item Debugger
21108 @tab OpenVMS Debug
21109 @tab gdb (Alpha),
21110 @item
21111 @tab
21112 @tab OpenVMS Debug (I64)
21113 @item Source Code Analyzer /@*Cross Referencer
21114 @tab HP SCA
21115 @tab GNAT XREF
21116 @item Test Manager
21117 @tab HP Digital Test@*Manager (DTM)
21118 @tab HP DTM
21119 @item Performance and@*Coverage Analyzer
21120 @tab HP PCA
21121 @tab HP PCA
21122 @item Module Management@*System
21123 @tab HP MMS
21124 @tab Not applicable
21125 @end multitable
21126 @end flushleft
21127 @end ifnottex
21128
21129 @end ifset
21130
21131 @c **************************************
21132 @node Platform-Specific Information for the Run-Time Libraries
21133 @appendix Platform-Specific Information for the Run-Time Libraries
21134 @cindex Tasking and threads libraries
21135 @cindex Threads libraries and tasking
21136 @cindex Run-time libraries (platform-specific information)
21137
21138 @noindent
21139 The GNAT run-time implementation may vary with respect to both the
21140 underlying threads library and the exception handling scheme.
21141 For threads support, one or more of the following are supplied:
21142 @itemize @bullet
21143 @item @b{native threads library}, a binding to the thread package from
21144 the underlying operating system
21145
21146 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21147 POSIX thread package
21148 @end itemize
21149
21150 @noindent
21151 For exception handling, either or both of two models are supplied:
21152 @itemize @bullet
21153 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21154 Most programs should experience a substantial speed improvement by
21155 being compiled with a ZCX run-time.
21156 This is especially true for
21157 tasking applications or applications with many exception handlers.}
21158 @cindex Zero-Cost Exceptions
21159 @cindex ZCX (Zero-Cost Exceptions)
21160 which uses binder-generated tables that
21161 are interrogated at run time to locate a handler
21162
21163 @item @b{setjmp / longjmp} (``SJLJ''),
21164 @cindex setjmp/longjmp Exception Model
21165 @cindex SJLJ (setjmp/longjmp Exception Model)
21166 which uses dynamically-set data to establish
21167 the set of handlers
21168 @end itemize
21169
21170 @noindent
21171 This appendix summarizes which combinations of threads and exception support
21172 are supplied on various GNAT platforms.
21173 It then shows how to select a particular library either
21174 permanently or temporarily,
21175 explains the properties of (and tradeoffs among) the various threads
21176 libraries, and provides some additional
21177 information about several specific platforms.
21178
21179 @menu
21180 * Summary of Run-Time Configurations::
21181 * Specifying a Run-Time Library::
21182 * Choosing the Scheduling Policy::
21183 * Solaris-Specific Considerations::
21184 * Linux-Specific Considerations::
21185 * AIX-Specific Considerations::
21186 * Irix-Specific Considerations::
21187 * RTX-Specific Considerations::
21188 * HP-UX-Specific Considerations::
21189 @end menu
21190
21191 @node Summary of Run-Time Configurations
21192 @section Summary of Run-Time Configurations
21193
21194 @multitable @columnfractions .30 .70
21195 @item @b{alpha-openvms}
21196 @item @code{@ @ }@i{rts-native (default)}
21197 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21198 @item @code{@ @ @ @ }Exceptions @tab ZCX
21199 @*
21200 @item @b{alpha-tru64}
21201 @item @code{@ @ }@i{rts-native (default)}
21202 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21203 @item @code{@ @ @ @ }Exceptions @tab ZCX
21204 @*
21205 @item @code{@ @ }@i{rts-sjlj}
21206 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21207 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21208 @*
21209 @item @b{ia64-hp_linux}
21210 @item @code{@ @ }@i{rts-native (default)}
21211 @item @code{@ @ @ @ }Tasking    @tab pthread library
21212 @item @code{@ @ @ @ }Exceptions @tab ZCX
21213 @*
21214 @item @b{ia64-hpux}
21215 @item @code{@ @ }@i{rts-native (default)}
21216 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21217 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21218 @*
21219 @item @b{ia64-openvms}
21220 @item @code{@ @ }@i{rts-native (default)}
21221 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21222 @item @code{@ @ @ @ }Exceptions @tab ZCX
21223 @*
21224 @item @b{ia64-sgi_linux}
21225 @item @code{@ @ }@i{rts-native (default)}
21226 @item @code{@ @ @ @ }Tasking    @tab pthread library
21227 @item @code{@ @ @ @ }Exceptions @tab ZCX
21228 @*
21229 @item @b{mips-irix}
21230 @item @code{@ @ }@i{rts-native (default)}
21231 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21232 @item @code{@ @ @ @ }Exceptions @tab ZCX
21233 @*
21234 @item @b{pa-hpux}
21235 @item @code{@ @ }@i{rts-native (default)}
21236 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21237 @item @code{@ @ @ @ }Exceptions @tab ZCX
21238 @*
21239 @item @code{@ @ }@i{rts-sjlj}
21240 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21241 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21242 @*
21243 @item @b{ppc-aix}
21244 @item @code{@ @ }@i{rts-native (default)}
21245 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21246 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21247 @*
21248 @item @b{ppc-darwin}
21249 @item @code{@ @ }@i{rts-native (default)}
21250 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21251 @item @code{@ @ @ @ }Exceptions @tab ZCX
21252 @*
21253 @item @b{sparc-solaris}  @tab
21254 @item @code{@ @ }@i{rts-native (default)}
21255 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21256 @item @code{@ @ @ @ }Exceptions @tab ZCX
21257 @*
21258 @item @code{@ @ }@i{rts-pthread}
21259 @item @code{@ @ @ @ }Tasking    @tab pthread library
21260 @item @code{@ @ @ @ }Exceptions @tab ZCX
21261 @*
21262 @item @code{@ @ }@i{rts-sjlj}
21263 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21264 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21265 @*
21266 @item @b{sparc64-solaris}  @tab
21267 @item @code{@ @ }@i{rts-native (default)}
21268 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21269 @item @code{@ @ @ @ }Exceptions @tab ZCX
21270 @*
21271 @item @b{x86-linux}
21272 @item @code{@ @ }@i{rts-native (default)}
21273 @item @code{@ @ @ @ }Tasking    @tab pthread library
21274 @item @code{@ @ @ @ }Exceptions @tab ZCX
21275 @*
21276 @item @code{@ @ }@i{rts-sjlj}
21277 @item @code{@ @ @ @ }Tasking    @tab pthread library
21278 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21279 @*
21280 @item @b{x86-lynx}
21281 @item @code{@ @ }@i{rts-native (default)}
21282 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21283 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21284 @*
21285 @item @b{x86-solaris}
21286 @item @code{@ @ }@i{rts-native (default)}
21287 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21288 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21289 @*
21290 @item @b{x86-windows}
21291 @item @code{@ @ }@i{rts-native (default)}
21292 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21293 @item @code{@ @ @ @ }Exceptions @tab ZCX
21294 @*
21295 @item @code{@ @ }@i{rts-sjlj (default)}
21296 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21297 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21298 @*
21299 @item @b{x86-windows-rtx}
21300 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21301 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21302 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21303 @*
21304 @item @code{@ @ }@i{rts-rtx-w32}
21305 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21306 @item @code{@ @ @ @ }Exceptions @tab ZCX
21307 @*
21308 @item @b{x86_64-linux}
21309 @item @code{@ @ }@i{rts-native (default)}
21310 @item @code{@ @ @ @ }Tasking    @tab pthread library
21311 @item @code{@ @ @ @ }Exceptions @tab ZCX
21312 @*
21313 @item @code{@ @ }@i{rts-sjlj}
21314 @item @code{@ @ @ @ }Tasking    @tab pthread library
21315 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21316 @*
21317 @end multitable
21318
21319 @node Specifying a Run-Time Library
21320 @section Specifying a Run-Time Library
21321
21322 @noindent
21323 The @file{adainclude} subdirectory containing the sources of the GNAT
21324 run-time library, and the @file{adalib} subdirectory containing the
21325 @file{ALI} files and the static and/or shared GNAT library, are located
21326 in the gcc target-dependent area:
21327
21328 @smallexample
21329 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21330 @end smallexample
21331
21332 @noindent
21333 As indicated above, on some platforms several run-time libraries are supplied.
21334 These libraries are installed in the target dependent area and
21335 contain a complete source and binary subdirectory. The detailed description
21336 below explains the differences between the different libraries in terms of
21337 their thread support.
21338
21339 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21340 This default run time is selected by the means of soft links.
21341 For example on x86-linux:
21342
21343 @smallexample
21344 @group
21345  $(target-dir)
21346      |
21347      +--- adainclude----------+
21348      |                        |
21349      +--- adalib-----------+  |
21350      |                     |  |
21351      +--- rts-native       |  |
21352      |    |                |  |
21353      |    +--- adainclude <---+
21354      |    |                |
21355      |    +--- adalib <----+
21356      |
21357      +--- rts-sjlj
21358           |
21359           +--- adainclude
21360           |
21361           +--- adalib
21362 @end group
21363 @end smallexample
21364
21365 @noindent
21366 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21367 these soft links can be modified with the following commands:
21368
21369 @smallexample
21370 $ cd $target
21371 $ rm -f adainclude adalib
21372 $ ln -s rts-sjlj/adainclude adainclude
21373 $ ln -s rts-sjlj/adalib adalib
21374 @end smallexample
21375
21376 @noindent
21377 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21378 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21379 @file{$target/ada_object_path}.
21380
21381 Selecting another run-time library temporarily can be
21382 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21383 @cindex @option{--RTS} option
21384
21385 @node Choosing the Scheduling Policy
21386 @section Choosing the Scheduling Policy
21387
21388 @noindent
21389 When using a POSIX threads implementation, you have a choice of several
21390 scheduling policies: @code{SCHED_FIFO},
21391 @cindex @code{SCHED_FIFO} scheduling policy
21392 @code{SCHED_RR}
21393 @cindex @code{SCHED_RR} scheduling policy
21394 and @code{SCHED_OTHER}.
21395 @cindex @code{SCHED_OTHER} scheduling policy
21396 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21397 or @code{SCHED_RR} requires special (e.g., root) privileges.
21398
21399 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21400 @code{SCHED_FIFO},
21401 @cindex @code{SCHED_FIFO} scheduling policy
21402 you can use one of the following:
21403
21404 @itemize @bullet
21405 @item
21406 @code{pragma Time_Slice (0.0)}
21407 @cindex pragma Time_Slice
21408 @item
21409 the corresponding binder option @option{-T0}
21410 @cindex @option{-T0} option
21411 @item
21412 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21413 @cindex pragma Task_Dispatching_Policy
21414 @end itemize
21415
21416 @noindent
21417 To specify @code{SCHED_RR},
21418 @cindex @code{SCHED_RR} scheduling policy
21419 you should use @code{pragma Time_Slice} with a
21420 value greater than @code{0.0}, or else use the corresponding @option{-T}
21421 binder option.
21422
21423 @node Solaris-Specific Considerations
21424 @section Solaris-Specific Considerations
21425 @cindex Solaris Sparc threads libraries
21426
21427 @noindent
21428 This section addresses some topics related to the various threads libraries
21429 on Sparc Solaris.
21430
21431 @menu
21432 * Solaris Threads Issues::
21433 @end menu
21434
21435 @node Solaris Threads Issues
21436 @subsection Solaris Threads Issues
21437
21438 @noindent
21439 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21440 library based on POSIX threads --- @emph{rts-pthread}.
21441 @cindex rts-pthread threads library
21442 This run-time library has the advantage of being mostly shared across all
21443 POSIX-compliant thread implementations, and it also provides under
21444 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21445 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21446 and @code{PTHREAD_PRIO_PROTECT}
21447 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21448 semantics that can be selected using the predefined pragma
21449 @code{Locking_Policy}
21450 @cindex pragma Locking_Policy (under rts-pthread)
21451 with respectively
21452 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21453 @cindex @code{Inheritance_Locking} (under rts-pthread)
21454 @cindex @code{Ceiling_Locking} (under rts-pthread)
21455
21456 As explained above, the native run-time library is based on the Solaris thread
21457 library (@code{libthread}) and is the default library.
21458
21459 When the Solaris threads library is used (this is the default), programs
21460 compiled with GNAT can automatically take advantage of
21461 and can thus execute on multiple processors.
21462 The user can alternatively specify a processor on which the program should run
21463 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21464 is made by
21465 setting the environment variable @env{GNAT_PROCESSOR}
21466 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21467 to one of the following:
21468
21469 @table @code
21470 @item -2
21471 Use the default configuration (run the program on all
21472 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21473 unset
21474
21475 @item -1
21476 Let the run-time implementation choose one processor and run the program on
21477 that processor
21478
21479 @item 0 .. Last_Proc
21480 Run the program on the specified processor.
21481 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21482 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21483 @end table
21484
21485 @node Linux-Specific Considerations
21486 @section Linux-Specific Considerations
21487 @cindex Linux threads libraries
21488
21489 @noindent
21490 On GNU/Linux without NPTL support (usually system with GNU C Library
21491 older than 2.3), the signal model is not POSIX compliant, which means
21492 that to send a signal to the process, you need to send the signal to all
21493 threads, e.g.@: by using @code{killpg()}.
21494
21495 @node AIX-Specific Considerations
21496 @section AIX-Specific Considerations
21497 @cindex AIX resolver library
21498
21499 @noindent
21500 On AIX, the resolver library initializes some internal structure on
21501 the first call to @code{get*by*} functions, which are used to implement
21502 @code{GNAT.Sockets.Get_Host_By_Name} and
21503 @code{GNAT.Sockets.Get_Host_By_Address}.
21504 If such initialization occurs within an Ada task, and the stack size for
21505 the task is the default size, a stack overflow may occur.
21506
21507 To avoid this overflow, the user should either ensure that the first call
21508 to @code{GNAT.Sockets.Get_Host_By_Name} or
21509 @code{GNAT.Sockets.Get_Host_By_Addrss}
21510 occurs in the environment task, or use @code{pragma Storage_Size} to
21511 specify a sufficiently large size for the stack of the task that contains
21512 this call.
21513
21514 @node Irix-Specific Considerations
21515 @section Irix-Specific Considerations
21516 @cindex Irix libraries
21517
21518 @noindent
21519 The GCC support libraries coming with the Irix compiler have moved to
21520 their canonical place with respect to the general Irix ABI related
21521 conventions. Running applications built with the default shared GNAT
21522 run-time now requires the LD_LIBRARY_PATH environment variable to
21523 include this location. A possible way to achieve this is to issue the
21524 following command line on a bash prompt:
21525
21526 @smallexample
21527 @group
21528 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21529 @end group
21530 @end smallexample
21531
21532 @node RTX-Specific Considerations
21533 @section RTX-Specific Considerations
21534 @cindex RTX libraries
21535
21536 @noindent
21537 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21538 API. Applications can be built to work in two different modes:
21539
21540 @itemize @bullet
21541 @item
21542 Windows executables that run in Ring 3 to utilize memory protection
21543 (@emph{rts-rtx-w32}).
21544
21545 @item
21546 Real-time subsystem (RTSS) executables that run in Ring 0, where
21547 performance can be optimized with RTSS applications taking precedent
21548 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21549 the Microsoft linker to handle RTSS libraries.
21550
21551 @end itemize
21552
21553 @node HP-UX-Specific Considerations
21554 @section HP-UX-Specific Considerations
21555 @cindex HP-UX Scheduling
21556
21557 @noindent
21558 On HP-UX, appropriate privileges are required to change the scheduling
21559 parameters of a task. The calling process must have appropriate
21560 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21561 successfully change the scheduling parameters.
21562
21563 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
21564 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
21565 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
21566
21567 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
21568 one of the following:
21569
21570 @itemize @bullet
21571 @item
21572 @code{pragma Time_Slice (0.0)}
21573 @cindex pragma Time_Slice
21574 @item
21575 the corresponding binder option @option{-T0}
21576 @cindex @option{-T0} option
21577 @item
21578 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21579 @cindex pragma Task_Dispatching_Policy
21580 @end itemize
21581
21582 @noindent
21583 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
21584 you should use @code{pragma Time_Slice} with a
21585 value greater than @code{0.0}, or use the corresponding @option{-T}
21586 binder option, or set the @code{pragma Task_Dispatching_Policy
21587 (Round_Robin_Within_Priorities)}.
21588
21589 @c *******************************
21590 @node Example of Binder Output File
21591 @appendix Example of Binder Output File
21592
21593 @noindent
21594 This Appendix displays the source code for @command{gnatbind}'s output
21595 file generated for a simple ``Hello World'' program.
21596 Comments have been added for clarification purposes.
21597
21598 @smallexample @c adanocomment
21599 @iftex
21600 @leftskip=0cm
21601 @end iftex
21602 --  The package is called Ada_Main unless this name is actually used
21603 --  as a unit name in the partition, in which case some other unique
21604 --  name is used.
21605
21606 with System;
21607 package ada_main is
21608
21609    Elab_Final_Code : Integer;
21610    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21611
21612    --  The main program saves the parameters (argument count,
21613    --  argument values, environment pointer) in global variables
21614    --  for later access by other units including
21615    --  Ada.Command_Line.
21616
21617    gnat_argc : Integer;
21618    gnat_argv : System.Address;
21619    gnat_envp : System.Address;
21620
21621    --  The actual variables are stored in a library routine. This
21622    --  is useful for some shared library situations, where there
21623    --  are problems if variables are not in the library.
21624
21625    pragma Import (C, gnat_argc);
21626    pragma Import (C, gnat_argv);
21627    pragma Import (C, gnat_envp);
21628
21629    --  The exit status is similarly an external location
21630
21631    gnat_exit_status : Integer;
21632    pragma Import (C, gnat_exit_status);
21633
21634    GNAT_Version : constant String :=
21635                     "GNAT Version: 6.0.0w (20061115)";
21636    pragma Export (C, GNAT_Version, "__gnat_version");
21637
21638    --  This is the generated adafinal routine that performs
21639    --  finalization at the end of execution. In the case where
21640    --  Ada is the main program, this main program makes a call
21641    --  to adafinal at program termination.
21642
21643    procedure adafinal;
21644    pragma Export (C, adafinal, "adafinal");
21645
21646    --  This is the generated adainit routine that performs
21647    --  initialization at the start of execution. In the case
21648    --  where Ada is the main program, this main program makes
21649    --  a call to adainit at program startup.
21650
21651    procedure adainit;
21652    pragma Export (C, adainit, "adainit");
21653
21654    --  This routine is called at the start of execution. It is
21655    --  a dummy routine that is used by the debugger to breakpoint
21656    --  at the start of execution.
21657
21658    procedure Break_Start;
21659    pragma Import (C, Break_Start, "__gnat_break_start");
21660
21661    --  This is the actual generated main program (it would be
21662    --  suppressed if the no main program switch were used). As
21663    --  required by standard system conventions, this program has
21664    --  the external name main.
21665
21666    function main
21667      (argc : Integer;
21668       argv : System.Address;
21669       envp : System.Address)
21670       return Integer;
21671    pragma Export (C, main, "main");
21672
21673    --  The following set of constants give the version
21674    --  identification values for every unit in the bound
21675    --  partition. This identification is computed from all
21676    --  dependent semantic units, and corresponds to the
21677    --  string that would be returned by use of the
21678    --  Body_Version or Version attributes.
21679
21680    type Version_32 is mod 2 ** 32;
21681    u00001 : constant Version_32 := 16#7880BEB3#;
21682    u00002 : constant Version_32 := 16#0D24CBD0#;
21683    u00003 : constant Version_32 := 16#3283DBEB#;
21684    u00004 : constant Version_32 := 16#2359F9ED#;
21685    u00005 : constant Version_32 := 16#664FB847#;
21686    u00006 : constant Version_32 := 16#68E803DF#;
21687    u00007 : constant Version_32 := 16#5572E604#;
21688    u00008 : constant Version_32 := 16#46B173D8#;
21689    u00009 : constant Version_32 := 16#156A40CF#;
21690    u00010 : constant Version_32 := 16#033DABE0#;
21691    u00011 : constant Version_32 := 16#6AB38FEA#;
21692    u00012 : constant Version_32 := 16#22B6217D#;
21693    u00013 : constant Version_32 := 16#68A22947#;
21694    u00014 : constant Version_32 := 16#18CC4A56#;
21695    u00015 : constant Version_32 := 16#08258E1B#;
21696    u00016 : constant Version_32 := 16#367D5222#;
21697    u00017 : constant Version_32 := 16#20C9ECA4#;
21698    u00018 : constant Version_32 := 16#50D32CB6#;
21699    u00019 : constant Version_32 := 16#39A8BB77#;
21700    u00020 : constant Version_32 := 16#5CF8FA2B#;
21701    u00021 : constant Version_32 := 16#2F1EB794#;
21702    u00022 : constant Version_32 := 16#31AB6444#;
21703    u00023 : constant Version_32 := 16#1574B6E9#;
21704    u00024 : constant Version_32 := 16#5109C189#;
21705    u00025 : constant Version_32 := 16#56D770CD#;
21706    u00026 : constant Version_32 := 16#02F9DE3D#;
21707    u00027 : constant Version_32 := 16#08AB6B2C#;
21708    u00028 : constant Version_32 := 16#3FA37670#;
21709    u00029 : constant Version_32 := 16#476457A0#;
21710    u00030 : constant Version_32 := 16#731E1B6E#;
21711    u00031 : constant Version_32 := 16#23C2E789#;
21712    u00032 : constant Version_32 := 16#0F1BD6A1#;
21713    u00033 : constant Version_32 := 16#7C25DE96#;
21714    u00034 : constant Version_32 := 16#39ADFFA2#;
21715    u00035 : constant Version_32 := 16#571DE3E7#;
21716    u00036 : constant Version_32 := 16#5EB646AB#;
21717    u00037 : constant Version_32 := 16#4249379B#;
21718    u00038 : constant Version_32 := 16#0357E00A#;
21719    u00039 : constant Version_32 := 16#3784FB72#;
21720    u00040 : constant Version_32 := 16#2E723019#;
21721    u00041 : constant Version_32 := 16#623358EA#;
21722    u00042 : constant Version_32 := 16#107F9465#;
21723    u00043 : constant Version_32 := 16#6843F68A#;
21724    u00044 : constant Version_32 := 16#63305874#;
21725    u00045 : constant Version_32 := 16#31E56CE1#;
21726    u00046 : constant Version_32 := 16#02917970#;
21727    u00047 : constant Version_32 := 16#6CCBA70E#;
21728    u00048 : constant Version_32 := 16#41CD4204#;
21729    u00049 : constant Version_32 := 16#572E3F58#;
21730    u00050 : constant Version_32 := 16#20729FF5#;
21731    u00051 : constant Version_32 := 16#1D4F93E8#;
21732    u00052 : constant Version_32 := 16#30B2EC3D#;
21733    u00053 : constant Version_32 := 16#34054F96#;
21734    u00054 : constant Version_32 := 16#5A199860#;
21735    u00055 : constant Version_32 := 16#0E7F912B#;
21736    u00056 : constant Version_32 := 16#5760634A#;
21737    u00057 : constant Version_32 := 16#5D851835#;
21738
21739    --  The following Export pragmas export the version numbers
21740    --  with symbolic names ending in B (for body) or S
21741    --  (for spec) so that they can be located in a link. The
21742    --  information provided here is sufficient to track down
21743    --  the exact versions of units used in a given build.
21744
21745    pragma Export (C, u00001, "helloB");
21746    pragma Export (C, u00002, "system__standard_libraryB");
21747    pragma Export (C, u00003, "system__standard_libraryS");
21748    pragma Export (C, u00004, "adaS");
21749    pragma Export (C, u00005, "ada__text_ioB");
21750    pragma Export (C, u00006, "ada__text_ioS");
21751    pragma Export (C, u00007, "ada__exceptionsB");
21752    pragma Export (C, u00008, "ada__exceptionsS");
21753    pragma Export (C, u00009, "gnatS");
21754    pragma Export (C, u00010, "gnat__heap_sort_aB");
21755    pragma Export (C, u00011, "gnat__heap_sort_aS");
21756    pragma Export (C, u00012, "systemS");
21757    pragma Export (C, u00013, "system__exception_tableB");
21758    pragma Export (C, u00014, "system__exception_tableS");
21759    pragma Export (C, u00015, "gnat__htableB");
21760    pragma Export (C, u00016, "gnat__htableS");
21761    pragma Export (C, u00017, "system__exceptionsS");
21762    pragma Export (C, u00018, "system__machine_state_operationsB");
21763    pragma Export (C, u00019, "system__machine_state_operationsS");
21764    pragma Export (C, u00020, "system__machine_codeS");
21765    pragma Export (C, u00021, "system__storage_elementsB");
21766    pragma Export (C, u00022, "system__storage_elementsS");
21767    pragma Export (C, u00023, "system__secondary_stackB");
21768    pragma Export (C, u00024, "system__secondary_stackS");
21769    pragma Export (C, u00025, "system__parametersB");
21770    pragma Export (C, u00026, "system__parametersS");
21771    pragma Export (C, u00027, "system__soft_linksB");
21772    pragma Export (C, u00028, "system__soft_linksS");
21773    pragma Export (C, u00029, "system__stack_checkingB");
21774    pragma Export (C, u00030, "system__stack_checkingS");
21775    pragma Export (C, u00031, "system__tracebackB");
21776    pragma Export (C, u00032, "system__tracebackS");
21777    pragma Export (C, u00033, "ada__streamsS");
21778    pragma Export (C, u00034, "ada__tagsB");
21779    pragma Export (C, u00035, "ada__tagsS");
21780    pragma Export (C, u00036, "system__string_opsB");
21781    pragma Export (C, u00037, "system__string_opsS");
21782    pragma Export (C, u00038, "interfacesS");
21783    pragma Export (C, u00039, "interfaces__c_streamsB");
21784    pragma Export (C, u00040, "interfaces__c_streamsS");
21785    pragma Export (C, u00041, "system__file_ioB");
21786    pragma Export (C, u00042, "system__file_ioS");
21787    pragma Export (C, u00043, "ada__finalizationB");
21788    pragma Export (C, u00044, "ada__finalizationS");
21789    pragma Export (C, u00045, "system__finalization_rootB");
21790    pragma Export (C, u00046, "system__finalization_rootS");
21791    pragma Export (C, u00047, "system__finalization_implementationB");
21792    pragma Export (C, u00048, "system__finalization_implementationS");
21793    pragma Export (C, u00049, "system__string_ops_concat_3B");
21794    pragma Export (C, u00050, "system__string_ops_concat_3S");
21795    pragma Export (C, u00051, "system__stream_attributesB");
21796    pragma Export (C, u00052, "system__stream_attributesS");
21797    pragma Export (C, u00053, "ada__io_exceptionsS");
21798    pragma Export (C, u00054, "system__unsigned_typesS");
21799    pragma Export (C, u00055, "system__file_control_blockS");
21800    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21801    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21802
21803    -- BEGIN ELABORATION ORDER
21804    -- ada (spec)
21805    -- gnat (spec)
21806    -- gnat.heap_sort_a (spec)
21807    -- gnat.heap_sort_a (body)
21808    -- gnat.htable (spec)
21809    -- gnat.htable (body)
21810    -- interfaces (spec)
21811    -- system (spec)
21812    -- system.machine_code (spec)
21813    -- system.parameters (spec)
21814    -- system.parameters (body)
21815    -- interfaces.c_streams (spec)
21816    -- interfaces.c_streams (body)
21817    -- system.standard_library (spec)
21818    -- ada.exceptions (spec)
21819    -- system.exception_table (spec)
21820    -- system.exception_table (body)
21821    -- ada.io_exceptions (spec)
21822    -- system.exceptions (spec)
21823    -- system.storage_elements (spec)
21824    -- system.storage_elements (body)
21825    -- system.machine_state_operations (spec)
21826    -- system.machine_state_operations (body)
21827    -- system.secondary_stack (spec)
21828    -- system.stack_checking (spec)
21829    -- system.soft_links (spec)
21830    -- system.soft_links (body)
21831    -- system.stack_checking (body)
21832    -- system.secondary_stack (body)
21833    -- system.standard_library (body)
21834    -- system.string_ops (spec)
21835    -- system.string_ops (body)
21836    -- ada.tags (spec)
21837    -- ada.tags (body)
21838    -- ada.streams (spec)
21839    -- system.finalization_root (spec)
21840    -- system.finalization_root (body)
21841    -- system.string_ops_concat_3 (spec)
21842    -- system.string_ops_concat_3 (body)
21843    -- system.traceback (spec)
21844    -- system.traceback (body)
21845    -- ada.exceptions (body)
21846    -- system.unsigned_types (spec)
21847    -- system.stream_attributes (spec)
21848    -- system.stream_attributes (body)
21849    -- system.finalization_implementation (spec)
21850    -- system.finalization_implementation (body)
21851    -- ada.finalization (spec)
21852    -- ada.finalization (body)
21853    -- ada.finalization.list_controller (spec)
21854    -- ada.finalization.list_controller (body)
21855    -- system.file_control_block (spec)
21856    -- system.file_io (spec)
21857    -- system.file_io (body)
21858    -- ada.text_io (spec)
21859    -- ada.text_io (body)
21860    -- hello (body)
21861    -- END ELABORATION ORDER
21862
21863 end ada_main;
21864
21865 --  The following source file name pragmas allow the generated file
21866 --  names to be unique for different main programs. They are needed
21867 --  since the package name will always be Ada_Main.
21868
21869 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21870 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21871
21872 --  Generated package body for Ada_Main starts here
21873
21874 package body ada_main is
21875
21876    --  The actual finalization is performed by calling the
21877    --  library routine in System.Standard_Library.Adafinal
21878
21879    procedure Do_Finalize;
21880    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21881
21882    -------------
21883    -- adainit --
21884    -------------
21885
21886 @findex adainit
21887    procedure adainit is
21888
21889       --  These booleans are set to True once the associated unit has
21890       --  been elaborated. It is also used to avoid elaborating the
21891       --  same unit twice.
21892
21893       E040 : Boolean;
21894       pragma Import (Ada, E040, "interfaces__c_streams_E");
21895
21896       E008 : Boolean;
21897       pragma Import (Ada, E008, "ada__exceptions_E");
21898
21899       E014 : Boolean;
21900       pragma Import (Ada, E014, "system__exception_table_E");
21901
21902       E053 : Boolean;
21903       pragma Import (Ada, E053, "ada__io_exceptions_E");
21904
21905       E017 : Boolean;
21906       pragma Import (Ada, E017, "system__exceptions_E");
21907
21908       E024 : Boolean;
21909       pragma Import (Ada, E024, "system__secondary_stack_E");
21910
21911       E030 : Boolean;
21912       pragma Import (Ada, E030, "system__stack_checking_E");
21913
21914       E028 : Boolean;
21915       pragma Import (Ada, E028, "system__soft_links_E");
21916
21917       E035 : Boolean;
21918       pragma Import (Ada, E035, "ada__tags_E");
21919
21920       E033 : Boolean;
21921       pragma Import (Ada, E033, "ada__streams_E");
21922
21923       E046 : Boolean;
21924       pragma Import (Ada, E046, "system__finalization_root_E");
21925
21926       E048 : Boolean;
21927       pragma Import (Ada, E048, "system__finalization_implementation_E");
21928
21929       E044 : Boolean;
21930       pragma Import (Ada, E044, "ada__finalization_E");
21931
21932       E057 : Boolean;
21933       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21934
21935       E055 : Boolean;
21936       pragma Import (Ada, E055, "system__file_control_block_E");
21937
21938       E042 : Boolean;
21939       pragma Import (Ada, E042, "system__file_io_E");
21940
21941       E006 : Boolean;
21942       pragma Import (Ada, E006, "ada__text_io_E");
21943
21944       --  Set_Globals is a library routine that stores away the
21945       --  value of the indicated set of global values in global
21946       --  variables within the library.
21947
21948       procedure Set_Globals
21949         (Main_Priority            : Integer;
21950          Time_Slice_Value         : Integer;
21951          WC_Encoding              : Character;
21952          Locking_Policy           : Character;
21953          Queuing_Policy           : Character;
21954          Task_Dispatching_Policy  : Character;
21955          Adafinal                 : System.Address;
21956          Unreserve_All_Interrupts : Integer;
21957          Exception_Tracebacks     : Integer);
21958 @findex __gnat_set_globals
21959       pragma Import (C, Set_Globals, "__gnat_set_globals");
21960
21961       --  SDP_Table_Build is a library routine used to build the
21962       --  exception tables. See unit Ada.Exceptions in files
21963       --  a-except.ads/adb for full details of how zero cost
21964       --  exception handling works. This procedure, the call to
21965       --  it, and the two following tables are all omitted if the
21966       --  build is in longjmp/setjmp exception mode.
21967
21968 @findex SDP_Table_Build
21969 @findex Zero Cost Exceptions
21970       procedure SDP_Table_Build
21971         (SDP_Addresses   : System.Address;
21972          SDP_Count       : Natural;
21973          Elab_Addresses  : System.Address;
21974          Elab_Addr_Count : Natural);
21975       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21976
21977       --  Table of Unit_Exception_Table addresses. Used for zero
21978       --  cost exception handling to build the top level table.
21979
21980       ST : aliased constant array (1 .. 23) of System.Address := (
21981         Hello'UET_Address,
21982         Ada.Text_Io'UET_Address,
21983         Ada.Exceptions'UET_Address,
21984         Gnat.Heap_Sort_A'UET_Address,
21985         System.Exception_Table'UET_Address,
21986         System.Machine_State_Operations'UET_Address,
21987         System.Secondary_Stack'UET_Address,
21988         System.Parameters'UET_Address,
21989         System.Soft_Links'UET_Address,
21990         System.Stack_Checking'UET_Address,
21991         System.Traceback'UET_Address,
21992         Ada.Streams'UET_Address,
21993         Ada.Tags'UET_Address,
21994         System.String_Ops'UET_Address,
21995         Interfaces.C_Streams'UET_Address,
21996         System.File_Io'UET_Address,
21997         Ada.Finalization'UET_Address,
21998         System.Finalization_Root'UET_Address,
21999         System.Finalization_Implementation'UET_Address,
22000         System.String_Ops_Concat_3'UET_Address,
22001         System.Stream_Attributes'UET_Address,
22002         System.File_Control_Block'UET_Address,
22003         Ada.Finalization.List_Controller'UET_Address);
22004
22005       --  Table of addresses of elaboration routines. Used for
22006       --  zero cost exception handling to make sure these
22007       --  addresses are included in the top level procedure
22008       --  address table.
22009
22010       EA : aliased constant array (1 .. 23) of System.Address := (
22011         adainit'Code_Address,
22012         Do_Finalize'Code_Address,
22013         Ada.Exceptions'Elab_Spec'Address,
22014         System.Exceptions'Elab_Spec'Address,
22015         Interfaces.C_Streams'Elab_Spec'Address,
22016         System.Exception_Table'Elab_Body'Address,
22017         Ada.Io_Exceptions'Elab_Spec'Address,
22018         System.Stack_Checking'Elab_Spec'Address,
22019         System.Soft_Links'Elab_Body'Address,
22020         System.Secondary_Stack'Elab_Body'Address,
22021         Ada.Tags'Elab_Spec'Address,
22022         Ada.Tags'Elab_Body'Address,
22023         Ada.Streams'Elab_Spec'Address,
22024         System.Finalization_Root'Elab_Spec'Address,
22025         Ada.Exceptions'Elab_Body'Address,
22026         System.Finalization_Implementation'Elab_Spec'Address,
22027         System.Finalization_Implementation'Elab_Body'Address,
22028         Ada.Finalization'Elab_Spec'Address,
22029         Ada.Finalization.List_Controller'Elab_Spec'Address,
22030         System.File_Control_Block'Elab_Spec'Address,
22031         System.File_Io'Elab_Body'Address,
22032         Ada.Text_Io'Elab_Spec'Address,
22033         Ada.Text_Io'Elab_Body'Address);
22034
22035    --  Start of processing for adainit
22036
22037    begin
22038
22039       --  Call SDP_Table_Build to build the top level procedure
22040       --  table for zero cost exception handling (omitted in
22041       --  longjmp/setjmp mode).
22042
22043       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22044
22045       --  Call Set_Globals to record various information for
22046       --  this partition.  The values are derived by the binder
22047       --  from information stored in the ali files by the compiler.
22048
22049 @findex __gnat_set_globals
22050       Set_Globals
22051         (Main_Priority            => -1,
22052          --  Priority of main program, -1 if no pragma Priority used
22053
22054          Time_Slice_Value         => -1,
22055          --  Time slice from Time_Slice pragma, -1 if none used
22056
22057          WC_Encoding              => 'b',
22058          --  Wide_Character encoding used, default is brackets
22059
22060          Locking_Policy           => ' ',
22061          --  Locking_Policy used, default of space means not
22062          --  specified, otherwise it is the first character of
22063          --  the policy name.
22064
22065          Queuing_Policy           => ' ',
22066          --  Queuing_Policy used, default of space means not
22067          --  specified, otherwise it is the first character of
22068          --  the policy name.
22069
22070          Task_Dispatching_Policy  => ' ',
22071          --  Task_Dispatching_Policy used, default of space means
22072          --  not specified, otherwise first character of the
22073          --  policy name.
22074
22075          Adafinal                 => System.Null_Address,
22076          --  Address of Adafinal routine, not used anymore
22077
22078          Unreserve_All_Interrupts => 0,
22079          --  Set true if pragma Unreserve_All_Interrupts was used
22080
22081          Exception_Tracebacks     => 0);
22082          --  Indicates if exception tracebacks are enabled
22083
22084       Elab_Final_Code := 1;
22085
22086       --  Now we have the elaboration calls for all units in the partition.
22087       --  The Elab_Spec and Elab_Body attributes generate references to the
22088       --  implicit elaboration procedures generated by the compiler for
22089       --  each unit that requires elaboration.
22090
22091       if not E040 then
22092          Interfaces.C_Streams'Elab_Spec;
22093       end if;
22094       E040 := True;
22095       if not E008 then
22096          Ada.Exceptions'Elab_Spec;
22097       end if;
22098       if not E014 then
22099          System.Exception_Table'Elab_Body;
22100          E014 := True;
22101       end if;
22102       if not E053 then
22103          Ada.Io_Exceptions'Elab_Spec;
22104          E053 := True;
22105       end if;
22106       if not E017 then
22107          System.Exceptions'Elab_Spec;
22108          E017 := True;
22109       end if;
22110       if not E030 then
22111          System.Stack_Checking'Elab_Spec;
22112       end if;
22113       if not E028 then
22114          System.Soft_Links'Elab_Body;
22115          E028 := True;
22116       end if;
22117       E030 := True;
22118       if not E024 then
22119          System.Secondary_Stack'Elab_Body;
22120          E024 := True;
22121       end if;
22122       if not E035 then
22123          Ada.Tags'Elab_Spec;
22124       end if;
22125       if not E035 then
22126          Ada.Tags'Elab_Body;
22127          E035 := True;
22128       end if;
22129       if not E033 then
22130          Ada.Streams'Elab_Spec;
22131          E033 := True;
22132       end if;
22133       if not E046 then
22134          System.Finalization_Root'Elab_Spec;
22135       end if;
22136       E046 := True;
22137       if not E008 then
22138          Ada.Exceptions'Elab_Body;
22139          E008 := True;
22140       end if;
22141       if not E048 then
22142          System.Finalization_Implementation'Elab_Spec;
22143       end if;
22144       if not E048 then
22145          System.Finalization_Implementation'Elab_Body;
22146          E048 := True;
22147       end if;
22148       if not E044 then
22149          Ada.Finalization'Elab_Spec;
22150       end if;
22151       E044 := True;
22152       if not E057 then
22153          Ada.Finalization.List_Controller'Elab_Spec;
22154       end if;
22155       E057 := True;
22156       if not E055 then
22157          System.File_Control_Block'Elab_Spec;
22158          E055 := True;
22159       end if;
22160       if not E042 then
22161          System.File_Io'Elab_Body;
22162          E042 := True;
22163       end if;
22164       if not E006 then
22165          Ada.Text_Io'Elab_Spec;
22166       end if;
22167       if not E006 then
22168          Ada.Text_Io'Elab_Body;
22169          E006 := True;
22170       end if;
22171
22172       Elab_Final_Code := 0;
22173    end adainit;
22174
22175    --------------
22176    -- adafinal --
22177    --------------
22178
22179 @findex adafinal
22180    procedure adafinal is
22181    begin
22182       Do_Finalize;
22183    end adafinal;
22184
22185    ----------
22186    -- main --
22187    ----------
22188
22189    --  main is actually a function, as in the ANSI C standard,
22190    --  defined to return the exit status. The three parameters
22191    --  are the argument count, argument values and environment
22192    --  pointer.
22193
22194 @findex Main Program
22195    function main
22196      (argc : Integer;
22197       argv : System.Address;
22198       envp : System.Address)
22199       return Integer
22200    is
22201       --  The initialize routine performs low level system
22202       --  initialization using a standard library routine which
22203       --  sets up signal handling and performs any other
22204       --  required setup. The routine can be found in file
22205       --  a-init.c.
22206
22207 @findex __gnat_initialize
22208       procedure initialize;
22209       pragma Import (C, initialize, "__gnat_initialize");
22210
22211       --  The finalize routine performs low level system
22212       --  finalization using a standard library routine. The
22213       --  routine is found in file a-final.c and in the standard
22214       --  distribution is a dummy routine that does nothing, so
22215       --  really this is a hook for special user finalization.
22216
22217 @findex __gnat_finalize
22218       procedure finalize;
22219       pragma Import (C, finalize, "__gnat_finalize");
22220
22221       --  We get to the main program of the partition by using
22222       --  pragma Import because if we try to with the unit and
22223       --  call it Ada style, then not only do we waste time
22224       --  recompiling it, but also, we don't really know the right
22225       --  switches (e.g.@: identifier character set) to be used
22226       --  to compile it.
22227
22228       procedure Ada_Main_Program;
22229       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22230
22231    --  Start of processing for main
22232
22233    begin
22234       --  Save global variables
22235
22236       gnat_argc := argc;
22237       gnat_argv := argv;
22238       gnat_envp := envp;
22239
22240       --  Call low level system initialization
22241
22242       Initialize;
22243
22244       --  Call our generated Ada initialization routine
22245
22246       adainit;
22247
22248       --  This is the point at which we want the debugger to get
22249       --  control
22250
22251       Break_Start;
22252
22253       --  Now we call the main program of the partition
22254
22255       Ada_Main_Program;
22256
22257       --  Perform Ada finalization
22258
22259       adafinal;
22260
22261       --  Perform low level system finalization
22262
22263       Finalize;
22264
22265       --  Return the proper exit status
22266       return (gnat_exit_status);
22267    end;
22268
22269 --  This section is entirely comments, so it has no effect on the
22270 --  compilation of the Ada_Main package. It provides the list of
22271 --  object files and linker options, as well as some standard
22272 --  libraries needed for the link. The gnatlink utility parses
22273 --  this b~hello.adb file to read these comment lines to generate
22274 --  the appropriate command line arguments for the call to the
22275 --  system linker. The BEGIN/END lines are used for sentinels for
22276 --  this parsing operation.
22277
22278 --  The exact file names will of course depend on the environment,
22279 --  host/target and location of files on the host system.
22280
22281 @findex Object file list
22282 -- BEGIN Object file/option list
22283    --   ./hello.o
22284    --   -L./
22285    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22286    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22287 -- END Object file/option list
22288
22289 end ada_main;
22290 @end smallexample
22291
22292 @noindent
22293 The Ada code in the above example is exactly what is generated by the
22294 binder. We have added comments to more clearly indicate the function
22295 of each part of the generated @code{Ada_Main} package.
22296
22297 The code is standard Ada in all respects, and can be processed by any
22298 tools that handle Ada. In particular, it is possible to use the debugger
22299 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22300 suppose that for reasons that you do not understand, your program is crashing
22301 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22302 you can place a breakpoint on the call:
22303
22304 @smallexample @c ada
22305 Ada.Text_Io'Elab_Body;
22306 @end smallexample
22307
22308 @noindent
22309 and trace the elaboration routine for this package to find out where
22310 the problem might be (more usually of course you would be debugging
22311 elaboration code in your own application).
22312
22313 @node Elaboration Order Handling in GNAT
22314 @appendix Elaboration Order Handling in GNAT
22315 @cindex Order of elaboration
22316 @cindex Elaboration control
22317
22318 @menu
22319 * Elaboration Code::
22320 * Checking the Elaboration Order::
22321 * Controlling the Elaboration Order::
22322 * Controlling Elaboration in GNAT - Internal Calls::
22323 * Controlling Elaboration in GNAT - External Calls::
22324 * Default Behavior in GNAT - Ensuring Safety::
22325 * Treatment of Pragma Elaborate::
22326 * Elaboration Issues for Library Tasks::
22327 * Mixing Elaboration Models::
22328 * What to Do If the Default Elaboration Behavior Fails::
22329 * Elaboration for Access-to-Subprogram Values::
22330 * Summary of Procedures for Elaboration Control::
22331 * Other Elaboration Order Considerations::
22332 @end menu
22333
22334 @noindent
22335 This chapter describes the handling of elaboration code in Ada and
22336 in GNAT, and discusses how the order of elaboration of program units can
22337 be controlled in GNAT, either automatically or with explicit programming
22338 features.
22339
22340 @node Elaboration Code
22341 @section Elaboration Code
22342
22343 @noindent
22344 Ada provides rather general mechanisms for executing code at elaboration
22345 time, that is to say before the main program starts executing. Such code arises
22346 in three contexts:
22347
22348 @table @asis
22349 @item Initializers for variables.
22350 Variables declared at the library level, in package specs or bodies, can
22351 require initialization that is performed at elaboration time, as in:
22352 @smallexample @c ada
22353 @cartouche
22354 Sqrt_Half : Float := Sqrt (0.5);
22355 @end cartouche
22356 @end smallexample
22357
22358 @item Package initialization code
22359 Code in a @code{BEGIN-END} section at the outer level of a package body is
22360 executed as part of the package body elaboration code.
22361
22362 @item Library level task allocators
22363 Tasks that are declared using task allocators at the library level
22364 start executing immediately and hence can execute at elaboration time.
22365 @end table
22366
22367 @noindent
22368 Subprogram calls are possible in any of these contexts, which means that
22369 any arbitrary part of the program may be executed as part of the elaboration
22370 code. It is even possible to write a program which does all its work at
22371 elaboration time, with a null main program, although stylistically this
22372 would usually be considered an inappropriate way to structure
22373 a program.
22374
22375 An important concern arises in the context of elaboration code:
22376 we have to be sure that it is executed in an appropriate order. What we
22377 have is a series of elaboration code sections, potentially one section
22378 for each unit in the program. It is important that these execute
22379 in the correct order. Correctness here means that, taking the above
22380 example of the declaration of @code{Sqrt_Half},
22381 if some other piece of
22382 elaboration code references @code{Sqrt_Half},
22383 then it must run after the
22384 section of elaboration code that contains the declaration of
22385 @code{Sqrt_Half}.
22386
22387 There would never be any order of elaboration problem if we made a rule
22388 that whenever you @code{with} a unit, you must elaborate both the spec and body
22389 of that unit before elaborating the unit doing the @code{with}'ing:
22390
22391 @smallexample @c ada
22392 @group
22393 @cartouche
22394 with Unit_1;
22395 package Unit_2 is @dots{}
22396 @end cartouche
22397 @end group
22398 @end smallexample
22399
22400 @noindent
22401 would require that both the body and spec of @code{Unit_1} be elaborated
22402 before the spec of @code{Unit_2}. However, a rule like that would be far too
22403 restrictive. In particular, it would make it impossible to have routines
22404 in separate packages that were mutually recursive.
22405
22406 You might think that a clever enough compiler could look at the actual
22407 elaboration code and determine an appropriate correct order of elaboration,
22408 but in the general case, this is not possible. Consider the following
22409 example.
22410
22411 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22412 that references
22413 the variable @code{Sqrt_1}, which is declared in the elaboration code
22414 of the body of @code{Unit_1}:
22415
22416 @smallexample @c ada
22417 @cartouche
22418 Sqrt_1 : Float := Sqrt (0.1);
22419 @end cartouche
22420 @end smallexample
22421
22422 @noindent
22423 The elaboration code of the body of @code{Unit_1} also contains:
22424
22425 @smallexample @c ada
22426 @group
22427 @cartouche
22428 if expression_1 = 1 then
22429    Q := Unit_2.Func_2;
22430 end if;
22431 @end cartouche
22432 @end group
22433 @end smallexample
22434
22435 @noindent
22436 @code{Unit_2} is exactly parallel,
22437 it has a procedure @code{Func_2} that references
22438 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22439 the body @code{Unit_2}:
22440
22441 @smallexample @c ada
22442 @cartouche
22443 Sqrt_2 : Float := Sqrt (0.1);
22444 @end cartouche
22445 @end smallexample
22446
22447 @noindent
22448 The elaboration code of the body of @code{Unit_2} also contains:
22449
22450 @smallexample @c ada
22451 @group
22452 @cartouche
22453 if expression_2 = 2 then
22454    Q := Unit_1.Func_1;
22455 end if;
22456 @end cartouche
22457 @end group
22458 @end smallexample
22459
22460 @noindent
22461 Now the question is, which of the following orders of elaboration is
22462 acceptable:
22463
22464 @smallexample
22465 @group
22466 Spec of Unit_1
22467 Spec of Unit_2
22468 Body of Unit_1
22469 Body of Unit_2
22470 @end group
22471 @end smallexample
22472
22473 @noindent
22474 or
22475
22476 @smallexample
22477 @group
22478 Spec of Unit_2
22479 Spec of Unit_1
22480 Body of Unit_2
22481 Body of Unit_1
22482 @end group
22483 @end smallexample
22484
22485 @noindent
22486 If you carefully analyze the flow here, you will see that you cannot tell
22487 at compile time the answer to this question.
22488 If @code{expression_1} is not equal to 1,
22489 and @code{expression_2} is not equal to 2,
22490 then either order is acceptable, because neither of the function calls is
22491 executed. If both tests evaluate to true, then neither order is acceptable
22492 and in fact there is no correct order.
22493
22494 If one of the two expressions is true, and the other is false, then one
22495 of the above orders is correct, and the other is incorrect. For example,
22496 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22497 then the call to @code{Func_1}
22498 will occur, but not the call to @code{Func_2.}
22499 This means that it is essential
22500 to elaborate the body of @code{Unit_1} before
22501 the body of @code{Unit_2}, so the first
22502 order of elaboration is correct and the second is wrong.
22503
22504 By making @code{expression_1} and @code{expression_2}
22505 depend on input data, or perhaps
22506 the time of day, we can make it impossible for the compiler or binder
22507 to figure out which of these expressions will be true, and hence it
22508 is impossible to guarantee a safe order of elaboration at run time.
22509
22510 @node Checking the Elaboration Order
22511 @section Checking the Elaboration Order
22512
22513 @noindent
22514 In some languages that involve the same kind of elaboration problems,
22515 e.g.@: Java and C++, the programmer is expected to worry about these
22516 ordering problems himself, and it is common to
22517 write a program in which an incorrect elaboration order  gives
22518 surprising results, because it references variables before they
22519 are initialized.
22520 Ada is designed to be a safe language, and a programmer-beware approach is
22521 clearly not sufficient. Consequently, the language provides three lines
22522 of defense:
22523
22524 @table @asis
22525 @item Standard rules
22526 Some standard rules restrict the possible choice of elaboration
22527 order. In particular, if you @code{with} a unit, then its spec is always
22528 elaborated before the unit doing the @code{with}. Similarly, a parent
22529 spec is always elaborated before the child spec, and finally
22530 a spec is always elaborated before its corresponding body.
22531
22532 @item Dynamic elaboration checks
22533 @cindex Elaboration checks
22534 @cindex Checks, elaboration
22535 Dynamic checks are made at run time, so that if some entity is accessed
22536 before it is elaborated (typically  by means of a subprogram call)
22537 then the exception (@code{Program_Error}) is raised.
22538
22539 @item Elaboration control
22540 Facilities are provided for the programmer to specify the desired order
22541 of elaboration.
22542 @end table
22543
22544 Let's look at these facilities in more detail. First, the rules for
22545 dynamic checking. One possible rule would be simply to say that the
22546 exception is raised if you access a variable which has not yet been
22547 elaborated. The trouble with this approach is that it could require
22548 expensive checks on every variable reference. Instead Ada has two
22549 rules which are a little more restrictive, but easier to check, and
22550 easier to state:
22551
22552 @table @asis
22553 @item Restrictions on calls
22554 A subprogram can only be called at elaboration time if its body
22555 has been elaborated. The rules for elaboration given above guarantee
22556 that the spec of the subprogram has been elaborated before the
22557 call, but not the body. If this rule is violated, then the
22558 exception @code{Program_Error} is raised.
22559
22560 @item Restrictions on instantiations
22561 A generic unit can only be instantiated if the body of the generic
22562 unit has been elaborated. Again, the rules for elaboration given above
22563 guarantee that the spec of the generic unit has been elaborated
22564 before the instantiation, but not the body. If this rule is
22565 violated, then the exception @code{Program_Error} is raised.
22566 @end table
22567
22568 @noindent
22569 The idea is that if the body has been elaborated, then any variables
22570 it references must have been elaborated; by checking for the body being
22571 elaborated we guarantee that none of its references causes any
22572 trouble. As we noted above, this is a little too restrictive, because a
22573 subprogram that has no non-local references in its body may in fact be safe
22574 to call. However, it really would be unsafe to rely on this, because
22575 it would mean that the caller was aware of details of the implementation
22576 in the body. This goes against the basic tenets of Ada.
22577
22578 A plausible implementation can be described as follows.
22579 A Boolean variable is associated with each subprogram
22580 and each generic unit. This variable is initialized to False, and is set to
22581 True at the point body is elaborated. Every call or instantiation checks the
22582 variable, and raises @code{Program_Error} if the variable is False.
22583
22584 Note that one might think that it would be good enough to have one Boolean
22585 variable for each package, but that would not deal with cases of trying
22586 to call a body in the same package as the call
22587 that has not been elaborated yet.
22588 Of course a compiler may be able to do enough analysis to optimize away
22589 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22590 does such optimizations, but still the easiest conceptual model is to
22591 think of there being one variable per subprogram.
22592
22593 @node Controlling the Elaboration Order
22594 @section Controlling the Elaboration Order
22595
22596 @noindent
22597 In the previous section we discussed the rules in Ada which ensure
22598 that @code{Program_Error} is raised if an incorrect elaboration order is
22599 chosen. This prevents erroneous executions, but we need mechanisms to
22600 specify a correct execution and avoid the exception altogether.
22601 To achieve this, Ada provides a number of features for controlling
22602 the order of elaboration. We discuss these features in this section.
22603
22604 First, there are several ways of indicating to the compiler that a given
22605 unit has no elaboration problems:
22606
22607 @table @asis
22608 @item packages that do not require a body
22609 A library package that does not require a body does not permit
22610 a body (this rule was introduced in Ada 95).
22611 Thus if we have a such a package, as in:
22612
22613 @smallexample @c ada
22614 @group
22615 @cartouche
22616 package Definitions is
22617    generic
22618       type m is new integer;
22619    package Subp is
22620       type a is array (1 .. 10) of m;
22621       type b is array (1 .. 20) of m;
22622    end Subp;
22623 end Definitions;
22624 @end cartouche
22625 @end group
22626 @end smallexample
22627
22628 @noindent
22629 A package that @code{with}'s @code{Definitions} may safely instantiate
22630 @code{Definitions.Subp} because the compiler can determine that there
22631 definitely is no package body to worry about in this case
22632
22633 @item pragma Pure
22634 @cindex pragma Pure
22635 @findex Pure
22636 Places sufficient restrictions on a unit to guarantee that
22637 no call to any subprogram in the unit can result in an
22638 elaboration problem. This means that the compiler does not need
22639 to worry about the point of elaboration of such units, and in
22640 particular, does not need to check any calls to any subprograms
22641 in this unit.
22642
22643 @item pragma Preelaborate
22644 @findex Preelaborate
22645 @cindex pragma Preelaborate
22646 This pragma places slightly less stringent restrictions on a unit than
22647 does pragma Pure,
22648 but these restrictions are still sufficient to ensure that there
22649 are no elaboration problems with any calls to the unit.
22650
22651 @item pragma Elaborate_Body
22652 @findex Elaborate_Body
22653 @cindex pragma Elaborate_Body
22654 This pragma requires that the body of a unit be elaborated immediately
22655 after its spec. Suppose a unit @code{A} has such a pragma,
22656 and unit @code{B} does
22657 a @code{with} of unit @code{A}. Recall that the standard rules require
22658 the spec of unit @code{A}
22659 to be elaborated before the @code{with}'ing unit; given the pragma in
22660 @code{A}, we also know that the body of @code{A}
22661 will be elaborated before @code{B}, so
22662 that calls to @code{A} are safe and do not need a check.
22663 @end table
22664
22665 @noindent
22666 Note that,
22667 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22668 the use of
22669 @code{Elaborate_Body} does not guarantee that the program is
22670 free of elaboration problems, because it may not be possible
22671 to satisfy the requested elaboration order.
22672 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22673 If a programmer
22674 marks @code{Unit_1} as @code{Elaborate_Body},
22675 and not @code{Unit_2,} then the order of
22676 elaboration will be:
22677
22678 @smallexample
22679 @group
22680 Spec of Unit_2
22681 Spec of Unit_1
22682 Body of Unit_1
22683 Body of Unit_2
22684 @end group
22685 @end smallexample
22686
22687 @noindent
22688 Now that means that the call to @code{Func_1} in @code{Unit_2}
22689 need not be checked,
22690 it must be safe. But the call to @code{Func_2} in
22691 @code{Unit_1} may still fail if
22692 @code{Expression_1} is equal to 1,
22693 and the programmer must still take
22694 responsibility for this not being the case.
22695
22696 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22697 eliminated, except for calls entirely within a body, which are
22698 in any case fully under programmer control. However, using the pragma
22699 everywhere is not always possible.
22700 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22701 we marked both of them as having pragma @code{Elaborate_Body}, then
22702 clearly there would be no possible elaboration order.
22703
22704 The above pragmas allow a server to guarantee safe use by clients, and
22705 clearly this is the preferable approach. Consequently a good rule
22706 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22707 and if this is not possible,
22708 mark them as @code{Elaborate_Body} if possible.
22709 As we have seen, there are situations where neither of these
22710 three pragmas can be used.
22711 So we also provide methods for clients to control the
22712 order of elaboration of the servers on which they depend:
22713
22714 @table @asis
22715 @item pragma Elaborate (unit)
22716 @findex Elaborate
22717 @cindex pragma Elaborate
22718 This pragma is placed in the context clause, after a @code{with} clause,
22719 and it requires that the body of the named unit be elaborated before
22720 the unit in which the pragma occurs. The idea is to use this pragma
22721 if the current unit calls at elaboration time, directly or indirectly,
22722 some subprogram in the named unit.
22723
22724 @item pragma Elaborate_All (unit)
22725 @findex Elaborate_All
22726 @cindex pragma Elaborate_All
22727 This is a stronger version of the Elaborate pragma. Consider the
22728 following example:
22729
22730 @smallexample
22731 Unit A @code{with}'s unit B and calls B.Func in elab code
22732 Unit B @code{with}'s unit C, and B.Func calls C.Func
22733 @end smallexample
22734
22735 @noindent
22736 Now if we put a pragma @code{Elaborate (B)}
22737 in unit @code{A}, this ensures that the
22738 body of @code{B} is elaborated before the call, but not the
22739 body of @code{C}, so
22740 the call to @code{C.Func} could still cause @code{Program_Error} to
22741 be raised.
22742
22743 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22744 not only that the body of the named unit be elaborated before the
22745 unit doing the @code{with}, but also the bodies of all units that the
22746 named unit uses, following @code{with} links transitively. For example,
22747 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22748 then it requires
22749 not only that the body of @code{B} be elaborated before @code{A},
22750 but also the
22751 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22752 @end table
22753
22754 @noindent
22755 We are now in a position to give a usage rule in Ada for avoiding
22756 elaboration problems, at least if dynamic dispatching and access to
22757 subprogram values are not used. We will handle these cases separately
22758 later.
22759
22760 The rule is simple. If a unit has elaboration code that can directly or
22761 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22762 a generic package in a @code{with}'ed unit,
22763 then if the @code{with}'ed unit does not have
22764 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22765 a pragma @code{Elaborate_All}
22766 for the @code{with}'ed unit. By following this rule a client is
22767 assured that calls can be made without risk of an exception.
22768
22769 For generic subprogram instantiations, the rule can be relaxed to
22770 require only a pragma @code{Elaborate} since elaborating the body
22771 of a subprogram cannot cause any transitive elaboration (we are
22772 not calling the subprogram in this case, just elaborating its
22773 declaration).
22774
22775 If this rule is not followed, then a program may be in one of four
22776 states:
22777
22778 @table @asis
22779 @item No order exists
22780 No order of elaboration exists which follows the rules, taking into
22781 account any @code{Elaborate}, @code{Elaborate_All},
22782 or @code{Elaborate_Body} pragmas. In
22783 this case, an Ada compiler must diagnose the situation at bind
22784 time, and refuse to build an executable program.
22785
22786 @item One or more orders exist, all incorrect
22787 One or more acceptable elaboration orders exist, and all of them
22788 generate an elaboration order problem. In this case, the binder
22789 can build an executable program, but @code{Program_Error} will be raised
22790 when the program is run.
22791
22792 @item Several orders exist, some right, some incorrect
22793 One or more acceptable elaboration orders exists, and some of them
22794 work, and some do not. The programmer has not controlled
22795 the order of elaboration, so the binder may or may not pick one of
22796 the correct orders, and the program may or may not raise an
22797 exception when it is run. This is the worst case, because it means
22798 that the program may fail when moved to another compiler, or even
22799 another version of the same compiler.
22800
22801 @item One or more orders exists, all correct
22802 One ore more acceptable elaboration orders exist, and all of them
22803 work. In this case the program runs successfully. This state of
22804 affairs can be guaranteed by following the rule we gave above, but
22805 may be true even if the rule is not followed.
22806 @end table
22807
22808 @noindent
22809 Note that one additional advantage of following our rules on the use
22810 of @code{Elaborate} and @code{Elaborate_All}
22811 is that the program continues to stay in the ideal (all orders OK) state
22812 even if maintenance
22813 changes some bodies of some units. Conversely, if a program that does
22814 not follow this rule happens to be safe at some point, this state of affairs
22815 may deteriorate silently as a result of maintenance changes.
22816
22817 You may have noticed that the above discussion did not mention
22818 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22819 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22820 code in the body makes calls to some other unit, so it is still necessary
22821 to use @code{Elaborate_All} on such units.
22822
22823 @node Controlling Elaboration in GNAT - Internal Calls
22824 @section Controlling Elaboration in GNAT - Internal Calls
22825
22826 @noindent
22827 In the case of internal calls, i.e., calls within a single package, the
22828 programmer has full control over the order of elaboration, and it is up
22829 to the programmer to elaborate declarations in an appropriate order. For
22830 example writing:
22831
22832 @smallexample @c ada
22833 @group
22834 @cartouche
22835 function One return Float;
22836
22837 Q : Float := One;
22838
22839 function One return Float is
22840 begin
22841      return 1.0;
22842 end One;
22843 @end cartouche
22844 @end group
22845 @end smallexample
22846
22847 @noindent
22848 will obviously raise @code{Program_Error} at run time, because function
22849 One will be called before its body is elaborated. In this case GNAT will
22850 generate a warning that the call will raise @code{Program_Error}:
22851
22852 @smallexample
22853 @group
22854 @cartouche
22855  1. procedure y is
22856  2.    function One return Float;
22857  3.
22858  4.    Q : Float := One;
22859                     |
22860     >>> warning: cannot call "One" before body is elaborated
22861     >>> warning: Program_Error will be raised at run time
22862
22863  5.
22864  6.    function One return Float is
22865  7.    begin
22866  8.         return 1.0;
22867  9.    end One;
22868 10.
22869 11. begin
22870 12.    null;
22871 13. end;
22872 @end cartouche
22873 @end group
22874 @end smallexample
22875
22876 @noindent
22877 Note that in this particular case, it is likely that the call is safe, because
22878 the function @code{One} does not access any global variables.
22879 Nevertheless in Ada, we do not want the validity of the check to depend on
22880 the contents of the body (think about the separate compilation case), so this
22881 is still wrong, as we discussed in the previous sections.
22882
22883 The error is easily corrected by rearranging the declarations so that the
22884 body of @code{One} appears before the declaration containing the call
22885 (note that in Ada 95 and Ada 2005,
22886 declarations can appear in any order, so there is no restriction that
22887 would prevent this reordering, and if we write:
22888
22889 @smallexample @c ada
22890 @group
22891 @cartouche
22892 function One return Float;
22893
22894 function One return Float is
22895 begin
22896      return 1.0;
22897 end One;
22898
22899 Q : Float := One;
22900 @end cartouche
22901 @end group
22902 @end smallexample
22903
22904 @noindent
22905 then all is well, no warning is generated, and no
22906 @code{Program_Error} exception
22907 will be raised.
22908 Things are more complicated when a chain of subprograms is executed:
22909
22910 @smallexample @c ada
22911 @group
22912 @cartouche
22913 function A return Integer;
22914 function B return Integer;
22915 function C return Integer;
22916
22917 function B return Integer is begin return A; end;
22918 function C return Integer is begin return B; end;
22919
22920 X : Integer := C;
22921
22922 function A return Integer is begin return 1; end;
22923 @end cartouche
22924 @end group
22925 @end smallexample
22926
22927 @noindent
22928 Now the call to @code{C}
22929 at elaboration time in the declaration of @code{X} is correct, because
22930 the body of @code{C} is already elaborated,
22931 and the call to @code{B} within the body of
22932 @code{C} is correct, but the call
22933 to @code{A} within the body of @code{B} is incorrect, because the body
22934 of @code{A} has not been elaborated, so @code{Program_Error}
22935 will be raised on the call to @code{A}.
22936 In this case GNAT will generate a
22937 warning that @code{Program_Error} may be
22938 raised at the point of the call. Let's look at the warning:
22939
22940 @smallexample
22941 @group
22942 @cartouche
22943  1. procedure x is
22944  2.    function A return Integer;
22945  3.    function B return Integer;
22946  4.    function C return Integer;
22947  5.
22948  6.    function B return Integer is begin return A; end;
22949                                                     |
22950     >>> warning: call to "A" before body is elaborated may
22951                  raise Program_Error
22952     >>> warning: "B" called at line 7
22953     >>> warning: "C" called at line 9
22954
22955  7.    function C return Integer is begin return B; end;
22956  8.
22957  9.    X : Integer := C;
22958 10.
22959 11.    function A return Integer is begin return 1; end;
22960 12.
22961 13. begin
22962 14.    null;
22963 15. end;
22964 @end cartouche
22965 @end group
22966 @end smallexample
22967
22968 @noindent
22969 Note that the message here says ``may raise'', instead of the direct case,
22970 where the message says ``will be raised''. That's because whether
22971 @code{A} is
22972 actually called depends in general on run-time flow of control.
22973 For example, if the body of @code{B} said
22974
22975 @smallexample @c ada
22976 @group
22977 @cartouche
22978 function B return Integer is
22979 begin
22980    if some-condition-depending-on-input-data then
22981       return A;
22982    else
22983       return 1;
22984    end if;
22985 end B;
22986 @end cartouche
22987 @end group
22988 @end smallexample
22989
22990 @noindent
22991 then we could not know until run time whether the incorrect call to A would
22992 actually occur, so @code{Program_Error} might
22993 or might not be raised. It is possible for a compiler to
22994 do a better job of analyzing bodies, to
22995 determine whether or not @code{Program_Error}
22996 might be raised, but it certainly
22997 couldn't do a perfect job (that would require solving the halting problem
22998 and is provably impossible), and because this is a warning anyway, it does
22999 not seem worth the effort to do the analysis. Cases in which it
23000 would be relevant are rare.
23001
23002 In practice, warnings of either of the forms given
23003 above will usually correspond to
23004 real errors, and should be examined carefully and eliminated.
23005 In the rare case where a warning is bogus, it can be suppressed by any of
23006 the following methods:
23007
23008 @itemize @bullet
23009 @item
23010 Compile with the @option{-gnatws} switch set
23011
23012 @item
23013 Suppress @code{Elaboration_Check} for the called subprogram
23014
23015 @item
23016 Use pragma @code{Warnings_Off} to turn warnings off for the call
23017 @end itemize
23018
23019 @noindent
23020 For the internal elaboration check case,
23021 GNAT by default generates the
23022 necessary run-time checks to ensure
23023 that @code{Program_Error} is raised if any
23024 call fails an elaboration check. Of course this can only happen if a
23025 warning has been issued as described above. The use of pragma
23026 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23027 some of these checks, meaning that it may be possible (but is not
23028 guaranteed) for a program to be able to call a subprogram whose body
23029 is not yet elaborated, without raising a @code{Program_Error} exception.
23030
23031 @node Controlling Elaboration in GNAT - External Calls
23032 @section Controlling Elaboration in GNAT - External Calls
23033
23034 @noindent
23035 The previous section discussed the case in which the execution of a
23036 particular thread of elaboration code occurred entirely within a
23037 single unit. This is the easy case to handle, because a programmer
23038 has direct and total control over the order of elaboration, and
23039 furthermore, checks need only be generated in cases which are rare
23040 and which the compiler can easily detect.
23041 The situation is more complex when separate compilation is taken into account.
23042 Consider the following:
23043
23044 @smallexample @c ada
23045 @cartouche
23046 @group
23047 package Math is
23048    function Sqrt (Arg : Float) return Float;
23049 end Math;
23050
23051 package body Math is
23052    function Sqrt (Arg : Float) return Float is
23053    begin
23054          @dots{}
23055    end Sqrt;
23056 end Math;
23057 @end group
23058 @group
23059 with Math;
23060 package Stuff is
23061    X : Float := Math.Sqrt (0.5);
23062 end Stuff;
23063
23064 with Stuff;
23065 procedure Main is
23066 begin
23067    @dots{}
23068 end Main;
23069 @end group
23070 @end cartouche
23071 @end smallexample
23072
23073 @noindent
23074 where @code{Main} is the main program. When this program is executed, the
23075 elaboration code must first be executed, and one of the jobs of the
23076 binder is to determine the order in which the units of a program are
23077 to be elaborated. In this case we have four units: the spec and body
23078 of @code{Math},
23079 the spec of @code{Stuff} and the body of @code{Main}).
23080 In what order should the four separate sections of elaboration code
23081 be executed?
23082
23083 There are some restrictions in the order of elaboration that the binder
23084 can choose. In particular, if unit U has a @code{with}
23085 for a package @code{X}, then you
23086 are assured that the spec of @code{X}
23087 is elaborated before U , but you are
23088 not assured that the body of @code{X}
23089 is elaborated before U.
23090 This means that in the above case, the binder is allowed to choose the
23091 order:
23092
23093 @smallexample
23094 spec of Math
23095 spec of Stuff
23096 body of Math
23097 body of Main
23098 @end smallexample
23099
23100 @noindent
23101 but that's not good, because now the call to @code{Math.Sqrt}
23102 that happens during
23103 the elaboration of the @code{Stuff}
23104 spec happens before the body of @code{Math.Sqrt} is
23105 elaborated, and hence causes @code{Program_Error} exception to be raised.
23106 At first glance, one might say that the binder is misbehaving, because
23107 obviously you want to elaborate the body of something you @code{with}
23108 first, but
23109 that is not a general rule that can be followed in all cases. Consider
23110
23111 @smallexample @c ada
23112 @group
23113 @cartouche
23114 package X is @dots{}
23115
23116 package Y is @dots{}
23117
23118 with X;
23119 package body Y is @dots{}
23120
23121 with Y;
23122 package body X is @dots{}
23123 @end cartouche
23124 @end group
23125 @end smallexample
23126
23127 @noindent
23128 This is a common arrangement, and, apart from the order of elaboration
23129 problems that might arise in connection with elaboration code, this works fine.
23130 A rule that says that you must first elaborate the body of anything you
23131 @code{with} cannot work in this case:
23132 the body of @code{X} @code{with}'s @code{Y},
23133 which means you would have to
23134 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23135 which means
23136 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23137 loop that cannot be broken.
23138
23139 It is true that the binder can in many cases guess an order of elaboration
23140 that is unlikely to cause a @code{Program_Error}
23141 exception to be raised, and it tries to do so (in the
23142 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23143 by default
23144 elaborate the body of @code{Math} right after its spec, so all will be well).
23145
23146 However, a program that blindly relies on the binder to be helpful can
23147 get into trouble, as we discussed in the previous sections, so
23148 GNAT
23149 provides a number of facilities for assisting the programmer in
23150 developing programs that are robust with respect to elaboration order.
23151
23152 @node Default Behavior in GNAT - Ensuring Safety
23153 @section Default Behavior in GNAT - Ensuring Safety
23154
23155 @noindent
23156 The default behavior in GNAT ensures elaboration safety. In its
23157 default mode GNAT implements the
23158 rule we previously described as the right approach. Let's restate it:
23159
23160 @itemize
23161 @item
23162 @emph{If a unit has elaboration code that can directly or indirectly make a
23163 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23164 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23165 does not have pragma @code{Pure} or
23166 @code{Preelaborate}, then the client should have an
23167 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23168
23169 @emph{In the case of instantiating a generic subprogram, it is always
23170 sufficient to have only an @code{Elaborate} pragma for the
23171 @code{with}'ed unit.}
23172 @end itemize
23173
23174 @noindent
23175 By following this rule a client is assured that calls and instantiations
23176 can be made without risk of an exception.
23177
23178 In this mode GNAT traces all calls that are potentially made from
23179 elaboration code, and puts in any missing implicit @code{Elaborate}
23180 and @code{Elaborate_All} pragmas.
23181 The advantage of this approach is that no elaboration problems
23182 are possible if the binder can find an elaboration order that is
23183 consistent with these implicit @code{Elaborate} and
23184 @code{Elaborate_All} pragmas. The
23185 disadvantage of this approach is that no such order may exist.
23186
23187 If the binder does not generate any diagnostics, then it means that it has
23188 found an elaboration order that is guaranteed to be safe. However, the binder
23189 may still be relying on implicitly generated @code{Elaborate} and
23190 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23191 guaranteed.
23192
23193 If it is important to guarantee portability, then the compilations should
23194 use the
23195 @option{-gnatwl}
23196 (warn on elaboration problems) switch. This will cause warning messages
23197 to be generated indicating the missing @code{Elaborate} and
23198 @code{Elaborate_All} pragmas.
23199 Consider the following source program:
23200
23201 @smallexample @c ada
23202 @group
23203 @cartouche
23204 with k;
23205 package j is
23206   m : integer := k.r;
23207 end;
23208 @end cartouche
23209 @end group
23210 @end smallexample
23211
23212 @noindent
23213 where it is clear that there
23214 should be a pragma @code{Elaborate_All}
23215 for unit @code{k}. An implicit pragma will be generated, and it is
23216 likely that the binder will be able to honor it. However, if you want
23217 to port this program to some other Ada compiler than GNAT.
23218 it is safer to include the pragma explicitly in the source. If this
23219 unit is compiled with the
23220 @option{-gnatwl}
23221 switch, then the compiler outputs a warning:
23222
23223 @smallexample
23224 @group
23225 @cartouche
23226 1. with k;
23227 2. package j is
23228 3.   m : integer := k.r;
23229                      |
23230    >>> warning: call to "r" may raise Program_Error
23231    >>> warning: missing pragma Elaborate_All for "k"
23232
23233 4. end;
23234 @end cartouche
23235 @end group
23236 @end smallexample
23237
23238 @noindent
23239 and these warnings can be used as a guide for supplying manually
23240 the missing pragmas. It is usually a bad idea to use this warning
23241 option during development. That's because it will warn you when
23242 you need to put in a pragma, but cannot warn you when it is time
23243 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23244 unnecessary dependencies and even false circularities.
23245
23246 This default mode is more restrictive than the Ada Reference
23247 Manual, and it is possible to construct programs which will compile
23248 using the dynamic model described there, but will run into a
23249 circularity using the safer static model we have described.
23250
23251 Of course any Ada compiler must be able to operate in a mode
23252 consistent with the requirements of the Ada Reference Manual,
23253 and in particular must have the capability of implementing the
23254 standard dynamic model of elaboration with run-time checks.
23255
23256 In GNAT, this standard mode can be achieved either by the use of
23257 the @option{-gnatE} switch on the compiler (@command{gcc} or
23258 @command{gnatmake}) command, or by the use of the configuration pragma:
23259
23260 @smallexample @c ada
23261 pragma Elaboration_Checks (DYNAMIC);
23262 @end smallexample
23263
23264 @noindent
23265 Either approach will cause the unit affected to be compiled using the
23266 standard dynamic run-time elaboration checks described in the Ada
23267 Reference Manual. The static model is generally preferable, since it
23268 is clearly safer to rely on compile and link time checks rather than
23269 run-time checks. However, in the case of legacy code, it may be
23270 difficult to meet the requirements of the static model. This
23271 issue is further discussed in
23272 @ref{What to Do If the Default Elaboration Behavior Fails}.
23273
23274 Note that the static model provides a strict subset of the allowed
23275 behavior and programs of the Ada Reference Manual, so if you do
23276 adhere to the static model and no circularities exist,
23277 then you are assured that your program will
23278 work using the dynamic model, providing that you remove any
23279 pragma Elaborate statements from the source.
23280
23281 @node Treatment of Pragma Elaborate
23282 @section Treatment of Pragma Elaborate
23283 @cindex Pragma Elaborate
23284
23285 @noindent
23286 The use of @code{pragma Elaborate}
23287 should generally be avoided in Ada 95 and Ada 2005 programs,
23288 since there is no guarantee that transitive calls
23289 will be properly handled. Indeed at one point, this pragma was placed
23290 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23291
23292 Now that's a bit restrictive. In practice, the case in which
23293 @code{pragma Elaborate} is useful is when the caller knows that there
23294 are no transitive calls, or that the called unit contains all necessary
23295 transitive @code{pragma Elaborate} statements, and legacy code often
23296 contains such uses.
23297
23298 Strictly speaking the static mode in GNAT should ignore such pragmas,
23299 since there is no assurance at compile time that the necessary safety
23300 conditions are met. In practice, this would cause GNAT to be incompatible
23301 with correctly written Ada 83 code that had all necessary
23302 @code{pragma Elaborate} statements in place. Consequently, we made the
23303 decision that GNAT in its default mode will believe that if it encounters
23304 a @code{pragma Elaborate} then the programmer knows what they are doing,
23305 and it will trust that no elaboration errors can occur.
23306
23307 The result of this decision is two-fold. First to be safe using the
23308 static mode, you should remove all @code{pragma Elaborate} statements.
23309 Second, when fixing circularities in existing code, you can selectively
23310 use @code{pragma Elaborate} statements to convince the static mode of
23311 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23312 statement.
23313
23314 When using the static mode with @option{-gnatwl}, any use of
23315 @code{pragma Elaborate} will generate a warning about possible
23316 problems.
23317
23318 @node Elaboration Issues for Library Tasks
23319 @section Elaboration Issues for Library Tasks
23320 @cindex Library tasks, elaboration issues
23321 @cindex Elaboration of library tasks
23322
23323 @noindent
23324 In this section we examine special elaboration issues that arise for
23325 programs that declare library level tasks.
23326
23327 Generally the model of execution of an Ada program is that all units are
23328 elaborated, and then execution of the program starts. However, the
23329 declaration of library tasks definitely does not fit this model. The
23330 reason for this is that library tasks start as soon as they are declared
23331 (more precisely, as soon as the statement part of the enclosing package
23332 body is reached), that is to say before elaboration
23333 of the program is complete. This means that if such a task calls a
23334 subprogram, or an entry in another task, the callee may or may not be
23335 elaborated yet, and in the standard
23336 Reference Manual model of dynamic elaboration checks, you can even
23337 get timing dependent Program_Error exceptions, since there can be
23338 a race between the elaboration code and the task code.
23339
23340 The static model of elaboration in GNAT seeks to avoid all such
23341 dynamic behavior, by being conservative, and the conservative
23342 approach in this particular case is to assume that all the code
23343 in a task body is potentially executed at elaboration time if
23344 a task is declared at the library level.
23345
23346 This can definitely result in unexpected circularities. Consider
23347 the following example
23348
23349 @smallexample @c ada
23350 package Decls is
23351   task Lib_Task is
23352      entry Start;
23353   end Lib_Task;
23354
23355   type My_Int is new Integer;
23356
23357   function Ident (M : My_Int) return My_Int;
23358 end Decls;
23359
23360 with Utils;
23361 package body Decls is
23362   task body Lib_Task is
23363   begin
23364      accept Start;
23365      Utils.Put_Val (2);
23366   end Lib_Task;
23367
23368   function Ident (M : My_Int) return My_Int is
23369   begin
23370      return M;
23371   end Ident;
23372 end Decls;
23373
23374 with Decls;
23375 package Utils is
23376   procedure Put_Val (Arg : Decls.My_Int);
23377 end Utils;
23378
23379 with Text_IO;
23380 package body Utils is
23381   procedure Put_Val (Arg : Decls.My_Int) is
23382   begin
23383      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23384   end Put_Val;
23385 end Utils;
23386
23387 with Decls;
23388 procedure Main is
23389 begin
23390    Decls.Lib_Task.Start;
23391 end;
23392 @end smallexample
23393
23394 @noindent
23395 If the above example is compiled in the default static elaboration
23396 mode, then a circularity occurs. The circularity comes from the call
23397 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23398 this call occurs in elaboration code, we need an implicit pragma
23399 @code{Elaborate_All} for @code{Utils}. This means that not only must
23400 the spec and body of @code{Utils} be elaborated before the body
23401 of @code{Decls}, but also the spec and body of any unit that is
23402 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23403 the body of @code{Decls}. This is the transitive implication of
23404 pragma @code{Elaborate_All} and it makes sense, because in general
23405 the body of @code{Put_Val} might have a call to something in a
23406 @code{with'ed} unit.
23407
23408 In this case, the body of Utils (actually its spec) @code{with's}
23409 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23410 must be elaborated before itself, in case there is a call from the
23411 body of @code{Utils}.
23412
23413 Here is the exact chain of events we are worrying about:
23414
23415 @enumerate
23416 @item
23417 In the body of @code{Decls} a call is made from within the body of a library
23418 task to a subprogram in the package @code{Utils}. Since this call may
23419 occur at elaboration time (given that the task is activated at elaboration
23420 time), we have to assume the worst, i.e., that the
23421 call does happen at elaboration time.
23422
23423 @item
23424 This means that the body and spec of @code{Util} must be elaborated before
23425 the body of @code{Decls} so that this call does not cause an access before
23426 elaboration.
23427
23428 @item
23429 Within the body of @code{Util}, specifically within the body of
23430 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23431 by this package.
23432
23433 @item
23434 One such @code{with}'ed package is package @code{Decls}, so there
23435 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23436 In fact there is such a call in this example, but we would have to
23437 assume that there was such a call even if it were not there, since
23438 we are not supposed to write the body of @code{Decls} knowing what
23439 is in the body of @code{Utils}; certainly in the case of the
23440 static elaboration model, the compiler does not know what is in
23441 other bodies and must assume the worst.
23442
23443 @item
23444 This means that the spec and body of @code{Decls} must also be
23445 elaborated before we elaborate the unit containing the call, but
23446 that unit is @code{Decls}! This means that the body of @code{Decls}
23447 must be elaborated before itself, and that's a circularity.
23448 @end enumerate
23449
23450 @noindent
23451 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23452 the body of @code{Decls} you will get a true Ada Reference Manual
23453 circularity that makes the program illegal.
23454
23455 In practice, we have found that problems with the static model of
23456 elaboration in existing code often arise from library tasks, so
23457 we must address this particular situation.
23458
23459 Note that if we compile and run the program above, using the dynamic model of
23460 elaboration (that is to say use the @option{-gnatE} switch),
23461 then it compiles, binds,
23462 links, and runs, printing the expected result of 2. Therefore in some sense
23463 the circularity here is only apparent, and we need to capture
23464 the properties of this program that  distinguish it from other library-level
23465 tasks that have real elaboration problems.
23466
23467 We have four possible answers to this question:
23468
23469 @itemize @bullet
23470
23471 @item
23472 Use the dynamic model of elaboration.
23473
23474 If we use the @option{-gnatE} switch, then as noted above, the program works.
23475 Why is this? If we examine the task body, it is apparent that the task cannot
23476 proceed past the
23477 @code{accept} statement until after elaboration has been completed, because
23478 the corresponding entry call comes from the main program, not earlier.
23479 This is why the dynamic model works here. But that's really giving
23480 up on a precise analysis, and we prefer to take this approach only if we cannot
23481 solve the
23482 problem in any other manner. So let us examine two ways to reorganize
23483 the program to avoid the potential elaboration problem.
23484
23485 @item
23486 Split library tasks into separate packages.
23487
23488 Write separate packages, so that library tasks are isolated from
23489 other declarations as much as possible. Let us look at a variation on
23490 the above program.
23491
23492 @smallexample @c ada
23493 package Decls1 is
23494   task Lib_Task is
23495      entry Start;
23496   end Lib_Task;
23497 end Decls1;
23498
23499 with Utils;
23500 package body Decls1 is
23501   task body Lib_Task is
23502   begin
23503      accept Start;
23504      Utils.Put_Val (2);
23505   end Lib_Task;
23506 end Decls1;
23507
23508 package Decls2 is
23509   type My_Int is new Integer;
23510   function Ident (M : My_Int) return My_Int;
23511 end Decls2;
23512
23513 with Utils;
23514 package body Decls2 is
23515   function Ident (M : My_Int) return My_Int is
23516   begin
23517      return M;
23518   end Ident;
23519 end Decls2;
23520
23521 with Decls2;
23522 package Utils is
23523   procedure Put_Val (Arg : Decls2.My_Int);
23524 end Utils;
23525
23526 with Text_IO;
23527 package body Utils is
23528   procedure Put_Val (Arg : Decls2.My_Int) is
23529   begin
23530      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23531   end Put_Val;
23532 end Utils;
23533
23534 with Decls1;
23535 procedure Main is
23536 begin
23537    Decls1.Lib_Task.Start;
23538 end;
23539 @end smallexample
23540
23541 @noindent
23542 All we have done is to split @code{Decls} into two packages, one
23543 containing the library task, and one containing everything else. Now
23544 there is no cycle, and the program compiles, binds, links and executes
23545 using the default static model of elaboration.
23546
23547 @item
23548 Declare separate task types.
23549
23550 A significant part of the problem arises because of the use of the
23551 single task declaration form. This means that the elaboration of
23552 the task type, and the elaboration of the task itself (i.e.@: the
23553 creation of the task) happen at the same time. A good rule
23554 of style in Ada is to always create explicit task types. By
23555 following the additional step of placing task objects in separate
23556 packages from the task type declaration, many elaboration problems
23557 are avoided. Here is another modified example of the example program:
23558
23559 @smallexample @c ada
23560 package Decls is
23561   task type Lib_Task_Type is
23562      entry Start;
23563   end Lib_Task_Type;
23564
23565   type My_Int is new Integer;
23566
23567   function Ident (M : My_Int) return My_Int;
23568 end Decls;
23569
23570 with Utils;
23571 package body Decls is
23572   task body Lib_Task_Type is
23573   begin
23574      accept Start;
23575      Utils.Put_Val (2);
23576   end Lib_Task_Type;
23577
23578   function Ident (M : My_Int) return My_Int is
23579   begin
23580      return M;
23581   end Ident;
23582 end Decls;
23583
23584 with Decls;
23585 package Utils is
23586   procedure Put_Val (Arg : Decls.My_Int);
23587 end Utils;
23588
23589 with Text_IO;
23590 package body Utils is
23591   procedure Put_Val (Arg : Decls.My_Int) is
23592   begin
23593      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23594   end Put_Val;
23595 end Utils;
23596
23597 with Decls;
23598 package Declst is
23599    Lib_Task : Decls.Lib_Task_Type;
23600 end Declst;
23601
23602 with Declst;
23603 procedure Main is
23604 begin
23605    Declst.Lib_Task.Start;
23606 end;
23607 @end smallexample
23608
23609 @noindent
23610 What we have done here is to replace the @code{task} declaration in
23611 package @code{Decls} with a @code{task type} declaration. Then we
23612 introduce a separate package @code{Declst} to contain the actual
23613 task object. This separates the elaboration issues for
23614 the @code{task type}
23615 declaration, which causes no trouble, from the elaboration issues
23616 of the task object, which is also unproblematic, since it is now independent
23617 of the elaboration of  @code{Utils}.
23618 This separation of concerns also corresponds to
23619 a generally sound engineering principle of separating declarations
23620 from instances. This version of the program also compiles, binds, links,
23621 and executes, generating the expected output.
23622
23623 @item
23624 Use No_Entry_Calls_In_Elaboration_Code restriction.
23625 @cindex No_Entry_Calls_In_Elaboration_Code
23626
23627 The previous two approaches described how a program can be restructured
23628 to avoid the special problems caused by library task bodies. in practice,
23629 however, such restructuring may be difficult to apply to existing legacy code,
23630 so we must consider solutions that do not require massive rewriting.
23631
23632 Let us consider more carefully why our original sample program works
23633 under the dynamic model of elaboration. The reason is that the code
23634 in the task body blocks immediately on the @code{accept}
23635 statement. Now of course there is nothing to prohibit elaboration
23636 code from making entry calls (for example from another library level task),
23637 so we cannot tell in isolation that
23638 the task will not execute the accept statement  during elaboration.
23639
23640 However, in practice it is very unusual to see elaboration code
23641 make any entry calls, and the pattern of tasks starting
23642 at elaboration time and then immediately blocking on @code{accept} or
23643 @code{select} statements is very common. What this means is that
23644 the compiler is being too pessimistic when it analyzes the
23645 whole package body as though it might be executed at elaboration
23646 time.
23647
23648 If we know that the elaboration code contains no entry calls, (a very safe
23649 assumption most of the time, that could almost be made the default
23650 behavior), then we can compile all units of the program under control
23651 of the following configuration pragma:
23652
23653 @smallexample
23654 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23655 @end smallexample
23656
23657 @noindent
23658 This pragma can be placed in the @file{gnat.adc} file in the usual
23659 manner. If we take our original unmodified program and compile it
23660 in the presence of a @file{gnat.adc} containing the above pragma,
23661 then once again, we can compile, bind, link, and execute, obtaining
23662 the expected result. In the presence of this pragma, the compiler does
23663 not trace calls in a task body, that appear after the first @code{accept}
23664 or @code{select} statement, and therefore does not report a potential
23665 circularity in the original program.
23666
23667 The compiler will check to the extent it can that the above
23668 restriction is not violated, but it is not always possible to do a
23669 complete check at compile time, so it is important to use this
23670 pragma only if the stated restriction is in fact met, that is to say
23671 no task receives an entry call before elaboration of all units is completed.
23672
23673 @end itemize
23674
23675 @node Mixing Elaboration Models
23676 @section Mixing Elaboration Models
23677 @noindent
23678 So far, we have assumed that the entire program is either compiled
23679 using the dynamic model or static model, ensuring consistency. It
23680 is possible to mix the two models, but rules have to be followed
23681 if this mixing is done to ensure that elaboration checks are not
23682 omitted.
23683
23684 The basic rule is that @emph{a unit compiled with the static model cannot
23685 be @code{with'ed} by a unit compiled with the dynamic model}. The
23686 reason for this is that in the static model, a unit assumes that
23687 its clients guarantee to use (the equivalent of) pragma
23688 @code{Elaborate_All} so that no elaboration checks are required
23689 in inner subprograms, and this assumption is violated if the
23690 client is compiled with dynamic checks.
23691
23692 The precise rule is as follows. A unit that is compiled with dynamic
23693 checks can only @code{with} a unit that meets at least one of the
23694 following criteria:
23695
23696 @itemize @bullet
23697
23698 @item
23699 The @code{with'ed} unit is itself compiled with dynamic elaboration
23700 checks (that is with the @option{-gnatE} switch.
23701
23702 @item
23703 The @code{with'ed} unit is an internal GNAT implementation unit from
23704 the System, Interfaces, Ada, or GNAT hierarchies.
23705
23706 @item
23707 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23708
23709 @item
23710 The @code{with'ing} unit (that is the client) has an explicit pragma
23711 @code{Elaborate_All} for the @code{with'ed} unit.
23712
23713 @end itemize
23714
23715 @noindent
23716 If this rule is violated, that is if a unit with dynamic elaboration
23717 checks @code{with's} a unit that does not meet one of the above four
23718 criteria, then the binder (@code{gnatbind}) will issue a warning
23719 similar to that in the following example:
23720
23721 @smallexample
23722 warning: "x.ads" has dynamic elaboration checks and with's
23723 warning:   "y.ads" which has static elaboration checks
23724 @end smallexample
23725
23726 @noindent
23727 These warnings indicate that the rule has been violated, and that as a result
23728 elaboration checks may be missed in the resulting executable file.
23729 This warning may be suppressed using the @option{-ws} binder switch
23730 in the usual manner.
23731
23732 One useful application of this mixing rule is in the case of a subsystem
23733 which does not itself @code{with} units from the remainder of the
23734 application. In this case, the entire subsystem can be compiled with
23735 dynamic checks to resolve a circularity in the subsystem, while
23736 allowing the main application that uses this subsystem to be compiled
23737 using the more reliable default static model.
23738
23739 @node What to Do If the Default Elaboration Behavior Fails
23740 @section What to Do If the Default Elaboration Behavior Fails
23741
23742 @noindent
23743 If the binder cannot find an acceptable order, it outputs detailed
23744 diagnostics. For example:
23745 @smallexample
23746 @group
23747 @iftex
23748 @leftskip=0cm
23749 @end iftex
23750 error: elaboration circularity detected
23751 info:   "proc (body)" must be elaborated before "pack (body)"
23752 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23753 info:     recompile "pack (body)" with -gnatwl
23754 info:                             for full details
23755 info:       "proc (body)"
23756 info:         is needed by its spec:
23757 info:       "proc (spec)"
23758 info:         which is withed by:
23759 info:       "pack (body)"
23760 info:  "pack (body)" must be elaborated before "proc (body)"
23761 info:     reason: pragma Elaborate in unit "proc (body)"
23762 @end group
23763
23764 @end smallexample
23765
23766 @noindent
23767 In this case we have a cycle that the binder cannot break. On the one
23768 hand, there is an explicit pragma Elaborate in @code{proc} for
23769 @code{pack}. This means that the body of @code{pack} must be elaborated
23770 before the body of @code{proc}. On the other hand, there is elaboration
23771 code in @code{pack} that calls a subprogram in @code{proc}. This means
23772 that for maximum safety, there should really be a pragma
23773 Elaborate_All in @code{pack} for @code{proc} which would require that
23774 the body of @code{proc} be elaborated before the body of
23775 @code{pack}. Clearly both requirements cannot be satisfied.
23776 Faced with a circularity of this kind, you have three different options.
23777
23778 @table @asis
23779 @item Fix the program
23780 The most desirable option from the point of view of long-term maintenance
23781 is to rearrange the program so that the elaboration problems are avoided.
23782 One useful technique is to place the elaboration code into separate
23783 child packages. Another is to move some of the initialization code to
23784 explicitly called subprograms, where the program controls the order
23785 of initialization explicitly. Although this is the most desirable option,
23786 it may be impractical and involve too much modification, especially in
23787 the case of complex legacy code.
23788
23789 @item Perform dynamic checks
23790 If the compilations are done using the
23791 @option{-gnatE}
23792 (dynamic elaboration check) switch, then GNAT behaves in a quite different
23793 manner. Dynamic checks are generated for all calls that could possibly result
23794 in raising an exception. With this switch, the compiler does not generate
23795 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
23796 exactly as specified in the @cite{Ada Reference Manual}.
23797 The binder will generate
23798 an executable program that may or may not raise @code{Program_Error}, and then
23799 it is the programmer's job to ensure that it does not raise an exception. Note
23800 that it is important to compile all units with the switch, it cannot be used
23801 selectively.
23802
23803 @item Suppress checks
23804 The drawback of dynamic checks is that they generate a
23805 significant overhead at run time, both in space and time. If you
23806 are absolutely sure that your program cannot raise any elaboration
23807 exceptions, and you still want to use the dynamic elaboration model,
23808 then you can use the configuration pragma
23809 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23810 example this pragma could be placed in the @file{gnat.adc} file.
23811
23812 @item Suppress checks selectively
23813 When you know that certain calls or instantiations in elaboration code cannot
23814 possibly lead to an elaboration error, and the binder nevertheless complains
23815 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
23816 elaboration circularities, it is possible to remove those warnings locally and
23817 obtain a program that will bind. Clearly this can be unsafe, and it is the
23818 responsibility of the programmer to make sure that the resulting program has no
23819 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
23820 used with different granularity to suppress warnings and break elaboration
23821 circularities:
23822
23823 @itemize @bullet
23824 @item
23825 Place the pragma that names the called subprogram in the declarative part
23826 that contains the call.
23827
23828 @item
23829 Place the pragma in the declarative part, without naming an entity. This
23830 disables warnings on all calls in the corresponding  declarative region.
23831
23832 @item
23833 Place the pragma in the package spec that declares the called subprogram,
23834 and name the subprogram. This disables warnings on all elaboration calls to
23835 that subprogram.
23836
23837 @item
23838 Place the pragma in the package spec that declares the called subprogram,
23839 without naming any entity. This disables warnings on all elaboration calls to
23840 all subprograms declared in this spec.
23841
23842 @item Use Pragma Elaborate
23843 As previously described in section @xref{Treatment of Pragma Elaborate},
23844 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23845 that no elaboration checks are required on calls to the designated unit.
23846 There may be cases in which the caller knows that no transitive calls
23847 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23848 case where @code{pragma Elaborate_All} would cause a circularity.
23849 @end itemize
23850
23851 @noindent
23852 These five cases are listed in order of decreasing safety, and therefore
23853 require increasing programmer care in their application. Consider the
23854 following program:
23855
23856 @smallexample @c adanocomment
23857 package Pack1 is
23858   function F1 return Integer;
23859   X1 : Integer;
23860 end Pack1;
23861
23862 package Pack2 is
23863   function F2 return Integer;
23864   function Pure (x : integer) return integer;
23865   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23866   --  pragma Suppress (Elaboration_Check);              -- (4)
23867 end Pack2;
23868
23869 with Pack2;
23870 package body Pack1 is
23871   function F1 return Integer is
23872   begin
23873     return 100;
23874   end F1;
23875   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23876 begin
23877   declare
23878     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23879     --  pragma Suppress(Elaboration_Check);             -- (2)
23880   begin
23881     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23882   end;
23883 end Pack1;
23884
23885 with Pack1;
23886 package body Pack2 is
23887   function F2 return Integer is
23888   begin
23889      return Pack1.F1;
23890   end F2;
23891   function Pure (x : integer) return integer is
23892   begin
23893      return x ** 3 - 3 * x;
23894   end;
23895 end Pack2;
23896
23897 with Pack1, Ada.Text_IO;
23898 procedure Proc3 is
23899 begin
23900   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23901 end Proc3;
23902 @end smallexample
23903 In the absence of any pragmas, an attempt to bind this program produces
23904 the following diagnostics:
23905 @smallexample
23906 @group
23907 @iftex
23908 @leftskip=.5cm
23909 @end iftex
23910 error: elaboration circularity detected
23911 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23912 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23913 info:       recompile "pack1 (body)" with -gnatwl for full details
23914 info:          "pack1 (body)"
23915 info:             must be elaborated along with its spec:
23916 info:          "pack1 (spec)"
23917 info:             which is withed by:
23918 info:          "pack2 (body)"
23919 info:             which must be elaborated along with its spec:
23920 info:          "pack2 (spec)"
23921 info:             which is withed by:
23922 info:          "pack1 (body)"
23923 @end group
23924 @end smallexample
23925 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23926 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23927 F2 is safe, even though F2 calls F1, because the call appears after the
23928 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23929 remove the warning on the call. It is also possible to use pragma (2)
23930 because there are no other potentially unsafe calls in the block.
23931
23932 @noindent
23933 The call to @code{Pure} is safe because this function does not depend on the
23934 state of @code{Pack2}. Therefore any call to this function is safe, and it
23935 is correct to place pragma (3) in the corresponding package spec.
23936
23937 @noindent
23938 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23939 warnings on all calls to functions declared therein. Note that this is not
23940 necessarily safe, and requires more detailed examination of the subprogram
23941 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23942 be already elaborated.
23943 @end table
23944
23945 @noindent
23946 It is hard to generalize on which of these four approaches should be
23947 taken. Obviously if it is possible to fix the program so that the default
23948 treatment works, this is preferable, but this may not always be practical.
23949 It is certainly simple enough to use
23950 @option{-gnatE}
23951 but the danger in this case is that, even if the GNAT binder
23952 finds a correct elaboration order, it may not always do so,
23953 and certainly a binder from another Ada compiler might not. A
23954 combination of testing and analysis (for which the warnings generated
23955 with the
23956 @option{-gnatwl}
23957 switch can be useful) must be used to ensure that the program is free
23958 of errors. One switch that is useful in this testing is the
23959 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23960 switch for
23961 @code{gnatbind}.
23962 Normally the binder tries to find an order that has the best chance
23963 of avoiding elaboration problems. However, if this switch is used, the binder
23964 plays a devil's advocate role, and tries to choose the order that
23965 has the best chance of failing. If your program works even with this
23966 switch, then it has a better chance of being error free, but this is still
23967 not a guarantee.
23968
23969 For an example of this approach in action, consider the C-tests (executable
23970 tests) from the ACVC suite. If these are compiled and run with the default
23971 treatment, then all but one of them succeed without generating any error
23972 diagnostics from the binder. However, there is one test that fails, and
23973 this is not surprising, because the whole point of this test is to ensure
23974 that the compiler can handle cases where it is impossible to determine
23975 a correct order statically, and it checks that an exception is indeed
23976 raised at run time.
23977
23978 This one test must be compiled and run using the
23979 @option{-gnatE}
23980 switch, and then it passes. Alternatively, the entire suite can
23981 be run using this switch. It is never wrong to run with the dynamic
23982 elaboration switch if your code is correct, and we assume that the
23983 C-tests are indeed correct (it is less efficient, but efficiency is
23984 not a factor in running the ACVC tests.)
23985
23986 @node Elaboration for Access-to-Subprogram Values
23987 @section Elaboration for Access-to-Subprogram Values
23988 @cindex Access-to-subprogram
23989
23990 @noindent
23991 Access-to-subprogram types (introduced in Ada 95) complicate
23992 the handling of elaboration. The trouble is that it becomes
23993 impossible to tell at compile time which procedure
23994 is being called. This means that it is not possible for the binder
23995 to analyze the elaboration requirements in this case.
23996
23997 If at the point at which the access value is created
23998 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23999 the body of the subprogram is
24000 known to have been elaborated, then the access value is safe, and its use
24001 does not require a check. This may be achieved by appropriate arrangement
24002 of the order of declarations if the subprogram is in the current unit,
24003 or, if the subprogram is in another unit, by using pragma
24004 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24005 on the referenced unit.
24006
24007 If the referenced body is not known to have been elaborated at the point
24008 the access value is created, then any use of the access value must do a
24009 dynamic check, and this dynamic check will fail and raise a
24010 @code{Program_Error} exception if the body has not been elaborated yet.
24011 GNAT will generate the necessary checks, and in addition, if the
24012 @option{-gnatwl}
24013 switch is set, will generate warnings that such checks are required.
24014
24015 The use of dynamic dispatching for tagged types similarly generates
24016 a requirement for dynamic checks, and premature calls to any primitive
24017 operation of a tagged type before the body of the operation has been
24018 elaborated, will result in the raising of @code{Program_Error}.
24019
24020 @node Summary of Procedures for Elaboration Control
24021 @section Summary of Procedures for Elaboration Control
24022 @cindex Elaboration control
24023
24024 @noindent
24025 First, compile your program with the default options, using none of
24026 the special elaboration control switches. If the binder successfully
24027 binds your program, then you can be confident that, apart from issues
24028 raised by the use of access-to-subprogram types and dynamic dispatching,
24029 the program is free of elaboration errors. If it is important that the
24030 program be portable, then use the
24031 @option{-gnatwl}
24032 switch to generate warnings about missing @code{Elaborate} or
24033 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24034
24035 If the program fails to bind using the default static elaboration
24036 handling, then you can fix the program to eliminate the binder
24037 message, or recompile the entire program with the
24038 @option{-gnatE} switch to generate dynamic elaboration checks,
24039 and, if you are sure there really are no elaboration problems,
24040 use a global pragma @code{Suppress (Elaboration_Check)}.
24041
24042 @node Other Elaboration Order Considerations
24043 @section Other Elaboration Order Considerations
24044 @noindent
24045 This section has been entirely concerned with the issue of finding a valid
24046 elaboration order, as defined by the Ada Reference Manual. In a case
24047 where several elaboration orders are valid, the task is to find one
24048 of the possible valid elaboration orders (and the static model in GNAT
24049 will ensure that this is achieved).
24050
24051 The purpose of the elaboration rules in the Ada Reference Manual is to
24052 make sure that no entity is accessed before it has been elaborated. For
24053 a subprogram, this means that the spec and body must have been elaborated
24054 before the subprogram is called. For an object, this means that the object
24055 must have been elaborated before its value is read or written. A violation
24056 of either of these two requirements is an access before elaboration order,
24057 and this section has been all about avoiding such errors.
24058
24059 In the case where more than one order of elaboration is possible, in the
24060 sense that access before elaboration errors are avoided, then any one of
24061 the orders is ``correct'' in the sense that it meets the requirements of
24062 the Ada Reference Manual, and no such error occurs.
24063
24064 However, it may be the case for a given program, that there are
24065 constraints on the order of elaboration that come not from consideration
24066 of avoiding elaboration errors, but rather from extra-lingual logic
24067 requirements. Consider this example:
24068
24069 @smallexample @c ada
24070 with Init_Constants;
24071 package Constants is
24072    X : Integer := 0;
24073    Y : Integer := 0;
24074 end Constants;
24075
24076 package Init_Constants is
24077    procedure P; -- require a body
24078 end Init_Constants;
24079
24080 with Constants;
24081 package body Init_Constants is
24082    procedure P is begin null; end;
24083 begin
24084    Constants.X := 3;
24085    Constants.Y := 4;
24086 end Init_Constants;
24087
24088 with Constants;
24089 package Calc is
24090    Z : Integer := Constants.X + Constants.Y;
24091 end Calc;
24092
24093 with Calc;
24094 with Text_IO; use Text_IO;
24095 procedure Main is
24096 begin
24097    Put_Line (Calc.Z'Img);
24098 end Main;
24099 @end smallexample
24100
24101 @noindent
24102 In this example, there is more than one valid order of elaboration. For
24103 example both the following are correct orders:
24104
24105 @smallexample
24106 Init_Constants spec
24107 Constants spec
24108 Calc spec
24109 Init_Constants body
24110 Main body
24111
24112   and
24113
24114 Init_Constants spec
24115 Init_Constants body
24116 Constants spec
24117 Calc spec
24118 Main body
24119 @end smallexample
24120
24121 @noindent
24122 There is no language rule to prefer one or the other, both are correct
24123 from an order of elaboration point of view. But the programmatic effects
24124 of the two orders are very different. In the first, the elaboration routine
24125 of @code{Calc} initializes @code{Z} to zero, and then the main program
24126 runs with this value of zero. But in the second order, the elaboration
24127 routine of @code{Calc} runs after the body of Init_Constants has set
24128 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24129 runs.
24130
24131 One could perhaps by applying pretty clever non-artificial intelligence
24132 to the situation guess that it is more likely that the second order of
24133 elaboration is the one desired, but there is no formal linguistic reason
24134 to prefer one over the other. In fact in this particular case, GNAT will
24135 prefer the second order, because of the rule that bodies are elaborated
24136 as soon as possible, but it's just luck that this is what was wanted
24137 (if indeed the second order was preferred).
24138
24139 If the program cares about the order of elaboration routines in a case like
24140 this, it is important to specify the order required. In this particular
24141 case, that could have been achieved by adding to the spec of Calc:
24142
24143 @smallexample @c ada
24144 pragma Elaborate_All (Constants);
24145 @end smallexample
24146
24147 @noindent
24148 which requires that the body (if any) and spec of @code{Constants},
24149 as well as the body and spec of any unit @code{with}'ed by
24150 @code{Constants} be elaborated before @code{Calc} is elaborated.
24151
24152 Clearly no automatic method can always guess which alternative you require,
24153 and if you are working with legacy code that had constraints of this kind
24154 which were not properly specified by adding @code{Elaborate} or
24155 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24156 compilers can choose different orders.
24157
24158 However, GNAT does attempt to diagnose the common situation where there
24159 are uninitialized variables in the visible part of a package spec, and the
24160 corresponding package body has an elaboration block that directly or
24161 indirectly initialized one or more of these variables. This is the situation
24162 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24163 a warning that suggests this addition if it detects this situation.
24164
24165 The @code{gnatbind}
24166 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24167 out problems. This switch causes bodies to be elaborated as late as possible
24168 instead of as early as possible. In the example above, it would have forced
24169 the choice of the first elaboration order. If you get different results
24170 when using this switch, and particularly if one set of results is right,
24171 and one is wrong as far as you are concerned, it shows that you have some
24172 missing @code{Elaborate} pragmas. For the example above, we have the
24173 following output:
24174
24175 @smallexample
24176 gnatmake -f -q main
24177 main
24178  7
24179 gnatmake -f -q main -bargs -p
24180 main
24181  0
24182 @end smallexample
24183
24184 @noindent
24185 It is of course quite unlikely that both these results are correct, so
24186 it is up to you in a case like this to investigate the source of the
24187 difference, by looking at the two elaboration orders that are chosen,
24188 and figuring out which is correct, and then adding the necessary
24189 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24190
24191
24192
24193 @c *******************************
24194 @node Conditional Compilation
24195 @appendix Conditional Compilation
24196 @c *******************************
24197 @cindex Conditional compilation
24198
24199 @noindent
24200 It is often necessary to arrange for a single source program
24201 to serve multiple purposes, where it is compiled in different
24202 ways to achieve these different goals. Some examples of the
24203 need for this feature are
24204
24205 @itemize @bullet
24206 @item  Adapting a program to a different hardware environment
24207 @item  Adapting a program to a different target architecture
24208 @item  Turning debugging features on and off
24209 @item  Arranging for a program to compile with different compilers
24210 @end itemize
24211
24212 @noindent
24213 In C, or C++, the typical approach would be to use the preprocessor
24214 that is defined as part of the language. The Ada language does not
24215 contain such a feature. This is not an oversight, but rather a very
24216 deliberate design decision, based on the experience that overuse of
24217 the preprocessing features in C and C++ can result in programs that
24218 are extremely difficult to maintain. For example, if we have ten
24219 switches that can be on or off, this means that there are a thousand
24220 separate programs, any one of which might not even be syntactically
24221 correct, and even if syntactically correct, the resulting program
24222 might not work correctly. Testing all combinations can quickly become
24223 impossible.
24224
24225 Nevertheless, the need to tailor programs certainly exists, and in
24226 this Appendix we will discuss how this can
24227 be achieved using Ada in general, and GNAT in particular.
24228
24229 @menu
24230 * Use of Boolean Constants::
24231 * Debugging - A Special Case::
24232 * Conditionalizing Declarations::
24233 * Use of Alternative Implementations::
24234 * Preprocessing::
24235 @end menu
24236
24237 @node Use of Boolean Constants
24238 @section Use of Boolean Constants
24239
24240 @noindent
24241 In the case where the difference is simply which code
24242 sequence is executed, the cleanest solution is to use Boolean
24243 constants to control which code is executed.
24244
24245 @smallexample @c ada
24246 @group
24247 FP_Initialize_Required : constant Boolean := True;
24248 @dots{}
24249 if FP_Initialize_Required then
24250 @dots{}
24251 end if;
24252 @end group
24253 @end smallexample
24254
24255 @noindent
24256 Not only will the code inside the @code{if} statement not be executed if
24257 the constant Boolean is @code{False}, but it will also be completely
24258 deleted from the program.
24259 However, the code is only deleted after the @code{if} statement
24260 has been checked for syntactic and semantic correctness.
24261 (In contrast, with preprocessors the code is deleted before the
24262 compiler ever gets to see it, so it is not checked until the switch
24263 is turned on.)
24264 @cindex Preprocessors (contrasted with conditional compilation)
24265
24266 Typically the Boolean constants will be in a separate package,
24267 something like:
24268
24269 @smallexample @c ada
24270 @group
24271 package Config is
24272    FP_Initialize_Required : constant Boolean := True;
24273    Reset_Available        : constant Boolean := False;
24274    @dots{}
24275 end Config;
24276 @end group
24277 @end smallexample
24278
24279 @noindent
24280 The @code{Config} package exists in multiple forms for the various targets,
24281 with an appropriate script selecting the version of @code{Config} needed.
24282 Then any other unit requiring conditional compilation can do a @code{with}
24283 of @code{Config} to make the constants visible.
24284
24285
24286 @node Debugging - A Special Case
24287 @section Debugging - A Special Case
24288
24289 @noindent
24290 A common use of conditional code is to execute statements (for example
24291 dynamic checks, or output of intermediate results) under control of a
24292 debug switch, so that the debugging behavior can be turned on and off.
24293 This can be done using a Boolean constant to control whether the code
24294 is active:
24295
24296 @smallexample @c ada
24297 @group
24298 if Debugging then
24299    Put_Line ("got to the first stage!");
24300 end if;
24301 @end group
24302 @end smallexample
24303
24304 @noindent
24305 or
24306
24307 @smallexample @c ada
24308 @group
24309 if Debugging and then Temperature > 999.0 then
24310    raise Temperature_Crazy;
24311 end if;
24312 @end group
24313 @end smallexample
24314
24315 @noindent
24316 Since this is a common case, there are special features to deal with
24317 this in a convenient manner. For the case of tests, Ada 2005 has added
24318 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24319 @cindex pragma @code{Assert}
24320 on the @code{Assert} pragma that has always been available in GNAT, so this
24321 feature may be used with GNAT even if you are not using Ada 2005 features.
24322 The use of pragma @code{Assert} is described in
24323 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24324 example, the last test could be written:
24325
24326 @smallexample @c ada
24327 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24328 @end smallexample
24329
24330 @noindent
24331 or simply
24332
24333 @smallexample @c ada
24334 pragma Assert (Temperature <= 999.0);
24335 @end smallexample
24336
24337 @noindent
24338 In both cases, if assertions are active and the temperature is excessive,
24339 the exception @code{Assert_Failure} will be raised, with the given string in
24340 the first case or a string indicating the location of the pragma in the second
24341 case used as the exception message.
24342
24343 You can turn assertions on and off by using the @code{Assertion_Policy}
24344 pragma.
24345 @cindex pragma @code{Assertion_Policy}
24346 This is an Ada 2005 pragma which is implemented in all modes by
24347 GNAT, but only in the latest versions of GNAT which include Ada 2005
24348 capability. Alternatively, you can use the @option{-gnata} switch
24349 @cindex @option{-gnata} switch
24350 to enable assertions from the command line (this is recognized by all versions
24351 of GNAT).
24352
24353 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24354 @code{Debug} can be used:
24355 @cindex pragma @code{Debug}
24356
24357 @smallexample @c ada
24358 pragma Debug (Put_Line ("got to the first stage!"));
24359 @end smallexample
24360
24361 @noindent
24362 If debug pragmas are enabled, the argument, which must be of the form of
24363 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24364 Only one call can be present, but of course a special debugging procedure
24365 containing any code you like can be included in the program and then
24366 called in a pragma @code{Debug} argument as needed.
24367
24368 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24369 construct is that pragma @code{Debug} can appear in declarative contexts,
24370 such as at the very beginning of a procedure, before local declarations have
24371 been elaborated.
24372
24373 Debug pragmas are enabled using either the @option{-gnata} switch that also
24374 controls assertions, or with a separate Debug_Policy pragma.
24375 @cindex pragma @code{Debug_Policy}
24376 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24377 in Ada 95 and Ada 83 programs as well), and is analogous to
24378 pragma @code{Assertion_Policy} to control assertions.
24379
24380 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24381 and thus they can appear in @file{gnat.adc} if you are not using a
24382 project file, or in the file designated to contain configuration pragmas
24383 in a project file.
24384 They then apply to all subsequent compilations. In practice the use of
24385 the @option{-gnata} switch is often the most convenient method of controlling
24386 the status of these pragmas.
24387
24388 Note that a pragma is not a statement, so in contexts where a statement
24389 sequence is required, you can't just write a pragma on its own. You have
24390 to add a @code{null} statement.
24391
24392 @smallexample @c ada
24393 @group
24394 if @dots{} then
24395    @dots{} -- some statements
24396 else
24397    pragma Assert (Num_Cases < 10);
24398    null;
24399 end if;
24400 @end group
24401 @end smallexample
24402
24403
24404 @node Conditionalizing Declarations
24405 @section Conditionalizing Declarations
24406
24407 @noindent
24408 In some cases, it may be necessary to conditionalize declarations to meet
24409 different requirements. For example we might want a bit string whose length
24410 is set to meet some hardware message requirement.
24411
24412 In some cases, it may be possible to do this using declare blocks controlled
24413 by conditional constants:
24414
24415 @smallexample @c ada
24416 @group
24417 if Small_Machine then
24418    declare
24419       X : Bit_String (1 .. 10);
24420    begin
24421       @dots{}
24422    end;
24423 else
24424    declare
24425       X : Large_Bit_String (1 .. 1000);
24426    begin
24427       @dots{}
24428    end;
24429 end if;
24430 @end group
24431 @end smallexample
24432
24433 @noindent
24434 Note that in this approach, both declarations are analyzed by the
24435 compiler so this can only be used where both declarations are legal,
24436 even though one of them will not be used.
24437
24438 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24439 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24440 that are parameterized by these constants. For example
24441
24442 @smallexample @c ada
24443 @group
24444 for Rec use
24445   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24446 end record;
24447 @end group
24448 @end smallexample
24449
24450 @noindent
24451 If @code{Bits_Per_Word} is set to 32, this generates either
24452
24453 @smallexample @c ada
24454 @group
24455 for Rec use
24456   Field1 at 0 range 0 .. 32;
24457 end record;
24458 @end group
24459 @end smallexample
24460
24461 @noindent
24462 for the big endian case, or
24463
24464 @smallexample @c ada
24465 @group
24466 for Rec use record
24467   Field1 at 0 range 10 .. 32;
24468 end record;
24469 @end group
24470 @end smallexample
24471
24472 @noindent
24473 for the little endian case. Since a powerful subset of Ada expression
24474 notation is usable for creating static constants, clever use of this
24475 feature can often solve quite difficult problems in conditionalizing
24476 compilation (note incidentally that in Ada 95, the little endian
24477 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24478 need to define this one yourself).
24479
24480
24481 @node Use of Alternative Implementations
24482 @section Use of Alternative Implementations
24483
24484 @noindent
24485 In some cases, none of the approaches described above are adequate. This
24486 can occur for example if the set of declarations required is radically
24487 different for two different configurations.
24488
24489 In this situation, the official Ada way of dealing with conditionalizing
24490 such code is to write separate units for the different cases. As long as
24491 this does not result in excessive duplication of code, this can be done
24492 without creating maintenance problems. The approach is to share common
24493 code as far as possible, and then isolate the code and declarations
24494 that are different. Subunits are often a convenient method for breaking
24495 out a piece of a unit that is to be conditionalized, with separate files
24496 for different versions of the subunit for different targets, where the
24497 build script selects the right one to give to the compiler.
24498 @cindex Subunits (and conditional compilation)
24499
24500 As an example, consider a situation where a new feature in Ada 2005
24501 allows something to be done in a really nice way. But your code must be able
24502 to compile with an Ada 95 compiler. Conceptually you want to say:
24503
24504 @smallexample @c ada
24505 @group
24506 if Ada_2005 then
24507    @dots{} neat Ada 2005 code
24508 else
24509    @dots{} not quite as neat Ada 95 code
24510 end if;
24511 @end group
24512 @end smallexample
24513
24514 @noindent
24515 where @code{Ada_2005} is a Boolean constant.
24516
24517 But this won't work when @code{Ada_2005} is set to @code{False},
24518 since the @code{then} clause will be illegal for an Ada 95 compiler.
24519 (Recall that although such unreachable code would eventually be deleted
24520 by the compiler, it still needs to be legal.  If it uses features
24521 introduced in Ada 2005, it will be illegal in Ada 95.)
24522
24523 So instead we write
24524
24525 @smallexample @c ada
24526 procedure Insert is separate;
24527 @end smallexample
24528
24529 @noindent
24530 Then we have two files for the subunit @code{Insert}, with the two sets of
24531 code.
24532 If the package containing this is called @code{File_Queries}, then we might
24533 have two files
24534
24535 @itemize @bullet
24536 @item    @file{file_queries-insert-2005.adb}
24537 @item    @file{file_queries-insert-95.adb}
24538 @end itemize
24539
24540 @noindent
24541 and the build script renames the appropriate file to
24542
24543 @smallexample
24544 file_queries-insert.adb
24545 @end smallexample
24546
24547 @noindent
24548 and then carries out the compilation.
24549
24550 This can also be done with project files' naming schemes. For example:
24551
24552 @smallexample @c project
24553 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24554 @end smallexample
24555
24556 @noindent
24557 Note also that with project files it is desirable to use a different extension
24558 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24559 conflict may arise through another commonly used feature: to declare as part
24560 of the project a set of directories containing all the sources obeying the
24561 default naming scheme.
24562
24563 The use of alternative units is certainly feasible in all situations,
24564 and for example the Ada part of the GNAT run-time is conditionalized
24565 based on the target architecture using this approach. As a specific example,
24566 consider the implementation of the AST feature in VMS. There is one
24567 spec:
24568
24569 @smallexample
24570 s-asthan.ads
24571 @end smallexample
24572
24573 @noindent
24574 which is the same for all architectures, and three bodies:
24575
24576 @table @file
24577 @item    s-asthan.adb
24578 used for all non-VMS operating systems
24579 @item    s-asthan-vms-alpha.adb
24580 used for VMS on the Alpha
24581 @item    s-asthan-vms-ia64.adb
24582 used for VMS on the ia64
24583 @end table
24584
24585 @noindent
24586 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
24587 this operating system feature is not available, and the two remaining
24588 versions interface with the corresponding versions of VMS to provide
24589 VMS-compatible AST handling. The GNAT build script knows the architecture
24590 and operating system, and automatically selects the right version,
24591 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
24592
24593 Another style for arranging alternative implementations is through Ada's
24594 access-to-subprogram facility.
24595 In case some functionality is to be conditionally included,
24596 you can declare an access-to-procedure variable @code{Ref} that is initialized
24597 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
24598 when appropriate.
24599 In some library package, set @code{Ref} to @code{Proc'Access} for some
24600 procedure @code{Proc} that performs the relevant processing.
24601 The initialization only occurs if the library package is included in the
24602 program.
24603 The same idea can also be implemented using tagged types and dispatching
24604 calls.
24605
24606
24607 @node Preprocessing
24608 @section Preprocessing
24609 @cindex Preprocessing
24610
24611 @noindent
24612 Although it is quite possible to conditionalize code without the use of
24613 C-style preprocessing, as described earlier in this section, it is
24614 nevertheless convenient in some cases to use the C approach. Moreover,
24615 older Ada compilers have often provided some preprocessing capability,
24616 so legacy code may depend on this approach, even though it is not
24617 standard.
24618
24619 To accommodate such use, GNAT provides a preprocessor (modeled to a large
24620 extent on the various preprocessors that have been used
24621 with legacy code on other compilers, to enable easier transition).
24622
24623 The preprocessor may be used in two separate modes. It can be used quite
24624 separately from the compiler, to generate a separate output source file
24625 that is then fed to the compiler as a separate step. This is the
24626 @code{gnatprep} utility, whose use is fully described in
24627 @ref{Preprocessing Using gnatprep}.
24628 @cindex @code{gnatprep}
24629
24630 The preprocessing language allows such constructs as
24631
24632 @smallexample
24633 @group
24634 #if DEBUG or PRIORITY > 4 then
24635    bunch of declarations
24636 #else
24637    completely different bunch of declarations
24638 #end if;
24639 @end group
24640 @end smallexample
24641
24642 @noindent
24643 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
24644 defined either on the command line or in a separate file.
24645
24646 The other way of running the preprocessor is even closer to the C style and
24647 often more convenient. In this approach the preprocessing is integrated into
24648 the compilation process. The compiler is fed the preprocessor input which
24649 includes @code{#if} lines etc, and then the compiler carries out the
24650 preprocessing internally and processes the resulting output.
24651 For more details on this approach, see @ref{Integrated Preprocessing}.
24652
24653
24654 @c *******************************
24655 @node Inline Assembler
24656 @appendix Inline Assembler
24657 @c *******************************
24658
24659 @noindent
24660 If you need to write low-level software that interacts directly
24661 with the hardware, Ada provides two ways to incorporate assembly
24662 language code into your program.  First, you can import and invoke
24663 external routines written in assembly language, an Ada feature fully
24664 supported by GNAT@.  However, for small sections of code it may be simpler
24665 or more efficient to include assembly language statements directly
24666 in your Ada source program, using the facilities of the implementation-defined
24667 package @code{System.Machine_Code}, which incorporates the gcc
24668 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24669 including the following:
24670
24671 @itemize @bullet
24672 @item No need to use non-Ada tools
24673 @item Consistent interface over different targets
24674 @item Automatic usage of the proper calling conventions
24675 @item Access to Ada constants and variables
24676 @item Definition of intrinsic routines
24677 @item Possibility of inlining a subprogram comprising assembler code
24678 @item Code optimizer can take Inline Assembler code into account
24679 @end itemize
24680
24681 This chapter presents a series of examples to show you how to use
24682 the Inline Assembler.  Although it focuses on the Intel x86,
24683 the general approach applies also to other processors.
24684 It is assumed that you are familiar with Ada
24685 and with assembly language programming.
24686
24687 @menu
24688 * Basic Assembler Syntax::
24689 * A Simple Example of Inline Assembler::
24690 * Output Variables in Inline Assembler::
24691 * Input Variables in Inline Assembler::
24692 * Inlining Inline Assembler Code::
24693 * Other Asm Functionality::
24694 @end menu
24695
24696 @c ---------------------------------------------------------------------------
24697 @node Basic Assembler Syntax
24698 @section Basic Assembler Syntax
24699
24700 @noindent
24701 The assembler used by GNAT and gcc is based not on the Intel assembly
24702 language, but rather on a language that descends from the AT&T Unix
24703 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24704 The following table summarizes the main features of @emph{as} syntax
24705 and points out the differences from the Intel conventions.
24706 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24707 pre-processor) documentation for further information.
24708
24709 @table @asis
24710 @item Register names
24711 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24712 @*
24713 Intel: No extra punctuation; for example @code{eax}
24714
24715 @item Immediate operand
24716 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24717 @*
24718 Intel: No extra punctuation; for example @code{4}
24719
24720 @item Address
24721 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24722 @*
24723 Intel: No extra punctuation; for example @code{loc}
24724
24725 @item Memory contents
24726 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24727 @*
24728 Intel: Square brackets; for example @code{[loc]}
24729
24730 @item Register contents
24731 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24732 @*
24733 Intel: Square brackets; for example @code{[eax]}
24734
24735 @item Hexadecimal numbers
24736 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24737 @*
24738 Intel: Trailing ``h''; for example @code{A0h}
24739
24740 @item Operand size
24741 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24742 a 16-bit word
24743 @*
24744 Intel: Implicit, deduced by assembler; for example @code{mov}
24745
24746 @item Instruction repetition
24747 gcc / @emph{as}: Split into two lines; for example
24748 @*
24749 @code{rep}
24750 @*
24751 @code{stosl}
24752 @*
24753 Intel: Keep on one line; for example @code{rep stosl}
24754
24755 @item Order of operands
24756 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24757 @*
24758 Intel: Destination first; for example @code{mov eax, 4}
24759 @end table
24760
24761 @c ---------------------------------------------------------------------------
24762 @node A Simple Example of Inline Assembler
24763 @section A Simple Example of Inline Assembler
24764
24765 @noindent
24766 The following example will generate a single assembly language statement,
24767 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24768 the example will be useful in illustrating the basics of
24769 the Inline Assembler facility.
24770
24771 @smallexample @c ada
24772 @group
24773 with System.Machine_Code; use System.Machine_Code;
24774 procedure Nothing is
24775 begin
24776    Asm ("nop");
24777 end Nothing;
24778 @end group
24779 @end smallexample
24780
24781 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24782 here it takes one parameter, a @emph{template string} that must be a static
24783 expression and that will form the generated instruction.
24784 @code{Asm} may be regarded as a compile-time procedure that parses
24785 the template string and additional parameters (none here),
24786 from which it generates a sequence of assembly language instructions.
24787
24788 The examples in this chapter will illustrate several of the forms
24789 for invoking @code{Asm}; a complete specification of the syntax
24790 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
24791 Manual}.
24792
24793 Under the standard GNAT conventions, the @code{Nothing} procedure
24794 should be in a file named @file{nothing.adb}.
24795 You can build the executable in the usual way:
24796 @smallexample
24797 gnatmake nothing
24798 @end smallexample
24799 However, the interesting aspect of this example is not its run-time behavior
24800 but rather the generated assembly code.
24801 To see this output, invoke the compiler as follows:
24802 @smallexample
24803    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24804 @end smallexample
24805 where the options are:
24806
24807 @table @code
24808 @item -c
24809 compile only (no bind or link)
24810 @item -S
24811 generate assembler listing
24812 @item -fomit-frame-pointer
24813 do not set up separate stack frames
24814 @item -gnatp
24815 do not add runtime checks
24816 @end table
24817
24818 This gives a human-readable assembler version of the code. The resulting
24819 file will have the same name as the Ada source file, but with a @code{.s}
24820 extension. In our example, the file @file{nothing.s} has the following
24821 contents:
24822
24823 @smallexample
24824 @group
24825 .file "nothing.adb"
24826 gcc2_compiled.:
24827 ___gnu_compiled_ada:
24828 .text
24829    .align 4
24830 .globl __ada_nothing
24831 __ada_nothing:
24832 #APP
24833    nop
24834 #NO_APP
24835    jmp L1
24836    .align 2,0x90
24837 L1:
24838    ret
24839 @end group
24840 @end smallexample
24841
24842 The assembly code you included is clearly indicated by
24843 the compiler, between the @code{#APP} and @code{#NO_APP}
24844 delimiters. The character before the 'APP' and 'NOAPP'
24845 can differ on different targets. For example, GNU/Linux uses '#APP' while
24846 on NT you will see '/APP'.
24847
24848 If you make a mistake in your assembler code (such as using the
24849 wrong size modifier, or using a wrong operand for the instruction) GNAT
24850 will report this error in a temporary file, which will be deleted when
24851 the compilation is finished.  Generating an assembler file will help
24852 in such cases, since you can assemble this file separately using the
24853 @emph{as} assembler that comes with gcc.
24854
24855 Assembling the file using the command
24856
24857 @smallexample
24858 as @file{nothing.s}
24859 @end smallexample
24860 @noindent
24861 will give you error messages whose lines correspond to the assembler
24862 input file, so you can easily find and correct any mistakes you made.
24863 If there are no errors, @emph{as} will generate an object file
24864 @file{nothing.out}.
24865
24866 @c ---------------------------------------------------------------------------
24867 @node Output Variables in Inline Assembler
24868 @section Output Variables in Inline Assembler
24869
24870 @noindent
24871 The examples in this section, showing how to access the processor flags,
24872 illustrate how to specify the destination operands for assembly language
24873 statements.
24874
24875 @smallexample @c ada
24876 @group
24877 with Interfaces; use Interfaces;
24878 with Ada.Text_IO; use Ada.Text_IO;
24879 with System.Machine_Code; use System.Machine_Code;
24880 procedure Get_Flags is
24881    Flags : Unsigned_32;
24882    use ASCII;
24883 begin
24884    Asm ("pushfl"          & LF & HT & -- push flags on stack
24885         "popl %%eax"      & LF & HT & -- load eax with flags
24886         "movl %%eax, %0",             -- store flags in variable
24887         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24888    Put_Line ("Flags register:" & Flags'Img);
24889 end Get_Flags;
24890 @end group
24891 @end smallexample
24892
24893 In order to have a nicely aligned assembly listing, we have separated
24894 multiple assembler statements in the Asm template string with linefeed
24895 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24896 The resulting section of the assembly output file is:
24897
24898 @smallexample
24899 @group
24900 #APP
24901    pushfl
24902    popl %eax
24903    movl %eax, -40(%ebp)
24904 #NO_APP
24905 @end group
24906 @end smallexample
24907
24908 It would have been legal to write the Asm invocation as:
24909
24910 @smallexample
24911 Asm ("pushfl popl %%eax movl %%eax, %0")
24912 @end smallexample
24913
24914 but in the generated assembler file, this would come out as:
24915
24916 @smallexample
24917 #APP
24918    pushfl popl %eax movl %eax, -40(%ebp)
24919 #NO_APP
24920 @end smallexample
24921
24922 which is not so convenient for the human reader.
24923
24924 We use Ada comments
24925 at the end of each line to explain what the assembler instructions
24926 actually do.  This is a useful convention.
24927
24928 When writing Inline Assembler instructions, you need to precede each register
24929 and variable name with a percent sign.  Since the assembler already requires
24930 a percent sign at the beginning of a register name, you need two consecutive
24931 percent signs for such names in the Asm template string, thus @code{%%eax}.
24932 In the generated assembly code, one of the percent signs will be stripped off.
24933
24934 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24935 variables: operands you later define using @code{Input} or @code{Output}
24936 parameters to @code{Asm}.
24937 An output variable is illustrated in
24938 the third statement in the Asm template string:
24939 @smallexample
24940 movl %%eax, %0
24941 @end smallexample
24942 The intent is to store the contents of the eax register in a variable that can
24943 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24944 necessarily work, since the compiler might optimize by using a register
24945 to hold Flags, and the expansion of the @code{movl} instruction would not be
24946 aware of this optimization.  The solution is not to store the result directly
24947 but rather to advise the compiler to choose the correct operand form;
24948 that is the purpose of the @code{%0} output variable.
24949
24950 Information about the output variable is supplied in the @code{Outputs}
24951 parameter to @code{Asm}:
24952 @smallexample
24953 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24954 @end smallexample
24955
24956 The output is defined by the @code{Asm_Output} attribute of the target type;
24957 the general format is
24958 @smallexample
24959 Type'Asm_Output (constraint_string, variable_name)
24960 @end smallexample
24961
24962 The constraint string directs the compiler how
24963 to store/access the associated variable.  In the example
24964 @smallexample
24965 Unsigned_32'Asm_Output ("=m", Flags);
24966 @end smallexample
24967 the @code{"m"} (memory) constraint tells the compiler that the variable
24968 @code{Flags} should be stored in a memory variable, thus preventing
24969 the optimizer from keeping it in a register.  In contrast,
24970 @smallexample
24971 Unsigned_32'Asm_Output ("=r", Flags);
24972 @end smallexample
24973 uses the @code{"r"} (register) constraint, telling the compiler to
24974 store the variable in a register.
24975
24976 If the constraint is preceded by the equal character (@strong{=}), it tells
24977 the compiler that the variable will be used to store data into it.
24978
24979 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24980 allowing the optimizer to choose whatever it deems best.
24981
24982 There are a fairly large number of constraints, but the ones that are
24983 most useful (for the Intel x86 processor) are the following:
24984
24985 @table @code
24986 @item =
24987 output constraint
24988 @item g
24989 global (i.e.@: can be stored anywhere)
24990 @item m
24991 in memory
24992 @item I
24993 a constant
24994 @item a
24995 use eax
24996 @item b
24997 use ebx
24998 @item c
24999 use ecx
25000 @item d
25001 use edx
25002 @item S
25003 use esi
25004 @item D
25005 use edi
25006 @item r
25007 use one of eax, ebx, ecx or edx
25008 @item q
25009 use one of eax, ebx, ecx, edx, esi or edi
25010 @end table
25011
25012 The full set of constraints is described in the gcc and @emph{as}
25013 documentation; note that it is possible to combine certain constraints
25014 in one constraint string.
25015
25016 You specify the association of an output variable with an assembler operand
25017 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25018 integer.  Thus in
25019 @smallexample @c ada
25020 @group
25021 Asm ("pushfl"          & LF & HT & -- push flags on stack
25022      "popl %%eax"      & LF & HT & -- load eax with flags
25023      "movl %%eax, %0",             -- store flags in variable
25024      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25025 @end group
25026 @end smallexample
25027 @noindent
25028 @code{%0} will be replaced in the expanded code by the appropriate operand,
25029 whatever
25030 the compiler decided for the @code{Flags} variable.
25031
25032 In general, you may have any number of output variables:
25033 @itemize @bullet
25034 @item
25035 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25036 @item
25037 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25038 of @code{Asm_Output} attributes
25039 @end itemize
25040
25041 For example:
25042 @smallexample @c ada
25043 @group
25044 Asm ("movl %%eax, %0" & LF & HT &
25045      "movl %%ebx, %1" & LF & HT &
25046      "movl %%ecx, %2",
25047      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25048                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25049                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25050 @end group
25051 @end smallexample
25052 @noindent
25053 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25054 in the Ada program.
25055
25056 As a variation on the @code{Get_Flags} example, we can use the constraints
25057 string to direct the compiler to store the eax register into the @code{Flags}
25058 variable, instead of including the store instruction explicitly in the
25059 @code{Asm} template string:
25060
25061 @smallexample @c ada
25062 @group
25063 with Interfaces; use Interfaces;
25064 with Ada.Text_IO; use Ada.Text_IO;
25065 with System.Machine_Code; use System.Machine_Code;
25066 procedure Get_Flags_2 is
25067    Flags : Unsigned_32;
25068    use ASCII;
25069 begin
25070    Asm ("pushfl"      & LF & HT & -- push flags on stack
25071         "popl %%eax",             -- save flags in eax
25072         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25073    Put_Line ("Flags register:" & Flags'Img);
25074 end Get_Flags_2;
25075 @end group
25076 @end smallexample
25077
25078 @noindent
25079 The @code{"a"} constraint tells the compiler that the @code{Flags}
25080 variable will come from the eax register. Here is the resulting code:
25081
25082 @smallexample
25083 @group
25084 #APP
25085    pushfl
25086    popl %eax
25087 #NO_APP
25088    movl %eax,-40(%ebp)
25089 @end group
25090 @end smallexample
25091
25092 @noindent
25093 The compiler generated the store of eax into Flags after
25094 expanding the assembler code.
25095
25096 Actually, there was no need to pop the flags into the eax register;
25097 more simply, we could just pop the flags directly into the program variable:
25098
25099 @smallexample @c ada
25100 @group
25101 with Interfaces; use Interfaces;
25102 with Ada.Text_IO; use Ada.Text_IO;
25103 with System.Machine_Code; use System.Machine_Code;
25104 procedure Get_Flags_3 is
25105    Flags : Unsigned_32;
25106    use ASCII;
25107 begin
25108    Asm ("pushfl"  & LF & HT & -- push flags on stack
25109         "pop %0",             -- save flags in Flags
25110         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25111    Put_Line ("Flags register:" & Flags'Img);
25112 end Get_Flags_3;
25113 @end group
25114 @end smallexample
25115
25116 @c ---------------------------------------------------------------------------
25117 @node Input Variables in Inline Assembler
25118 @section Input Variables in Inline Assembler
25119
25120 @noindent
25121 The example in this section illustrates how to specify the source operands
25122 for assembly language statements.
25123 The program simply increments its input value by 1:
25124
25125 @smallexample @c ada
25126 @group
25127 with Interfaces; use Interfaces;
25128 with Ada.Text_IO; use Ada.Text_IO;
25129 with System.Machine_Code; use System.Machine_Code;
25130 procedure Increment is
25131
25132    function Incr (Value : Unsigned_32) return Unsigned_32 is
25133       Result : Unsigned_32;
25134    begin
25135       Asm ("incl %0",
25136            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25137            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25138       return Result;
25139    end Incr;
25140
25141    Value : Unsigned_32;
25142
25143 begin
25144    Value := 5;
25145    Put_Line ("Value before is" & Value'Img);
25146    Value := Incr (Value);
25147    Put_Line ("Value after is" & Value'Img);
25148 end Increment;
25149 @end group
25150 @end smallexample
25151
25152 The @code{Outputs} parameter to @code{Asm} specifies
25153 that the result will be in the eax register and that it is to be stored
25154 in the @code{Result} variable.
25155
25156 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25157 but with an @code{Asm_Input} attribute.
25158 The @code{"="} constraint, indicating an output value, is not present.
25159
25160 You can have multiple input variables, in the same way that you can have more
25161 than one output variable.
25162
25163 The parameter count (%0, %1) etc, now starts at the first input
25164 statement, and continues with the output statements.
25165 When both parameters use the same variable, the
25166 compiler will treat them as the same %n operand, which is the case here.
25167
25168 Just as the @code{Outputs} parameter causes the register to be stored into the
25169 target variable after execution of the assembler statements, so does the
25170 @code{Inputs} parameter cause its variable to be loaded into the register
25171 before execution of the assembler statements.
25172
25173 Thus the effect of the @code{Asm} invocation is:
25174 @enumerate
25175 @item load the 32-bit value of @code{Value} into eax
25176 @item execute the @code{incl %eax} instruction
25177 @item store the contents of eax into the @code{Result} variable
25178 @end enumerate
25179
25180 The resulting assembler file (with @option{-O2} optimization) contains:
25181 @smallexample
25182 @group
25183 _increment__incr.1:
25184    subl $4,%esp
25185    movl 8(%esp),%eax
25186 #APP
25187    incl %eax
25188 #NO_APP
25189    movl %eax,%edx
25190    movl %ecx,(%esp)
25191    addl $4,%esp
25192    ret
25193 @end group
25194 @end smallexample
25195
25196 @c ---------------------------------------------------------------------------
25197 @node Inlining Inline Assembler Code
25198 @section Inlining Inline Assembler Code
25199
25200 @noindent
25201 For a short subprogram such as the @code{Incr} function in the previous
25202 section, the overhead of the call and return (creating / deleting the stack
25203 frame) can be significant, compared to the amount of code in the subprogram
25204 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25205 which directs the compiler to expand invocations of the subprogram at the
25206 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25207 Here is the resulting program:
25208
25209 @smallexample @c ada
25210 @group
25211 with Interfaces; use Interfaces;
25212 with Ada.Text_IO; use Ada.Text_IO;
25213 with System.Machine_Code; use System.Machine_Code;
25214 procedure Increment_2 is
25215
25216    function Incr (Value : Unsigned_32) return Unsigned_32 is
25217       Result : Unsigned_32;
25218    begin
25219       Asm ("incl %0",
25220            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25221            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25222       return Result;
25223    end Incr;
25224    pragma Inline (Increment);
25225
25226    Value : Unsigned_32;
25227
25228 begin
25229    Value := 5;
25230    Put_Line ("Value before is" & Value'Img);
25231    Value := Increment (Value);
25232    Put_Line ("Value after is" & Value'Img);
25233 end Increment_2;
25234 @end group
25235 @end smallexample
25236
25237 Compile the program with both optimization (@option{-O2}) and inlining
25238 (@option{-gnatn}) enabled.
25239
25240 The @code{Incr} function is still compiled as usual, but at the
25241 point in @code{Increment} where our function used to be called:
25242
25243 @smallexample
25244 @group
25245 pushl %edi
25246 call _increment__incr.1
25247 @end group
25248 @end smallexample
25249
25250 @noindent
25251 the code for the function body directly appears:
25252
25253 @smallexample
25254 @group
25255 movl %esi,%eax
25256 #APP
25257    incl %eax
25258 #NO_APP
25259    movl %eax,%edx
25260 @end group
25261 @end smallexample
25262
25263 @noindent
25264 thus saving the overhead of stack frame setup and an out-of-line call.
25265
25266 @c ---------------------------------------------------------------------------
25267 @node Other Asm Functionality
25268 @section Other @code{Asm} Functionality
25269
25270 @noindent
25271 This section describes two important parameters to the @code{Asm}
25272 procedure: @code{Clobber}, which identifies register usage;
25273 and @code{Volatile}, which inhibits unwanted optimizations.
25274
25275 @menu
25276 * The Clobber Parameter::
25277 * The Volatile Parameter::
25278 @end menu
25279
25280 @c ---------------------------------------------------------------------------
25281 @node The Clobber Parameter
25282 @subsection The @code{Clobber} Parameter
25283
25284 @noindent
25285 One of the dangers of intermixing assembly language and a compiled language
25286 such as Ada is that the compiler needs to be aware of which registers are
25287 being used by the assembly code.  In some cases, such as the earlier examples,
25288 the constraint string is sufficient to indicate register usage (e.g.,
25289 @code{"a"} for
25290 the eax register).  But more generally, the compiler needs an explicit
25291 identification of the registers that are used by the Inline Assembly
25292 statements.
25293
25294 Using a register that the compiler doesn't know about
25295 could be a side effect of an instruction (like @code{mull}
25296 storing its result in both eax and edx).
25297 It can also arise from explicit register usage in your
25298 assembly code; for example:
25299 @smallexample
25300 @group
25301 Asm ("movl %0, %%ebx" & LF & HT &
25302      "movl %%ebx, %1",
25303      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25304      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25305 @end group
25306 @end smallexample
25307 @noindent
25308 where the compiler (since it does not analyze the @code{Asm} template string)
25309 does not know you are using the ebx register.
25310
25311 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25312 to identify the registers that will be used by your assembly code:
25313
25314 @smallexample
25315 @group
25316 Asm ("movl %0, %%ebx" & LF & HT &
25317      "movl %%ebx, %1",
25318      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25319      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25320      Clobber => "ebx");
25321 @end group
25322 @end smallexample
25323
25324 The Clobber parameter is a static string expression specifying the
25325 register(s) you are using.  Note that register names are @emph{not} prefixed
25326 by a percent sign. Also, if more than one register is used then their names
25327 are separated by commas; e.g., @code{"eax, ebx"}
25328
25329 The @code{Clobber} parameter has several additional uses:
25330 @enumerate
25331 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25332 @item Use ``register'' name @code{memory} if you changed a memory location
25333 @end enumerate
25334
25335 @c ---------------------------------------------------------------------------
25336 @node The Volatile Parameter
25337 @subsection The @code{Volatile} Parameter
25338 @cindex Volatile parameter
25339
25340 @noindent
25341 Compiler optimizations in the presence of Inline Assembler may sometimes have
25342 unwanted effects.  For example, when an @code{Asm} invocation with an input
25343 variable is inside a loop, the compiler might move the loading of the input
25344 variable outside the loop, regarding it as a one-time initialization.
25345
25346 If this effect is not desired, you can disable such optimizations by setting
25347 the @code{Volatile} parameter to @code{True}; for example:
25348
25349 @smallexample @c ada
25350 @group
25351 Asm ("movl %0, %%ebx" & LF & HT &
25352      "movl %%ebx, %1",
25353      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25354      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25355      Clobber  => "ebx",
25356      Volatile => True);
25357 @end group
25358 @end smallexample
25359
25360 By default, @code{Volatile} is set to @code{False} unless there is no
25361 @code{Outputs} parameter.
25362
25363 Although setting @code{Volatile} to @code{True} prevents unwanted
25364 optimizations, it will also disable other optimizations that might be
25365 important for efficiency. In general, you should set @code{Volatile}
25366 to @code{True} only if the compiler's optimizations have created
25367 problems.
25368 @c END OF INLINE ASSEMBLER CHAPTER
25369 @c ===============================
25370
25371 @c ***********************************
25372 @c * Compatibility and Porting Guide *
25373 @c ***********************************
25374 @node Compatibility and Porting Guide
25375 @appendix Compatibility and Porting Guide
25376
25377 @noindent
25378 This chapter describes the compatibility issues that may arise between
25379 GNAT and other Ada compilation systems (including those for Ada 83),
25380 and shows how GNAT can expedite porting
25381 applications developed in other Ada environments.
25382
25383 @menu
25384 * Compatibility with Ada 83::
25385 * Compatibility between Ada 95 and Ada 2005::
25386 * Implementation-dependent characteristics::
25387 * Compatibility with Other Ada Systems::
25388 * Representation Clauses::
25389 @ifclear vms
25390 @c Brief section is only in non-VMS version
25391 @c Full chapter is in VMS version
25392 * Compatibility with HP Ada 83::
25393 @end ifclear
25394 @ifset vms
25395 * Transitioning to 64-Bit GNAT for OpenVMS::
25396 @end ifset
25397 @end menu
25398
25399 @node Compatibility with Ada 83
25400 @section Compatibility with Ada 83
25401 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25402
25403 @noindent
25404 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25405 particular, the design intention was that the difficulties associated
25406 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25407 that occur when moving from one Ada 83 system to another.
25408
25409 However, there are a number of points at which there are minor
25410 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25411 full details of these issues,
25412 and should be consulted for a complete treatment.
25413 In practice the
25414 following subsections treat the most likely issues to be encountered.
25415
25416 @menu
25417 * Legal Ada 83 programs that are illegal in Ada 95::
25418 * More deterministic semantics::
25419 * Changed semantics::
25420 * Other language compatibility issues::
25421 @end menu
25422
25423 @node Legal Ada 83 programs that are illegal in Ada 95
25424 @subsection Legal Ada 83 programs that are illegal in Ada 95
25425
25426 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25427 Ada 95 and thus also in Ada 2005:
25428
25429 @table @emph
25430 @item Character literals
25431 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25432 @code{Wide_Character} as a new predefined character type, some uses of
25433 character literals that were legal in Ada 83 are illegal in Ada 95.
25434 For example:
25435 @smallexample @c ada
25436    for Char in 'A' .. 'Z' loop @dots{} end loop;
25437 @end smallexample
25438
25439 @noindent
25440 The problem is that @code{'A'} and @code{'Z'} could be from either
25441 @code{Character} or @code{Wide_Character}.  The simplest correction
25442 is to make the type explicit; e.g.:
25443 @smallexample @c ada
25444    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25445 @end smallexample
25446
25447 @item New reserved words
25448 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25449 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25450 Existing Ada 83 code using any of these identifiers must be edited to
25451 use some alternative name.
25452
25453 @item Freezing rules
25454 The rules in Ada 95 are slightly different with regard to the point at
25455 which entities are frozen, and representation pragmas and clauses are
25456 not permitted past the freeze point.  This shows up most typically in
25457 the form of an error message complaining that a representation item
25458 appears too late, and the appropriate corrective action is to move
25459 the item nearer to the declaration of the entity to which it refers.
25460
25461 A particular case is that representation pragmas
25462 @ifset vms
25463 (including the
25464 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25465 @end ifset
25466 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25467 declaration must be introduced to which the pragma can be applied.
25468
25469 @item Optional bodies for library packages
25470 In Ada 83, a package that did not require a package body was nevertheless
25471 allowed to have one.  This lead to certain surprises in compiling large
25472 systems (situations in which the body could be unexpectedly ignored by the
25473 binder).  In Ada 95, if a package does not require a body then it is not
25474 permitted to have a body.  To fix this problem, simply remove a redundant
25475 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25476 into the spec that makes the body required.  One approach is to add a private
25477 part to the package declaration (if necessary), and define a parameterless
25478 procedure called @code{Requires_Body}, which must then be given a dummy
25479 procedure body in the package body, which then becomes required.
25480 Another approach (assuming that this does not introduce elaboration
25481 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25482 since one effect of this pragma is to require the presence of a package body.
25483
25484 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25485 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25486 @code{Constraint_Error}.
25487 This means that it is illegal to have separate exception handlers for
25488 the two exceptions.  The fix is simply to remove the handler for the
25489 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25490 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25491
25492 @item Indefinite subtypes in generics
25493 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25494 as the actual for a generic formal private type, but then the instantiation
25495 would be illegal if there were any instances of declarations of variables
25496 of this type in the generic body.  In Ada 95, to avoid this clear violation
25497 of the methodological principle known as the ``contract model'',
25498 the generic declaration explicitly indicates whether
25499 or not such instantiations are permitted.  If a generic formal parameter
25500 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25501 type name, then it can be instantiated with indefinite types, but no
25502 stand-alone variables can be declared of this type.  Any attempt to declare
25503 such a variable will result in an illegality at the time the generic is
25504 declared.  If the @code{(<>)} notation is not used, then it is illegal
25505 to instantiate the generic with an indefinite type.
25506 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25507 It will show up as a compile time error, and
25508 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25509 @end table
25510
25511 @node More deterministic semantics
25512 @subsection More deterministic semantics
25513
25514 @table @emph
25515 @item Conversions
25516 Conversions from real types to integer types round away from 0.  In Ada 83
25517 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25518 implementation freedom was intended to support unbiased rounding in
25519 statistical applications, but in practice it interfered with portability.
25520 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25521 is required.  Numeric code may be affected by this change in semantics.
25522 Note, though, that this issue is no worse than already existed in Ada 83
25523 when porting code from one vendor to another.
25524
25525 @item Tasking
25526 The Real-Time Annex introduces a set of policies that define the behavior of
25527 features that were implementation dependent in Ada 83, such as the order in
25528 which open select branches are executed.
25529 @end table
25530
25531 @node Changed semantics
25532 @subsection Changed semantics
25533
25534 @noindent
25535 The worst kind of incompatibility is one where a program that is legal in
25536 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25537 possible in Ada 83.  Fortunately this is extremely rare, but the one
25538 situation that you should be alert to is the change in the predefined type
25539 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25540
25541 @table @emph
25542 @item Range of type @code{Character}
25543 The range of @code{Standard.Character} is now the full 256 characters
25544 of Latin-1, whereas in most Ada 83 implementations it was restricted
25545 to 128 characters. Although some of the effects of
25546 this change will be manifest in compile-time rejection of legal
25547 Ada 83 programs it is possible for a working Ada 83 program to have
25548 a different effect in Ada 95, one that was not permitted in Ada 83.
25549 As an example, the expression
25550 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25551 delivers @code{255} as its value.
25552 In general, you should look at the logic of any
25553 character-processing Ada 83 program and see whether it needs to be adapted
25554 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25555 character handling package that may be relevant if code needs to be adapted
25556 to account for the additional Latin-1 elements.
25557 The desirable fix is to
25558 modify the program to accommodate the full character set, but in some cases
25559 it may be convenient to define a subtype or derived type of Character that
25560 covers only the restricted range.
25561 @cindex Latin-1
25562 @end table
25563
25564 @node Other language compatibility issues
25565 @subsection Other language compatibility issues
25566
25567 @table @emph
25568 @item @option{-gnat83} switch
25569 All implementations of GNAT provide a switch that causes GNAT to operate
25570 in Ada 83 mode.  In this mode, some but not all compatibility problems
25571 of the type described above are handled automatically.  For example, the
25572 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
25573 as identifiers as in Ada 83.
25574 However,
25575 in practice, it is usually advisable to make the necessary modifications
25576 to the program to remove the need for using this switch.
25577 See @ref{Compiling Different Versions of Ada}.
25578
25579 @item Support for removed Ada 83 pragmas and attributes
25580 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
25581 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
25582 compilers are allowed, but not required, to implement these missing
25583 elements.  In contrast with some other compilers, GNAT implements all
25584 such pragmas and attributes, eliminating this compatibility concern.  These
25585 include @code{pragma Interface} and the floating point type attributes
25586 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25587 @end table
25588
25589
25590 @node Compatibility between Ada 95 and Ada 2005
25591 @section Compatibility between Ada 95 and Ada 2005
25592 @cindex Compatibility between Ada 95 and Ada 2005
25593
25594 @noindent
25595 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
25596 a number of incompatibilities. Several are enumerated below;
25597 for a complete description please see the
25598 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
25599 @cite{Rationale for Ada 2005}.
25600
25601 @table @emph
25602 @item New reserved words.
25603 The words @code{interface}, @code{overriding} and @code{synchronized} are
25604 reserved in Ada 2005.
25605 A pre-Ada 2005 program that uses any of these as an identifier will be
25606 illegal.
25607
25608 @item New declarations in predefined packages.
25609 A number of packages in the predefined environment contain new declarations:
25610 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
25611 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
25612 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
25613 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
25614 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
25615 If an Ada 95 program does a @code{with} and @code{use} of any of these
25616 packages, the new declarations may cause name clashes.
25617
25618 @item Access parameters.
25619 A nondispatching subprogram with an access parameter cannot be renamed
25620 as a dispatching operation.  This was permitted in Ada 95.
25621
25622 @item Access types, discriminants, and constraints.
25623 Rule changes in this area have led to some incompatibilities; for example,
25624 constrained subtypes of some access types are not permitted in Ada 2005.
25625
25626 @item Aggregates for limited types.
25627 The allowance of aggregates for limited types in Ada 2005 raises the
25628 possibility of ambiguities in legal Ada 95 programs, since additional types
25629 now need to be considered in expression resolution.
25630
25631 @item Fixed-point multiplication and division.
25632 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
25633 were legal in Ada 95 and invoked the predefined versions of these operations,
25634 are now ambiguous.
25635 The ambiguity may be resolved either by applying a type conversion to the
25636 expression, or by explicitly invoking the operation from package
25637 @code{Standard}.
25638
25639 @item Return-by-reference types.
25640 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
25641 can declare a function returning a value from an anonymous access type.
25642 @end table
25643
25644
25645 @node Implementation-dependent characteristics
25646 @section Implementation-dependent characteristics
25647 @noindent
25648 Although the Ada language defines the semantics of each construct as
25649 precisely as practical, in some situations (for example for reasons of
25650 efficiency, or where the effect is heavily dependent on the host or target
25651 platform) the implementation is allowed some freedom.  In porting Ada 83
25652 code to GNAT, you need to be aware of whether / how the existing code
25653 exercised such implementation dependencies.  Such characteristics fall into
25654 several categories, and GNAT offers specific support in assisting the
25655 transition from certain Ada 83 compilers.
25656
25657 @menu
25658 * Implementation-defined pragmas::
25659 * Implementation-defined attributes::
25660 * Libraries::
25661 * Elaboration order::
25662 * Target-specific aspects::
25663 @end menu
25664
25665 @node Implementation-defined pragmas
25666 @subsection Implementation-defined pragmas
25667
25668 @noindent
25669 Ada compilers are allowed to supplement the language-defined pragmas, and
25670 these are a potential source of non-portability.  All GNAT-defined pragmas
25671 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
25672 Reference Manual}, and these include several that are specifically
25673 intended to correspond to other vendors' Ada 83 pragmas.
25674 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25675 For compatibility with HP Ada 83, GNAT supplies the pragmas
25676 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25677 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25678 and @code{Volatile}.
25679 Other relevant pragmas include @code{External} and @code{Link_With}.
25680 Some vendor-specific
25681 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25682 recognized, thus
25683 avoiding compiler rejection of units that contain such pragmas; they are not
25684 relevant in a GNAT context and hence are not otherwise implemented.
25685
25686 @node Implementation-defined attributes
25687 @subsection Implementation-defined attributes
25688
25689 Analogous to pragmas, the set of attributes may be extended by an
25690 implementation.  All GNAT-defined attributes are described in
25691 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
25692 Manual}, and these include several that are specifically intended
25693 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25694 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
25695 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25696 @code{Type_Class}.
25697
25698 @node Libraries
25699 @subsection Libraries
25700 @noindent
25701 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25702 code uses vendor-specific libraries then there are several ways to manage
25703 this in Ada 95 or Ada 2005:
25704 @enumerate
25705 @item
25706 If the source code for the libraries (specs and bodies) are
25707 available, then the libraries can be migrated in the same way as the
25708 application.
25709 @item
25710 If the source code for the specs but not the bodies are
25711 available, then you can reimplement the bodies.
25712 @item
25713 Some features introduced by Ada 95 obviate the need for library support.  For
25714 example most Ada 83 vendors supplied a package for unsigned integers.  The
25715 Ada 95 modular type feature is the preferred way to handle this need, so
25716 instead of migrating or reimplementing the unsigned integer package it may
25717 be preferable to retrofit the application using modular types.
25718 @end enumerate
25719
25720 @node Elaboration order
25721 @subsection Elaboration order
25722 @noindent
25723 The implementation can choose any elaboration order consistent with the unit
25724 dependency relationship.  This freedom means that some orders can result in
25725 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25726 to invoke a subprogram its body has been elaborated, or to instantiate a
25727 generic before the generic body has been elaborated.  By default GNAT
25728 attempts to choose a safe order (one that will not encounter access before
25729 elaboration problems) by implicitly inserting @code{Elaborate} or
25730 @code{Elaborate_All} pragmas where
25731 needed.  However, this can lead to the creation of elaboration circularities
25732 and a resulting rejection of the program by gnatbind.  This issue is
25733 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25734 In brief, there are several
25735 ways to deal with this situation:
25736
25737 @itemize @bullet
25738 @item
25739 Modify the program to eliminate the circularities, e.g.@: by moving
25740 elaboration-time code into explicitly-invoked procedures
25741 @item
25742 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25743 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25744 @code{Elaborate_All}
25745 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25746 (by selectively suppressing elaboration checks via pragma
25747 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25748 @end itemize
25749
25750 @node Target-specific aspects
25751 @subsection Target-specific aspects
25752 @noindent
25753 Low-level applications need to deal with machine addresses, data
25754 representations, interfacing with assembler code, and similar issues.  If
25755 such an Ada 83 application is being ported to different target hardware (for
25756 example where the byte endianness has changed) then you will need to
25757 carefully examine the program logic; the porting effort will heavily depend
25758 on the robustness of the original design.  Moreover, Ada 95 (and thus
25759 Ada 2005) are sometimes
25760 incompatible with typical Ada 83 compiler practices regarding implicit
25761 packing, the meaning of the Size attribute, and the size of access values.
25762 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25763
25764 @node Compatibility with Other Ada Systems
25765 @section Compatibility with Other Ada Systems
25766
25767 @noindent
25768 If programs avoid the use of implementation dependent and
25769 implementation defined features, as documented in the @cite{Ada
25770 Reference Manual}, there should be a high degree of portability between
25771 GNAT and other Ada systems.  The following are specific items which
25772 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
25773 compilers, but do not affect porting code to GNAT@.
25774 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
25775 the following issues may or may not arise for Ada 2005 programs
25776 when other compilers appear.)
25777
25778 @table @emph
25779 @item Ada 83 Pragmas and Attributes
25780 Ada 95 compilers are allowed, but not required, to implement the missing
25781 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25782 GNAT implements all such pragmas and attributes, eliminating this as
25783 a compatibility concern, but some other Ada 95 compilers reject these
25784 pragmas and attributes.
25785
25786 @item Specialized Needs Annexes
25787 GNAT implements the full set of special needs annexes.  At the
25788 current time, it is the only Ada 95 compiler to do so.  This means that
25789 programs making use of these features may not be portable to other Ada
25790 95 compilation systems.
25791
25792 @item Representation Clauses
25793 Some other Ada 95 compilers implement only the minimal set of
25794 representation clauses required by the Ada 95 reference manual.  GNAT goes
25795 far beyond this minimal set, as described in the next section.
25796 @end table
25797
25798 @node Representation Clauses
25799 @section Representation Clauses
25800
25801 @noindent
25802 The Ada 83 reference manual was quite vague in describing both the minimal
25803 required implementation of representation clauses, and also their precise
25804 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
25805 minimal set of capabilities required is still quite limited.
25806
25807 GNAT implements the full required set of capabilities in
25808 Ada 95 and Ada 2005, but also goes much further, and in particular
25809 an effort has been made to be compatible with existing Ada 83 usage to the
25810 greatest extent possible.
25811
25812 A few cases exist in which Ada 83 compiler behavior is incompatible with
25813 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
25814 intentional or accidental dependence on specific implementation dependent
25815 characteristics of these Ada 83 compilers.  The following is a list of
25816 the cases most likely to arise in existing Ada 83 code.
25817
25818 @table @emph
25819 @item Implicit Packing
25820 Some Ada 83 compilers allowed a Size specification to cause implicit
25821 packing of an array or record.  This could cause expensive implicit
25822 conversions for change of representation in the presence of derived
25823 types, and the Ada design intends to avoid this possibility.
25824 Subsequent AI's were issued to make it clear that such implicit
25825 change of representation in response to a Size clause is inadvisable,
25826 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
25827 Reference Manuals as implementation advice that is followed by GNAT@.
25828 The problem will show up as an error
25829 message rejecting the size clause.  The fix is simply to provide
25830 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25831 a Component_Size clause.
25832
25833 @item Meaning of Size Attribute
25834 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
25835 the minimal number of bits required to hold values of the type.  For example,
25836 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
25837 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25838 some 32 in this situation.  This problem will usually show up as a compile
25839 time error, but not always.  It is a good idea to check all uses of the
25840 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25841 Object_Size can provide a useful way of duplicating the behavior of
25842 some Ada 83 compiler systems.
25843
25844 @item Size of Access Types
25845 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25846 and that therefore it will be the same size as a System.Address value.  This
25847 assumption is true for GNAT in most cases with one exception.  For the case of
25848 a pointer to an unconstrained array type (where the bounds may vary from one
25849 value of the access type to another), the default is to use a ``fat pointer'',
25850 which is represented as two separate pointers, one to the bounds, and one to
25851 the array.  This representation has a number of advantages, including improved
25852 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25853 code which makes the assumption that, for example, pointers fit in 32 bits on
25854 a machine with 32-bit addressing.
25855
25856 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25857 access types in this case (where the designated type is an unconstrained array
25858 type).  These thin pointers are indeed the same size as a System.Address value.
25859 To specify a thin pointer, use a size clause for the type, for example:
25860
25861 @smallexample @c ada
25862 type X is access all String;
25863 for X'Size use Standard'Address_Size;
25864 @end smallexample
25865
25866 @noindent
25867 which will cause the type X to be represented using a single pointer.
25868 When using this representation, the bounds are right behind the array.
25869 This representation is slightly less efficient, and does not allow quite
25870 such flexibility in the use of foreign pointers or in using the
25871 Unrestricted_Access attribute to create pointers to non-aliased objects.
25872 But for any standard portable use of the access type it will work in
25873 a functionally correct manner and allow porting of existing code.
25874 Note that another way of forcing a thin pointer representation
25875 is to use a component size clause for the element size in an array,
25876 or a record representation clause for an access field in a record.
25877 @end table
25878
25879 @ifclear vms
25880 @c This brief section is only in the non-VMS version
25881 @c The complete chapter on HP Ada is in the VMS version
25882 @node Compatibility with HP Ada 83
25883 @section Compatibility with HP Ada 83
25884
25885 @noindent
25886 The VMS version of GNAT fully implements all the pragmas and attributes
25887 provided by HP Ada 83, as well as providing the standard HP Ada 83
25888 libraries, including Starlet.  In addition, data layouts and parameter
25889 passing conventions are highly compatible.  This means that porting
25890 existing HP Ada 83 code to GNAT in VMS systems should be easier than
25891 most other porting efforts.  The following are some of the most
25892 significant differences between GNAT and HP Ada 83.
25893
25894 @table @emph
25895 @item Default floating-point representation
25896 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
25897 it is VMS format.  GNAT does implement the necessary pragmas
25898 (Long_Float, Float_Representation) for changing this default.
25899
25900 @item System
25901 The package System in GNAT exactly corresponds to the definition in the
25902 Ada 95 reference manual, which means that it excludes many of the
25903 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
25904 that contains the additional definitions, and a special pragma,
25905 Extend_System allows this package to be treated transparently as an
25906 extension of package System.
25907
25908 @item To_Address
25909 The definitions provided by Aux_DEC are exactly compatible with those
25910 in the HP Ada 83 version of System, with one exception.
25911 HP Ada provides the following declarations:
25912
25913 @smallexample @c ada
25914 TO_ADDRESS (INTEGER)
25915 TO_ADDRESS (UNSIGNED_LONGWORD)
25916 TO_ADDRESS (@i{universal_integer})
25917 @end smallexample
25918
25919 @noindent
25920 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
25921 an extension to Ada 83 not strictly compatible with the reference manual.
25922 In GNAT, we are constrained to be exactly compatible with the standard,
25923 and this means we cannot provide this capability.  In HP Ada 83, the
25924 point of this definition is to deal with a call like:
25925
25926 @smallexample @c ada
25927 TO_ADDRESS (16#12777#);
25928 @end smallexample
25929
25930 @noindent
25931 Normally, according to the Ada 83 standard, one would expect this to be
25932 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25933 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
25934 definition using @i{universal_integer} takes precedence.
25935
25936 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
25937 is not possible to be 100% compatible.  Since there are many programs using
25938 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25939 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25940 declarations provided in the GNAT version of AUX_Dec are:
25941
25942 @smallexample @c ada
25943 function To_Address (X : Integer) return Address;
25944 pragma Pure_Function (To_Address);
25945
25946 function To_Address_Long (X : Unsigned_Longword)
25947  return Address;
25948 pragma Pure_Function (To_Address_Long);
25949 @end smallexample
25950
25951 @noindent
25952 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25953 change the name to TO_ADDRESS_LONG@.
25954
25955 @item Task_Id values
25956 The Task_Id values assigned will be different in the two systems, and GNAT
25957 does not provide a specified value for the Task_Id of the environment task,
25958 which in GNAT is treated like any other declared task.
25959 @end table
25960
25961 @noindent
25962 For full details on these and other less significant compatibility issues,
25963 see appendix E of the HP publication entitled @cite{HP Ada, Technical
25964 Overview and Comparison on HP Platforms}.
25965
25966 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25967 attributes are recognized, although only a subset of them can sensibly
25968 be implemented.  The description of pragmas in @ref{Implementation
25969 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
25970 indicates whether or not they are applicable to non-VMS systems.
25971 @end ifclear
25972
25973 @ifset vms
25974 @node Transitioning to 64-Bit GNAT for OpenVMS
25975 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
25976
25977 @noindent
25978 This section is meant to assist users of pre-2006 @value{EDITION}
25979 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
25980 the version of the GNAT technology supplied in 2006 and later for
25981 OpenVMS on both Alpha and I64.
25982
25983 @menu
25984 * Introduction to transitioning::
25985 * Migration of 32 bit code::
25986 * Taking advantage of 64 bit addressing::
25987 * Technical details::
25988 @end menu
25989
25990 @node Introduction to transitioning
25991 @subsection Introduction
25992
25993 @noindent
25994 64-bit @value{EDITION} for Open VMS has been designed to meet
25995 three main goals:
25996
25997 @enumerate
25998 @item
25999 Providing a full conforming implementation of Ada 95 and Ada 2005
26000
26001 @item
26002 Allowing maximum backward compatibility, thus easing migration of existing
26003 Ada source code
26004
26005 @item
26006 Supplying a path for exploiting the full 64-bit address range
26007 @end enumerate
26008
26009 @noindent
26010 Ada's strong typing semantics has made it
26011 impractical to have different 32-bit and 64-bit modes. As soon as
26012 one object could possibly be outside the 32-bit address space, this
26013 would make it necessary for the @code{System.Address} type to be 64 bits.
26014 In particular, this would cause inconsistencies if 32-bit code is
26015 called from 64-bit code that raises an exception.
26016
26017 This issue has been resolved by always using 64-bit addressing
26018 at the system level, but allowing for automatic conversions between
26019 32-bit and 64-bit addresses where required. Thus users who
26020 do not currently require 64-bit addressing capabilities, can
26021 recompile their code with only minimal changes (and indeed
26022 if the code is written in portable Ada, with no assumptions about
26023 the size of the @code{Address} type, then no changes at all are necessary).
26024 At the same time,
26025 this approach provides a simple, gradual upgrade path to future
26026 use of larger memories than available for 32-bit systems.
26027 Also, newly written applications or libraries will by default
26028 be fully compatible with future systems exploiting 64-bit
26029 addressing capabilities.
26030
26031 @ref{Migration of 32 bit code}, will focus on porting applications
26032 that do not require more than 2 GB of
26033 addressable memory. This code will be referred to as
26034 @emph{32-bit code}.
26035 For applications intending to exploit the full 64-bit address space,
26036 @ref{Taking advantage of 64 bit addressing},
26037 will consider further changes that may be required.
26038 Such code will be referred to below as @emph{64-bit code}.
26039
26040 @node Migration of 32 bit code
26041 @subsection Migration of 32-bit code
26042
26043 @menu
26044 * Address types::
26045 * Access types and 32/64-bit allocation::
26046 * Unchecked conversions::
26047 * Predefined constants::
26048 * Interfacing with C::
26049 * 32/64-bit descriptors::
26050 * Experience with source compatibility::
26051 @end menu
26052
26053 @node Address types
26054 @subsubsection Address types
26055
26056 @noindent
26057 To solve the problem of mixing 64-bit and 32-bit addressing,
26058 while maintaining maximum backward compatibility, the following
26059 approach has been taken:
26060
26061 @itemize @bullet
26062 @item
26063 @code{System.Address} always has a size of 64 bits
26064 @cindex @code{System.Address} size
26065 @cindex @code{Address} size
26066
26067 @item
26068 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26069 @cindex @code{System.Short_Address} size
26070 @cindex @code{Short_Address} size
26071 @end itemize
26072
26073 @noindent
26074 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26075 a @code{Short_Address}
26076 may be used where an @code{Address} is required, and vice versa, without
26077 needing explicit type conversions.
26078 By virtue of the Open VMS parameter passing conventions,
26079 even imported
26080 and exported subprograms that have 32-bit address parameters are
26081 compatible with those that have 64-bit address parameters.
26082 (See @ref{Making code 64 bit clean} for details.)
26083
26084 The areas that may need attention are those where record types have
26085 been defined that contain components of the type @code{System.Address}, and
26086 where objects of this type are passed to code expecting a record layout with
26087 32-bit addresses.
26088
26089 Different compilers on different platforms cannot be
26090 expected to represent the same type in the same way,
26091 since alignment constraints
26092 and other system-dependent properties affect the compiler's decision.
26093 For that reason, Ada code
26094 generally uses representation clauses to specify the expected
26095 layout where required.
26096
26097 If such a representation clause uses 32 bits for a component having
26098 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26099 will detect that error and produce a specific diagnostic message.
26100 The developer should then determine whether the representation
26101 should be 64 bits or not and make either of two changes:
26102 change the size to 64 bits and leave the type as @code{System.Address}, or
26103 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26104 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26105 required in any code setting or accessing the field; the compiler will
26106 automatically perform any needed conversions between address
26107 formats.
26108
26109 @node Access types and 32/64-bit allocation
26110 @subsubsection Access types and 32/64-bit allocation
26111 @cindex 32-bit allocation
26112 @cindex 64-bit allocation
26113
26114 @noindent
26115 By default, objects designated by access values are always allocated in
26116 the 64-bit address space, and access values themselves are represented
26117 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26118 is required (for example if the address of an allocated object is assigned
26119 to a @code{Short_Address} variable), then several alternatives are available:
26120
26121 @itemize @bullet
26122 @item
26123 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26124 definition is @code{access T} versus @code{access all T} or
26125 @code{access constant T}), may be declared with a @code{'Size} representation
26126 clause that establishes the size as 32 bits.
26127 In such circumstances allocations for that type will
26128 be from the 32-bit heap.  Such a clause is not permitted
26129 for a general access type (declared with @code{access all} or
26130 @code{access constant}) as values of such types must be able to refer
26131 to any object of the designated type, including objects residing outside
26132 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26133 type definitions, however, since general access types were introduced
26134 in @w{Ada 95}.
26135
26136 @item
26137 Switches for @command{GNAT BIND} control whether the internal GNAT
26138 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26139 @cindex @code{__gnat_malloc}
26140 The switches are respectively @option{-H64} (the default) and
26141 @option{-H32}.
26142 @cindex @option{-H32} (@command{gnatbind})
26143 @cindex @option{-H64} (@command{gnatbind})
26144
26145 @item
26146 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26147 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26148 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26149 If this variable is left
26150 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26151 then the default (64-bit) allocation is used.
26152 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26153 then 32-bit allocation is used.  The gnatbind qualifiers described above
26154 override this logical name.
26155
26156 @item
26157 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26158 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26159 at a low level to convert explicit calls to @code{malloc} and related
26160 functions from the C run-time library so that they perform allocations
26161 in the 32-bit heap.
26162 Since all internal allocations from GNAT use @code{__gnat_malloc},
26163 this switch is not required unless the program makes explicit calls on
26164 @code{malloc} (or related functions) from interfaced C code.
26165 @end itemize
26166
26167
26168 @node Unchecked conversions
26169 @subsubsection Unchecked conversions
26170
26171 @noindent
26172 In the case of an @code{Unchecked_Conversion} where the source type is a
26173 64-bit access type or the type @code{System.Address}, and the target
26174 type is a 32-bit type, the compiler will generate a warning.
26175 Even though the generated code will still perform the required
26176 conversions, it is highly recommended in these cases to use
26177 respectively a 32-bit access type or @code{System.Short_Address}
26178 as the source type.
26179
26180 @node Predefined constants
26181 @subsubsection Predefined constants
26182
26183 @noindent
26184 The following table shows the correspondence between pre-2006 versions of
26185 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26186 (``New''):
26187
26188 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26189 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26190 @item   @code{System.Word_Size}          @tab 32      @tab 64
26191 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26192 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26193 @item   @code{System.Address_Size}       @tab 32      @tab 64
26194 @end multitable
26195
26196 @noindent
26197 If you need to refer to the specific
26198 memory size of a 32-bit implementation, instead of the
26199 actual memory size, use @code{System.Short_Memory_Size}
26200 rather than @code{System.Memory_Size}.
26201 Similarly, references to @code{System.Address_Size} may need
26202 to be replaced by @code{System.Short_Address'Size}.
26203 The program @command{gnatfind} may be useful for locating
26204 references to the above constants, so that you can verify that they
26205 are still correct.
26206
26207 @node Interfacing with C
26208 @subsubsection Interfacing with C
26209
26210 @noindent
26211 In order to minimize the impact of the transition to 64-bit addresses on
26212 legacy programs, some fundamental types in the @code{Interfaces.C}
26213 package hierarchy continue to be represented in 32 bits.
26214 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26215 This eases integration with the default HP C layout choices, for example
26216 as found in the system routines in @code{DECC$SHR.EXE}.
26217 Because of this implementation choice, the type fully compatible with
26218 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26219 Depending on the context the compiler will issue a
26220 warning or an error when type @code{Address} is used, alerting the user to a
26221 potential problem. Otherwise 32-bit programs that use
26222 @code{Interfaces.C} should normally not require code modifications
26223
26224 The other issue arising with C interfacing concerns pragma @code{Convention}.
26225 For VMS 64-bit systems, there is an issue of the appropriate default size
26226 of C convention pointers in the absence of an explicit size clause. The HP
26227 C compiler can choose either 32 or 64 bits depending on compiler options.
26228 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26229 clause is given. This proves a better choice for porting 32-bit legacy
26230 applications. In order to have a 64-bit representation, it is necessary to
26231 specify a size representation clause. For example:
26232
26233 @smallexample @c ada
26234 type int_star is access Interfaces.C.int;
26235 pragma Convention(C, int_star);
26236 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26237 @end smallexample
26238
26239 @node 32/64-bit descriptors
26240 @subsubsection 32/64-bit descriptors
26241
26242 @noindent
26243 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
26244 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26245 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26246 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26247 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26248
26249 If the configuration pragma @code{Short_Descriptors} is supplied, then
26250 all descriptors will be 32 bits.
26251 @cindex pragma @code{Short_Descriptors}
26252
26253 @node Experience with source compatibility
26254 @subsubsection Experience with source compatibility
26255
26256 @noindent
26257 The Security Server and STARLET on I64 provide an interesting ``test case''
26258 for source compatibility issues, since it is in such system code
26259 where assumptions about @code{Address} size might be expected to occur.
26260 Indeed, there were a small number of occasions in the Security Server
26261 file @file{jibdef.ads}
26262 where a representation clause for a record type specified
26263 32 bits for a component of type @code{Address}.
26264 All of these errors were detected by the compiler.
26265 The repair was obvious and immediate; to simply replace @code{Address} by
26266 @code{Short_Address}.
26267
26268 In the case of STARLET, there were several record types that should
26269 have had representation clauses but did not.  In these record types
26270 there was an implicit assumption that an @code{Address} value occupied
26271 32 bits.
26272 These compiled without error, but their usage resulted in run-time error
26273 returns from STARLET system calls.
26274 Future GNAT technology enhancements may include a tool that detects and flags
26275 these sorts of potential source code porting problems.
26276
26277 @c ****************************************
26278 @node Taking advantage of 64 bit addressing
26279 @subsection Taking advantage of 64-bit addressing
26280
26281 @menu
26282 * Making code 64 bit clean::
26283 * Allocating memory from the 64 bit storage pool::
26284 * Restrictions on use of 64 bit objects::
26285 * STARLET and other predefined libraries::
26286 @end menu
26287
26288 @node Making code 64 bit clean
26289 @subsubsection Making code 64-bit clean
26290
26291 @noindent
26292 In order to prevent problems that may occur when (parts of) a
26293 system start using memory outside the 32-bit address range,
26294 we recommend some additional guidelines:
26295
26296 @itemize @bullet
26297 @item
26298 For imported subprograms that take parameters of the
26299 type @code{System.Address}, ensure that these subprograms can
26300 indeed handle 64-bit addresses. If not, or when in doubt,
26301 change the subprogram declaration to specify
26302 @code{System.Short_Address} instead.
26303
26304 @item
26305 Resolve all warnings related to size mismatches in
26306 unchecked conversions. Failing to do so causes
26307 erroneous execution if the source object is outside
26308 the 32-bit address space.
26309
26310 @item
26311 (optional) Explicitly use the 32-bit storage pool
26312 for access types used in a 32-bit context, or use
26313 generic access types where possible
26314 (@pxref{Restrictions on use of 64 bit objects}).
26315 @end itemize
26316
26317 @noindent
26318 If these rules are followed, the compiler will automatically insert
26319 any necessary checks to ensure that no addresses or access values
26320 passed to 32-bit code ever refer to objects outside the 32-bit
26321 address range.
26322 Any attempt to do this will raise @code{Constraint_Error}.
26323
26324 @node Allocating memory from the 64 bit storage pool
26325 @subsubsection Allocating memory from the 64-bit storage pool
26326
26327 @noindent
26328 By default, all allocations -- for both pool-specific and general
26329 access types -- use the 64-bit storage pool.  To override
26330 this default, for an individual access type or globally, see
26331 @ref{Access types and 32/64-bit allocation}.
26332
26333 @node Restrictions on use of 64 bit objects
26334 @subsubsection Restrictions on use of 64-bit objects
26335
26336 @noindent
26337 Taking the address of an object allocated from a 64-bit storage pool,
26338 and then passing this address to a subprogram expecting
26339 @code{System.Short_Address},
26340 or assigning it to a variable of type @code{Short_Address}, will cause
26341 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26342 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26343 no exception is raised and execution
26344 will become erroneous.
26345
26346 @node STARLET and other predefined libraries
26347 @subsubsection STARLET and other predefined libraries
26348
26349 @noindent
26350 All code that comes as part of GNAT is 64-bit clean, but the
26351 restrictions given in @ref{Restrictions on use of 64 bit objects},
26352 still apply. Look at the package
26353 specs to see in which contexts objects allocated
26354 in 64-bit address space are acceptable.
26355
26356 @node Technical details
26357 @subsection Technical details
26358
26359 @noindent
26360 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26361 Ada standard with respect to the type of @code{System.Address}. Previous
26362 versions of GNAT Pro have defined this type as private and implemented it as a
26363 modular type.
26364
26365 In order to allow defining @code{System.Short_Address} as a proper subtype,
26366 and to match the implicit sign extension in parameter passing,
26367 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26368 visible (i.e., non-private) integer type.
26369 Standard operations on the type, such as the binary operators ``+'', ``-'',
26370 etc., that take @code{Address} operands and return an @code{Address} result,
26371 have been hidden by declaring these
26372 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26373 ambiguities that would otherwise result from overloading.
26374 (Note that, although @code{Address} is a visible integer type,
26375 good programming practice dictates against exploiting the type's
26376 integer properties such as literals, since this will compromise
26377 code portability.)
26378
26379 Defining @code{Address} as a visible integer type helps achieve
26380 maximum compatibility for existing Ada code,
26381 without sacrificing the capabilities of the 64-bit architecture.
26382 @end ifset
26383
26384 @c ************************************************
26385 @ifset unw
26386 @node Microsoft Windows Topics
26387 @appendix Microsoft Windows Topics
26388 @cindex Windows NT
26389 @cindex Windows 95
26390 @cindex Windows 98
26391
26392 @noindent
26393 This chapter describes topics that are specific to the Microsoft Windows
26394 platforms (NT, 2000, and XP Professional).
26395
26396 @menu
26397 * Using GNAT on Windows::
26398 * Using a network installation of GNAT::
26399 * CONSOLE and WINDOWS subsystems::
26400 * Temporary Files::
26401 * Mixed-Language Programming on Windows::
26402 * Windows Calling Conventions::
26403 * Introduction to Dynamic Link Libraries (DLLs)::
26404 * Using DLLs with GNAT::
26405 * Building DLLs with GNAT Project files::
26406 * Building DLLs with GNAT::
26407 * Building DLLs with gnatdll::
26408 * GNAT and Windows Resources::
26409 * Debugging a DLL::
26410 * Setting Stack Size from gnatlink::
26411 * Setting Heap Size from gnatlink::
26412 @end menu
26413
26414 @node Using GNAT on Windows
26415 @section Using GNAT on Windows
26416
26417 @noindent
26418 One of the strengths of the GNAT technology is that its tool set
26419 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26420 @code{gdb} debugger, etc.) is used in the same way regardless of the
26421 platform.
26422
26423 On Windows this tool set is complemented by a number of Microsoft-specific
26424 tools that have been provided to facilitate interoperability with Windows
26425 when this is required. With these tools:
26426
26427 @itemize @bullet
26428
26429 @item
26430 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26431 subsystems.
26432
26433 @item
26434 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26435 relocatable and non-relocatable DLLs are supported).
26436
26437 @item
26438 You can build Ada DLLs for use in other applications. These applications
26439 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26440 relocatable and non-relocatable Ada DLLs are supported.
26441
26442 @item
26443 You can include Windows resources in your Ada application.
26444
26445 @item
26446 You can use or create COM/DCOM objects.
26447 @end itemize
26448
26449 @noindent
26450 Immediately below are listed all known general GNAT-for-Windows restrictions.
26451 Other restrictions about specific features like Windows Resources and DLLs
26452 are listed in separate sections below.
26453
26454 @itemize @bullet
26455
26456 @item
26457 It is not possible to use @code{GetLastError} and @code{SetLastError}
26458 when tasking, protected records, or exceptions are used. In these
26459 cases, in order to implement Ada semantics, the GNAT run-time system
26460 calls certain Win32 routines that set the last error variable to 0 upon
26461 success. It should be possible to use @code{GetLastError} and
26462 @code{SetLastError} when tasking, protected record, and exception
26463 features are not used, but it is not guaranteed to work.
26464
26465 @item
26466 It is not possible to link against Microsoft libraries except for
26467 import libraries. Interfacing must be done by the mean of DLLs.
26468
26469 @item
26470 When the compilation environment is located on FAT32 drives, users may
26471 experience recompilations of the source files that have not changed if
26472 Daylight Saving Time (DST) state has changed since the last time files
26473 were compiled. NTFS drives do not have this problem.
26474
26475 @item
26476 No components of the GNAT toolset use any entries in the Windows
26477 registry. The only entries that can be created are file associations and
26478 PATH settings, provided the user has chosen to create them at installation
26479 time, as well as some minimal book-keeping information needed to correctly
26480 uninstall or integrate different GNAT products.
26481 @end itemize
26482
26483 @node Using a network installation of GNAT
26484 @section Using a network installation of GNAT
26485
26486 @noindent
26487 Make sure the system on which GNAT is installed is accessible from the
26488 current machine, i.e., the install location is shared over the network.
26489 Shared resources are accessed on Windows by means of UNC paths, which
26490 have the format @code{\\server\sharename\path}
26491
26492 In order to use such a network installation, simply add the UNC path of the
26493 @file{bin} directory of your GNAT installation in front of your PATH. For
26494 example, if GNAT is installed in @file{\GNAT} directory of a share location
26495 called @file{c-drive} on a machine @file{LOKI}, the following command will
26496 make it available:
26497
26498 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26499
26500 Be aware that every compilation using the network installation results in the
26501 transfer of large amounts of data across the network and will likely cause
26502 serious performance penalty.
26503
26504 @node CONSOLE and WINDOWS subsystems
26505 @section CONSOLE and WINDOWS subsystems
26506 @cindex CONSOLE Subsystem
26507 @cindex WINDOWS Subsystem
26508 @cindex -mwindows
26509
26510 @noindent
26511 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26512 (which is the default subsystem) will always create a console when
26513 launching the application. This is not something desirable when the
26514 application has a Windows GUI. To get rid of this console the
26515 application must be using the @code{WINDOWS} subsystem. To do so
26516 the @option{-mwindows} linker option must be specified.
26517
26518 @smallexample
26519 $ gnatmake winprog -largs -mwindows
26520 @end smallexample
26521
26522 @node Temporary Files
26523 @section Temporary Files
26524 @cindex Temporary files
26525
26526 @noindent
26527 It is possible to control where temporary files gets created by setting
26528 the @env{TMP} environment variable. The file will be created:
26529
26530 @itemize
26531 @item Under the directory pointed to by the @env{TMP} environment variable if
26532 this directory exists.
26533
26534 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26535 set (or not pointing to a directory) and if this directory exists.
26536
26537 @item Under the current working directory otherwise.
26538 @end itemize
26539
26540 @noindent
26541 This allows you to determine exactly where the temporary
26542 file will be created. This is particularly useful in networked
26543 environments where you may not have write access to some
26544 directories.
26545
26546 @node Mixed-Language Programming on Windows
26547 @section Mixed-Language Programming on Windows
26548
26549 @noindent
26550 Developing pure Ada applications on Windows is no different than on
26551 other GNAT-supported platforms. However, when developing or porting an
26552 application that contains a mix of Ada and C/C++, the choice of your
26553 Windows C/C++ development environment conditions your overall
26554 interoperability strategy.
26555
26556 If you use @command{gcc} to compile the non-Ada part of your application,
26557 there are no Windows-specific restrictions that affect the overall
26558 interoperability with your Ada code. If you do want to use the
26559 Microsoft tools for your non-Ada code, you have two choices:
26560
26561 @enumerate
26562 @item
26563 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26564 application. In this case, use the Microsoft or whatever environment to
26565 build the DLL and use GNAT to build your executable
26566 (@pxref{Using DLLs with GNAT}).
26567
26568 @item
26569 Or you can encapsulate your Ada code in a DLL to be linked with the
26570 other part of your application. In this case, use GNAT to build the DLL
26571 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
26572 or whatever environment to build your executable.
26573 @end enumerate
26574
26575 @node Windows Calling Conventions
26576 @section Windows Calling Conventions
26577 @findex Stdcall
26578 @findex APIENTRY
26579
26580 This section pertain only to Win32. On Win64 there is a single native
26581 calling convention. All convention specifiers are ignored on this
26582 platform.
26583
26584 @menu
26585 * C Calling Convention::
26586 * Stdcall Calling Convention::
26587 * Win32 Calling Convention::
26588 * DLL Calling Convention::
26589 @end menu
26590
26591 @noindent
26592 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26593 (callee), there are several ways to push @code{G}'s parameters on the
26594 stack and there are several possible scenarios to clean up the stack
26595 upon @code{G}'s return. A calling convention is an agreed upon software
26596 protocol whereby the responsibilities between the caller (@code{F}) and
26597 the callee (@code{G}) are clearly defined. Several calling conventions
26598 are available for Windows:
26599
26600 @itemize @bullet
26601 @item
26602 @code{C} (Microsoft defined)
26603
26604 @item
26605 @code{Stdcall} (Microsoft defined)
26606
26607 @item
26608 @code{Win32} (GNAT specific)
26609
26610 @item
26611 @code{DLL} (GNAT specific)
26612 @end itemize
26613
26614 @node C Calling Convention
26615 @subsection @code{C} Calling Convention
26616
26617 @noindent
26618 This is the default calling convention used when interfacing to C/C++
26619 routines compiled with either @command{gcc} or Microsoft Visual C++.
26620
26621 In the @code{C} calling convention subprogram parameters are pushed on the
26622 stack by the caller from right to left. The caller itself is in charge of
26623 cleaning up the stack after the call. In addition, the name of a routine
26624 with @code{C} calling convention is mangled by adding a leading underscore.
26625
26626 The name to use on the Ada side when importing (or exporting) a routine
26627 with @code{C} calling convention is the name of the routine. For
26628 instance the C function:
26629
26630 @smallexample
26631 int get_val (long);
26632 @end smallexample
26633
26634 @noindent
26635 should be imported from Ada as follows:
26636
26637 @smallexample @c ada
26638 @group
26639 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26640 pragma Import (C, Get_Val, External_Name => "get_val");
26641 @end group
26642 @end smallexample
26643
26644 @noindent
26645 Note that in this particular case the @code{External_Name} parameter could
26646 have been omitted since, when missing, this parameter is taken to be the
26647 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26648 is missing, as in the above example, this parameter is set to be the
26649 @code{External_Name} with a leading underscore.
26650
26651 When importing a variable defined in C, you should always use the @code{C}
26652 calling convention unless the object containing the variable is part of a
26653 DLL (in which case you should use the @code{Stdcall} calling
26654 convention, @pxref{Stdcall Calling Convention}).
26655
26656 @node Stdcall Calling Convention
26657 @subsection @code{Stdcall} Calling Convention
26658
26659 @noindent
26660 This convention, which was the calling convention used for Pascal
26661 programs, is used by Microsoft for all the routines in the Win32 API for
26662 efficiency reasons. It must be used to import any routine for which this
26663 convention was specified.
26664
26665 In the @code{Stdcall} calling convention subprogram parameters are pushed
26666 on the stack by the caller from right to left. The callee (and not the
26667 caller) is in charge of cleaning the stack on routine exit. In addition,
26668 the name of a routine with @code{Stdcall} calling convention is mangled by
26669 adding a leading underscore (as for the @code{C} calling convention) and a
26670 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
26671 bytes) of the parameters passed to the routine.
26672
26673 The name to use on the Ada side when importing a C routine with a
26674 @code{Stdcall} calling convention is the name of the C routine. The leading
26675 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
26676 the compiler. For instance the Win32 function:
26677
26678 @smallexample
26679 @b{APIENTRY} int get_val (long);
26680 @end smallexample
26681
26682 @noindent
26683 should be imported from Ada as follows:
26684
26685 @smallexample @c ada
26686 @group
26687 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26688 pragma Import (Stdcall, Get_Val);
26689 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26690 @end group
26691 @end smallexample
26692
26693 @noindent
26694 As for the @code{C} calling convention, when the @code{External_Name}
26695 parameter is missing, it is taken to be the name of the Ada entity in lower
26696 case. If instead of writing the above import pragma you write:
26697
26698 @smallexample @c ada
26699 @group
26700 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26701 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26702 @end group
26703 @end smallexample
26704
26705 @noindent
26706 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26707 of specifying the @code{External_Name} parameter you specify the
26708 @code{Link_Name} as in the following example:
26709
26710 @smallexample @c ada
26711 @group
26712 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26713 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26714 @end group
26715 @end smallexample
26716
26717 @noindent
26718 then the imported routine is @code{retrieve_val}, that is, there is no
26719 decoration at all. No leading underscore and no Stdcall suffix
26720 @code{@@}@code{@var{nn}}.
26721
26722 @noindent
26723 This is especially important as in some special cases a DLL's entry
26724 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
26725 name generated for a call has it.
26726
26727 @noindent
26728 It is also possible to import variables defined in a DLL by using an
26729 import pragma for a variable. As an example, if a DLL contains a
26730 variable defined as:
26731
26732 @smallexample
26733 int my_var;
26734 @end smallexample
26735
26736 @noindent
26737 then, to access this variable from Ada you should write:
26738
26739 @smallexample @c ada
26740 @group
26741 My_Var : Interfaces.C.int;
26742 pragma Import (Stdcall, My_Var);
26743 @end group
26744 @end smallexample
26745
26746 @noindent
26747 Note that to ease building cross-platform bindings this convention
26748 will be handled as a @code{C} calling convention on non-Windows platforms.
26749
26750 @node Win32 Calling Convention
26751 @subsection @code{Win32} Calling Convention
26752
26753 @noindent
26754 This convention, which is GNAT-specific is fully equivalent to the
26755 @code{Stdcall} calling convention described above.
26756
26757 @node DLL Calling Convention
26758 @subsection @code{DLL} Calling Convention
26759
26760 @noindent
26761 This convention, which is GNAT-specific is fully equivalent to the
26762 @code{Stdcall} calling convention described above.
26763
26764 @node Introduction to Dynamic Link Libraries (DLLs)
26765 @section Introduction to Dynamic Link Libraries (DLLs)
26766 @findex DLL
26767
26768 @noindent
26769 A Dynamically Linked Library (DLL) is a library that can be shared by
26770 several applications running under Windows. A DLL can contain any number of
26771 routines and variables.
26772
26773 One advantage of DLLs is that you can change and enhance them without
26774 forcing all the applications that depend on them to be relinked or
26775 recompiled. However, you should be aware than all calls to DLL routines are
26776 slower since, as you will understand below, such calls are indirect.
26777
26778 To illustrate the remainder of this section, suppose that an application
26779 wants to use the services of a DLL @file{API.dll}. To use the services
26780 provided by @file{API.dll} you must statically link against the DLL or
26781 an import library which contains a jump table with an entry for each
26782 routine and variable exported by the DLL. In the Microsoft world this
26783 import library is called @file{API.lib}. When using GNAT this import
26784 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
26785 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26786
26787 After you have linked your application with the DLL or the import library
26788 and you run your application, here is what happens:
26789
26790 @enumerate
26791 @item
26792 Your application is loaded into memory.
26793
26794 @item
26795 The DLL @file{API.dll} is mapped into the address space of your
26796 application. This means that:
26797
26798 @itemize @bullet
26799 @item
26800 The DLL will use the stack of the calling thread.
26801
26802 @item
26803 The DLL will use the virtual address space of the calling process.
26804
26805 @item
26806 The DLL will allocate memory from the virtual address space of the calling
26807 process.
26808
26809 @item
26810 Handles (pointers) can be safely exchanged between routines in the DLL
26811 routines and routines in the application using the DLL.
26812 @end itemize
26813
26814 @item
26815 The entries in the jump table (from the import library @file{libAPI.dll.a}
26816 or @file{API.lib} or automatically created when linking against a DLL)
26817 which is part of your application are initialized with the addresses
26818 of the routines and variables in @file{API.dll}.
26819
26820 @item
26821 If present in @file{API.dll}, routines @code{DllMain} or
26822 @code{DllMainCRTStartup} are invoked. These routines typically contain
26823 the initialization code needed for the well-being of the routines and
26824 variables exported by the DLL.
26825 @end enumerate
26826
26827 @noindent
26828 There is an additional point which is worth mentioning. In the Windows
26829 world there are two kind of DLLs: relocatable and non-relocatable
26830 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26831 in the target application address space. If the addresses of two
26832 non-relocatable DLLs overlap and these happen to be used by the same
26833 application, a conflict will occur and the application will run
26834 incorrectly. Hence, when possible, it is always preferable to use and
26835 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26836 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26837 User's Guide) removes the debugging symbols from the DLL but the DLL can
26838 still be relocated.
26839
26840 As a side note, an interesting difference between Microsoft DLLs and
26841 Unix shared libraries, is the fact that on most Unix systems all public
26842 routines are exported by default in a Unix shared library, while under
26843 Windows it is possible (but not required) to list exported routines in
26844 a definition file (@pxref{The Definition File}).
26845
26846 @node Using DLLs with GNAT
26847 @section Using DLLs with GNAT
26848
26849 @menu
26850 * Creating an Ada Spec for the DLL Services::
26851 * Creating an Import Library::
26852 @end menu
26853
26854 @noindent
26855 To use the services of a DLL, say @file{API.dll}, in your Ada application
26856 you must have:
26857
26858 @enumerate
26859 @item
26860 The Ada spec for the routines and/or variables you want to access in
26861 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26862 header files provided with the DLL.
26863
26864 @item
26865 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
26866 mentioned an import library is a statically linked library containing the
26867 import table which will be filled at load time to point to the actual
26868 @file{API.dll} routines. Sometimes you don't have an import library for the
26869 DLL you want to use. The following sections will explain how to build
26870 one. Note that this is optional.
26871
26872 @item
26873 The actual DLL, @file{API.dll}.
26874 @end enumerate
26875
26876 @noindent
26877 Once you have all the above, to compile an Ada application that uses the
26878 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26879 you simply issue the command
26880
26881 @smallexample
26882 $ gnatmake my_ada_app -largs -lAPI
26883 @end smallexample
26884
26885 @noindent
26886 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26887 tells the GNAT linker to look for an import library. The linker will
26888 look for a library name in this specific order:
26889
26890 @enumerate
26891 @item @file{libAPI.dll.a}
26892 @item @file{API.dll.a}
26893 @item @file{libAPI.a}
26894 @item @file{API.lib}
26895 @item @file{libAPI.dll}
26896 @item @file{API.dll}
26897 @end enumerate
26898
26899 The first three are the GNU style import libraries. The third is the
26900 Microsoft style import libraries. The last two are the actual DLL names.
26901
26902 Note that if the Ada package spec for @file{API.dll} contains the
26903 following pragma
26904
26905 @smallexample @c ada
26906 pragma Linker_Options ("-lAPI");
26907 @end smallexample
26908
26909 @noindent
26910 you do not have to add @option{-largs -lAPI} at the end of the
26911 @command{gnatmake} command.
26912
26913 If any one of the items above is missing you will have to create it
26914 yourself. The following sections explain how to do so using as an
26915 example a fictitious DLL called @file{API.dll}.
26916
26917 @node Creating an Ada Spec for the DLL Services
26918 @subsection Creating an Ada Spec for the DLL Services
26919
26920 @noindent
26921 A DLL typically comes with a C/C++ header file which provides the
26922 definitions of the routines and variables exported by the DLL. The Ada
26923 equivalent of this header file is a package spec that contains definitions
26924 for the imported entities. If the DLL you intend to use does not come with
26925 an Ada spec you have to generate one such spec yourself. For example if
26926 the header file of @file{API.dll} is a file @file{api.h} containing the
26927 following two definitions:
26928
26929 @smallexample
26930 @group
26931 @cartouche
26932 int some_var;
26933 int get (char *);
26934 @end cartouche
26935 @end group
26936 @end smallexample
26937
26938 @noindent
26939 then the equivalent Ada spec could be:
26940
26941 @smallexample @c ada
26942 @group
26943 @cartouche
26944 with Interfaces.C.Strings;
26945 package API is
26946    use Interfaces;
26947
26948    Some_Var : C.int;
26949    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26950
26951 private
26952    pragma Import (C, Get);
26953    pragma Import (DLL, Some_Var);
26954 end API;
26955 @end cartouche
26956 @end group
26957 @end smallexample
26958
26959 @noindent
26960 Note that a variable is
26961 @strong{always imported with a DLL convention}. A function
26962 can have @code{C} or @code{Stdcall} convention.
26963 (@pxref{Windows Calling Conventions}).
26964
26965 @node Creating an Import Library
26966 @subsection Creating an Import Library
26967 @cindex Import library
26968
26969 @menu
26970 * The Definition File::
26971 * GNAT-Style Import Library::
26972 * Microsoft-Style Import Library::
26973 @end menu
26974
26975 @noindent
26976 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26977 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
26978 with @file{API.dll} you can skip this section. You can also skip this
26979 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
26980 as in this case it is possible to link directly against the
26981 DLL. Otherwise read on.
26982
26983 @node The Definition File
26984 @subsubsection The Definition File
26985 @cindex Definition file
26986 @findex .def
26987
26988 @noindent
26989 As previously mentioned, and unlike Unix systems, the list of symbols
26990 that are exported from a DLL must be provided explicitly in Windows.
26991 The main goal of a definition file is precisely that: list the symbols
26992 exported by a DLL. A definition file (usually a file with a @code{.def}
26993 suffix) has the following structure:
26994
26995 @smallexample
26996 @group
26997 @cartouche
26998 @r{[}LIBRARY @var{name}@r{]}
26999 @r{[}DESCRIPTION @var{string}@r{]}
27000 EXPORTS
27001    @var{symbol1}
27002    @var{symbol2}
27003    @dots{}
27004 @end cartouche
27005 @end group
27006 @end smallexample
27007
27008 @table @code
27009 @item LIBRARY @var{name}
27010 This section, which is optional, gives the name of the DLL.
27011
27012 @item DESCRIPTION @var{string}
27013 This section, which is optional, gives a description string that will be
27014 embedded in the import library.
27015
27016 @item EXPORTS
27017 This section gives the list of exported symbols (procedures, functions or
27018 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27019 section of @file{API.def} looks like:
27020
27021 @smallexample
27022 @group
27023 @cartouche
27024 EXPORTS
27025    some_var
27026    get
27027 @end cartouche
27028 @end group
27029 @end smallexample
27030 @end table
27031
27032 @noindent
27033 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27034 (@pxref{Windows Calling Conventions}) for a Stdcall
27035 calling convention function in the exported symbols list.
27036
27037 @noindent
27038 There can actually be other sections in a definition file, but these
27039 sections are not relevant to the discussion at hand.
27040
27041 @node GNAT-Style Import Library
27042 @subsubsection GNAT-Style Import Library
27043
27044 @noindent
27045 To create a static import library from @file{API.dll} with the GNAT tools
27046 you should proceed as follows:
27047
27048 @enumerate
27049 @item
27050 Create the definition file @file{API.def} (@pxref{The Definition File}).
27051 For that use the @code{dll2def} tool as follows:
27052
27053 @smallexample
27054 $ dll2def API.dll > API.def
27055 @end smallexample
27056
27057 @noindent
27058 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27059 to standard output the list of entry points in the DLL. Note that if
27060 some routines in the DLL have the @code{Stdcall} convention
27061 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27062 suffix then you'll have to edit @file{api.def} to add it, and specify
27063 @option{-k} to @command{gnatdll} when creating the import library.
27064
27065 @noindent
27066 Here are some hints to find the right @code{@@}@var{nn} suffix.
27067
27068 @enumerate
27069 @item
27070 If you have the Microsoft import library (.lib), it is possible to get
27071 the right symbols by using Microsoft @code{dumpbin} tool (see the
27072 corresponding Microsoft documentation for further details).
27073
27074 @smallexample
27075 $ dumpbin /exports api.lib
27076 @end smallexample
27077
27078 @item
27079 If you have a message about a missing symbol at link time the compiler
27080 tells you what symbol is expected. You just have to go back to the
27081 definition file and add the right suffix.
27082 @end enumerate
27083
27084 @item
27085 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27086 (@pxref{Using gnatdll}) as follows:
27087
27088 @smallexample
27089 $ gnatdll -e API.def -d API.dll
27090 @end smallexample
27091
27092 @noindent
27093 @code{gnatdll} takes as input a definition file @file{API.def} and the
27094 name of the DLL containing the services listed in the definition file
27095 @file{API.dll}. The name of the static import library generated is
27096 computed from the name of the definition file as follows: if the
27097 definition file name is @var{xyz}@code{.def}, the import library name will
27098 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27099 @option{-e} could have been removed because the name of the definition
27100 file (before the ``@code{.def}'' suffix) is the same as the name of the
27101 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27102 @end enumerate
27103
27104 @node Microsoft-Style Import Library
27105 @subsubsection Microsoft-Style Import Library
27106
27107 @noindent
27108 With GNAT you can either use a GNAT-style or Microsoft-style import
27109 library. A Microsoft import library is needed only if you plan to make an
27110 Ada DLL available to applications developed with Microsoft
27111 tools (@pxref{Mixed-Language Programming on Windows}).
27112
27113 To create a Microsoft-style import library for @file{API.dll} you
27114 should proceed as follows:
27115
27116 @enumerate
27117 @item
27118 Create the definition file @file{API.def} from the DLL. For this use either
27119 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27120 tool (see the corresponding Microsoft documentation for further details).
27121
27122 @item
27123 Build the actual import library using Microsoft's @code{lib} utility:
27124
27125 @smallexample
27126 $ lib -machine:IX86 -def:API.def -out:API.lib
27127 @end smallexample
27128
27129 @noindent
27130 If you use the above command the definition file @file{API.def} must
27131 contain a line giving the name of the DLL:
27132
27133 @smallexample
27134 LIBRARY      "API"
27135 @end smallexample
27136
27137 @noindent
27138 See the Microsoft documentation for further details about the usage of
27139 @code{lib}.
27140 @end enumerate
27141
27142 @node Building DLLs with GNAT Project files
27143 @section Building DLLs with GNAT Project files
27144 @cindex DLLs, building
27145
27146 @noindent
27147 There is nothing specific to Windows in the build process.
27148 @pxref{Library Projects}.
27149
27150 @noindent
27151 Due to a system limitation, it is not possible under Windows to create threads
27152 when inside the @code{DllMain} routine which is used for auto-initialization
27153 of shared libraries, so it is not possible to have library level tasks in SALs.
27154
27155 @node Building DLLs with GNAT
27156 @section Building DLLs with GNAT
27157 @cindex DLLs, building
27158
27159 @noindent
27160 This section explain how to build DLLs using the GNAT built-in DLL
27161 support. With the following procedure it is straight forward to build
27162 and use DLLs with GNAT.
27163
27164 @enumerate
27165
27166 @item building object files
27167
27168 The first step is to build all objects files that are to be included
27169 into the DLL. This is done by using the standard @command{gnatmake} tool.
27170
27171 @item building the DLL
27172
27173 To build the DLL you must use @command{gcc}'s @option{-shared} and
27174 @option{-shared-libgcc} options. It is quite simple to use this method:
27175
27176 @smallexample
27177 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27178 @end smallexample
27179
27180 It is important to note that in this case all symbols found in the
27181 object files are automatically exported. It is possible to restrict
27182 the set of symbols to export by passing to @command{gcc} a definition
27183 file, @pxref{The Definition File}. For example:
27184
27185 @smallexample
27186 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27187 @end smallexample
27188
27189 If you use a definition file you must export the elaboration procedures
27190 for every package that required one. Elaboration procedures are named
27191 using the package name followed by "_E".
27192
27193 @item preparing DLL to be used
27194
27195 For the DLL to be used by client programs the bodies must be hidden
27196 from it and the .ali set with read-only attribute. This is very important
27197 otherwise GNAT will recompile all packages and will not actually use
27198 the code in the DLL. For example:
27199
27200 @smallexample
27201 $ mkdir apilib
27202 $ copy *.ads *.ali api.dll apilib
27203 $ attrib +R apilib\*.ali
27204 @end smallexample
27205
27206 @end enumerate
27207
27208 At this point it is possible to use the DLL by directly linking
27209 against it. Note that you must use the GNAT shared runtime when using
27210 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27211 option.
27212
27213 @smallexample
27214 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27215 @end smallexample
27216
27217 @node Building DLLs with gnatdll
27218 @section Building DLLs with gnatdll
27219 @cindex DLLs, building
27220
27221 @menu
27222 * Limitations When Using Ada DLLs from Ada::
27223 * Exporting Ada Entities::
27224 * Ada DLLs and Elaboration::
27225 * Ada DLLs and Finalization::
27226 * Creating a Spec for Ada DLLs::
27227 * Creating the Definition File::
27228 * Using gnatdll::
27229 @end menu
27230
27231 @noindent
27232 Note that it is preferred to use GNAT Project files
27233 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27234 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27235
27236 This section explains how to build DLLs containing Ada code using
27237 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27238 remainder of this section.
27239
27240 The steps required to build an Ada DLL that is to be used by Ada as well as
27241 non-Ada applications are as follows:
27242
27243 @enumerate
27244 @item
27245 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27246 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27247 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27248 skip this step if you plan to use the Ada DLL only from Ada applications.
27249
27250 @item
27251 Your Ada code must export an initialization routine which calls the routine
27252 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27253 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27254 routine exported by the Ada DLL must be invoked by the clients of the DLL
27255 to initialize the DLL.
27256
27257 @item
27258 When useful, the DLL should also export a finalization routine which calls
27259 routine @code{adafinal} generated by @command{gnatbind} to perform the
27260 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27261 The finalization routine exported by the Ada DLL must be invoked by the
27262 clients of the DLL when the DLL services are no further needed.
27263
27264 @item
27265 You must provide a spec for the services exported by the Ada DLL in each
27266 of the programming languages to which you plan to make the DLL available.
27267
27268 @item
27269 You must provide a definition file listing the exported entities
27270 (@pxref{The Definition File}).
27271
27272 @item
27273 Finally you must use @code{gnatdll} to produce the DLL and the import
27274 library (@pxref{Using gnatdll}).
27275 @end enumerate
27276
27277 @noindent
27278 Note that a relocatable DLL stripped using the @code{strip}
27279 binutils tool will not be relocatable anymore. To build a DLL without
27280 debug information pass @code{-largs -s} to @code{gnatdll}. This
27281 restriction does not apply to a DLL built using a Library Project.
27282 @pxref{Library Projects}.
27283
27284 @node Limitations When Using Ada DLLs from Ada
27285 @subsection Limitations When Using Ada DLLs from Ada
27286
27287 @noindent
27288 When using Ada DLLs from Ada applications there is a limitation users
27289 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27290 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27291 each Ada DLL includes the services of the GNAT run time that are necessary
27292 to the Ada code inside the DLL. As a result, when an Ada program uses an
27293 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27294 one in the main program.
27295
27296 It is therefore not possible to exchange GNAT run-time objects between the
27297 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27298 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27299 types, etc.
27300
27301 It is completely safe to exchange plain elementary, array or record types,
27302 Windows object handles, etc.
27303
27304 @node Exporting Ada Entities
27305 @subsection Exporting Ada Entities
27306 @cindex Export table
27307
27308 @noindent
27309 Building a DLL is a way to encapsulate a set of services usable from any
27310 application. As a result, the Ada entities exported by a DLL should be
27311 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27312 any Ada name mangling. As an example here is an Ada package
27313 @code{API}, spec and body, exporting two procedures, a function, and a
27314 variable:
27315
27316 @smallexample @c ada
27317 @group
27318 @cartouche
27319 with Interfaces.C; use Interfaces;
27320 package API is
27321    Count : C.int := 0;
27322    function Factorial (Val : C.int) return C.int;
27323
27324    procedure Initialize_API;
27325    procedure Finalize_API;
27326    --  Initialization & Finalization routines. More in the next section.
27327 private
27328    pragma Export (C, Initialize_API);
27329    pragma Export (C, Finalize_API);
27330    pragma Export (C, Count);
27331    pragma Export (C, Factorial);
27332 end API;
27333 @end cartouche
27334 @end group
27335 @end smallexample
27336
27337 @smallexample @c ada
27338 @group
27339 @cartouche
27340 package body API is
27341    function Factorial (Val : C.int) return C.int is
27342       Fact : C.int := 1;
27343    begin
27344       Count := Count + 1;
27345       for K in 1 .. Val loop
27346          Fact := Fact * K;
27347       end loop;
27348       return Fact;
27349    end Factorial;
27350
27351    procedure Initialize_API is
27352       procedure Adainit;
27353       pragma Import (C, Adainit);
27354    begin
27355       Adainit;
27356    end Initialize_API;
27357
27358    procedure Finalize_API is
27359       procedure Adafinal;
27360       pragma Import (C, Adafinal);
27361    begin
27362       Adafinal;
27363    end Finalize_API;
27364 end API;
27365 @end cartouche
27366 @end group
27367 @end smallexample
27368
27369 @noindent
27370 If the Ada DLL you are building will only be used by Ada applications
27371 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27372 convention. As an example, the previous package could be written as
27373 follows:
27374
27375 @smallexample @c ada
27376 @group
27377 @cartouche
27378 package API is
27379    Count : Integer := 0;
27380    function Factorial (Val : Integer) return Integer;
27381
27382    procedure Initialize_API;
27383    procedure Finalize_API;
27384    --  Initialization and Finalization routines.
27385 end API;
27386 @end cartouche
27387 @end group
27388 @end smallexample
27389
27390 @smallexample @c ada
27391 @group
27392 @cartouche
27393 package body API is
27394    function Factorial (Val : Integer) return Integer is
27395       Fact : Integer := 1;
27396    begin
27397       Count := Count + 1;
27398       for K in 1 .. Val loop
27399          Fact := Fact * K;
27400       end loop;
27401       return Fact;
27402    end Factorial;
27403
27404    @dots{}
27405    --  The remainder of this package body is unchanged.
27406 end API;
27407 @end cartouche
27408 @end group
27409 @end smallexample
27410
27411 @noindent
27412 Note that if you do not export the Ada entities with a @code{C} or
27413 @code{Stdcall} convention you will have to provide the mangled Ada names
27414 in the definition file of the Ada DLL
27415 (@pxref{Creating the Definition File}).
27416
27417 @node Ada DLLs and Elaboration
27418 @subsection Ada DLLs and Elaboration
27419 @cindex DLLs and elaboration
27420
27421 @noindent
27422 The DLL that you are building contains your Ada code as well as all the
27423 routines in the Ada library that are needed by it. The first thing a
27424 user of your DLL must do is elaborate the Ada code
27425 (@pxref{Elaboration Order Handling in GNAT}).
27426
27427 To achieve this you must export an initialization routine
27428 (@code{Initialize_API} in the previous example), which must be invoked
27429 before using any of the DLL services. This elaboration routine must call
27430 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27431 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27432 @code{Initialize_Api} for an example. Note that the GNAT binder is
27433 automatically invoked during the DLL build process by the @code{gnatdll}
27434 tool (@pxref{Using gnatdll}).
27435
27436 When a DLL is loaded, Windows systematically invokes a routine called
27437 @code{DllMain}. It would therefore be possible to call @code{adainit}
27438 directly from @code{DllMain} without having to provide an explicit
27439 initialization routine. Unfortunately, it is not possible to call
27440 @code{adainit} from the @code{DllMain} if your program has library level
27441 tasks because access to the @code{DllMain} entry point is serialized by
27442 the system (that is, only a single thread can execute ``through'' it at a
27443 time), which means that the GNAT run time will deadlock waiting for the
27444 newly created task to complete its initialization.
27445
27446 @node Ada DLLs and Finalization
27447 @subsection Ada DLLs and Finalization
27448 @cindex DLLs and finalization
27449
27450 @noindent
27451 When the services of an Ada DLL are no longer needed, the client code should
27452 invoke the DLL finalization routine, if available. The DLL finalization
27453 routine is in charge of releasing all resources acquired by the DLL. In the
27454 case of the Ada code contained in the DLL, this is achieved by calling
27455 routine @code{adafinal} generated by the GNAT binder
27456 (@pxref{Binding with Non-Ada Main Programs}).
27457 See the body of @code{Finalize_Api} for an
27458 example. As already pointed out the GNAT binder is automatically invoked
27459 during the DLL build process by the @code{gnatdll} tool
27460 (@pxref{Using gnatdll}).
27461
27462 @node Creating a Spec for Ada DLLs
27463 @subsection Creating a Spec for Ada DLLs
27464
27465 @noindent
27466 To use the services exported by the Ada DLL from another programming
27467 language (e.g.@: C), you have to translate the specs of the exported Ada
27468 entities in that language. For instance in the case of @code{API.dll},
27469 the corresponding C header file could look like:
27470
27471 @smallexample
27472 @group
27473 @cartouche
27474 extern int *_imp__count;
27475 #define count (*_imp__count)
27476 int factorial (int);
27477 @end cartouche
27478 @end group
27479 @end smallexample
27480
27481 @noindent
27482 It is important to understand that when building an Ada DLL to be used by
27483 other Ada applications, you need two different specs for the packages
27484 contained in the DLL: one for building the DLL and the other for using
27485 the DLL. This is because the @code{DLL} calling convention is needed to
27486 use a variable defined in a DLL, but when building the DLL, the variable
27487 must have either the @code{Ada} or @code{C} calling convention. As an
27488 example consider a DLL comprising the following package @code{API}:
27489
27490 @smallexample @c ada
27491 @group
27492 @cartouche
27493 package API is
27494    Count : Integer := 0;
27495    @dots{}
27496    --  Remainder of the package omitted.
27497 end API;
27498 @end cartouche
27499 @end group
27500 @end smallexample
27501
27502 @noindent
27503 After producing a DLL containing package @code{API}, the spec that
27504 must be used to import @code{API.Count} from Ada code outside of the
27505 DLL is:
27506
27507 @smallexample @c ada
27508 @group
27509 @cartouche
27510 package API is
27511    Count : Integer;
27512    pragma Import (DLL, Count);
27513 end API;
27514 @end cartouche
27515 @end group
27516 @end smallexample
27517
27518 @node Creating the Definition File
27519 @subsection Creating the Definition File
27520
27521 @noindent
27522 The definition file is the last file needed to build the DLL. It lists
27523 the exported symbols. As an example, the definition file for a DLL
27524 containing only package @code{API} (where all the entities are exported
27525 with a @code{C} calling convention) is:
27526
27527 @smallexample
27528 @group
27529 @cartouche
27530 EXPORTS
27531     count
27532     factorial
27533     finalize_api
27534     initialize_api
27535 @end cartouche
27536 @end group
27537 @end smallexample
27538
27539 @noindent
27540 If the @code{C} calling convention is missing from package @code{API},
27541 then the definition file contains the mangled Ada names of the above
27542 entities, which in this case are:
27543
27544 @smallexample
27545 @group
27546 @cartouche
27547 EXPORTS
27548     api__count
27549     api__factorial
27550     api__finalize_api
27551     api__initialize_api
27552 @end cartouche
27553 @end group
27554 @end smallexample
27555
27556 @node Using gnatdll
27557 @subsection Using @code{gnatdll}
27558 @findex gnatdll
27559
27560 @menu
27561 * gnatdll Example::
27562 * gnatdll behind the Scenes::
27563 * Using dlltool::
27564 @end menu
27565
27566 @noindent
27567 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27568 and non-Ada sources that make up your DLL have been compiled.
27569 @code{gnatdll} is actually in charge of two distinct tasks: build the
27570 static import library for the DLL and the actual DLL. The form of the
27571 @code{gnatdll} command is
27572
27573 @smallexample
27574 @cartouche
27575 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27576 @c Expanding @ovar macro inline (explanation in macro def comments)
27577 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27578 @end cartouche
27579 @end smallexample
27580
27581 @noindent
27582 where @var{list-of-files} is a list of ALI and object files. The object
27583 file list must be the exact list of objects corresponding to the non-Ada
27584 sources whose services are to be included in the DLL. The ALI file list
27585 must be the exact list of ALI files for the corresponding Ada sources
27586 whose services are to be included in the DLL. If @var{list-of-files} is
27587 missing, only the static import library is generated.
27588
27589 @noindent
27590 You may specify any of the following switches to @code{gnatdll}:
27591
27592 @table @code
27593 @c @item -a@ovar{address}
27594 @c Expanding @ovar macro inline (explanation in macro def comments)
27595 @item -a@r{[}@var{address}@r{]}
27596 @cindex @option{-a} (@code{gnatdll})
27597 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27598 specified the default address @var{0x11000000} will be used. By default,
27599 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27600 advise the reader to build relocatable DLL.
27601
27602 @item -b @var{address}
27603 @cindex @option{-b} (@code{gnatdll})
27604 Set the relocatable DLL base address. By default the address is
27605 @code{0x11000000}.
27606
27607 @item -bargs @var{opts}
27608 @cindex @option{-bargs} (@code{gnatdll})
27609 Binder options. Pass @var{opts} to the binder.
27610
27611 @item -d @var{dllfile}
27612 @cindex @option{-d} (@code{gnatdll})
27613 @var{dllfile} is the name of the DLL. This switch must be present for
27614 @code{gnatdll} to do anything. The name of the generated import library is
27615 obtained algorithmically from @var{dllfile} as shown in the following
27616 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27617 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
27618 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27619 as shown in the following example:
27620 if @var{dllfile} is @code{xyz.dll}, the definition
27621 file used is @code{xyz.def}.
27622
27623 @item -e @var{deffile}
27624 @cindex @option{-e} (@code{gnatdll})
27625 @var{deffile} is the name of the definition file.
27626
27627 @item -g
27628 @cindex @option{-g} (@code{gnatdll})
27629 Generate debugging information. This information is stored in the object
27630 file and copied from there to the final DLL file by the linker,
27631 where it can be read by the debugger. You must use the
27632 @option{-g} switch if you plan on using the debugger or the symbolic
27633 stack traceback.
27634
27635 @item -h
27636 @cindex @option{-h} (@code{gnatdll})
27637 Help mode. Displays @code{gnatdll} switch usage information.
27638
27639 @item -Idir
27640 @cindex @option{-I} (@code{gnatdll})
27641 Direct @code{gnatdll} to search the @var{dir} directory for source and
27642 object files needed to build the DLL.
27643 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27644
27645 @item -k
27646 @cindex @option{-k} (@code{gnatdll})
27647 Removes the @code{@@}@var{nn} suffix from the import library's exported
27648 names, but keeps them for the link names. You must specify this
27649 option if you want to use a @code{Stdcall} function in a DLL for which
27650 the @code{@@}@var{nn} suffix has been removed. This is the case for most
27651 of the Windows NT DLL for example. This option has no effect when
27652 @option{-n} option is specified.
27653
27654 @item -l @var{file}
27655 @cindex @option{-l} (@code{gnatdll})
27656 The list of ALI and object files used to build the DLL are listed in
27657 @var{file}, instead of being given in the command line. Each line in
27658 @var{file} contains the name of an ALI or object file.
27659
27660 @item -n
27661 @cindex @option{-n} (@code{gnatdll})
27662 No Import. Do not create the import library.
27663
27664 @item -q
27665 @cindex @option{-q} (@code{gnatdll})
27666 Quiet mode. Do not display unnecessary messages.
27667
27668 @item -v
27669 @cindex @option{-v} (@code{gnatdll})
27670 Verbose mode. Display extra information.
27671
27672 @item -largs @var{opts}
27673 @cindex @option{-largs} (@code{gnatdll})
27674 Linker options. Pass @var{opts} to the linker.
27675 @end table
27676
27677 @node gnatdll Example
27678 @subsubsection @code{gnatdll} Example
27679
27680 @noindent
27681 As an example the command to build a relocatable DLL from @file{api.adb}
27682 once @file{api.adb} has been compiled and @file{api.def} created is
27683
27684 @smallexample
27685 $ gnatdll -d api.dll api.ali
27686 @end smallexample
27687
27688 @noindent
27689 The above command creates two files: @file{libapi.dll.a} (the import
27690 library) and @file{api.dll} (the actual DLL). If you want to create
27691 only the DLL, just type:
27692
27693 @smallexample
27694 $ gnatdll -d api.dll -n api.ali
27695 @end smallexample
27696
27697 @noindent
27698 Alternatively if you want to create just the import library, type:
27699
27700 @smallexample
27701 $ gnatdll -d api.dll
27702 @end smallexample
27703
27704 @node gnatdll behind the Scenes
27705 @subsubsection @code{gnatdll} behind the Scenes
27706
27707 @noindent
27708 This section details the steps involved in creating a DLL. @code{gnatdll}
27709 does these steps for you. Unless you are interested in understanding what
27710 goes on behind the scenes, you should skip this section.
27711
27712 We use the previous example of a DLL containing the Ada package @code{API},
27713 to illustrate the steps necessary to build a DLL. The starting point is a
27714 set of objects that will make up the DLL and the corresponding ALI
27715 files. In the case of this example this means that @file{api.o} and
27716 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27717 the following:
27718
27719 @enumerate
27720 @item
27721 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27722 the information necessary to generate relocation information for the
27723 DLL.
27724
27725 @smallexample
27726 @group
27727 $ gnatbind -n api
27728 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27729 @end group
27730 @end smallexample
27731
27732 @noindent
27733 In addition to the base file, the @command{gnatlink} command generates an
27734 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27735 asks @command{gnatlink} to generate the routines @code{DllMain} and
27736 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27737 is loaded into memory.
27738
27739 @item
27740 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27741 export table (@file{api.exp}). The export table contains the relocation
27742 information in a form which can be used during the final link to ensure
27743 that the Windows loader is able to place the DLL anywhere in memory.
27744
27745 @smallexample
27746 @group
27747 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27748           --output-exp api.exp
27749 @end group
27750 @end smallexample
27751
27752 @item
27753 @code{gnatdll} builds the base file using the new export table. Note that
27754 @command{gnatbind} must be called once again since the binder generated file
27755 has been deleted during the previous call to @command{gnatlink}.
27756
27757 @smallexample
27758 @group
27759 $ gnatbind -n api
27760 $ gnatlink api -o api.jnk api.exp -mdll
27761       -Wl,--base-file,api.base
27762 @end group
27763 @end smallexample
27764
27765 @item
27766 @code{gnatdll} builds the new export table using the new base file and
27767 generates the DLL import library @file{libAPI.dll.a}.
27768
27769 @smallexample
27770 @group
27771 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27772           --output-exp api.exp --output-lib libAPI.a
27773 @end group
27774 @end smallexample
27775
27776 @item
27777 Finally @code{gnatdll} builds the relocatable DLL using the final export
27778 table.
27779
27780 @smallexample
27781 @group
27782 $ gnatbind -n api
27783 $ gnatlink api api.exp -o api.dll -mdll
27784 @end group
27785 @end smallexample
27786 @end enumerate
27787
27788 @node Using dlltool
27789 @subsubsection Using @code{dlltool}
27790
27791 @noindent
27792 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27793 DLLs and static import libraries. This section summarizes the most
27794 common @code{dlltool} switches. The form of the @code{dlltool} command
27795 is
27796
27797 @smallexample
27798 @c $ dlltool @ovar{switches}
27799 @c Expanding @ovar macro inline (explanation in macro def comments)
27800 $ dlltool @r{[}@var{switches}@r{]}
27801 @end smallexample
27802
27803 @noindent
27804 @code{dlltool} switches include:
27805
27806 @table @option
27807 @item --base-file @var{basefile}
27808 @cindex @option{--base-file} (@command{dlltool})
27809 Read the base file @var{basefile} generated by the linker. This switch
27810 is used to create a relocatable DLL.
27811
27812 @item --def @var{deffile}
27813 @cindex @option{--def} (@command{dlltool})
27814 Read the definition file.
27815
27816 @item --dllname @var{name}
27817 @cindex @option{--dllname} (@command{dlltool})
27818 Gives the name of the DLL. This switch is used to embed the name of the
27819 DLL in the static import library generated by @code{dlltool} with switch
27820 @option{--output-lib}.
27821
27822 @item -k
27823 @cindex @option{-k} (@command{dlltool})
27824 Kill @code{@@}@var{nn} from exported names
27825 (@pxref{Windows Calling Conventions}
27826 for a discussion about @code{Stdcall}-style symbols.
27827
27828 @item --help
27829 @cindex @option{--help} (@command{dlltool})
27830 Prints the @code{dlltool} switches with a concise description.
27831
27832 @item --output-exp @var{exportfile}
27833 @cindex @option{--output-exp} (@command{dlltool})
27834 Generate an export file @var{exportfile}. The export file contains the
27835 export table (list of symbols in the DLL) and is used to create the DLL.
27836
27837 @item --output-lib @var{libfile}
27838 @cindex @option{--output-lib} (@command{dlltool})
27839 Generate a static import library @var{libfile}.
27840
27841 @item -v
27842 @cindex @option{-v} (@command{dlltool})
27843 Verbose mode.
27844
27845 @item --as @var{assembler-name}
27846 @cindex @option{--as} (@command{dlltool})
27847 Use @var{assembler-name} as the assembler. The default is @code{as}.
27848 @end table
27849
27850 @node GNAT and Windows Resources
27851 @section GNAT and Windows Resources
27852 @cindex Resources, windows
27853
27854 @menu
27855 * Building Resources::
27856 * Compiling Resources::
27857 * Using Resources::
27858 @end menu
27859
27860 @noindent
27861 Resources are an easy way to add Windows specific objects to your
27862 application. The objects that can be added as resources include:
27863
27864 @itemize @bullet
27865 @item menus
27866
27867 @item accelerators
27868
27869 @item dialog boxes
27870
27871 @item string tables
27872
27873 @item bitmaps
27874
27875 @item cursors
27876
27877 @item icons
27878
27879 @item fonts
27880
27881 @item version information
27882 @end itemize
27883
27884 For example, a version information resource can be defined as follow and
27885 embedded into an executable or DLL:
27886
27887 A version information resource can be used to embed information into an
27888 executable or a DLL. These information can be viewed using the file properties
27889 from the Windows Explorer. Here is an example of a version information
27890 resource:
27891
27892 @smallexample
27893 @group
27894 1 VERSIONINFO
27895 FILEVERSION     1,0,0,0
27896 PRODUCTVERSION  1,0,0,0
27897 BEGIN
27898   BLOCK "StringFileInfo"
27899   BEGIN
27900     BLOCK "080904E4"
27901     BEGIN
27902       VALUE "CompanyName", "My Company Name"
27903       VALUE "FileDescription", "My application"
27904       VALUE "FileVersion", "1.0"
27905       VALUE "InternalName", "my_app"
27906       VALUE "LegalCopyright", "My Name"
27907       VALUE "OriginalFilename", "my_app.exe"
27908       VALUE "ProductName", "My App"
27909       VALUE "ProductVersion", "1.0"
27910     END
27911   END
27912
27913   BLOCK "VarFileInfo"
27914   BEGIN
27915     VALUE "Translation", 0x809, 1252
27916   END
27917 END
27918 @end group
27919 @end smallexample
27920
27921 The value @code{0809} (langID) is for the U.K English language and
27922 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
27923 multilingual.
27924
27925 @noindent
27926 This section explains how to build, compile and use resources. Note that this
27927 section does not cover all resource objects, for a complete description see
27928 the corresponding Microsoft documentation.
27929
27930 @node Building Resources
27931 @subsection Building Resources
27932 @cindex Resources, building
27933
27934 @noindent
27935 A resource file is an ASCII file. By convention resource files have an
27936 @file{.rc} extension.
27937 The easiest way to build a resource file is to use Microsoft tools
27938 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27939 @code{dlgedit.exe} to build dialogs.
27940 It is always possible to build an @file{.rc} file yourself by writing a
27941 resource script.
27942
27943 It is not our objective to explain how to write a resource file. A
27944 complete description of the resource script language can be found in the
27945 Microsoft documentation.
27946
27947 @node Compiling Resources
27948 @subsection Compiling Resources
27949 @findex rc
27950 @findex windres
27951 @cindex Resources, compiling
27952
27953 @noindent
27954 This section describes how to build a GNAT-compatible (COFF) object file
27955 containing the resources. This is done using the Resource Compiler
27956 @code{windres} as follows:
27957
27958 @smallexample
27959 $ windres -i myres.rc -o myres.o
27960 @end smallexample
27961
27962 @noindent
27963 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27964 file. You can specify an alternate preprocessor (usually named
27965 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27966 parameter. A list of all possible options may be obtained by entering
27967 the command @code{windres} @option{--help}.
27968
27969 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27970 to produce a @file{.res} file (binary resource file). See the
27971 corresponding Microsoft documentation for further details. In this case
27972 you need to use @code{windres} to translate the @file{.res} file to a
27973 GNAT-compatible object file as follows:
27974
27975 @smallexample
27976 $ windres -i myres.res -o myres.o
27977 @end smallexample
27978
27979 @node Using Resources
27980 @subsection Using Resources
27981 @cindex Resources, using
27982
27983 @noindent
27984 To include the resource file in your program just add the
27985 GNAT-compatible object file for the resource(s) to the linker
27986 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27987 option:
27988
27989 @smallexample
27990 $ gnatmake myprog -largs myres.o
27991 @end smallexample
27992
27993 @node Debugging a DLL
27994 @section Debugging a DLL
27995 @cindex DLL debugging
27996
27997 @menu
27998 * Program and DLL Both Built with GCC/GNAT::
27999 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28000 @end menu
28001
28002 @noindent
28003 Debugging a DLL is similar to debugging a standard program. But
28004 we have to deal with two different executable parts: the DLL and the
28005 program that uses it. We have the following four possibilities:
28006
28007 @enumerate 1
28008 @item
28009 The program and the DLL are built with @code{GCC/GNAT}.
28010 @item
28011 The program is built with foreign tools and the DLL is built with
28012 @code{GCC/GNAT}.
28013 @item
28014 The program is built with @code{GCC/GNAT} and the DLL is built with
28015 foreign tools.
28016 @end enumerate
28017
28018 @noindent
28019 In this section we address only cases one and two above.
28020 There is no point in trying to debug
28021 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28022 information in it. To do so you must use a debugger compatible with the
28023 tools suite used to build the DLL.
28024
28025 @node Program and DLL Both Built with GCC/GNAT
28026 @subsection Program and DLL Both Built with GCC/GNAT
28027
28028 @noindent
28029 This is the simplest case. Both the DLL and the program have @code{GDB}
28030 compatible debugging information. It is then possible to break anywhere in
28031 the process. Let's suppose here that the main procedure is named
28032 @code{ada_main} and that in the DLL there is an entry point named
28033 @code{ada_dll}.
28034
28035 @noindent
28036 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28037 program must have been built with the debugging information (see GNAT -g
28038 switch). Here are the step-by-step instructions for debugging it:
28039
28040 @enumerate 1
28041 @item Launch @code{GDB} on the main program.
28042
28043 @smallexample
28044 $ gdb -nw ada_main
28045 @end smallexample
28046
28047 @item Start the program and stop at the beginning of the main procedure
28048
28049 @smallexample
28050 (gdb) start
28051 @end smallexample
28052
28053 @noindent
28054 This step is required to be able to set a breakpoint inside the DLL. As long
28055 as the program is not run, the DLL is not loaded. This has the
28056 consequence that the DLL debugging information is also not loaded, so it is not
28057 possible to set a breakpoint in the DLL.
28058
28059 @item Set a breakpoint inside the DLL
28060
28061 @smallexample
28062 (gdb) break ada_dll
28063 (gdb) cont
28064 @end smallexample
28065
28066 @end enumerate
28067
28068 @noindent
28069 At this stage a breakpoint is set inside the DLL. From there on
28070 you can use the standard approach to debug the whole program
28071 (@pxref{Running and Debugging Ada Programs}).
28072
28073 @ignore
28074 @c This used to work, probably because the DLLs were non-relocatable
28075 @c keep this section around until the problem is sorted out.
28076
28077 To break on the @code{DllMain} routine it is not possible to follow
28078 the procedure above. At the time the program stop on @code{ada_main}
28079 the @code{DllMain} routine as already been called. Either you can use
28080 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28081
28082 @enumerate 1
28083 @item Launch @code{GDB} on the main program.
28084
28085 @smallexample
28086 $ gdb ada_main
28087 @end smallexample
28088
28089 @item Load DLL symbols
28090
28091 @smallexample
28092 (gdb) add-sym api.dll
28093 @end smallexample
28094
28095 @item Set a breakpoint inside the DLL
28096
28097 @smallexample
28098 (gdb) break ada_dll.adb:45
28099 @end smallexample
28100
28101 Note that at this point it is not possible to break using the routine symbol
28102 directly as the program is not yet running. The solution is to break
28103 on the proper line (break in @file{ada_dll.adb} line 45).
28104
28105 @item Start the program
28106
28107 @smallexample
28108 (gdb) run
28109 @end smallexample
28110
28111 @end enumerate
28112 @end ignore
28113
28114 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28115 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28116
28117 @menu
28118 * Debugging the DLL Directly::
28119 * Attaching to a Running Process::
28120 @end menu
28121
28122 @noindent
28123 In this case things are slightly more complex because it is not possible to
28124 start the main program and then break at the beginning to load the DLL and the
28125 associated DLL debugging information. It is not possible to break at the
28126 beginning of the program because there is no @code{GDB} debugging information,
28127 and therefore there is no direct way of getting initial control. This
28128 section addresses this issue by describing some methods that can be used
28129 to break somewhere in the DLL to debug it.
28130
28131 @noindent
28132 First suppose that the main procedure is named @code{main} (this is for
28133 example some C code built with Microsoft Visual C) and that there is a
28134 DLL named @code{test.dll} containing an Ada entry point named
28135 @code{ada_dll}.
28136
28137 @noindent
28138 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28139 been built with debugging information (see GNAT -g option).
28140
28141 @node Debugging the DLL Directly
28142 @subsubsection Debugging the DLL Directly
28143
28144 @enumerate 1
28145 @item
28146 Find out the executable starting address
28147
28148 @smallexample
28149 $ objdump --file-header main.exe
28150 @end smallexample
28151
28152 The starting address is reported on the last line. For example:
28153
28154 @smallexample
28155 main.exe:     file format pei-i386
28156 architecture: i386, flags 0x0000010a:
28157 EXEC_P, HAS_DEBUG, D_PAGED
28158 start address 0x00401010
28159 @end smallexample
28160
28161 @item
28162 Launch the debugger on the executable.
28163
28164 @smallexample
28165 $ gdb main.exe
28166 @end smallexample
28167
28168 @item
28169 Set a breakpoint at the starting address, and launch the program.
28170
28171 @smallexample
28172 $ (gdb) break *0x00401010
28173 $ (gdb) run
28174 @end smallexample
28175
28176 The program will stop at the given address.
28177
28178 @item
28179 Set a breakpoint on a DLL subroutine.
28180
28181 @smallexample
28182 (gdb) break ada_dll.adb:45
28183 @end smallexample
28184
28185 Or if you want to break using a symbol on the DLL, you need first to
28186 select the Ada language (language used by the DLL).
28187
28188 @smallexample
28189 (gdb) set language ada
28190 (gdb) break ada_dll
28191 @end smallexample
28192
28193 @item
28194 Continue the program.
28195
28196 @smallexample
28197 (gdb) cont
28198 @end smallexample
28199
28200 @noindent
28201 This will run the program until it reaches the breakpoint that has been
28202 set. From that point you can use the standard way to debug a program
28203 as described in (@pxref{Running and Debugging Ada Programs}).
28204
28205 @end enumerate
28206
28207 @noindent
28208 It is also possible to debug the DLL by attaching to a running process.
28209
28210 @node Attaching to a Running Process
28211 @subsubsection Attaching to a Running Process
28212 @cindex DLL debugging, attach to process
28213
28214 @noindent
28215 With @code{GDB} it is always possible to debug a running process by
28216 attaching to it. It is possible to debug a DLL this way. The limitation
28217 of this approach is that the DLL must run long enough to perform the
28218 attach operation. It may be useful for instance to insert a time wasting
28219 loop in the code of the DLL to meet this criterion.
28220
28221 @enumerate 1
28222
28223 @item Launch the main program @file{main.exe}.
28224
28225 @smallexample
28226 $ main
28227 @end smallexample
28228
28229 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28230 that the process PID for @file{main.exe} is 208.
28231
28232 @item Launch gdb.
28233
28234 @smallexample
28235 $ gdb
28236 @end smallexample
28237
28238 @item Attach to the running process to be debugged.
28239
28240 @smallexample
28241 (gdb) attach 208
28242 @end smallexample
28243
28244 @item Load the process debugging information.
28245
28246 @smallexample
28247 (gdb) symbol-file main.exe
28248 @end smallexample
28249
28250 @item Break somewhere in the DLL.
28251
28252 @smallexample
28253 (gdb) break ada_dll
28254 @end smallexample
28255
28256 @item Continue process execution.
28257
28258 @smallexample
28259 (gdb) cont
28260 @end smallexample
28261
28262 @end enumerate
28263
28264 @noindent
28265 This last step will resume the process execution, and stop at
28266 the breakpoint we have set. From there you can use the standard
28267 approach to debug a program as described in
28268 (@pxref{Running and Debugging Ada Programs}).
28269
28270 @node Setting Stack Size from gnatlink
28271 @section Setting Stack Size from @command{gnatlink}
28272
28273 @noindent
28274 It is possible to specify the program stack size at link time. On modern
28275 versions of Windows, starting with XP, this is mostly useful to set the size of
28276 the main stack (environment task). The other task stacks are set with pragma
28277 Storage_Size or with the @command{gnatbind -d} command.
28278
28279 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28280 reserve size of individual tasks, the link-time stack size applies to all
28281 tasks, and pragma Storage_Size has no effect.
28282 In particular, Stack Overflow checks are made against this
28283 link-time specified size.
28284
28285 This setting can be done with
28286 @command{gnatlink} using either:
28287
28288 @itemize @bullet
28289
28290 @item using @option{-Xlinker} linker option
28291
28292 @smallexample
28293 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28294 @end smallexample
28295
28296 This sets the stack reserve size to 0x10000 bytes and the stack commit
28297 size to 0x1000 bytes.
28298
28299 @item using @option{-Wl} linker option
28300
28301 @smallexample
28302 $ gnatlink hello -Wl,--stack=0x1000000
28303 @end smallexample
28304
28305 This sets the stack reserve size to 0x1000000 bytes. Note that with
28306 @option{-Wl} option it is not possible to set the stack commit size
28307 because the coma is a separator for this option.
28308
28309 @end itemize
28310
28311 @node Setting Heap Size from gnatlink
28312 @section Setting Heap Size from @command{gnatlink}
28313
28314 @noindent
28315 Under Windows systems, it is possible to specify the program heap size from
28316 @command{gnatlink} using either:
28317
28318 @itemize @bullet
28319
28320 @item using @option{-Xlinker} linker option
28321
28322 @smallexample
28323 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28324 @end smallexample
28325
28326 This sets the heap reserve size to 0x10000 bytes and the heap commit
28327 size to 0x1000 bytes.
28328
28329 @item using @option{-Wl} linker option
28330
28331 @smallexample
28332 $ gnatlink hello -Wl,--heap=0x1000000
28333 @end smallexample
28334
28335 This sets the heap reserve size to 0x1000000 bytes. Note that with
28336 @option{-Wl} option it is not possible to set the heap commit size
28337 because the coma is a separator for this option.
28338
28339 @end itemize
28340
28341 @end ifset
28342
28343 @c **********************************
28344 @c * GNU Free Documentation License *
28345 @c **********************************
28346 @include fdl.texi
28347 @c GNU Free Documentation License
28348
28349 @node Index,,GNU Free Documentation License, Top
28350 @unnumbered Index
28351
28352 @printindex cp
28353
28354 @contents
28355 @c Put table of contents at end, otherwise it precedes the "title page" in
28356 @c the .txt version
28357 @c Edit the pdf file to move the contents to the beginning, after the title
28358 @c page
28359
28360 @bye