OSDN Git Service

2012-02-08 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-2012, Free Software Foundation, Inc.          o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Creating Unit Tests Using gnattest::
196 * Generating Ada Bindings for C and C++ headers::
197 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
199 @ifclear vms
200 * Code Coverage and Profiling::
201 @end ifclear
202 @ifset vms
203 * Compatibility with HP Ada::
204 @end ifset
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Conditional Compilation::
209 * Inline Assembler::
210 * Compatibility and Porting Guide::
211 @ifset unw
212 * Microsoft Windows Topics::
213 @end ifset
214 * GNU Free Documentation License::
215 * Index::
216
217  --- The Detailed Node Listing ---
218
219 About This Guide
220
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
224 * Conventions::
225
226 Getting Started with GNAT
227
228 * Running GNAT::
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
232 @ifset vms
233 * Editing with Emacs::
234 @end ifset
235 @ifclear vms
236 * Introduction to GPS::
237 @end ifclear
238
239 The GNAT Compilation Model
240
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
251 @ifclear vms
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
254 @end ifclear
255 * Comparison between GNAT and Conventional Ada Library Models::
256 @ifset vms
257 * Placement of temporary files::
258 @end ifset
259
260 Foreign Language Representation
261
262 * Latin-1::
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
265
266 Compiling Ada Programs With gcc
267
268 * Compiling Programs::
269 * Switches for gcc::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
272 * Examples::
273
274 Switches for gcc
275
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
280 * Style Checking::
281 * Run-Time Checks::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
293 @ifset vms
294 * Return Codes::
295 @end ifset
296
297 Binding Ada Programs With gnatbind
298
299 * Running gnatbind::
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
304
305 Switches for gnatbind
306
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
310 * Output Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
313
314 Linking Using gnatlink
315
316 * Running gnatlink::
317 * Switches for gnatlink::
318
319 The GNAT Make Program gnatmake
320
321 * Running gnatmake::
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
327
328 Improving Performance
329 * Performance Considerations::
330 * Text_IO Suggestions::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
333
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Vectorization of loops::
341 * Other Optimization Switches::
342 * Optimization and Strict Aliasing::
343 @ifset vms
344 * Coverage Analysis::
345 @end ifset
346
347 Reducing Size of Ada Executables with gnatelim
348 * About gnatelim::
349 * Running gnatelim::
350 * Processing Precompiled Libraries::
351 * Correcting the List of Eliminate Pragmas::
352 * Making Your Executables Smaller::
353 * Summary of the gnatelim Usage Cycle::
354
355 Reducing Size of Executables with unused subprogram/data elimination
356 * About unused subprogram/data elimination::
357 * Compilation options::
358
359 Renaming Files Using gnatchop
360
361 * Handling Files with Multiple Units::
362 * Operating gnatchop in Compilation Mode::
363 * Command Line for gnatchop::
364 * Switches for gnatchop::
365 * Examples of gnatchop Usage::
366
367 Configuration Pragmas
368
369 * Handling of Configuration Pragmas::
370 * The Configuration Pragmas Files::
371
372 Handling Arbitrary File Naming Conventions Using gnatname
373
374 * Arbitrary File Naming Conventions::
375 * Running gnatname::
376 * Switches for gnatname::
377 * Examples of gnatname Usage::
378
379 The Cross-Referencing Tools gnatxref and gnatfind
380
381 * Switches for gnatxref::
382 * Switches for gnatfind::
383 * Project Files for gnatxref and gnatfind::
384 * Regular Expressions in gnatfind and gnatxref::
385 * Examples of gnatxref Usage::
386 * Examples of gnatfind Usage::
387
388 The GNAT Pretty-Printer gnatpp
389
390 * Switches for gnatpp::
391 * Formatting Rules::
392
393 The GNAT Metrics Tool gnatmetric
394
395 * Switches for gnatmetric::
396
397 File Name Krunching Using gnatkr
398
399 * About gnatkr::
400 * Using gnatkr::
401 * Krunching Method::
402 * Examples of gnatkr Usage::
403
404 Preprocessing Using gnatprep
405 * Preprocessing Symbols::
406 * Using gnatprep::
407 * Switches for gnatprep::
408 * Form of Definitions File::
409 * Form of Input Text for gnatprep::
410
411 The GNAT Library Browser gnatls
412
413 * Running gnatls::
414 * Switches for gnatls::
415 * Examples of gnatls Usage::
416
417 Cleaning Up Using gnatclean
418
419 * Running gnatclean::
420 * Switches for gnatclean::
421 @c * Examples of gnatclean Usage::
422
423 @ifclear vms
424
425 GNAT and Libraries
426
427 * Introduction to Libraries in GNAT::
428 * General Ada Libraries::
429 * Stand-alone Ada Libraries::
430 * Rebuilding the GNAT Run-Time Library::
431
432 Using the GNU make Utility
433
434 * Using gnatmake in a Makefile::
435 * Automatically Creating a List of Directories::
436 * Generating the Command Line Switches::
437 * Overcoming Command Line Length Limits::
438 @end ifclear
439
440 Memory Management Issues
441
442 * Some Useful Memory Pools::
443 * The GNAT Debug Pool Facility::
444 @ifclear vms
445 * The gnatmem Tool::
446 @end ifclear
447
448 Stack Related Facilities
449
450 * Stack Overflow Checking::
451 * Static Stack Usage Analysis::
452 * Dynamic Stack Usage Analysis::
453
454 Some Useful Memory Pools
455
456 The GNAT Debug Pool Facility
457
458 @ifclear vms
459 The gnatmem Tool
460
461 * Running gnatmem::
462 * Switches for gnatmem::
463 * Example of gnatmem Usage::
464 @end ifclear
465
466 Verifying Properties Using gnatcheck
467
468 Sample Bodies Using gnatstub
469
470 * Running gnatstub::
471 * Switches for gnatstub::
472
473 Creating Unit Tests Using gnattest
474
475 * Running gnattest::
476 * Switches for gnattest::
477 * Project Attributes for gnattest::
478 * Simple Example::
479 * Setting Up and Tearing Down the Testing Environment::
480 * Regenerating Tests::
481 * Default Test Behavior::
482 * Testing Primitive Operations of Tagged Types::
483 * Testing Inheritance::
484 * Tagged Types Substitutability Testing::
485 * Testing with Contracts::
486 * Additional Tests::
487 * Current Limitations::
488
489 Other Utility Programs
490
491 * Using Other Utility Programs with GNAT::
492 * The External Symbol Naming Scheme of GNAT::
493 * Converting Ada Files to html with gnathtml::
494
495 @ifclear vms
496 Code Coverage and Profiling
497
498 * Code Coverage of Ada Programs using gcov::
499 * Profiling an Ada Program using gprof::
500 @end ifclear
501
502 Running and Debugging Ada Programs
503
504 * The GNAT Debugger GDB::
505 * Running GDB::
506 * Introduction to GDB Commands::
507 * Using Ada Expressions::
508 * Calling User-Defined Subprograms::
509 * Using the Next Command in a Function::
510 * Ada Exceptions::
511 * Ada Tasks::
512 * Debugging Generic Units::
513 * Remote Debugging using gdbserver::
514 * GNAT Abnormal Termination or Failure to Terminate::
515 * Naming Conventions for GNAT Source Files::
516 * Getting Internal Debugging Information::
517 * Stack Traceback::
518
519 @ifset vms
520 * LSE::
521 @end ifset
522
523 @ifset vms
524 Compatibility with HP Ada
525
526 * Ada Language Compatibility::
527 * Differences in the Definition of Package System::
528 * Language-Related Features::
529 * The Package STANDARD::
530 * The Package SYSTEM::
531 * Tasking and Task-Related Features::
532 * Pragmas and Pragma-Related Features::
533 * Library of Predefined Units::
534 * Bindings::
535 * Main Program Definition::
536 * Implementation-Defined Attributes::
537 * Compiler and Run-Time Interfacing::
538 * Program Compilation and Library Management::
539 * Input-Output::
540 * Implementation Limits::
541 * Tools and Utilities::
542
543 Language-Related Features
544
545 * Integer Types and Representations::
546 * Floating-Point Types and Representations::
547 * Pragmas Float_Representation and Long_Float::
548 * Fixed-Point Types and Representations::
549 * Record and Array Component Alignment::
550 * Address Clauses::
551 * Other Representation Clauses::
552
553 Tasking and Task-Related Features
554
555 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
556 * Assigning Task IDs::
557 * Task IDs and Delays::
558 * Task-Related Pragmas::
559 * Scheduling and Task Priority::
560 * The Task Stack::
561 * External Interrupts::
562
563 Pragmas and Pragma-Related Features
564
565 * Restrictions on the Pragma INLINE::
566 * Restrictions on the Pragma INTERFACE::
567 * Restrictions on the Pragma SYSTEM_NAME::
568
569 Library of Predefined Units
570
571 * Changes to DECLIB::
572
573 Bindings
574
575 * Shared Libraries and Options Files::
576 * Interfaces to C::
577 @end ifset
578
579 Platform-Specific Information for the Run-Time Libraries
580
581 * Summary of Run-Time Configurations::
582 * Specifying a Run-Time Library::
583 * Choosing the Scheduling Policy::
584 * Solaris-Specific Considerations::
585 * Linux-Specific Considerations::
586 * AIX-Specific Considerations::
587 * Irix-Specific Considerations::
588 * RTX-Specific Considerations::
589 * HP-UX-Specific Considerations::
590
591 Example of Binder Output File
592
593 Elaboration Order Handling in GNAT
594
595 * Elaboration Code::
596 * Checking the Elaboration Order::
597 * Controlling the Elaboration Order::
598 * Controlling Elaboration in GNAT - Internal Calls::
599 * Controlling Elaboration in GNAT - External Calls::
600 * Default Behavior in GNAT - Ensuring Safety::
601 * Treatment of Pragma Elaborate::
602 * Elaboration Issues for Library Tasks::
603 * Mixing Elaboration Models::
604 * What to Do If the Default Elaboration Behavior Fails::
605 * Elaboration for Access-to-Subprogram Values::
606 * Summary of Procedures for Elaboration Control::
607 * Other Elaboration Order Considerations::
608
609 Conditional Compilation
610 * Use of Boolean Constants::
611 * Debugging - A Special Case::
612 * Conditionalizing Declarations::
613 * Use of Alternative Implementations::
614 * Preprocessing::
615
616 Inline Assembler
617
618 * Basic Assembler Syntax::
619 * A Simple Example of Inline Assembler::
620 * Output Variables in Inline Assembler::
621 * Input Variables in Inline Assembler::
622 * Inlining Inline Assembler Code::
623 * Other Asm Functionality::
624
625 Compatibility and Porting Guide
626
627 * Compatibility with Ada 83::
628 * Compatibility between Ada 95 and Ada 2005::
629 * Implementation-dependent characteristics::
630 @ifclear vms
631 @c This brief section is only in the non-VMS version
632 @c The complete chapter on HP Ada issues is in the VMS version
633 * Compatibility with HP Ada 83::
634 @end ifclear
635 * Compatibility with Other Ada Systems::
636 * Representation Clauses::
637 @ifset vms
638 * Transitioning to 64-Bit GNAT for OpenVMS::
639 @end ifset
640
641 @ifset unw
642 Microsoft Windows Topics
643
644 * Using GNAT on Windows::
645 * CONSOLE and WINDOWS subsystems::
646 * Temporary Files::
647 * Mixed-Language Programming on Windows::
648 * Windows Calling Conventions::
649 * Introduction to Dynamic Link Libraries (DLLs)::
650 * Using DLLs with GNAT::
651 * Building DLLs with GNAT::
652 * GNAT and Windows Resources::
653 * Debugging a DLL::
654 * Setting Stack Size from gnatlink::
655 * Setting Heap Size from gnatlink::
656 @end ifset
657
658 * Index::
659 @end menu
660 @end ifnottex
661
662 @node About This Guide
663 @unnumbered About This Guide
664
665 @noindent
666 @ifset vms
667 This guide describes the use of @value{EDITION},
668 a compiler and software development toolset for the full Ada
669 programming language, implemented on OpenVMS for HP's Alpha and
670 Integrity server (I64) platforms.
671 @end ifset
672 @ifclear vms
673 This guide describes the use of @value{EDITION},
674 a compiler and software development
675 toolset for the full Ada programming language.
676 @end ifclear
677 It documents the features of the compiler and tools, and explains
678 how to use them to build Ada applications.
679
680 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
681 Ada 83 compatibility mode.
682 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
683 but you can override with a compiler switch
684 (@pxref{Compiling Different Versions of Ada})
685 to explicitly specify the language version.
686 Throughout this manual, references to ``Ada'' without a year suffix
687 apply to both the Ada 95 and Ada 2005 versions of the language.
688
689
690 @ifclear FSFEDITION
691 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
692 ``GNAT'' in the remainder of this document.
693 @end ifclear
694
695
696
697
698 @menu
699 * What This Guide Contains::
700 * What You Should Know before Reading This Guide::
701 * Related Information::
702 * Conventions::
703 @end menu
704
705 @node What This Guide Contains
706 @unnumberedsec What This Guide Contains
707
708 @noindent
709 This guide contains the following chapters:
710 @itemize @bullet
711
712 @item
713 @ref{Getting Started with GNAT}, describes how to get started compiling
714 and running Ada programs with the GNAT Ada programming environment.
715 @item
716 @ref{The GNAT Compilation Model}, describes the compilation model used
717 by GNAT.
718
719 @item
720 @ref{Compiling Using gcc}, describes how to compile
721 Ada programs with @command{gcc}, the Ada compiler.
722
723 @item
724 @ref{Binding Using gnatbind}, describes how to
725 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
726 utility.
727
728 @item
729 @ref{Linking Using gnatlink},
730 describes @command{gnatlink}, a
731 program that provides for linking using the GNAT run-time library to
732 construct a program. @command{gnatlink} can also incorporate foreign language
733 object units into the executable.
734
735 @item
736 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
737 utility that automatically determines the set of sources
738 needed by an Ada compilation unit, and executes the necessary compilations
739 binding and link.
740
741 @item
742 @ref{Improving Performance}, shows various techniques for making your
743 Ada program run faster or take less space.
744 It discusses the effect of the compiler's optimization switch and
745 also describes the @command{gnatelim} tool and unused subprogram/data
746 elimination.
747
748 @item
749 @ref{Renaming Files Using gnatchop}, describes
750 @code{gnatchop}, a utility that allows you to preprocess a file that
751 contains Ada source code, and split it into one or more new files, one
752 for each compilation unit.
753
754 @item
755 @ref{Configuration Pragmas}, describes the configuration pragmas
756 handled by GNAT.
757
758 @item
759 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
760 shows how to override the default GNAT file naming conventions,
761 either for an individual unit or globally.
762
763 @item
764 @ref{GNAT Project Manager}, describes how to use project files
765 to organize large projects.
766
767 @item
768 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
769 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
770 way to navigate through sources.
771
772 @item
773 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
774 version of an Ada source file with control over casing, indentation,
775 comment placement, and other elements of program presentation style.
776
777 @item
778 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
779 metrics for an Ada source file, such as the number of types and subprograms,
780 and assorted complexity measures.
781
782 @item
783 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
784 file name krunching utility, used to handle shortened
785 file names on operating systems with a limit on the length of names.
786
787 @item
788 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
789 preprocessor utility that allows a single source file to be used to
790 generate multiple or parameterized source files by means of macro
791 substitution.
792
793 @item
794 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
795 utility that displays information about compiled units, including dependences
796 on the corresponding sources files, and consistency of compilations.
797
798 @item
799 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
800 to delete files that are produced by the compiler, binder and linker.
801
802 @ifclear vms
803 @item
804 @ref{GNAT and Libraries}, describes the process of creating and using
805 Libraries with GNAT. It also describes how to recompile the GNAT run-time
806 library.
807
808 @item
809 @ref{Using the GNU make Utility}, describes some techniques for using
810 the GNAT toolset in Makefiles.
811 @end ifclear
812
813 @item
814 @ref{Memory Management Issues}, describes some useful predefined storage pools
815 and in particular the GNAT Debug Pool facility, which helps detect incorrect
816 memory references.
817 @ifclear vms
818 It also describes @command{gnatmem}, a utility that monitors dynamic
819 allocation and deallocation and helps detect ``memory leaks''.
820 @end ifclear
821
822 @item
823 @ref{Stack Related Facilities}, describes some useful tools associated with
824 stack checking and analysis.
825
826 @item
827 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
828 a utility that checks Ada code against a set of rules.
829
830 @item
831 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
832 a utility that generates empty but compilable bodies for library units.
833
834 @item
835 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
836 a utility that generates unit testing templates for library units.
837
838 @item
839 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
840 generate automatically Ada bindings from C and C++ headers.
841
842 @item
843 @ref{Other Utility Programs}, discusses several other GNAT utilities,
844 including @code{gnathtml}.
845
846 @ifclear vms
847 @item
848 @ref{Code Coverage and Profiling}, describes how to perform a structural
849 coverage and profile the execution of Ada programs.
850 @end ifclear
851
852 @item
853 @ref{Running and Debugging Ada Programs}, describes how to run and debug
854 Ada programs.
855
856 @ifset vms
857 @item
858 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
859 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
860 developed by Digital Equipment Corporation and currently supported by HP.}
861 for OpenVMS Alpha. This product was formerly known as DEC Ada,
862 @cindex DEC Ada
863 and for
864 historical compatibility reasons, the relevant libraries still use the
865 DEC prefix.
866 @end ifset
867
868 @item
869 @ref{Platform-Specific Information for the Run-Time Libraries},
870 describes the various run-time
871 libraries supported by GNAT on various platforms and explains how to
872 choose a particular library.
873
874 @item
875 @ref{Example of Binder Output File}, shows the source code for the binder
876 output file for a sample program.
877
878 @item
879 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
880 you deal with elaboration order issues.
881
882 @item
883 @ref{Conditional Compilation}, describes how to model conditional compilation,
884 both with Ada in general and with GNAT facilities in particular.
885
886 @item
887 @ref{Inline Assembler}, shows how to use the inline assembly facility
888 in an Ada program.
889
890 @item
891 @ref{Compatibility and Porting Guide}, contains sections on compatibility
892 of GNAT with other Ada development environments (including Ada 83 systems),
893 to assist in porting code from those environments.
894
895 @ifset unw
896 @item
897 @ref{Microsoft Windows Topics}, presents information relevant to the
898 Microsoft Windows platform.
899 @end ifset
900 @end itemize
901
902 @c *************************************************
903 @node What You Should Know before Reading This Guide
904 @c *************************************************
905 @unnumberedsec What You Should Know before Reading This Guide
906
907 @cindex Ada 95 Language Reference Manual
908 @cindex Ada 2005 Language Reference Manual
909 @noindent
910 This guide assumes a basic familiarity with the Ada 95 language, as
911 described in the International Standard ANSI/ISO/IEC-8652:1995, January
912 1995.
913 It does not require knowledge of the new features introduced by Ada 2005,
914 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
915 and Amendment 1).
916 Both reference manuals are included in the GNAT documentation
917 package.
918
919 @node Related Information
920 @unnumberedsec Related Information
921
922 @noindent
923 For further information about related tools, refer to the following
924 documents:
925
926 @itemize @bullet
927 @item
928 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
929 Reference Manual}, which contains all reference material for the GNAT
930 implementation of Ada.
931
932 @ifset unw
933 @item
934 @cite{Using the GNAT Programming Studio}, which describes the GPS
935 Integrated Development Environment.
936
937 @item
938 @cite{GNAT Programming Studio Tutorial}, which introduces the
939 main GPS features through examples.
940 @end ifset
941
942 @item
943 @cite{Ada 95 Reference Manual}, which contains reference
944 material for the Ada 95 programming language.
945
946 @item
947 @cite{Ada 2005 Reference Manual}, which contains reference
948 material for the Ada 2005 programming language.
949
950 @item
951 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
952 @ifset vms
953 in the GNU:[DOCS] directory,
954 @end ifset
955 for all details on the use of the GNU source-level debugger.
956
957 @item
958 @xref{Top,, The extensible self-documenting text editor, emacs,
959 GNU Emacs Manual},
960 @ifset vms
961 located in the GNU:[DOCS] directory if the EMACS kit is installed,
962 @end ifset
963 for full information on the extensible editor and programming
964 environment Emacs.
965
966 @end itemize
967
968 @c **************
969 @node Conventions
970 @unnumberedsec Conventions
971 @cindex Conventions
972 @cindex Typographical conventions
973
974 @noindent
975 Following are examples of the typographical and graphic conventions used
976 in this guide:
977
978 @itemize @bullet
979 @item
980 @code{Functions}, @command{utility program names}, @code{standard names},
981 and @code{classes}.
982
983 @item
984 @option{Option flags}
985
986 @item
987 @file{File names}, @samp{button names}, and @samp{field names}.
988
989 @item
990 @code{Variables}, @env{environment variables}, and @var{metasyntactic
991 variables}.
992
993 @item
994 @emph{Emphasis}.
995
996 @item
997 @r{[}optional information or parameters@r{]}
998
999 @item
1000 Examples are described by text
1001 @smallexample
1002 and then shown this way.
1003 @end smallexample
1004 @end itemize
1005
1006 @noindent
1007 Commands that are entered by the user are preceded in this manual by the
1008 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1009 uses this sequence as a prompt, then the commands will appear exactly as
1010 you see them in the manual. If your system uses some other prompt, then
1011 the command will appear with the @code{$} replaced by whatever prompt
1012 character you are using.
1013
1014 @ifset unw
1015 Full file names are shown with the ``@code{/}'' character
1016 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1017 If you are using GNAT on a Windows platform, please note that
1018 the ``@code{\}'' character should be used instead.
1019 @end ifset
1020
1021 @c ****************************
1022 @node Getting Started with GNAT
1023 @chapter Getting Started with GNAT
1024
1025 @noindent
1026 This chapter describes some simple ways of using GNAT to build
1027 executable Ada programs.
1028 @ifset unw
1029 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1030 show how to use the command line environment.
1031 @ref{Introduction to GPS}, provides a brief
1032 introduction to the GNAT Programming Studio, a visually-oriented
1033 Integrated Development Environment for GNAT.
1034 GPS offers a graphical ``look and feel'', support for development in
1035 other programming languages, comprehensive browsing features, and
1036 many other capabilities.
1037 For information on GPS please refer to
1038 @cite{Using the GNAT Programming Studio}.
1039 @end ifset
1040
1041 @menu
1042 * Running GNAT::
1043 * Running a Simple Ada Program::
1044 * Running a Program with Multiple Units::
1045 * Using the gnatmake Utility::
1046 @ifset vms
1047 * Editing with Emacs::
1048 @end ifset
1049 @ifclear vms
1050 * Introduction to GPS::
1051 @end ifclear
1052 @end menu
1053
1054 @node Running GNAT
1055 @section Running GNAT
1056
1057 @noindent
1058 Three steps are needed to create an executable file from an Ada source
1059 file:
1060
1061 @enumerate
1062 @item
1063 The source file(s) must be compiled.
1064 @item
1065 The file(s) must be bound using the GNAT binder.
1066 @item
1067 All appropriate object files must be linked to produce an executable.
1068 @end enumerate
1069
1070 @noindent
1071 All three steps are most commonly handled by using the @command{gnatmake}
1072 utility program that, given the name of the main program, automatically
1073 performs the necessary compilation, binding and linking steps.
1074
1075 @node Running a Simple Ada Program
1076 @section Running a Simple Ada Program
1077
1078 @noindent
1079 Any text editor may be used to prepare an Ada program.
1080 (If @code{Emacs} is
1081 used, the optional Ada mode may be helpful in laying out the program.)
1082 The
1083 program text is a normal text file. We will assume in our initial
1084 example that you have used your editor to prepare the following
1085 standard format text file:
1086
1087 @smallexample @c ada
1088 @cartouche
1089 with Ada.Text_IO; use Ada.Text_IO;
1090 procedure Hello is
1091 begin
1092    Put_Line ("Hello WORLD!");
1093 end Hello;
1094 @end cartouche
1095 @end smallexample
1096
1097 @noindent
1098 This file should be named @file{hello.adb}.
1099 With the normal default file naming conventions, GNAT requires
1100 that each file
1101 contain a single compilation unit whose file name is the
1102 unit name,
1103 with periods replaced by hyphens; the
1104 extension is @file{ads} for a
1105 spec and @file{adb} for a body.
1106 You can override this default file naming convention by use of the
1107 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1108 Alternatively, if you want to rename your files according to this default
1109 convention, which is probably more convenient if you will be using GNAT
1110 for all your compilations, then the @code{gnatchop} utility
1111 can be used to generate correctly-named source files
1112 (@pxref{Renaming Files Using gnatchop}).
1113
1114 You can compile the program using the following command (@code{$} is used
1115 as the command prompt in the examples in this document):
1116
1117 @smallexample
1118 $ gcc -c hello.adb
1119 @end smallexample
1120
1121 @noindent
1122 @command{gcc} is the command used to run the compiler. This compiler is
1123 capable of compiling programs in several languages, including Ada and
1124 C. It assumes that you have given it an Ada program if the file extension is
1125 either @file{.ads} or @file{.adb}, and it will then call
1126 the GNAT compiler to compile the specified file.
1127
1128 @ifclear vms
1129 The @option{-c} switch is required. It tells @command{gcc} to only do a
1130 compilation. (For C programs, @command{gcc} can also do linking, but this
1131 capability is not used directly for Ada programs, so the @option{-c}
1132 switch must always be present.)
1133 @end ifclear
1134
1135 This compile command generates a file
1136 @file{hello.o}, which is the object
1137 file corresponding to your Ada program. It also generates
1138 an ``Ada Library Information'' file @file{hello.ali},
1139 which contains additional information used to check
1140 that an Ada program is consistent.
1141 To build an executable file,
1142 use @code{gnatbind} to bind the program
1143 and @command{gnatlink} to link it. The
1144 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1145 @file{ALI} file, but the default extension of @file{.ali} can
1146 be omitted. This means that in the most common case, the argument
1147 is simply the name of the main program:
1148
1149 @smallexample
1150 $ gnatbind hello
1151 $ gnatlink hello
1152 @end smallexample
1153
1154 @noindent
1155 A simpler method of carrying out these steps is to use
1156 @command{gnatmake},
1157 a master program that invokes all the required
1158 compilation, binding and linking tools in the correct order. In particular,
1159 @command{gnatmake} automatically recompiles any sources that have been
1160 modified since they were last compiled, or sources that depend
1161 on such modified sources, so that ``version skew'' is avoided.
1162 @cindex Version skew (avoided by @command{gnatmake})
1163
1164 @smallexample
1165 $ gnatmake hello.adb
1166 @end smallexample
1167
1168 @noindent
1169 The result is an executable program called @file{hello}, which can be
1170 run by entering:
1171
1172 @smallexample
1173 $ ^hello^RUN HELLO^
1174 @end smallexample
1175
1176 @noindent
1177 assuming that the current directory is on the search path
1178 for executable programs.
1179
1180 @noindent
1181 and, if all has gone well, you will see
1182
1183 @smallexample
1184 Hello WORLD!
1185 @end smallexample
1186
1187 @noindent
1188 appear in response to this command.
1189
1190 @c ****************************************
1191 @node Running a Program with Multiple Units
1192 @section Running a Program with Multiple Units
1193
1194 @noindent
1195 Consider a slightly more complicated example that has three files: a
1196 main program, and the spec and body of a package:
1197
1198 @smallexample @c ada
1199 @cartouche
1200 @group
1201 package Greetings is
1202    procedure Hello;
1203    procedure Goodbye;
1204 end Greetings;
1205
1206 with Ada.Text_IO; use Ada.Text_IO;
1207 package body Greetings is
1208    procedure Hello is
1209    begin
1210       Put_Line ("Hello WORLD!");
1211    end Hello;
1212
1213    procedure Goodbye is
1214    begin
1215       Put_Line ("Goodbye WORLD!");
1216    end Goodbye;
1217 end Greetings;
1218 @end group
1219
1220 @group
1221 with Greetings;
1222 procedure Gmain is
1223 begin
1224    Greetings.Hello;
1225    Greetings.Goodbye;
1226 end Gmain;
1227 @end group
1228 @end cartouche
1229 @end smallexample
1230
1231 @noindent
1232 Following the one-unit-per-file rule, place this program in the
1233 following three separate files:
1234
1235 @table @file
1236 @item greetings.ads
1237 spec of package @code{Greetings}
1238
1239 @item greetings.adb
1240 body of package @code{Greetings}
1241
1242 @item gmain.adb
1243 body of main program
1244 @end table
1245
1246 @noindent
1247 To build an executable version of
1248 this program, we could use four separate steps to compile, bind, and link
1249 the program, as follows:
1250
1251 @smallexample
1252 $ gcc -c gmain.adb
1253 $ gcc -c greetings.adb
1254 $ gnatbind gmain
1255 $ gnatlink gmain
1256 @end smallexample
1257
1258 @noindent
1259 Note that there is no required order of compilation when using GNAT.
1260 In particular it is perfectly fine to compile the main program first.
1261 Also, it is not necessary to compile package specs in the case where
1262 there is an accompanying body; you only need to compile the body. If you want
1263 to submit these files to the compiler for semantic checking and not code
1264 generation, then use the
1265 @option{-gnatc} switch:
1266
1267 @smallexample
1268 $ gcc -c greetings.ads -gnatc
1269 @end smallexample
1270
1271 @noindent
1272 Although the compilation can be done in separate steps as in the
1273 above example, in practice it is almost always more convenient
1274 to use the @command{gnatmake} tool. All you need to know in this case
1275 is the name of the main program's source file. The effect of the above four
1276 commands can be achieved with a single one:
1277
1278 @smallexample
1279 $ gnatmake gmain.adb
1280 @end smallexample
1281
1282 @noindent
1283 In the next section we discuss the advantages of using @command{gnatmake} in
1284 more detail.
1285
1286 @c *****************************
1287 @node Using the gnatmake Utility
1288 @section Using the @command{gnatmake} Utility
1289
1290 @noindent
1291 If you work on a program by compiling single components at a time using
1292 @command{gcc}, you typically keep track of the units you modify. In order to
1293 build a consistent system, you compile not only these units, but also any
1294 units that depend on the units you have modified.
1295 For example, in the preceding case,
1296 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1297 you edit @file{greetings.ads}, you must recompile both
1298 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1299 units that depend on @file{greetings.ads}.
1300
1301 @code{gnatbind} will warn you if you forget one of these compilation
1302 steps, so that it is impossible to generate an inconsistent program as a
1303 result of forgetting to do a compilation. Nevertheless it is tedious and
1304 error-prone to keep track of dependencies among units.
1305 One approach to handle the dependency-bookkeeping is to use a
1306 makefile. However, makefiles present maintenance problems of their own:
1307 if the dependencies change as you change the program, you must make
1308 sure that the makefile is kept up-to-date manually, which is also an
1309 error-prone process.
1310
1311 The @command{gnatmake} utility takes care of these details automatically.
1312 Invoke it using either one of the following forms:
1313
1314 @smallexample
1315 $ gnatmake gmain.adb
1316 $ gnatmake ^gmain^GMAIN^
1317 @end smallexample
1318
1319 @noindent
1320 The argument is the name of the file containing the main program;
1321 you may omit the extension. @command{gnatmake}
1322 examines the environment, automatically recompiles any files that need
1323 recompiling, and binds and links the resulting set of object files,
1324 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1325 In a large program, it
1326 can be extremely helpful to use @command{gnatmake}, because working out by hand
1327 what needs to be recompiled can be difficult.
1328
1329 Note that @command{gnatmake}
1330 takes into account all the Ada rules that
1331 establish dependencies among units. These include dependencies that result
1332 from inlining subprogram bodies, and from
1333 generic instantiation. Unlike some other
1334 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1335 found by the compiler on a previous compilation, which may possibly
1336 be wrong when sources change. @command{gnatmake} determines the exact set of
1337 dependencies from scratch each time it is run.
1338
1339 @ifset vms
1340 @node Editing with Emacs
1341 @section Editing with Emacs
1342 @cindex Emacs
1343
1344 @noindent
1345 Emacs is an extensible self-documenting text editor that is available in a
1346 separate VMSINSTAL kit.
1347
1348 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1349 click on the Emacs Help menu and run the Emacs Tutorial.
1350 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1351 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1352
1353 Documentation on Emacs and other tools is available in Emacs under the
1354 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1355 use the middle mouse button to select a topic (e.g.@: Emacs).
1356
1357 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1358 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1359 get to the Emacs manual.
1360 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1361 prompt.
1362
1363 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1364 which is sufficiently extensible to provide for a complete programming
1365 environment and shell for the sophisticated user.
1366 @end ifset
1367
1368 @ifclear vms
1369 @node Introduction to GPS
1370 @section Introduction to GPS
1371 @cindex GPS (GNAT Programming Studio)
1372 @cindex GNAT Programming Studio (GPS)
1373 @noindent
1374 Although the command line interface (@command{gnatmake}, etc.) alone
1375 is sufficient, a graphical Interactive Development
1376 Environment can make it easier for you to compose, navigate, and debug
1377 programs.  This section describes the main features of GPS
1378 (``GNAT Programming Studio''), the GNAT graphical IDE.
1379 You will see how to use GPS to build and debug an executable, and
1380 you will also learn some of the basics of the GNAT ``project'' facility.
1381
1382 GPS enables you to do much more than is presented here;
1383 e.g., you can produce a call graph, interface to a third-party
1384 Version Control System, and inspect the generated assembly language
1385 for a program.
1386 Indeed, GPS also supports languages other than Ada.
1387 Such additional information, and an explanation of all of the GPS menu
1388 items. may be found in the on-line help, which includes
1389 a user's guide and a tutorial (these are also accessible from the GNAT
1390 startup menu).
1391
1392 @menu
1393 * Building a New Program with GPS::
1394 * Simple Debugging with GPS::
1395 @end menu
1396
1397 @node Building a New Program with GPS
1398 @subsection Building a New Program with GPS
1399 @noindent
1400 GPS invokes the GNAT compilation tools using information
1401 contained in a @emph{project} (also known as a @emph{project file}):
1402 a collection of properties such
1403 as source directories, identities of main subprograms, tool switches, etc.,
1404 and their associated values.
1405 See @ref{GNAT Project Manager} for details.
1406 In order to run GPS, you will need to either create a new project
1407 or else open an existing one.
1408
1409 This section will explain how you can use GPS to create a project,
1410 to associate Ada source files with a project, and to build and run
1411 programs.
1412
1413 @enumerate
1414 @item @emph{Creating a project}
1415
1416 Invoke GPS, either from the command line or the platform's IDE.
1417 After it starts, GPS will display a ``Welcome'' screen with three
1418 radio buttons:
1419
1420 @itemize @bullet
1421 @item
1422 @code{Start with default project in directory}
1423
1424 @item
1425 @code{Create new project with wizard}
1426
1427 @item
1428 @code{Open existing project}
1429 @end itemize
1430
1431 @noindent
1432 Select @code{Create new project with wizard} and press @code{OK}.
1433 A new window will appear.  In the text box labeled with
1434 @code{Enter the name of the project to create}, type @file{sample}
1435 as the project name.
1436 In the next box, browse to choose the directory in which you
1437 would like to create the project file.
1438 After selecting an appropriate directory, press @code{Forward}.
1439
1440 A window will appear with the title
1441 @code{Version Control System Configuration}.
1442 Simply press @code{Forward}.
1443
1444 A window will appear with the title
1445 @code{Please select the source directories for this project}.
1446 The directory that you specified for the project file will be selected
1447 by default as the one to use for sources; simply press @code{Forward}.
1448
1449 A window will appear with the title
1450 @code{Please select the build directory for this project}.
1451 The directory that you specified for the project file will be selected
1452 by default for object files and executables;
1453 simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the main units for this project}.
1457 You will supply this information later, after creating the source file.
1458 Simply press @code{Forward} for now.
1459
1460 A window will appear with the title
1461 @code{Please select the switches to build the project}.
1462 Press @code{Apply}.  This will create a project file named
1463 @file{sample.prj} in the directory that you had specified.
1464
1465 @item @emph{Creating and saving the source file}
1466
1467 After you create the new project, a GPS window will appear, which is
1468 partitioned into two main sections:
1469
1470 @itemize @bullet
1471 @item
1472 A @emph{Workspace area}, initially greyed out, which you will use for
1473 creating and editing source files
1474
1475 @item
1476 Directly below, a @emph{Messages area}, which initially displays a
1477 ``Welcome'' message.
1478 (If the Messages area is not visible, drag its border upward to expand it.)
1479 @end itemize
1480
1481 @noindent
1482 Select @code{File} on the menu bar, and then the @code{New} command.
1483 The Workspace area will become white, and you can now
1484 enter the source program explicitly.
1485 Type the following text
1486
1487 @smallexample @c ada
1488 @group
1489 with Ada.Text_IO; use Ada.Text_IO;
1490 procedure Hello is
1491 begin
1492   Put_Line("Hello from GPS!");
1493 end Hello;
1494 @end group
1495 @end smallexample
1496
1497 @noindent
1498 Select @code{File}, then @code{Save As}, and enter the source file name
1499 @file{hello.adb}.
1500 The file will be saved in the same directory you specified as the
1501 location of the default project file.
1502
1503 @item @emph{Updating the project file}
1504
1505 You need to add the new source file to the project.
1506 To do this, select
1507 the @code{Project} menu and then @code{Edit project properties}.
1508 Click the @code{Main files} tab on the left, and then the
1509 @code{Add} button.
1510 Choose @file{hello.adb} from the list, and press @code{Open}.
1511 The project settings window will reflect this action.
1512 Click @code{OK}.
1513
1514 @item @emph{Building and running the program}
1515
1516 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1517 and select @file{hello.adb}.
1518 The Messages window will display the resulting invocations of @command{gcc},
1519 @command{gnatbind}, and @command{gnatlink}
1520 (reflecting the default switch settings from the
1521 project file that you created) and then a ``successful compilation/build''
1522 message.
1523
1524 To run the program, choose the @code{Build} menu, then @code{Run}, and
1525 select @command{hello}.
1526 An @emph{Arguments Selection} window will appear.
1527 There are no command line arguments, so just click @code{OK}.
1528
1529 The Messages window will now display the program's output (the string
1530 @code{Hello from GPS}), and at the bottom of the GPS window a status
1531 update is displayed (@code{Run: hello}).
1532 Close the GPS window (or select @code{File}, then @code{Exit}) to
1533 terminate this GPS session.
1534 @end enumerate
1535
1536 @node Simple Debugging with GPS
1537 @subsection Simple Debugging with GPS
1538 @noindent
1539 This section illustrates basic debugging techniques (setting breakpoints,
1540 examining/modifying variables, single stepping).
1541
1542 @enumerate
1543 @item @emph{Opening a project}
1544
1545 Start GPS and select @code{Open existing project}; browse to
1546 specify the project file @file{sample.prj} that you had created in the
1547 earlier example.
1548
1549 @item @emph{Creating a source file}
1550
1551 Select @code{File}, then @code{New}, and type in the following program:
1552
1553 @smallexample @c ada
1554 @group
1555 with Ada.Text_IO; use Ada.Text_IO;
1556 procedure Example is
1557    Line : String (1..80);
1558    N    : Natural;
1559 begin
1560    Put_Line("Type a line of text at each prompt; an empty line to exit");
1561    loop
1562       Put(": ");
1563       Get_Line (Line, N);
1564       Put_Line (Line (1..N) );
1565       exit when N=0;
1566    end loop;
1567 end Example;
1568 @end group
1569 @end smallexample
1570
1571 @noindent
1572 Select @code{File}, then @code{Save as}, and enter the file name
1573 @file{example.adb}.
1574
1575 @item @emph{Updating the project file}
1576
1577 Add @code{Example} as a new main unit for the project:
1578 @enumerate a
1579 @item
1580 Select @code{Project}, then @code{Edit Project Properties}.
1581
1582 @item
1583 Select the @code{Main files} tab, click @code{Add}, then
1584 select the file @file{example.adb} from the list, and
1585 click @code{Open}.
1586 You will see the file name appear in the list of main units
1587
1588 @item
1589 Click @code{OK}
1590 @end enumerate
1591
1592 @item @emph{Building/running the executable}
1593
1594 To build the executable
1595 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1596
1597 Run the program to see its effect (in the Messages area).
1598 Each line that you enter is displayed; an empty line will
1599 cause the loop to exit and the program to terminate.
1600
1601 @item @emph{Debugging the program}
1602
1603 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1604 which are required for debugging, are on by default when you create
1605 a new project.
1606 Thus unless you intentionally remove these settings, you will be able
1607 to debug any program that you develop using GPS.
1608
1609 @enumerate a
1610 @item @emph{Initializing}
1611
1612 Select @code{Debug}, then @code{Initialize}, then @file{example}
1613
1614 @item @emph{Setting a breakpoint}
1615
1616 After performing the initialization step, you will observe a small
1617 icon to the right of each line number.
1618 This serves as a toggle for breakpoints; clicking the icon will
1619 set a breakpoint at the corresponding line (the icon will change to
1620 a red circle with an ``x''), and clicking it again
1621 will remove the breakpoint / reset the icon.
1622
1623 For purposes of this example, set a breakpoint at line 10 (the
1624 statement @code{Put_Line@ (Line@ (1..N));}
1625
1626 @item @emph{Starting program execution}
1627
1628 Select @code{Debug}, then @code{Run}.  When the
1629 @code{Program Arguments} window appears, click @code{OK}.
1630 A console window will appear; enter some line of text,
1631 e.g.@: @code{abcde}, at the prompt.
1632 The program will pause execution when it gets to the
1633 breakpoint, and the corresponding line is highlighted.
1634
1635 @item @emph{Examining a variable}
1636
1637 Move the mouse over one of the occurrences of the variable @code{N}.
1638 You will see the value (5) displayed, in ``tool tip'' fashion.
1639 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1640 You will see information about @code{N} appear in the @code{Debugger Data}
1641 pane, showing the value as 5.
1642
1643 @item @emph{Assigning a new value to a variable}
1644
1645 Right click on the @code{N} in the @code{Debugger Data} pane, and
1646 select @code{Set value of N}.
1647 When the input window appears, enter the value @code{4} and click
1648 @code{OK}.
1649 This value does not automatically appear in the @code{Debugger Data}
1650 pane; to see it, right click again on the @code{N} in the
1651 @code{Debugger Data} pane and select @code{Update value}.
1652 The new value, 4, will appear in red.
1653
1654 @item @emph{Single stepping}
1655
1656 Select @code{Debug}, then @code{Next}.
1657 This will cause the next statement to be executed, in this case the
1658 call of @code{Put_Line} with the string slice.
1659 Notice in the console window that the displayed string is simply
1660 @code{abcd} and not @code{abcde} which you had entered.
1661 This is because the upper bound of the slice is now 4 rather than 5.
1662
1663 @item @emph{Removing a breakpoint}
1664
1665 Toggle the breakpoint icon at line 10.
1666
1667 @item @emph{Resuming execution from a breakpoint}
1668
1669 Select @code{Debug}, then @code{Continue}.
1670 The program will reach the next iteration of the loop, and
1671 wait for input after displaying the prompt.
1672 This time, just hit the @kbd{Enter} key.
1673 The value of @code{N} will be 0, and the program will terminate.
1674 The console window will disappear.
1675 @end enumerate
1676 @end enumerate
1677 @end ifclear
1678
1679 @node The GNAT Compilation Model
1680 @chapter The GNAT Compilation Model
1681 @cindex GNAT compilation model
1682 @cindex Compilation model
1683
1684 @menu
1685 * Source Representation::
1686 * Foreign Language Representation::
1687 * File Naming Rules::
1688 * Using Other File Names::
1689 * Alternative File Naming Schemes::
1690 * Generating Object Files::
1691 * Source Dependencies::
1692 * The Ada Library Information Files::
1693 * Binding an Ada Program::
1694 * Mixed Language Programming::
1695 @ifclear vms
1696 * Building Mixed Ada & C++ Programs::
1697 * Comparison between GNAT and C/C++ Compilation Models::
1698 @end ifclear
1699 * Comparison between GNAT and Conventional Ada Library Models::
1700 @ifset vms
1701 * Placement of temporary files::
1702 @end ifset
1703 @end menu
1704
1705 @noindent
1706 This chapter describes the compilation model used by GNAT. Although
1707 similar to that used by other languages, such as C and C++, this model
1708 is substantially different from the traditional Ada compilation models,
1709 which are based on a library. The model is initially described without
1710 reference to the library-based model. If you have not previously used an
1711 Ada compiler, you need only read the first part of this chapter. The
1712 last section describes and discusses the differences between the GNAT
1713 model and the traditional Ada compiler models. If you have used other
1714 Ada compilers, this section will help you to understand those
1715 differences, and the advantages of the GNAT model.
1716
1717 @node Source Representation
1718 @section Source Representation
1719 @cindex Latin-1
1720
1721 @noindent
1722 Ada source programs are represented in standard text files, using
1723 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1724 7-bit ASCII set, plus additional characters used for
1725 representing foreign languages (@pxref{Foreign Language Representation}
1726 for support of non-USA character sets). The format effector characters
1727 are represented using their standard ASCII encodings, as follows:
1728
1729 @table @code
1730 @item VT
1731 @findex VT
1732 Vertical tab, @code{16#0B#}
1733
1734 @item HT
1735 @findex HT
1736 Horizontal tab, @code{16#09#}
1737
1738 @item CR
1739 @findex CR
1740 Carriage return, @code{16#0D#}
1741
1742 @item LF
1743 @findex LF
1744 Line feed, @code{16#0A#}
1745
1746 @item FF
1747 @findex FF
1748 Form feed, @code{16#0C#}
1749 @end table
1750
1751 @noindent
1752 Source files are in standard text file format. In addition, GNAT will
1753 recognize a wide variety of stream formats, in which the end of
1754 physical lines is marked by any of the following sequences:
1755 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1756 in accommodating files that are imported from other operating systems.
1757
1758 @cindex End of source file
1759 @cindex Source file, end
1760 @findex SUB
1761 The end of a source file is normally represented by the physical end of
1762 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1763 recognized as signalling the end of the source file. Again, this is
1764 provided for compatibility with other operating systems where this
1765 code is used to represent the end of file.
1766
1767 Each file contains a single Ada compilation unit, including any pragmas
1768 associated with the unit. For example, this means you must place a
1769 package declaration (a package @dfn{spec}) and the corresponding body in
1770 separate files. An Ada @dfn{compilation} (which is a sequence of
1771 compilation units) is represented using a sequence of files. Similarly,
1772 you will place each subunit or child unit in a separate file.
1773
1774 @node Foreign Language Representation
1775 @section Foreign Language Representation
1776
1777 @noindent
1778 GNAT supports the standard character sets defined in Ada as well as
1779 several other non-standard character sets for use in localized versions
1780 of the compiler (@pxref{Character Set Control}).
1781 @menu
1782 * Latin-1::
1783 * Other 8-Bit Codes::
1784 * Wide Character Encodings::
1785 @end menu
1786
1787 @node Latin-1
1788 @subsection Latin-1
1789 @cindex Latin-1
1790
1791 @noindent
1792 The basic character set is Latin-1. This character set is defined by ISO
1793 standard 8859, part 1. The lower half (character codes @code{16#00#}
1794 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1795 half is used to represent additional characters. These include extended letters
1796 used by European languages, such as French accents, the vowels with umlauts
1797 used in German, and the extra letter A-ring used in Swedish.
1798
1799 @findex Ada.Characters.Latin_1
1800 For a complete list of Latin-1 codes and their encodings, see the source
1801 file of library unit @code{Ada.Characters.Latin_1} in file
1802 @file{a-chlat1.ads}.
1803 You may use any of these extended characters freely in character or
1804 string literals. In addition, the extended characters that represent
1805 letters can be used in identifiers.
1806
1807 @node Other 8-Bit Codes
1808 @subsection Other 8-Bit Codes
1809
1810 @noindent
1811 GNAT also supports several other 8-bit coding schemes:
1812
1813 @table @asis
1814 @item ISO 8859-2 (Latin-2)
1815 @cindex Latin-2
1816 @cindex ISO 8859-2
1817 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1818 equivalence.
1819
1820 @item ISO 8859-3 (Latin-3)
1821 @cindex Latin-3
1822 @cindex ISO 8859-3
1823 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1824 equivalence.
1825
1826 @item ISO 8859-4 (Latin-4)
1827 @cindex Latin-4
1828 @cindex ISO 8859-4
1829 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-5 (Cyrillic)
1833 @cindex ISO 8859-5
1834 @cindex Cyrillic
1835 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1836 lowercase equivalence.
1837
1838 @item ISO 8859-15 (Latin-9)
1839 @cindex ISO 8859-15
1840 @cindex Latin-9
1841 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1842 lowercase equivalence
1843
1844 @item IBM PC (code page 437)
1845 @cindex code page 437
1846 This code page is the normal default for PCs in the U.S. It corresponds
1847 to the original IBM PC character set. This set has some, but not all, of
1848 the extended Latin-1 letters, but these letters do not have the same
1849 encoding as Latin-1. In this mode, these letters are allowed in
1850 identifiers with uppercase and lowercase equivalence.
1851
1852 @item IBM PC (code page 850)
1853 @cindex code page 850
1854 This code page is a modification of 437 extended to include all the
1855 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1856 mode, all these letters are allowed in identifiers with uppercase and
1857 lowercase equivalence.
1858
1859 @item Full Upper 8-bit
1860 Any character in the range 80-FF allowed in identifiers, and all are
1861 considered distinct. In other words, there are no uppercase and lowercase
1862 equivalences in this range. This is useful in conjunction with
1863 certain encoding schemes used for some foreign character sets (e.g.,
1864 the typical method of representing Chinese characters on the PC).
1865
1866 @item No Upper-Half
1867 No upper-half characters in the range 80-FF are allowed in identifiers.
1868 This gives Ada 83 compatibility for identifier names.
1869 @end table
1870
1871 @noindent
1872 For precise data on the encodings permitted, and the uppercase and lowercase
1873 equivalences that are recognized, see the file @file{csets.adb} in
1874 the GNAT compiler sources. You will need to obtain a full source release
1875 of GNAT to obtain this file.
1876
1877 @node Wide Character Encodings
1878 @subsection Wide Character Encodings
1879
1880 @noindent
1881 GNAT allows wide character codes to appear in character and string
1882 literals, and also optionally in identifiers, by means of the following
1883 possible encoding schemes:
1884
1885 @table @asis
1886
1887 @item Hex Coding
1888 In this encoding, a wide character is represented by the following five
1889 character sequence:
1890
1891 @smallexample
1892 ESC a b c d
1893 @end smallexample
1894
1895 @noindent
1896 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1897 characters (using uppercase letters) of the wide character code. For
1898 example, ESC A345 is used to represent the wide character with code
1899 @code{16#A345#}.
1900 This scheme is compatible with use of the full Wide_Character set.
1901
1902 @item Upper-Half Coding
1903 @cindex Upper-Half Coding
1904 The wide character with encoding @code{16#abcd#} where the upper bit is on
1905 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1906 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1907 character, but is not required to be in the upper half. This method can
1908 be also used for shift-JIS or EUC, where the internal coding matches the
1909 external coding.
1910
1911 @item Shift JIS Coding
1912 @cindex Shift JIS Coding
1913 A wide character is represented by a two-character sequence,
1914 @code{16#ab#} and
1915 @code{16#cd#}, with the restrictions described for upper-half encoding as
1916 described above. The internal character code is the corresponding JIS
1917 character according to the standard algorithm for Shift-JIS
1918 conversion. Only characters defined in the JIS code set table can be
1919 used with this encoding method.
1920
1921 @item EUC Coding
1922 @cindex EUC Coding
1923 A wide character is represented by a two-character sequence
1924 @code{16#ab#} and
1925 @code{16#cd#}, with both characters being in the upper half. The internal
1926 character code is the corresponding JIS character according to the EUC
1927 encoding algorithm. Only characters defined in the JIS code set table
1928 can be used with this encoding method.
1929
1930 @item UTF-8 Coding
1931 A wide character is represented using
1932 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1933 10646-1/Am.2. Depending on the character value, the representation
1934 is a one, two, or three byte sequence:
1935 @smallexample
1936 @iftex
1937 @leftskip=.7cm
1938 @end iftex
1939 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1940 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1941 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1942
1943 @end smallexample
1944
1945 @noindent
1946 where the @var{xxx} bits correspond to the left-padded bits of the
1947 16-bit character value. Note that all lower half ASCII characters
1948 are represented as ASCII bytes and all upper half characters and
1949 other wide characters are represented as sequences of upper-half
1950 (The full UTF-8 scheme allows for encoding 31-bit characters as
1951 6-byte sequences, but in this implementation, all UTF-8 sequences
1952 of four or more bytes length will be treated as illegal).
1953 @item Brackets Coding
1954 In this encoding, a wide character is represented by the following eight
1955 character sequence:
1956
1957 @smallexample
1958 [ " a b c d " ]
1959 @end smallexample
1960
1961 @noindent
1962 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1963 characters (using uppercase letters) of the wide character code. For
1964 example, [``A345''] is used to represent the wide character with code
1965 @code{16#A345#}. It is also possible (though not required) to use the
1966 Brackets coding for upper half characters. For example, the code
1967 @code{16#A3#} can be represented as @code{[``A3'']}.
1968
1969 This scheme is compatible with use of the full Wide_Character set,
1970 and is also the method used for wide character encoding in the standard
1971 ACVC (Ada Compiler Validation Capability) test suite distributions.
1972
1973 @end table
1974
1975 @noindent
1976 Note: Some of these coding schemes do not permit the full use of the
1977 Ada character set. For example, neither Shift JIS, nor EUC allow the
1978 use of the upper half of the Latin-1 set.
1979
1980 @node File Naming Rules
1981 @section File Naming Rules
1982
1983 @noindent
1984 The default file name is determined by the name of the unit that the
1985 file contains. The name is formed by taking the full expanded name of
1986 the unit and replacing the separating dots with hyphens and using
1987 ^lowercase^uppercase^ for all letters.
1988
1989 An exception arises if the file name generated by the above rules starts
1990 with one of the characters
1991 @ifset vms
1992 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1993 @end ifset
1994 @ifclear vms
1995 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1996 @end ifclear
1997 and the second character is a
1998 minus. In this case, the character ^tilde^dollar sign^ is used in place
1999 of the minus. The reason for this special rule is to avoid clashes with
2000 the standard names for child units of the packages System, Ada,
2001 Interfaces, and GNAT, which use the prefixes
2002 @ifset vms
2003 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2004 @end ifset
2005 @ifclear vms
2006 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2007 @end ifclear
2008 respectively.
2009
2010 The file extension is @file{.ads} for a spec and
2011 @file{.adb} for a body. The following list shows some
2012 examples of these rules.
2013
2014 @table @file
2015 @item main.ads
2016 Main (spec)
2017 @item main.adb
2018 Main (body)
2019 @item arith_functions.ads
2020 Arith_Functions (package spec)
2021 @item arith_functions.adb
2022 Arith_Functions (package body)
2023 @item func-spec.ads
2024 Func.Spec (child package spec)
2025 @item func-spec.adb
2026 Func.Spec (child package body)
2027 @item main-sub.adb
2028 Sub (subunit of Main)
2029 @item ^a~bad.adb^A$BAD.ADB^
2030 A.Bad (child package body)
2031 @end table
2032
2033 @noindent
2034 Following these rules can result in excessively long
2035 file names if corresponding
2036 unit names are long (for example, if child units or subunits are
2037 heavily nested). An option is available to shorten such long file names
2038 (called file name ``krunching''). This may be particularly useful when
2039 programs being developed with GNAT are to be used on operating systems
2040 with limited file name lengths. @xref{Using gnatkr}.
2041
2042 Of course, no file shortening algorithm can guarantee uniqueness over
2043 all possible unit names; if file name krunching is used, it is your
2044 responsibility to ensure no name clashes occur. Alternatively you
2045 can specify the exact file names that you want used, as described
2046 in the next section. Finally, if your Ada programs are migrating from a
2047 compiler with a different naming convention, you can use the gnatchop
2048 utility to produce source files that follow the GNAT naming conventions.
2049 (For details @pxref{Renaming Files Using gnatchop}.)
2050
2051 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2052 systems, case is not significant. So for example on @code{Windows XP}
2053 if the canonical name is @code{main-sub.adb}, you can use the file name
2054 @code{Main-Sub.adb} instead. However, case is significant for other
2055 operating systems, so for example, if you want to use other than
2056 canonically cased file names on a Unix system, you need to follow
2057 the procedures described in the next section.
2058
2059 @node Using Other File Names
2060 @section Using Other File Names
2061 @cindex File names
2062
2063 @noindent
2064 In the previous section, we have described the default rules used by
2065 GNAT to determine the file name in which a given unit resides. It is
2066 often convenient to follow these default rules, and if you follow them,
2067 the compiler knows without being explicitly told where to find all
2068 the files it needs.
2069
2070 However, in some cases, particularly when a program is imported from
2071 another Ada compiler environment, it may be more convenient for the
2072 programmer to specify which file names contain which units. GNAT allows
2073 arbitrary file names to be used by means of the Source_File_Name pragma.
2074 The form of this pragma is as shown in the following examples:
2075 @cindex Source_File_Name pragma
2076
2077 @smallexample @c ada
2078 @cartouche
2079 pragma Source_File_Name (My_Utilities.Stacks,
2080   Spec_File_Name => "myutilst_a.ada");
2081 pragma Source_File_name (My_Utilities.Stacks,
2082   Body_File_Name => "myutilst.ada");
2083 @end cartouche
2084 @end smallexample
2085
2086 @noindent
2087 As shown in this example, the first argument for the pragma is the unit
2088 name (in this example a child unit). The second argument has the form
2089 of a named association. The identifier
2090 indicates whether the file name is for a spec or a body;
2091 the file name itself is given by a string literal.
2092
2093 The source file name pragma is a configuration pragma, which means that
2094 normally it will be placed in the @file{gnat.adc}
2095 file used to hold configuration
2096 pragmas that apply to a complete compilation environment.
2097 For more details on how the @file{gnat.adc} file is created and used
2098 see @ref{Handling of Configuration Pragmas}.
2099 @cindex @file{gnat.adc}
2100
2101 @ifclear vms
2102 GNAT allows completely arbitrary file names to be specified using the
2103 source file name pragma. However, if the file name specified has an
2104 extension other than @file{.ads} or @file{.adb} it is necessary to use
2105 a special syntax when compiling the file. The name in this case must be
2106 preceded by the special sequence @option{-x} followed by a space and the name
2107 of the language, here @code{ada}, as in:
2108
2109 @smallexample
2110 $ gcc -c -x ada peculiar_file_name.sim
2111 @end smallexample
2112 @end ifclear
2113
2114 @noindent
2115 @command{gnatmake} handles non-standard file names in the usual manner (the
2116 non-standard file name for the main program is simply used as the
2117 argument to gnatmake). Note that if the extension is also non-standard,
2118 then it must be included in the @command{gnatmake} command, it may not
2119 be omitted.
2120
2121 @node Alternative File Naming Schemes
2122 @section Alternative File Naming Schemes
2123 @cindex File naming schemes, alternative
2124 @cindex File names
2125
2126 In the previous section, we described the use of the @code{Source_File_Name}
2127 pragma to allow arbitrary names to be assigned to individual source files.
2128 However, this approach requires one pragma for each file, and especially in
2129 large systems can result in very long @file{gnat.adc} files, and also create
2130 a maintenance problem.
2131
2132 GNAT also provides a facility for specifying systematic file naming schemes
2133 other than the standard default naming scheme previously described. An
2134 alternative scheme for naming is specified by the use of
2135 @code{Source_File_Name} pragmas having the following format:
2136 @cindex Source_File_Name pragma
2137
2138 @smallexample @c ada
2139 pragma Source_File_Name (
2140    Spec_File_Name  => FILE_NAME_PATTERN
2141  @r{[},Casing          => CASING_SPEC@r{]}
2142  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2143
2144 pragma Source_File_Name (
2145    Body_File_Name  => FILE_NAME_PATTERN
2146  @r{[},Casing          => CASING_SPEC@r{]}
2147  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2148
2149 pragma Source_File_Name (
2150    Subunit_File_Name  => FILE_NAME_PATTERN
2151  @r{[},Casing             => CASING_SPEC@r{]}
2152  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2153
2154 FILE_NAME_PATTERN ::= STRING_LITERAL
2155 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2156 @end smallexample
2157
2158 @noindent
2159 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2160 It contains a single asterisk character, and the unit name is substituted
2161 systematically for this asterisk. The optional parameter
2162 @code{Casing} indicates
2163 whether the unit name is to be all upper-case letters, all lower-case letters,
2164 or mixed-case. If no
2165 @code{Casing} parameter is used, then the default is all
2166 ^lower-case^upper-case^.
2167
2168 The optional @code{Dot_Replacement} string is used to replace any periods
2169 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2170 argument is used then separating dots appear unchanged in the resulting
2171 file name.
2172 Although the above syntax indicates that the
2173 @code{Casing} argument must appear
2174 before the @code{Dot_Replacement} argument, but it
2175 is also permissible to write these arguments in the opposite order.
2176
2177 As indicated, it is possible to specify different naming schemes for
2178 bodies, specs, and subunits. Quite often the rule for subunits is the
2179 same as the rule for bodies, in which case, there is no need to give
2180 a separate @code{Subunit_File_Name} rule, and in this case the
2181 @code{Body_File_name} rule is used for subunits as well.
2182
2183 The separate rule for subunits can also be used to implement the rather
2184 unusual case of a compilation environment (e.g.@: a single directory) which
2185 contains a subunit and a child unit with the same unit name. Although
2186 both units cannot appear in the same partition, the Ada Reference Manual
2187 allows (but does not require) the possibility of the two units coexisting
2188 in the same environment.
2189
2190 The file name translation works in the following steps:
2191
2192 @itemize @bullet
2193
2194 @item
2195 If there is a specific @code{Source_File_Name} pragma for the given unit,
2196 then this is always used, and any general pattern rules are ignored.
2197
2198 @item
2199 If there is a pattern type @code{Source_File_Name} pragma that applies to
2200 the unit, then the resulting file name will be used if the file exists. If
2201 more than one pattern matches, the latest one will be tried first, and the
2202 first attempt resulting in a reference to a file that exists will be used.
2203
2204 @item
2205 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2206 for which the corresponding file exists, then the standard GNAT default
2207 naming rules are used.
2208
2209 @end itemize
2210
2211 @noindent
2212 As an example of the use of this mechanism, consider a commonly used scheme
2213 in which file names are all lower case, with separating periods copied
2214 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2215 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2216 two pragmas appear:
2217
2218 @smallexample @c ada
2219 pragma Source_File_Name
2220   (Spec_File_Name => "*.1.ada");
2221 pragma Source_File_Name
2222   (Body_File_Name => "*.2.ada");
2223 @end smallexample
2224
2225 @noindent
2226 The default GNAT scheme is actually implemented by providing the following
2227 default pragmas internally:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2234 @end smallexample
2235
2236 @noindent
2237 Our final example implements a scheme typically used with one of the
2238 Ada 83 compilers, where the separator character for subunits was ``__''
2239 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2240 by adding @file{.ADA}, and subunits by
2241 adding @file{.SEP}. All file names were
2242 upper case. Child units were not present of course since this was an
2243 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2244 the same double underscore separator for child units.
2245
2246 @smallexample @c ada
2247 pragma Source_File_Name
2248   (Spec_File_Name => "*_.ADA",
2249    Dot_Replacement => "__",
2250    Casing = Uppercase);
2251 pragma Source_File_Name
2252   (Body_File_Name => "*.ADA",
2253    Dot_Replacement => "__",
2254    Casing = Uppercase);
2255 pragma Source_File_Name
2256   (Subunit_File_Name => "*.SEP",
2257    Dot_Replacement => "__",
2258    Casing = Uppercase);
2259 @end smallexample
2260
2261 @node Generating Object Files
2262 @section Generating Object Files
2263
2264 @noindent
2265 An Ada program consists of a set of source files, and the first step in
2266 compiling the program is to generate the corresponding object files.
2267 These are generated by compiling a subset of these source files.
2268 The files you need to compile are the following:
2269
2270 @itemize @bullet
2271 @item
2272 If a package spec has no body, compile the package spec to produce the
2273 object file for the package.
2274
2275 @item
2276 If a package has both a spec and a body, compile the body to produce the
2277 object file for the package. The source file for the package spec need
2278 not be compiled in this case because there is only one object file, which
2279 contains the code for both the spec and body of the package.
2280
2281 @item
2282 For a subprogram, compile the subprogram body to produce the object file
2283 for the subprogram. The spec, if one is present, is as usual in a
2284 separate file, and need not be compiled.
2285
2286 @item
2287 @cindex Subunits
2288 In the case of subunits, only compile the parent unit. A single object
2289 file is generated for the entire subunit tree, which includes all the
2290 subunits.
2291
2292 @item
2293 Compile child units independently of their parent units
2294 (though, of course, the spec of all the ancestor unit must be present in order
2295 to compile a child unit).
2296
2297 @item
2298 @cindex Generics
2299 Compile generic units in the same manner as any other units. The object
2300 files in this case are small dummy files that contain at most the
2301 flag used for elaboration checking. This is because GNAT always handles generic
2302 instantiation by means of macro expansion. However, it is still necessary to
2303 compile generic units, for dependency checking and elaboration purposes.
2304 @end itemize
2305
2306 @noindent
2307 The preceding rules describe the set of files that must be compiled to
2308 generate the object files for a program. Each object file has the same
2309 name as the corresponding source file, except that the extension is
2310 @file{.o} as usual.
2311
2312 You may wish to compile other files for the purpose of checking their
2313 syntactic and semantic correctness. For example, in the case where a
2314 package has a separate spec and body, you would not normally compile the
2315 spec. However, it is convenient in practice to compile the spec to make
2316 sure it is error-free before compiling clients of this spec, because such
2317 compilations will fail if there is an error in the spec.
2318
2319 GNAT provides an option for compiling such files purely for the
2320 purposes of checking correctness; such compilations are not required as
2321 part of the process of building a program. To compile a file in this
2322 checking mode, use the @option{-gnatc} switch.
2323
2324 @node Source Dependencies
2325 @section Source Dependencies
2326
2327 @noindent
2328 A given object file clearly depends on the source file which is compiled
2329 to produce it. Here we are using @dfn{depends} in the sense of a typical
2330 @code{make} utility; in other words, an object file depends on a source
2331 file if changes to the source file require the object file to be
2332 recompiled.
2333 In addition to this basic dependency, a given object may depend on
2334 additional source files as follows:
2335
2336 @itemize @bullet
2337 @item
2338 If a file being compiled @code{with}'s a unit @var{X}, the object file
2339 depends on the file containing the spec of unit @var{X}. This includes
2340 files that are @code{with}'ed implicitly either because they are parents
2341 of @code{with}'ed child units or they are run-time units required by the
2342 language constructs used in a particular unit.
2343
2344 @item
2345 If a file being compiled instantiates a library level generic unit, the
2346 object file depends on both the spec and body files for this generic
2347 unit.
2348
2349 @item
2350 If a file being compiled instantiates a generic unit defined within a
2351 package, the object file depends on the body file for the package as
2352 well as the spec file.
2353
2354 @item
2355 @findex Inline
2356 @cindex @option{-gnatn} switch
2357 If a file being compiled contains a call to a subprogram for which
2358 pragma @code{Inline} applies and inlining is activated with the
2359 @option{-gnatn} switch, the object file depends on the file containing the
2360 body of this subprogram as well as on the file containing the spec. Note
2361 that for inlining to actually occur as a result of the use of this switch,
2362 it is necessary to compile in optimizing mode.
2363
2364 @cindex @option{-gnatN} switch
2365 The use of @option{-gnatN} activates  inlining optimization
2366 that is performed by the front end of the compiler. This inlining does
2367 not require that the code generation be optimized. Like @option{-gnatn},
2368 the use of this switch generates additional dependencies.
2369
2370 When using a gcc-based back end (in practice this means using any version
2371 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2372 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2373 Historically front end inlining was more extensive than the gcc back end
2374 inlining, but that is no longer the case.
2375
2376 @item
2377 If an object file @file{O} depends on the proper body of a subunit through
2378 inlining or instantiation, it depends on the parent unit of the subunit.
2379 This means that any modification of the parent unit or one of its subunits
2380 affects the compilation of @file{O}.
2381
2382 @item
2383 The object file for a parent unit depends on all its subunit body files.
2384
2385 @item
2386 The previous two rules meant that for purposes of computing dependencies and
2387 recompilation, a body and all its subunits are treated as an indivisible whole.
2388
2389 @noindent
2390 These rules are applied transitively: if unit @code{A} @code{with}'s
2391 unit @code{B}, whose elaboration calls an inlined procedure in package
2392 @code{C}, the object file for unit @code{A} will depend on the body of
2393 @code{C}, in file @file{c.adb}.
2394
2395 The set of dependent files described by these rules includes all the
2396 files on which the unit is semantically dependent, as dictated by the
2397 Ada language standard. However, it is a superset of what the
2398 standard describes, because it includes generic, inline, and subunit
2399 dependencies.
2400
2401 An object file must be recreated by recompiling the corresponding source
2402 file if any of the source files on which it depends are modified. For
2403 example, if the @code{make} utility is used to control compilation,
2404 the rule for an Ada object file must mention all the source files on
2405 which the object file depends, according to the above definition.
2406 The determination of the necessary
2407 recompilations is done automatically when one uses @command{gnatmake}.
2408 @end itemize
2409
2410 @node The Ada Library Information Files
2411 @section The Ada Library Information Files
2412 @cindex Ada Library Information files
2413 @cindex @file{ALI} files
2414
2415 @noindent
2416 Each compilation actually generates two output files. The first of these
2417 is the normal object file that has a @file{.o} extension. The second is a
2418 text file containing full dependency information. It has the same
2419 name as the source file, but an @file{.ali} extension.
2420 This file is known as the Ada Library Information (@file{ALI}) file.
2421 The following information is contained in the @file{ALI} file.
2422
2423 @itemize @bullet
2424 @item
2425 Version information (indicates which version of GNAT was used to compile
2426 the unit(s) in question)
2427
2428 @item
2429 Main program information (including priority and time slice settings,
2430 as well as the wide character encoding used during compilation).
2431
2432 @item
2433 List of arguments used in the @command{gcc} command for the compilation
2434
2435 @item
2436 Attributes of the unit, including configuration pragmas used, an indication
2437 of whether the compilation was successful, exception model used etc.
2438
2439 @item
2440 A list of relevant restrictions applying to the unit (used for consistency)
2441 checking.
2442
2443 @item
2444 Categorization information (e.g.@: use of pragma @code{Pure}).
2445
2446 @item
2447 Information on all @code{with}'ed units, including presence of
2448 @code{Elaborate} or @code{Elaborate_All} pragmas.
2449
2450 @item
2451 Information from any @code{Linker_Options} pragmas used in the unit
2452
2453 @item
2454 Information on the use of @code{Body_Version} or @code{Version}
2455 attributes in the unit.
2456
2457 @item
2458 Dependency information. This is a list of files, together with
2459 time stamp and checksum information. These are files on which
2460 the unit depends in the sense that recompilation is required
2461 if any of these units are modified.
2462
2463 @item
2464 Cross-reference data. Contains information on all entities referenced
2465 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2466 provide cross-reference information.
2467
2468 @end itemize
2469
2470 @noindent
2471 For a full detailed description of the format of the @file{ALI} file,
2472 see the source of the body of unit @code{Lib.Writ}, contained in file
2473 @file{lib-writ.adb} in the GNAT compiler sources.
2474
2475 @node Binding an Ada Program
2476 @section Binding an Ada Program
2477
2478 @noindent
2479 When using languages such as C and C++, once the source files have been
2480 compiled the only remaining step in building an executable program
2481 is linking the object modules together. This means that it is possible to
2482 link an inconsistent version of a program, in which two units have
2483 included different versions of the same header.
2484
2485 The rules of Ada do not permit such an inconsistent program to be built.
2486 For example, if two clients have different versions of the same package,
2487 it is illegal to build a program containing these two clients.
2488 These rules are enforced by the GNAT binder, which also determines an
2489 elaboration order consistent with the Ada rules.
2490
2491 The GNAT binder is run after all the object files for a program have
2492 been created. It is given the name of the main program unit, and from
2493 this it determines the set of units required by the program, by reading the
2494 corresponding ALI files. It generates error messages if the program is
2495 inconsistent or if no valid order of elaboration exists.
2496
2497 If no errors are detected, the binder produces a main program, in Ada by
2498 default, that contains calls to the elaboration procedures of those
2499 compilation unit that require them, followed by
2500 a call to the main program. This Ada program is compiled to generate the
2501 object file for the main program. The name of
2502 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2503 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2504 main program unit.
2505
2506 Finally, the linker is used to build the resulting executable program,
2507 using the object from the main program from the bind step as well as the
2508 object files for the Ada units of the program.
2509
2510 @node Mixed Language Programming
2511 @section Mixed Language Programming
2512 @cindex Mixed Language Programming
2513
2514 @noindent
2515 This section describes how to develop a mixed-language program,
2516 specifically one that comprises units in both Ada and C.
2517
2518 @menu
2519 * Interfacing to C::
2520 * Calling Conventions::
2521 @end menu
2522
2523 @node Interfacing to C
2524 @subsection Interfacing to C
2525 @noindent
2526 Interfacing Ada with a foreign language such as C involves using
2527 compiler directives to import and/or export entity definitions in each
2528 language---using @code{extern} statements in C, for instance, and the
2529 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2530 A full treatment of these topics is provided in Appendix B, section 1
2531 of the Ada Reference Manual.
2532
2533 There are two ways to build a program using GNAT that contains some Ada
2534 sources and some foreign language sources, depending on whether or not
2535 the main subprogram is written in Ada.  Here is a source example with
2536 the main subprogram in Ada:
2537
2538 @smallexample
2539 /* file1.c */
2540 #include <stdio.h>
2541
2542 void print_num (int num)
2543 @{
2544   printf ("num is %d.\n", num);
2545   return;
2546 @}
2547
2548 /* file2.c */
2549
2550 /* num_from_Ada is declared in my_main.adb */
2551 extern int num_from_Ada;
2552
2553 int get_num (void)
2554 @{
2555   return num_from_Ada;
2556 @}
2557 @end smallexample
2558
2559 @smallexample @c ada
2560 --  my_main.adb
2561 procedure My_Main is
2562
2563    --  Declare then export an Integer entity called num_from_Ada
2564    My_Num : Integer := 10;
2565    pragma Export (C, My_Num, "num_from_Ada");
2566
2567    --  Declare an Ada function spec for Get_Num, then use
2568    --  C function get_num for the implementation.
2569    function Get_Num return Integer;
2570    pragma Import (C, Get_Num, "get_num");
2571
2572    --  Declare an Ada procedure spec for Print_Num, then use
2573    --  C function print_num for the implementation.
2574    procedure Print_Num (Num : Integer);
2575    pragma Import (C, Print_Num, "print_num");
2576
2577 begin
2578    Print_Num (Get_Num);
2579 end My_Main;
2580 @end smallexample
2581
2582 @enumerate
2583 @item
2584 To build this example, first compile the foreign language files to
2585 generate object files:
2586 @smallexample
2587 ^gcc -c file1.c^gcc -c FILE1.C^
2588 ^gcc -c file2.c^gcc -c FILE2.C^
2589 @end smallexample
2590
2591 @item
2592 Then, compile the Ada units to produce a set of object files and ALI
2593 files:
2594 @smallexample
2595 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2596 @end smallexample
2597
2598 @item
2599 Run the Ada binder on the Ada main program:
2600 @smallexample
2601 gnatbind my_main.ali
2602 @end smallexample
2603
2604 @item
2605 Link the Ada main program, the Ada objects and the other language
2606 objects:
2607 @smallexample
2608 gnatlink my_main.ali file1.o file2.o
2609 @end smallexample
2610 @end enumerate
2611
2612 The last three steps can be grouped in a single command:
2613 @smallexample
2614 gnatmake my_main.adb -largs file1.o file2.o
2615 @end smallexample
2616
2617 @cindex Binder output file
2618 @noindent
2619 If the main program is in a language other than Ada, then you may have
2620 more than one entry point into the Ada subsystem. You must use a special
2621 binder option to generate callable routines that initialize and
2622 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2623 Calls to the initialization and finalization routines must be inserted
2624 in the main program, or some other appropriate point in the code. The
2625 call to initialize the Ada units must occur before the first Ada
2626 subprogram is called, and the call to finalize the Ada units must occur
2627 after the last Ada subprogram returns. The binder will place the
2628 initialization and finalization subprograms into the
2629 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2630 sources.  To illustrate, we have the following example:
2631
2632 @smallexample
2633 /* main.c */
2634 extern void adainit (void);
2635 extern void adafinal (void);
2636 extern int add (int, int);
2637 extern int sub (int, int);
2638
2639 int main (int argc, char *argv[])
2640 @{
2641   int a = 21, b = 7;
2642
2643   adainit();
2644
2645   /* Should print "21 + 7 = 28" */
2646   printf ("%d + %d = %d\n", a, b, add (a, b));
2647   /* Should print "21 - 7 = 14" */
2648   printf ("%d - %d = %d\n", a, b, sub (a, b));
2649
2650   adafinal();
2651 @}
2652 @end smallexample
2653
2654 @smallexample @c ada
2655 --  unit1.ads
2656 package Unit1 is
2657    function Add (A, B : Integer) return Integer;
2658    pragma Export (C, Add, "add");
2659 end Unit1;
2660
2661 --  unit1.adb
2662 package body Unit1 is
2663    function Add (A, B : Integer) return Integer is
2664    begin
2665       return A + B;
2666    end Add;
2667 end Unit1;
2668
2669 --  unit2.ads
2670 package Unit2 is
2671    function Sub (A, B : Integer) return Integer;
2672    pragma Export (C, Sub, "sub");
2673 end Unit2;
2674
2675 --  unit2.adb
2676 package body Unit2 is
2677    function Sub (A, B : Integer) return Integer is
2678    begin
2679       return A - B;
2680    end Sub;
2681 end Unit2;
2682 @end smallexample
2683
2684 @enumerate
2685 @item
2686 The build procedure for this application is similar to the last
2687 example's.  First, compile the foreign language files to generate object
2688 files:
2689 @smallexample
2690 ^gcc -c main.c^gcc -c main.c^
2691 @end smallexample
2692
2693 @item
2694 Next, compile the Ada units to produce a set of object files and ALI
2695 files:
2696 @smallexample
2697 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2698 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2699 @end smallexample
2700
2701 @item
2702 Run the Ada binder on every generated ALI file.  Make sure to use the
2703 @option{-n} option to specify a foreign main program:
2704 @smallexample
2705 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2706 @end smallexample
2707
2708 @item
2709 Link the Ada main program, the Ada objects and the foreign language
2710 objects. You need only list the last ALI file here:
2711 @smallexample
2712 gnatlink unit2.ali main.o -o exec_file
2713 @end smallexample
2714
2715 This procedure yields a binary executable called @file{exec_file}.
2716 @end enumerate
2717
2718 @noindent
2719 Depending on the circumstances (for example when your non-Ada main object
2720 does not provide symbol @code{main}), you may also need to instruct the
2721 GNAT linker not to include the standard startup objects by passing the
2722 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2723
2724 @node Calling Conventions
2725 @subsection Calling Conventions
2726 @cindex Foreign Languages
2727 @cindex Calling Conventions
2728 GNAT follows standard calling sequence conventions and will thus interface
2729 to any other language that also follows these conventions. The following
2730 Convention identifiers are recognized by GNAT:
2731
2732 @table @code
2733 @cindex Interfacing to Ada
2734 @cindex Other Ada compilers
2735 @cindex Convention Ada
2736 @item Ada
2737 This indicates that the standard Ada calling sequence will be
2738 used and all Ada data items may be passed without any limitations in the
2739 case where GNAT is used to generate both the caller and callee. It is also
2740 possible to mix GNAT generated code and code generated by another Ada
2741 compiler. In this case, the data types should be restricted to simple
2742 cases, including primitive types. Whether complex data types can be passed
2743 depends on the situation. Probably it is safe to pass simple arrays, such
2744 as arrays of integers or floats. Records may or may not work, depending
2745 on whether both compilers lay them out identically. Complex structures
2746 involving variant records, access parameters, tasks, or protected types,
2747 are unlikely to be able to be passed.
2748
2749 Note that in the case of GNAT running
2750 on a platform that supports HP Ada 83, a higher degree of compatibility
2751 can be guaranteed, and in particular records are layed out in an identical
2752 manner in the two compilers. Note also that if output from two different
2753 compilers is mixed, the program is responsible for dealing with elaboration
2754 issues. Probably the safest approach is to write the main program in the
2755 version of Ada other than GNAT, so that it takes care of its own elaboration
2756 requirements, and then call the GNAT-generated adainit procedure to ensure
2757 elaboration of the GNAT components. Consult the documentation of the other
2758 Ada compiler for further details on elaboration.
2759
2760 However, it is not possible to mix the tasking run time of GNAT and
2761 HP Ada 83, All the tasking operations must either be entirely within
2762 GNAT compiled sections of the program, or entirely within HP Ada 83
2763 compiled sections of the program.
2764
2765 @cindex Interfacing to Assembly
2766 @cindex Convention Assembler
2767 @item Assembler
2768 Specifies assembler as the convention. In practice this has the
2769 same effect as convention Ada (but is not equivalent in the sense of being
2770 considered the same convention).
2771
2772 @cindex Convention Asm
2773 @findex Asm
2774 @item Asm
2775 Equivalent to Assembler.
2776
2777 @cindex Interfacing to COBOL
2778 @cindex Convention COBOL
2779 @findex COBOL
2780 @item COBOL
2781 Data will be passed according to the conventions described
2782 in section B.4 of the Ada Reference Manual.
2783
2784 @findex C
2785 @cindex Interfacing to C
2786 @cindex Convention C
2787 @item C
2788 Data will be passed according to the conventions described
2789 in section B.3 of the Ada Reference Manual.
2790
2791 A note on interfacing to a C ``varargs'' function:
2792 @findex C varargs function
2793 @cindex Interfacing to C varargs function
2794 @cindex varargs function interfaces
2795
2796 @itemize @bullet
2797 @item
2798 In C, @code{varargs} allows a function to take a variable number of
2799 arguments. There is no direct equivalent in this to Ada. One
2800 approach that can be used is to create a C wrapper for each
2801 different profile and then interface to this C wrapper. For
2802 example, to print an @code{int} value using @code{printf},
2803 create a C function @code{printfi} that takes two arguments, a
2804 pointer to a string and an int, and calls @code{printf}.
2805 Then in the Ada program, use pragma @code{Import} to
2806 interface to @code{printfi}.
2807
2808 @item
2809 It may work on some platforms to directly interface to
2810 a @code{varargs} function by providing a specific Ada profile
2811 for a particular call. However, this does not work on
2812 all platforms, since there is no guarantee that the
2813 calling sequence for a two argument normal C function
2814 is the same as for calling a @code{varargs} C function with
2815 the same two arguments.
2816 @end itemize
2817
2818 @cindex Convention Default
2819 @findex Default
2820 @item Default
2821 Equivalent to C.
2822
2823 @cindex Convention External
2824 @findex External
2825 @item External
2826 Equivalent to C.
2827
2828 @ifclear vms
2829 @findex C++
2830 @cindex Interfacing to C++
2831 @cindex Convention C++
2832 @item C_Plus_Plus (or CPP)
2833 This stands for C++. For most purposes this is identical to C.
2834 See the separate description of the specialized GNAT pragmas relating to
2835 C++ interfacing for further details.
2836 @end ifclear
2837
2838 @findex Fortran
2839 @cindex Interfacing to Fortran
2840 @cindex Convention Fortran
2841 @item Fortran
2842 Data will be passed according to the conventions described
2843 in section B.5 of the Ada Reference Manual.
2844
2845 @item Intrinsic
2846 This applies to an intrinsic operation, as defined in the Ada
2847 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2848 this means that the body of the subprogram is provided by the compiler itself,
2849 usually by means of an efficient code sequence, and that the user does not
2850 supply an explicit body for it. In an application program, the pragma may
2851 be applied to the following sets of names:
2852
2853 @itemize @bullet
2854 @item
2855 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2856 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2857 two formal parameters. The
2858 first one must be a signed integer type or a modular type with a binary
2859 modulus, and the second parameter must be of type Natural.
2860 The return type must be the same as the type of the first argument. The size
2861 of this type can only be 8, 16, 32, or 64.
2862
2863 @item
2864 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2865 The corresponding operator declaration must have parameters and result type
2866 that have the same root numeric type (for example, all three are long_float
2867 types). This simplifies the definition of operations that use type checking
2868 to perform dimensional checks:
2869
2870 @smallexample @c ada
2871 type Distance is new Long_Float;
2872 type Time     is new Long_Float;
2873 type Velocity is new Long_Float;
2874 function "/" (D : Distance; T : Time)
2875   return Velocity;
2876 pragma Import (Intrinsic, "/");
2877 @end smallexample
2878
2879 @noindent
2880 This common idiom is often programmed with a generic definition and an
2881 explicit body. The pragma makes it simpler to introduce such declarations.
2882 It incurs no overhead in compilation time or code size, because it is
2883 implemented as a single machine instruction.
2884
2885 @item
2886 General subprogram entities, to bind an Ada subprogram declaration to
2887 a compiler builtin by name with back-ends where such interfaces are
2888 available. A typical example is the set of ``__builtin'' functions
2889 exposed by the GCC back-end, as in the following example:
2890
2891 @smallexample @c ada
2892    function builtin_sqrt (F : Float) return Float;
2893    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2894 @end smallexample
2895
2896 Most of the GCC builtins are accessible this way, and as for other
2897 import conventions (e.g. C), it is the user's responsibility to ensure
2898 that the Ada subprogram profile matches the underlying builtin
2899 expectations.
2900 @end itemize
2901
2902 @noindent
2903
2904 @ifset unw
2905 @findex Stdcall
2906 @cindex Convention Stdcall
2907 @item Stdcall
2908 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2909 and specifies that the @code{Stdcall} calling sequence will be used,
2910 as defined by the NT API. Nevertheless, to ease building
2911 cross-platform bindings this convention will be handled as a @code{C} calling
2912 convention on non-Windows platforms.
2913
2914 @findex DLL
2915 @cindex Convention DLL
2916 @item DLL
2917 This is equivalent to @code{Stdcall}.
2918
2919 @findex Win32
2920 @cindex Convention Win32
2921 @item Win32
2922 This is equivalent to @code{Stdcall}.
2923 @end ifset
2924
2925 @findex Stubbed
2926 @cindex Convention Stubbed
2927 @item Stubbed
2928 This is a special convention that indicates that the compiler
2929 should provide a stub body that raises @code{Program_Error}.
2930 @end table
2931
2932 @noindent
2933 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2934 that can be used to parameterize conventions and allow additional synonyms
2935 to be specified. For example if you have legacy code in which the convention
2936 identifier Fortran77 was used for Fortran, you can use the configuration
2937 pragma:
2938
2939 @smallexample @c ada
2940 pragma Convention_Identifier (Fortran77, Fortran);
2941 @end smallexample
2942
2943 @noindent
2944 And from now on the identifier Fortran77 may be used as a convention
2945 identifier (for example in an @code{Import} pragma) with the same
2946 meaning as Fortran.
2947
2948 @ifclear vms
2949 @node Building Mixed Ada & C++ Programs
2950 @section Building Mixed Ada and C++ Programs
2951
2952 @noindent
2953 A programmer inexperienced with mixed-language development may find that
2954 building an application containing both Ada and C++ code can be a
2955 challenge.  This section gives a few
2956 hints that should make this task easier. The first section addresses
2957 the differences between interfacing with C and interfacing with C++.
2958 The second section
2959 looks into the delicate problem of linking the complete application from
2960 its Ada and C++ parts. The last section gives some hints on how the GNAT
2961 run-time library can be adapted in order to allow inter-language dispatching
2962 with a new C++ compiler.
2963
2964 @menu
2965 * Interfacing to C++::
2966 * Linking a Mixed C++ & Ada Program::
2967 * A Simple Example::
2968 * Interfacing with C++ constructors::
2969 * Interfacing with C++ at the Class Level::
2970 @end menu
2971
2972 @node Interfacing to C++
2973 @subsection Interfacing to C++
2974
2975 @noindent
2976 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2977 generating code that is compatible with the G++ Application Binary
2978 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2979
2980 @noindent
2981 Interfacing can be done at 3 levels: simple data, subprograms, and
2982 classes. In the first two cases, GNAT offers a specific @code{Convention
2983 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2984 Usually, C++ mangles the names of subprograms. To generate proper mangled
2985 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2986 This problem can also be addressed manually in two ways:
2987
2988 @itemize @bullet
2989 @item
2990 by modifying the C++ code in order to force a C convention using
2991 the @code{extern "C"} syntax.
2992
2993 @item
2994 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2995 Link_Name argument of the pragma import.
2996 @end itemize
2997
2998 @noindent
2999 Interfacing at the class level can be achieved by using the GNAT specific
3000 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3001 gnat_rm, GNAT Reference Manual}, for additional information.
3002
3003 @node Linking a Mixed C++ & Ada Program
3004 @subsection Linking a Mixed C++ & Ada Program
3005
3006 @noindent
3007 Usually the linker of the C++ development system must be used to link
3008 mixed applications because most C++ systems will resolve elaboration
3009 issues (such as calling constructors on global class instances)
3010 transparently during the link phase. GNAT has been adapted to ease the
3011 use of a foreign linker for the last phase. Three cases can be
3012 considered:
3013 @enumerate
3014
3015 @item
3016 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3017 The C++ linker can simply be called by using the C++ specific driver
3018 called @code{g++}.
3019
3020 Note that if the C++ code uses inline functions, you will need to
3021 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3022 order to provide an existing function implementation that the Ada code can
3023 link with.
3024
3025 @smallexample
3026 $ g++ -c -fkeep-inline-functions file1.C
3027 $ g++ -c -fkeep-inline-functions file2.C
3028 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3029 @end smallexample
3030
3031 @item
3032 Using GNAT and G++ from two different GCC installations: If both
3033 compilers are on the @env{PATH}, the previous method may be used. It is
3034 important to note that environment variables such as
3035 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3036 @env{GCC_ROOT} will affect both compilers
3037 at the same time and may make one of the two compilers operate
3038 improperly if set during invocation of the wrong compiler.  It is also
3039 very important that the linker uses the proper @file{libgcc.a} GCC
3040 library -- that is, the one from the C++ compiler installation. The
3041 implicit link command as suggested in the @command{gnatmake} command
3042 from the former example can be replaced by an explicit link command with
3043 the full-verbosity option in order to verify which library is used:
3044 @smallexample
3045 $ gnatbind ada_unit
3046 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3047 @end smallexample
3048 If there is a problem due to interfering environment variables, it can
3049 be worked around by using an intermediate script. The following example
3050 shows the proper script to use when GNAT has not been installed at its
3051 default location and g++ has been installed at its default location:
3052
3053 @smallexample
3054 $ cat ./my_script
3055 #!/bin/sh
3056 unset BINUTILS_ROOT
3057 unset GCC_ROOT
3058 c++ $*
3059 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3060 @end smallexample
3061
3062 @item
3063 Using a non-GNU C++ compiler: The commands previously described can be
3064 used to insure that the C++ linker is used. Nonetheless, you need to add
3065 a few more parameters to the link command line, depending on the exception
3066 mechanism used.
3067
3068 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3069 to the libgcc libraries are required:
3070
3071 @smallexample
3072 $ cat ./my_script
3073 #!/bin/sh
3074 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3075 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3076 @end smallexample
3077
3078 Where CC is the name of the non-GNU C++ compiler.
3079
3080 If the @code{zero cost} exception mechanism is used, and the platform
3081 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3082 paths to more objects are required:
3083
3084 @smallexample
3085 $ cat ./my_script
3086 #!/bin/sh
3087 CC `gcc -print-file-name=crtbegin.o` $* \
3088 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3089 `gcc -print-file-name=crtend.o`
3090 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3091 @end smallexample
3092
3093 If the @code{zero cost} exception mechanism is used, and the platform
3094 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3095 Tru64 or AIX), the simple approach described above will not work and
3096 a pre-linking phase using GNAT will be necessary.
3097
3098 @end enumerate
3099
3100 Another alternative is to use the @command{gprbuild} multi-language builder
3101 which has a large knowledge base and knows how to link Ada and C++ code
3102 together automatically in most cases.
3103
3104 @node A Simple Example
3105 @subsection  A Simple Example
3106 @noindent
3107 The following example, provided as part of the GNAT examples, shows how
3108 to achieve procedural interfacing between Ada and C++ in both
3109 directions. The C++ class A has two methods. The first method is exported
3110 to Ada by the means of an extern C wrapper function. The second method
3111 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3112 a limited record with a layout comparable to the C++ class. The Ada
3113 subprogram, in turn, calls the C++ method. So, starting from the C++
3114 main program, the process passes back and forth between the two
3115 languages.
3116
3117 @noindent
3118 Here are the compilation commands:
3119 @smallexample
3120 $ gnatmake -c simple_cpp_interface
3121 $ g++ -c cpp_main.C
3122 $ g++ -c ex7.C
3123 $ gnatbind -n simple_cpp_interface
3124 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3125       -lstdc++ ex7.o cpp_main.o
3126 @end smallexample
3127
3128 @noindent
3129 Here are the corresponding sources:
3130 @smallexample
3131
3132 //cpp_main.C
3133
3134 #include "ex7.h"
3135
3136 extern "C" @{
3137   void adainit (void);
3138   void adafinal (void);
3139   void method1 (A *t);
3140 @}
3141
3142 void method1 (A *t)
3143 @{
3144   t->method1 ();
3145 @}
3146
3147 int main ()
3148 @{
3149   A obj;
3150   adainit ();
3151   obj.method2 (3030);
3152   adafinal ();
3153 @}
3154
3155 //ex7.h
3156
3157 class Origin @{
3158  public:
3159   int o_value;
3160 @};
3161 class A : public Origin @{
3162  public:
3163   void method1 (void);
3164   void method2 (int v);
3165   A();
3166   int   a_value;
3167 @};
3168
3169 //ex7.C
3170
3171 #include "ex7.h"
3172 #include <stdio.h>
3173
3174 extern "C" @{ void ada_method2 (A *t, int v);@}
3175
3176 void A::method1 (void)
3177 @{
3178   a_value = 2020;
3179   printf ("in A::method1, a_value = %d \n",a_value);
3180
3181 @}
3182
3183 void A::method2 (int v)
3184 @{
3185    ada_method2 (this, v);
3186    printf ("in A::method2, a_value = %d \n",a_value);
3187
3188 @}
3189
3190 A::A(void)
3191 @{
3192    a_value = 1010;
3193   printf ("in A::A, a_value = %d \n",a_value);
3194 @}
3195 @end smallexample
3196
3197 @smallexample @c ada
3198 -- Ada sources
3199 package body Simple_Cpp_Interface is
3200
3201    procedure Ada_Method2 (This : in out A; V : Integer) is
3202    begin
3203       Method1 (This);
3204       This.A_Value := V;
3205    end Ada_Method2;
3206
3207 end Simple_Cpp_Interface;
3208
3209 with System;
3210 package Simple_Cpp_Interface is
3211    type A is limited
3212       record
3213          Vptr    : System.Address;
3214          O_Value : Integer;
3215          A_Value : Integer;
3216       end record;
3217    pragma Convention (C, A);
3218
3219    procedure Method1 (This : in out A);
3220    pragma Import (C, Method1);
3221
3222    procedure Ada_Method2 (This : in out A; V : Integer);
3223    pragma Export (C, Ada_Method2);
3224
3225 end Simple_Cpp_Interface;
3226 @end smallexample
3227
3228 @node Interfacing with C++ constructors
3229 @subsection Interfacing with C++ constructors
3230 @noindent
3231
3232 In order to interface with C++ constructors GNAT provides the
3233 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3234 gnat_rm, GNAT Reference Manual}, for additional information).
3235 In this section we present some common uses of C++ constructors
3236 in mixed-languages programs in GNAT.
3237
3238 Let us assume that we need to interface with the following
3239 C++ class:
3240
3241 @smallexample
3242 @b{class} Root @{
3243 @b{public}:
3244   int  a_value;
3245   int  b_value;
3246   @b{virtual} int Get_Value ();
3247   Root();              // Default constructor
3248   Root(int v);         // 1st non-default constructor
3249   Root(int v, int w);  // 2nd non-default constructor
3250 @};
3251 @end smallexample
3252
3253 For this purpose we can write the following package spec (further
3254 information on how to build this spec is available in
3255 @ref{Interfacing with C++ at the Class Level} and
3256 @ref{Generating Ada Bindings for C and C++ headers}).
3257
3258 @smallexample @c ada
3259 with Interfaces.C; use Interfaces.C;
3260 package Pkg_Root is
3261   type Root is tagged limited record
3262      A_Value : int;
3263      B_Value : int;
3264   end record;
3265   pragma Import (CPP, Root);
3266
3267   function Get_Value (Obj : Root) return int;
3268   pragma Import (CPP, Get_Value);
3269
3270   function Constructor return Root;
3271   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3272
3273   function Constructor (v : Integer) return Root;
3274   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3275
3276   function Constructor (v, w : Integer) return Root;
3277   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3278 end Pkg_Root;
3279 @end smallexample
3280
3281 On the Ada side the constructor is represented by a function (whose
3282 name is arbitrary) that returns the classwide type corresponding to
3283 the imported C++ class. Although the constructor is described as a
3284 function, it is typically a procedure with an extra implicit argument
3285 (the object being initialized) at the implementation level. GNAT
3286 issues the appropriate call, whatever it is, to get the object
3287 properly initialized.
3288
3289 Constructors can only appear in the following contexts:
3290
3291 @itemize @bullet
3292 @item
3293 On the right side of an initialization of an object of type @var{T}.
3294 @item
3295 On the right side of an initialization of a record component of type @var{T}.
3296 @item
3297 In an Ada 2005 limited aggregate.
3298 @item
3299 In an Ada 2005 nested limited aggregate.
3300 @item
3301 In an Ada 2005 limited aggregate that initializes an object built in
3302 place by an extended return statement.
3303 @end itemize
3304
3305 @noindent
3306 In a declaration of an object whose type is a class imported from C++,
3307 either the default C++ constructor is implicitly called by GNAT, or
3308 else the required C++ constructor must be explicitly called in the
3309 expression that initializes the object. For example:
3310
3311 @smallexample @c ada
3312   Obj1 : Root;
3313   Obj2 : Root := Constructor;
3314   Obj3 : Root := Constructor (v => 10);
3315   Obj4 : Root := Constructor (30, 40);
3316 @end smallexample
3317
3318 The first two declarations are equivalent: in both cases the default C++
3319 constructor is invoked (in the former case the call to the constructor is
3320 implicit, and in the latter case the call is explicit in the object
3321 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3322 that takes an integer argument, and @code{Obj4} is initialized by the
3323 non-default C++ constructor that takes two integers.
3324
3325 Let us derive the imported C++ class in the Ada side. For example:
3326
3327 @smallexample @c ada
3328   type DT is new Root with record
3329      C_Value : Natural := 2009;
3330   end record;
3331 @end smallexample
3332
3333 In this case the components DT inherited from the C++ side must be
3334 initialized by a C++ constructor, and the additional Ada components
3335 of type DT are initialized by GNAT. The initialization of such an
3336 object is done either by default, or by means of a function returning
3337 an aggregate of type DT, or by means of an extension aggregate.
3338
3339 @smallexample @c ada
3340   Obj5 : DT;
3341   Obj6 : DT := Function_Returning_DT (50);
3342   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3343 @end smallexample
3344
3345 The declaration of @code{Obj5} invokes the default constructors: the
3346 C++ default constructor of the parent type takes care of the initialization
3347 of the components inherited from Root, and GNAT takes care of the default
3348 initialization of the additional Ada components of type DT (that is,
3349 @code{C_Value} is initialized to value 2009). The order of invocation of
3350 the constructors is consistent with the order of elaboration required by
3351 Ada and C++. That is, the constructor of the parent type is always called
3352 before the constructor of the derived type.
3353
3354 Let us now consider a record that has components whose type is imported
3355 from C++. For example:
3356
3357 @smallexample @c ada
3358   type Rec1 is limited record
3359      Data1 : Root := Constructor (10);
3360      Value : Natural := 1000;
3361   end record;
3362
3363   type Rec2 (D : Integer := 20) is limited record
3364      Rec   : Rec1;
3365      Data2 : Root := Constructor (D, 30);
3366   end record;
3367 @end smallexample
3368
3369 The initialization of an object of type @code{Rec2} will call the
3370 non-default C++ constructors specified for the imported components.
3371 For example:
3372
3373 @smallexample @c ada
3374   Obj8 : Rec2 (40);
3375 @end smallexample
3376
3377 Using Ada 2005 we can use limited aggregates to initialize an object
3378 invoking C++ constructors that differ from those specified in the type
3379 declarations. For example:
3380
3381 @smallexample @c ada
3382   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3383                           others => <>),
3384                   others => <>);
3385 @end smallexample
3386
3387 The above declaration uses an Ada 2005 limited aggregate to
3388 initialize @code{Obj9}, and the C++ constructor that has two integer
3389 arguments is invoked to initialize the @code{Data1} component instead
3390 of the constructor specified in the declaration of type @code{Rec1}. In
3391 Ada 2005 the box in the aggregate indicates that unspecified components
3392 are initialized using the expression (if any) available in the component
3393 declaration. That is, in this case discriminant @code{D} is initialized
3394 to value @code{20}, @code{Value} is initialized to value 1000, and the
3395 non-default C++ constructor that handles two integers takes care of
3396 initializing component @code{Data2} with values @code{20,30}.
3397
3398 In Ada 2005 we can use the extended return statement to build the Ada
3399 equivalent to C++ non-default constructors. For example:
3400
3401 @smallexample @c ada
3402   function Constructor (V : Integer) return Rec2 is
3403   begin
3404      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3405                                    others => <>),
3406                            others => <>) do
3407         --  Further actions required for construction of
3408         --  objects of type Rec2
3409         ...
3410      end record;
3411   end Constructor;
3412 @end smallexample
3413
3414 In this example the extended return statement construct is used to
3415 build in place the returned object whose components are initialized
3416 by means of a limited aggregate. Any further action associated with
3417 the constructor can be placed inside the construct.
3418
3419 @node Interfacing with C++ at the Class Level
3420 @subsection Interfacing with C++ at the Class Level
3421 @noindent
3422 In this section we demonstrate the GNAT features for interfacing with
3423 C++ by means of an example making use of Ada 2005 abstract interface
3424 types. This example consists of a classification of animals; classes
3425 have been used to model our main classification of animals, and
3426 interfaces provide support for the management of secondary
3427 classifications. We first demonstrate a case in which the types and
3428 constructors are defined on the C++ side and imported from the Ada
3429 side, and latter the reverse case.
3430
3431 The root of our derivation will be the @code{Animal} class, with a
3432 single private attribute (the @code{Age} of the animal) and two public
3433 primitives to set and get the value of this attribute.
3434
3435 @smallexample
3436 @b{class} Animal @{
3437  @b{public}:
3438    @b{virtual} void Set_Age (int New_Age);
3439    @b{virtual} int Age ();
3440  @b{private}:
3441    int Age_Count;
3442 @};
3443 @end smallexample
3444
3445 Abstract interface types are defined in C++ by means of classes with pure
3446 virtual functions and no data members. In our example we will use two
3447 interfaces that provide support for the common management of @code{Carnivore}
3448 and @code{Domestic} animals:
3449
3450 @smallexample
3451 @b{class} Carnivore @{
3452 @b{public}:
3453    @b{virtual} int Number_Of_Teeth () = 0;
3454 @};
3455
3456 @b{class} Domestic @{
3457 @b{public}:
3458    @b{virtual void} Set_Owner (char* Name) = 0;
3459 @};
3460 @end smallexample
3461
3462 Using these declarations, we can now say that a @code{Dog} is an animal that is
3463 both Carnivore and Domestic, that is:
3464
3465 @smallexample
3466 @b{class} Dog : Animal, Carnivore, Domestic @{
3467  @b{public}:
3468    @b{virtual} int  Number_Of_Teeth ();
3469    @b{virtual} void Set_Owner (char* Name);
3470
3471    Dog(); // Constructor
3472  @b{private}:
3473    int  Tooth_Count;
3474    char *Owner;
3475 @};
3476 @end smallexample
3477
3478 In the following examples we will assume that the previous declarations are
3479 located in a file named @code{animals.h}. The following package demonstrates
3480 how to import these C++ declarations from the Ada side:
3481
3482 @smallexample @c ada
3483 with Interfaces.C.Strings; use Interfaces.C.Strings;
3484 package Animals is
3485   type Carnivore is interface;
3486   pragma Convention (C_Plus_Plus, Carnivore);
3487   function Number_Of_Teeth (X : Carnivore)
3488      return Natural is abstract;
3489
3490   type Domestic is interface;
3491   pragma Convention (C_Plus_Plus, Set_Owner);
3492   procedure Set_Owner
3493     (X    : in out Domestic;
3494      Name : Chars_Ptr) is abstract;
3495
3496   type Animal is tagged record
3497     Age : Natural := 0;
3498   end record;
3499   pragma Import (C_Plus_Plus, Animal);
3500
3501   procedure Set_Age (X : in out Animal; Age : Integer);
3502   pragma Import (C_Plus_Plus, Set_Age);
3503
3504   function Age (X : Animal) return Integer;
3505   pragma Import (C_Plus_Plus, Age);
3506
3507   type Dog is new Animal and Carnivore and Domestic with record
3508     Tooth_Count : Natural;
3509     Owner       : String (1 .. 30);
3510   end record;
3511   pragma Import (C_Plus_Plus, Dog);
3512
3513   function Number_Of_Teeth (A : Dog) return Integer;
3514   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3515
3516   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3517   pragma Import (C_Plus_Plus, Set_Owner);
3518
3519   function New_Dog return Dog;
3520   pragma CPP_Constructor (New_Dog);
3521   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3522 end Animals;
3523 @end smallexample
3524
3525 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3526 interfacing with these C++ classes is easy. The only requirement is that all
3527 the primitives and components must be declared exactly in the same order in
3528 the two languages.
3529
3530 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3531 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3532 the arguments to the called primitives will be the same as for C++. For the
3533 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3534 to indicate that they have been defined on the C++ side; this is required
3535 because the dispatch table associated with these tagged types will be built
3536 in the C++ side and therefore will not contain the predefined Ada primitives
3537 which Ada would otherwise expect.
3538
3539 As the reader can see there is no need to indicate the C++ mangled names
3540 associated with each subprogram because it is assumed that all the calls to
3541 these primitives will be dispatching calls. The only exception is the
3542 constructor, which must be registered with the compiler by means of
3543 @code{pragma CPP_Constructor} and needs to provide its associated C++
3544 mangled name because the Ada compiler generates direct calls to it.
3545
3546 With the above packages we can now declare objects of type Dog on the Ada side
3547 and dispatch calls to the corresponding subprograms on the C++ side. We can
3548 also extend the tagged type Dog with further fields and primitives, and
3549 override some of its C++ primitives on the Ada side. For example, here we have
3550 a type derivation defined on the Ada side that inherits all the dispatching
3551 primitives of the ancestor from the C++ side.
3552
3553 @smallexample
3554 @b{with} Animals; @b{use} Animals;
3555 @b{package} Vaccinated_Animals @b{is}
3556   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3557   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3558 @b{end} Vaccinated_Animals;
3559 @end smallexample
3560
3561 It is important to note that, because of the ABI compatibility, the programmer
3562 does not need to add any further information to indicate either the object
3563 layout or the dispatch table entry associated with each dispatching operation.
3564
3565 Now let us define all the types and constructors on the Ada side and export
3566 them to C++, using the same hierarchy of our previous example:
3567
3568 @smallexample @c ada
3569 with Interfaces.C.Strings;
3570 use Interfaces.C.Strings;
3571 package Animals is
3572   type Carnivore is interface;
3573   pragma Convention (C_Plus_Plus, Carnivore);
3574   function Number_Of_Teeth (X : Carnivore)
3575      return Natural is abstract;
3576
3577   type Domestic is interface;
3578   pragma Convention (C_Plus_Plus, Set_Owner);
3579   procedure Set_Owner
3580     (X    : in out Domestic;
3581      Name : Chars_Ptr) is abstract;
3582
3583   type Animal is tagged record
3584     Age : Natural := 0;
3585   end record;
3586   pragma Convention (C_Plus_Plus, Animal);
3587
3588   procedure Set_Age (X : in out Animal; Age : Integer);
3589   pragma Export (C_Plus_Plus, Set_Age);
3590
3591   function Age (X : Animal) return Integer;
3592   pragma Export (C_Plus_Plus, Age);
3593
3594   type Dog is new Animal and Carnivore and Domestic with record
3595     Tooth_Count : Natural;
3596     Owner       : String (1 .. 30);
3597   end record;
3598   pragma Convention (C_Plus_Plus, Dog);
3599
3600   function Number_Of_Teeth (A : Dog) return Integer;
3601   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3602
3603   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3604   pragma Export (C_Plus_Plus, Set_Owner);
3605
3606   function New_Dog return Dog'Class;
3607   pragma Export (C_Plus_Plus, New_Dog);
3608 end Animals;
3609 @end smallexample
3610
3611 Compared with our previous example the only difference is the use of
3612 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3613 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3614 nothing else to be done; as explained above, the only requirement is that all
3615 the primitives and components are declared in exactly the same order.
3616
3617 For completeness, let us see a brief C++ main program that uses the
3618 declarations available in @code{animals.h} (presented in our first example) to
3619 import and use the declarations from the Ada side, properly initializing and
3620 finalizing the Ada run-time system along the way:
3621
3622 @smallexample
3623 @b{#include} "animals.h"
3624 @b{#include} <iostream>
3625 @b{using namespace} std;
3626
3627 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3628 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3629 void Check_Animal (Animal *obj)       @{@dots{}@}
3630 void Check_Dog (Dog *obj)             @{@dots{}@}
3631
3632 @b{extern} "C" @{
3633   void adainit (void);
3634   void adafinal (void);
3635   Dog* new_dog ();
3636 @}
3637
3638 void test ()
3639 @{
3640   Dog *obj = new_dog();  // Ada constructor
3641   Check_Carnivore (obj); // Check secondary DT
3642   Check_Domestic (obj);  // Check secondary DT
3643   Check_Animal (obj);    // Check primary DT
3644   Check_Dog (obj);       // Check primary DT
3645 @}
3646
3647 int main ()
3648 @{
3649   adainit ();  test();  adafinal ();
3650   return 0;
3651 @}
3652 @end smallexample
3653
3654 @node Comparison between GNAT and C/C++ Compilation Models
3655 @section Comparison between GNAT and C/C++ Compilation Models
3656
3657 @noindent
3658 The GNAT model of compilation is close to the C and C++ models. You can
3659 think of Ada specs as corresponding to header files in C. As in C, you
3660 don't need to compile specs; they are compiled when they are used. The
3661 Ada @code{with} is similar in effect to the @code{#include} of a C
3662 header.
3663
3664 One notable difference is that, in Ada, you may compile specs separately
3665 to check them for semantic and syntactic accuracy. This is not always
3666 possible with C headers because they are fragments of programs that have
3667 less specific syntactic or semantic rules.
3668
3669 The other major difference is the requirement for running the binder,
3670 which performs two important functions. First, it checks for
3671 consistency. In C or C++, the only defense against assembling
3672 inconsistent programs lies outside the compiler, in a makefile, for
3673 example. The binder satisfies the Ada requirement that it be impossible
3674 to construct an inconsistent program when the compiler is used in normal
3675 mode.
3676
3677 @cindex Elaboration order control
3678 The other important function of the binder is to deal with elaboration
3679 issues. There are also elaboration issues in C++ that are handled
3680 automatically. This automatic handling has the advantage of being
3681 simpler to use, but the C++ programmer has no control over elaboration.
3682 Where @code{gnatbind} might complain there was no valid order of
3683 elaboration, a C++ compiler would simply construct a program that
3684 malfunctioned at run time.
3685 @end ifclear
3686
3687 @node Comparison between GNAT and Conventional Ada Library Models
3688 @section Comparison between GNAT and Conventional Ada Library Models
3689
3690 @noindent
3691 This section is intended for Ada programmers who have
3692 used an Ada compiler implementing the traditional Ada library
3693 model, as described in the Ada Reference Manual.
3694
3695 @cindex GNAT library
3696 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3697 source files themselves acts as the library. Compiling Ada programs does
3698 not generate any centralized information, but rather an object file and
3699 a ALI file, which are of interest only to the binder and linker.
3700 In a traditional system, the compiler reads information not only from
3701 the source file being compiled, but also from the centralized library.
3702 This means that the effect of a compilation depends on what has been
3703 previously compiled. In particular:
3704
3705 @itemize @bullet
3706 @item
3707 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3708 to the version of the unit most recently compiled into the library.
3709
3710 @item
3711 Inlining is effective only if the necessary body has already been
3712 compiled into the library.
3713
3714 @item
3715 Compiling a unit may obsolete other units in the library.
3716 @end itemize
3717
3718 @noindent
3719 In GNAT, compiling one unit never affects the compilation of any other
3720 units because the compiler reads only source files. Only changes to source
3721 files can affect the results of a compilation. In particular:
3722
3723 @itemize @bullet
3724 @item
3725 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3726 to the source version of the unit that is currently accessible to the
3727 compiler.
3728
3729 @item
3730 @cindex Inlining
3731 Inlining requires the appropriate source files for the package or
3732 subprogram bodies to be available to the compiler. Inlining is always
3733 effective, independent of the order in which units are complied.
3734
3735 @item
3736 Compiling a unit never affects any other compilations. The editing of
3737 sources may cause previous compilations to be out of date if they
3738 depended on the source file being modified.
3739 @end itemize
3740
3741 @noindent
3742 The most important result of these differences is that order of compilation
3743 is never significant in GNAT. There is no situation in which one is
3744 required to do one compilation before another. What shows up as order of
3745 compilation requirements in the traditional Ada library becomes, in
3746 GNAT, simple source dependencies; in other words, there is only a set
3747 of rules saying what source files must be present when a file is
3748 compiled.
3749
3750 @ifset vms
3751 @node Placement of temporary files
3752 @section Placement of temporary files
3753 @cindex Temporary files (user control over placement)
3754
3755 @noindent
3756 GNAT creates temporary files in the directory designated by the environment
3757 variable @env{TMPDIR}.
3758 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3759 for detailed information on how environment variables are resolved.
3760 For most users the easiest way to make use of this feature is to simply
3761 define @env{TMPDIR} as a job level logical name).
3762 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3763 for compiler temporary files, then you can include something like the
3764 following command in your @file{LOGIN.COM} file:
3765
3766 @smallexample
3767 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3768 @end smallexample
3769
3770 @noindent
3771 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3772 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3773 designated by @env{TEMP}.
3774 If none of these environment variables are defined then GNAT uses the
3775 directory designated by the logical name @code{SYS$SCRATCH:}
3776 (by default the user's home directory). If all else fails
3777 GNAT uses the current directory for temporary files.
3778 @end ifset
3779
3780 @c *************************
3781 @node Compiling Using gcc
3782 @chapter Compiling Using @command{gcc}
3783
3784 @noindent
3785 This chapter discusses how to compile Ada programs using the @command{gcc}
3786 command. It also describes the set of switches
3787 that can be used to control the behavior of the compiler.
3788 @menu
3789 * Compiling Programs::
3790 * Switches for gcc::
3791 * Search Paths and the Run-Time Library (RTL)::
3792 * Order of Compilation Issues::
3793 * Examples::
3794 @end menu
3795
3796 @node Compiling Programs
3797 @section Compiling Programs
3798
3799 @noindent
3800 The first step in creating an executable program is to compile the units
3801 of the program using the @command{gcc} command. You must compile the
3802 following files:
3803
3804 @itemize @bullet
3805 @item
3806 the body file (@file{.adb}) for a library level subprogram or generic
3807 subprogram
3808
3809 @item
3810 the spec file (@file{.ads}) for a library level package or generic
3811 package that has no body
3812
3813 @item
3814 the body file (@file{.adb}) for a library level package
3815 or generic package that has a body
3816
3817 @end itemize
3818
3819 @noindent
3820 You need @emph{not} compile the following files
3821
3822 @itemize @bullet
3823
3824 @item
3825 the spec of a library unit which has a body
3826
3827 @item
3828 subunits
3829 @end itemize
3830
3831 @noindent
3832 because they are compiled as part of compiling related units. GNAT
3833 package specs
3834 when the corresponding body is compiled, and subunits when the parent is
3835 compiled.
3836
3837 @cindex cannot generate code
3838 If you attempt to compile any of these files, you will get one of the
3839 following error messages (where @var{fff} is the name of the file you
3840 compiled):
3841
3842 @smallexample
3843 cannot generate code for file @var{fff} (package spec)
3844 to check package spec, use -gnatc
3845
3846 cannot generate code for file @var{fff} (missing subunits)
3847 to check parent unit, use -gnatc
3848
3849 cannot generate code for file @var{fff} (subprogram spec)
3850 to check subprogram spec, use -gnatc
3851
3852 cannot generate code for file @var{fff} (subunit)
3853 to check subunit, use -gnatc
3854 @end smallexample
3855
3856 @noindent
3857 As indicated by the above error messages, if you want to submit
3858 one of these files to the compiler to check for correct semantics
3859 without generating code, then use the @option{-gnatc} switch.
3860
3861 The basic command for compiling a file containing an Ada unit is
3862
3863 @smallexample
3864 @c $ gcc -c @ovar{switches} @file{file name}
3865 @c Expanding @ovar macro inline (explanation in macro def comments)
3866 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3867 @end smallexample
3868
3869 @noindent
3870 where @var{file name} is the name of the Ada file (usually
3871 having an extension
3872 @file{.ads} for a spec or @file{.adb} for a body).
3873 @ifclear vms
3874 You specify the
3875 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3876 @end ifclear
3877 The result of a successful compilation is an object file, which has the
3878 same name as the source file but an extension of @file{.o} and an Ada
3879 Library Information (ALI) file, which also has the same name as the
3880 source file, but with @file{.ali} as the extension. GNAT creates these
3881 two output files in the current directory, but you may specify a source
3882 file in any directory using an absolute or relative path specification
3883 containing the directory information.
3884
3885 @findex gnat1
3886 @command{gcc} is actually a driver program that looks at the extensions of
3887 the file arguments and loads the appropriate compiler. For example, the
3888 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3889 These programs are in directories known to the driver program (in some
3890 configurations via environment variables you set), but need not be in
3891 your path. The @command{gcc} driver also calls the assembler and any other
3892 utilities needed to complete the generation of the required object
3893 files.
3894
3895 It is possible to supply several file names on the same @command{gcc}
3896 command. This causes @command{gcc} to call the appropriate compiler for
3897 each file. For example, the following command lists three separate
3898 files to be compiled:
3899
3900 @smallexample
3901 $ gcc -c x.adb y.adb z.c
3902 @end smallexample
3903
3904 @noindent
3905 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3906 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3907 The compiler generates three object files @file{x.o}, @file{y.o} and
3908 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3909 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3910 @ifclear vms
3911 except for
3912 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3913 @end ifclear
3914
3915 @node Switches for gcc
3916 @section Switches for @command{gcc}
3917
3918 @noindent
3919 The @command{gcc} command accepts switches that control the
3920 compilation process. These switches are fully described in this section.
3921 First we briefly list all the switches, in alphabetical order, then we
3922 describe the switches in more detail in functionally grouped sections.
3923
3924 More switches exist for GCC than those documented here, especially
3925 for specific targets. However, their use is not recommended as
3926 they may change code generation in ways that are incompatible with
3927 the Ada run-time library, or can cause inconsistencies between
3928 compilation units.
3929
3930 @menu
3931 * Output and Error Message Control::
3932 * Warning Message Control::
3933 * Debugging and Assertion Control::
3934 * Validity Checking::
3935 * Style Checking::
3936 * Run-Time Checks::
3937 * Using gcc for Syntax Checking::
3938 * Using gcc for Semantic Checking::
3939 * Compiling Different Versions of Ada::
3940 * Character Set Control::
3941 * File Naming Control::
3942 * Subprogram Inlining Control::
3943 * Auxiliary Output Control::
3944 * Debugging Control::
3945 * Exception Handling Control::
3946 * Units to Sources Mapping Files::
3947 * Integrated Preprocessing::
3948 * Code Generation Control::
3949 @ifset vms
3950 * Return Codes::
3951 @end ifset
3952 @end menu
3953
3954 @table @option
3955 @c !sort!
3956 @ifclear vms
3957 @cindex @option{-b} (@command{gcc})
3958 @item -b @var{target}
3959 Compile your program to run on @var{target}, which is the name of a
3960 system configuration. You must have a GNAT cross-compiler built if
3961 @var{target} is not the same as your host system.
3962
3963 @item -B@var{dir}
3964 @cindex @option{-B} (@command{gcc})
3965 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3966 from @var{dir} instead of the default location. Only use this switch
3967 when multiple versions of the GNAT compiler are available.
3968 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3969 GNU Compiler Collection (GCC)}, for further details. You would normally
3970 use the @option{-b} or @option{-V} switch instead.
3971
3972 @item -c
3973 @cindex @option{-c} (@command{gcc})
3974 Compile. Always use this switch when compiling Ada programs.
3975
3976 Note: for some other languages when using @command{gcc}, notably in
3977 the case of C and C++, it is possible to use
3978 use @command{gcc} without a @option{-c} switch to
3979 compile and link in one step. In the case of GNAT, you
3980 cannot use this approach, because the binder must be run
3981 and @command{gcc} cannot be used to run the GNAT binder.
3982 @end ifclear
3983
3984 @item -fno-inline
3985 @cindex @option{-fno-inline} (@command{gcc})
3986 Suppresses all inlining, even if other optimization or inlining
3987 switches are set.  This includes suppression of inlining that
3988 results from the use of the pragma @code{Inline_Always}.
3989 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3990 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3991 effect if this switch is present.
3992
3993 @item -fno-inline-functions
3994 @cindex @option{-fno-inline-functions} (@command{gcc})
3995 Suppresses automatic inlining of subprograms, which is enabled
3996 if @option{-O3} is used.
3997
3998 @item -fno-inline-small-functions
3999 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4000 Suppresses automatic inlining of small subprograms, which is enabled
4001 if @option{-O2} is used.
4002
4003 @item -fno-inline-functions-called-once
4004 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4005 Suppresses inlining of subprograms local to the unit and called once
4006 from within it, which is enabled if @option{-O1} is used.
4007
4008 @item -fno-ivopts
4009 @cindex @option{-fno-ivopts} (@command{gcc})
4010 Suppresses high-level loop induction variable optimizations, which are
4011 enabled if @option{-O1} is used. These optimizations are generally
4012 profitable but, for some specific cases of loops with numerous uses
4013 of the iteration variable that follow a common pattern, they may end
4014 up destroying the regularity that could be exploited at a lower level
4015 and thus producing inferior code.
4016
4017 @item -fno-strict-aliasing
4018 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4019 Causes the compiler to avoid assumptions regarding non-aliasing
4020 of objects of different types. See
4021 @ref{Optimization and Strict Aliasing} for details.
4022
4023 @item -fstack-check
4024 @cindex @option{-fstack-check} (@command{gcc})
4025 Activates stack checking.
4026 See @ref{Stack Overflow Checking} for details.
4027
4028 @item -fstack-usage
4029 @cindex @option{-fstack-usage} (@command{gcc})
4030 Makes the compiler output stack usage information for the program, on a
4031 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4032
4033 @item -fcallgraph-info@r{[}=su@r{]}
4034 @cindex @option{-fcallgraph-info} (@command{gcc})
4035 Makes the compiler output callgraph information for the program, on a
4036 per-file basis.  The information is generated in the VCG format.  It can
4037 be decorated with stack-usage per-node information.
4038
4039 @item ^-g^/DEBUG^
4040 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4041 Generate debugging information. This information is stored in the object
4042 file and copied from there to the final executable file by the linker,
4043 where it can be read by the debugger. You must use the
4044 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4045
4046 @item -gnat83
4047 @cindex @option{-gnat83} (@command{gcc})
4048 Enforce Ada 83 restrictions.
4049
4050 @item -gnat95
4051 @cindex @option{-gnat95} (@command{gcc})
4052 Enforce Ada 95 restrictions.
4053
4054 @item -gnat05
4055 @cindex @option{-gnat05} (@command{gcc})
4056 Allow full Ada 2005 features.
4057
4058 @item -gnat2005
4059 @cindex @option{-gnat2005} (@command{gcc})
4060 Allow full Ada 2005 features (same as @option{-gnat05})
4061
4062 @item -gnat12
4063 @cindex @option{-gnat12} (@command{gcc})
4064
4065 @item -gnat2012
4066 @cindex @option{-gnat2012} (@command{gcc})
4067 Allow full Ada 2012 features (same as @option{-gnat12})
4068
4069 @item -gnata
4070 @cindex @option{-gnata} (@command{gcc})
4071 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4072 activated. Note that these pragmas can also be controlled using the
4073 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4074 It also activates pragmas @code{Check}, @code{Precondition}, and
4075 @code{Postcondition}. Note that these pragmas can also be controlled
4076 using the configuration pragma @code{Check_Policy}.
4077
4078 @item -gnatA
4079 @cindex @option{-gnatA} (@command{gcc})
4080 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4081 it will be ignored.
4082
4083 @item -gnatb
4084 @cindex @option{-gnatb} (@command{gcc})
4085 Generate brief messages to @file{stderr} even if verbose mode set.
4086
4087 @item -gnatB
4088 @cindex @option{-gnatB} (@command{gcc})
4089 Assume no invalid (bad) values except for 'Valid attribute use
4090 (@pxref{Validity Checking}).
4091
4092 @item -gnatc
4093 @cindex @option{-gnatc} (@command{gcc})
4094 Check syntax and semantics only (no code generation attempted).
4095
4096 @item -gnatC
4097 @cindex @option{-gnatC} (@command{gcc})
4098 Generate CodePeer information (no code generation attempted).
4099 This switch will generate an intermediate representation suitable for
4100 use by CodePeer (@file{.scil} files). This switch is not compatible with
4101 code generation (it will, among other things, disable some switches such
4102 as -gnatn, and enable others such as -gnata).
4103
4104 @item -gnatd
4105 @cindex @option{-gnatd} (@command{gcc})
4106 Specify debug options for the compiler. The string of characters after
4107 the @option{-gnatd} specify the specific debug options. The possible
4108 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4109 compiler source file @file{debug.adb} for details of the implemented
4110 debug options. Certain debug options are relevant to applications
4111 programmers, and these are documented at appropriate points in this
4112 users guide.
4113
4114 @ifclear vms
4115 @item -gnatD
4116 @cindex @option{-gnatD[nn]} (@command{gcc})
4117 @end ifclear
4118 @ifset vms
4119 @item /XDEBUG /LXDEBUG=nnn
4120 @end ifset
4121 Create expanded source files for source level debugging. This switch
4122 also suppress generation of cross-reference information
4123 (see @option{-gnatx}).
4124
4125 @item -gnatec=@var{path}
4126 @cindex @option{-gnatec} (@command{gcc})
4127 Specify a configuration pragma file
4128 @ifclear vms
4129 (the equal sign is optional)
4130 @end ifclear
4131 (@pxref{The Configuration Pragmas Files}).
4132
4133 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4134 @cindex @option{-gnateD} (@command{gcc})
4135 Defines a symbol, associated with @var{value}, for preprocessing.
4136 (@pxref{Integrated Preprocessing}).
4137
4138 @item -gnateE
4139 @cindex @option{-gnateE} (@command{gcc})
4140 Generate extra information in exception messages. In particular, display
4141 extra column information and the value and range associated with index and
4142 range check failures, and extra column information for access checks.
4143 In cases where the compiler is able to determine at compile time that
4144 a check will fail, it gives a warning, and the extra information is not
4145 produced at run time.
4146
4147 @item -gnatef
4148 @cindex @option{-gnatef} (@command{gcc})
4149 Display full source path name in brief error messages.
4150
4151 @item -gnateG
4152 @cindex @option{-gnateG} (@command{gcc})
4153 Save result of preprocessing in a text file.
4154
4155 @item ^-gnateI^/MULTI_UNIT_INDEX=^@var{nnn}
4156 @cindex @option{-gnateI} (@command{gcc})
4157 Indicates that the source is a multi-unit source and that the index of the
4158 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4159 to be a valid index in the multi-unit source.
4160
4161 @item -gnatem=@var{path}
4162 @cindex @option{-gnatem} (@command{gcc})
4163 Specify a mapping file
4164 @ifclear vms
4165 (the equal sign is optional)
4166 @end ifclear
4167 (@pxref{Units to Sources Mapping Files}).
4168
4169 @item -gnatep=@var{file}
4170 @cindex @option{-gnatep} (@command{gcc})
4171 Specify a preprocessing data file
4172 @ifclear vms
4173 (the equal sign is optional)
4174 @end ifclear
4175 (@pxref{Integrated Preprocessing}).
4176
4177 @item -gnateP
4178 @cindex @option{-gnateP} (@command{gcc})
4179 Turn categorization dependency errors into warnings.
4180 Ada requires that units that WITH one another have compatible categories, for
4181 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4182 these errors become warnings (which can be ignored, or suppressed in the usual
4183 manner). This can be useful in some specialized circumstances such as the
4184 temporary use of special test software.
4185 @item -gnateS
4186 @cindex @option{-gnateS} (@command{gcc})
4187 Generate SCO (Source Coverage Obligation) information in the ALI
4188 file. This information is used by advanced coverage tools. See
4189 unit @file{SCOs} in the compiler sources for details in files
4190 @file{scos.ads} and @file{scos.adb}.
4191
4192 @item -gnatE
4193 @cindex @option{-gnatE} (@command{gcc})
4194 Full dynamic elaboration checks.
4195
4196 @item -gnatf
4197 @cindex @option{-gnatf} (@command{gcc})
4198 Full errors. Multiple errors per line, all undefined references, do not
4199 attempt to suppress cascaded errors.
4200
4201 @item -gnatF
4202 @cindex @option{-gnatF} (@command{gcc})
4203 Externals names are folded to all uppercase.
4204
4205 @item ^-gnatg^/GNAT_INTERNAL^
4206 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4207 Internal GNAT implementation mode. This should not be used for
4208 applications programs, it is intended only for use by the compiler
4209 and its run-time library. For documentation, see the GNAT sources.
4210 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4211 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4212 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4213 so that all standard warnings and all standard style options are turned on.
4214 All warnings and style messages are treated as errors.
4215
4216 @ifclear vms
4217 @item -gnatG=nn
4218 @cindex @option{-gnatG[nn]} (@command{gcc})
4219 @end ifclear
4220 @ifset vms
4221 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4222 @end ifset
4223 List generated expanded code in source form.
4224
4225 @item ^-gnath^/HELP^
4226 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4227 Output usage information. The output is written to @file{stdout}.
4228
4229 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4230 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4231 Identifier character set
4232 @ifclear vms
4233 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4234 @end ifclear
4235 For details of the possible selections for @var{c},
4236 see @ref{Character Set Control}.
4237
4238 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4239 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4240 Ignore representation clauses. When this switch is used,
4241 representation clauses are treated as comments. This is useful
4242 when initially porting code where you want to ignore rep clause
4243 problems, and also for compiling foreign code (particularly
4244 for use with ASIS). The representation clauses that are ignored
4245 are: enumeration_representation_clause, record_representation_clause,
4246 and attribute_definition_clause for the following attributes:
4247 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4248 Object_Size, Size, Small, Stream_Size, and Value_Size.
4249 Note that this option should be used only for compiling -- the
4250 code is likely to malfunction at run time.
4251
4252 @item -gnatjnn
4253 @cindex @option{-gnatjnn} (@command{gcc})
4254 Reformat error messages to fit on nn character lines
4255
4256 @item -gnatk=@var{n}
4257 @cindex @option{-gnatk} (@command{gcc})
4258 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4259
4260 @item -gnatl
4261 @cindex @option{-gnatl} (@command{gcc})
4262 Output full source listing with embedded error messages.
4263
4264 @item -gnatL
4265 @cindex @option{-gnatL} (@command{gcc})
4266 Used in conjunction with -gnatG or -gnatD to intersperse original
4267 source lines (as comment lines with line numbers) in the expanded
4268 source output.
4269
4270 @item -gnatm=@var{n}
4271 @cindex @option{-gnatm} (@command{gcc})
4272 Limit number of detected error or warning messages to @var{n}
4273 where @var{n} is in the range 1..999999. The default setting if
4274 no switch is given is 9999. If the number of warnings reaches this
4275 limit, then a message is output and further warnings are suppressed,
4276 but the compilation is continued. If the number of error messages
4277 reaches this limit, then a message is output and the compilation
4278 is abandoned. The equal sign here is optional. A value of zero
4279 means that no limit applies.
4280
4281 @item -gnatn
4282 @cindex @option{-gnatn} (@command{gcc})
4283 Activate inlining for subprograms for which
4284 pragma @code{Inline} is specified. This inlining is performed
4285 by the GCC back-end.
4286
4287 @item -gnatN
4288 @cindex @option{-gnatN} (@command{gcc})
4289 Activate front end inlining for subprograms for which
4290 pragma @code{Inline} is specified. This inlining is performed
4291 by the front end and will be visible in the
4292 @option{-gnatG} output.
4293
4294 When using a gcc-based back end (in practice this means using any version
4295 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4296 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4297 Historically front end inlining was more extensive than the gcc back end
4298 inlining, but that is no longer the case.
4299
4300 @item -gnato
4301 @cindex @option{-gnato} (@command{gcc})
4302 Enable numeric overflow checking (which is not normally enabled by
4303 default). Note that division by zero is a separate check that is not
4304 controlled by this switch (division by zero checking is on by default).
4305
4306 @item -gnatp
4307 @cindex @option{-gnatp} (@command{gcc})
4308 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4309 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4310
4311 @item -gnat-p
4312 @cindex @option{-gnat-p} (@command{gcc})
4313 Cancel effect of previous @option{-gnatp} switch.
4314
4315 @item -gnatP
4316 @cindex @option{-gnatP} (@command{gcc})
4317 Enable polling. This is required on some systems (notably Windows NT) to
4318 obtain asynchronous abort and asynchronous transfer of control capability.
4319 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4320 details.
4321
4322 @item -gnatq
4323 @cindex @option{-gnatq} (@command{gcc})
4324 Don't quit. Try semantics, even if parse errors.
4325
4326 @item -gnatQ
4327 @cindex @option{-gnatQ} (@command{gcc})
4328 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4329
4330 @item -gnatr
4331 @cindex @option{-gnatr} (@command{gcc})
4332 Treat pragma Restrictions as Restriction_Warnings.
4333
4334 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4335 @cindex @option{-gnatR} (@command{gcc})
4336 Output representation information for declared types and objects.
4337
4338 @item -gnats
4339 @cindex @option{-gnats} (@command{gcc})
4340 Syntax check only.
4341
4342 @item -gnatS
4343 @cindex @option{-gnatS} (@command{gcc})
4344 Print package Standard.
4345
4346 @item -gnatt
4347 @cindex @option{-gnatt} (@command{gcc})
4348 Generate tree output file.
4349
4350 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4351 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4352 All compiler tables start at @var{nnn} times usual starting size.
4353
4354 @item -gnatu
4355 @cindex @option{-gnatu} (@command{gcc})
4356 List units for this compilation.
4357
4358 @item -gnatU
4359 @cindex @option{-gnatU} (@command{gcc})
4360 Tag all error messages with the unique string ``error:''
4361
4362 @item -gnatv
4363 @cindex @option{-gnatv} (@command{gcc})
4364 Verbose mode. Full error output with source lines to @file{stdout}.
4365
4366 @item -gnatV
4367 @cindex @option{-gnatV} (@command{gcc})
4368 Control level of validity checking (@pxref{Validity Checking}).
4369
4370 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4371 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4372 Warning mode where
4373 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4374 the exact warnings that
4375 are enabled or disabled (@pxref{Warning Message Control}).
4376
4377 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4378 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4379 Wide character encoding method
4380 @ifclear vms
4381 (@var{e}=n/h/u/s/e/8).
4382 @end ifclear
4383 @ifset vms
4384 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4385 @end ifset
4386
4387 @item -gnatx
4388 @cindex @option{-gnatx} (@command{gcc})
4389 Suppress generation of cross-reference information.
4390
4391 @item -gnatX
4392 @cindex @option{-gnatX} (@command{gcc})
4393 Enable GNAT implementation extensions and latest Ada version.
4394
4395 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4396 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4397 Enable built-in style checks (@pxref{Style Checking}).
4398
4399 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4400 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4401 Distribution stub generation and compilation
4402 @ifclear vms
4403 (@var{m}=r/c for receiver/caller stubs).
4404 @end ifclear
4405 @ifset vms
4406 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4407 to be generated and compiled).
4408 @end ifset
4409
4410 @item ^-I^/SEARCH=^@var{dir}
4411 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4412 @cindex RTL
4413 Direct GNAT to search the @var{dir} directory for source files needed by
4414 the current compilation
4415 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4416
4417 @item ^-I-^/NOCURRENT_DIRECTORY^
4418 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4419 @cindex RTL
4420 Except for the source file named in the command line, do not look for source
4421 files in the directory containing the source file named in the command line
4422 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4423
4424 @ifclear vms
4425 @item -mbig-switch
4426 @cindex @option{-mbig-switch} (@command{gcc})
4427 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4428 This standard gcc switch causes the compiler to use larger offsets in its
4429 jump table representation for @code{case} statements.
4430 This may result in less efficient code, but is sometimes necessary
4431 (for example on HP-UX targets)
4432 @cindex HP-UX and @option{-mbig-switch} option
4433 in order to compile large and/or nested @code{case} statements.
4434
4435 @item -o @var{file}
4436 @cindex @option{-o} (@command{gcc})
4437 This switch is used in @command{gcc} to redirect the generated object file
4438 and its associated ALI file. Beware of this switch with GNAT, because it may
4439 cause the object file and ALI file to have different names which in turn
4440 may confuse the binder and the linker.
4441 @end ifclear
4442
4443 @item -nostdinc
4444 @cindex @option{-nostdinc} (@command{gcc})
4445 Inhibit the search of the default location for the GNAT Run Time
4446 Library (RTL) source files.
4447
4448 @item -nostdlib
4449 @cindex @option{-nostdlib} (@command{gcc})
4450 Inhibit the search of the default location for the GNAT Run Time
4451 Library (RTL) ALI files.
4452
4453 @ifclear vms
4454 @c @item -O@ovar{n}
4455 @c Expanding @ovar macro inline (explanation in macro def comments)
4456 @item -O@r{[}@var{n}@r{]}
4457 @cindex @option{-O} (@command{gcc})
4458 @var{n} controls the optimization level.
4459
4460 @table @asis
4461 @item n = 0
4462 No optimization, the default setting if no @option{-O} appears
4463
4464 @item n = 1
4465 Normal optimization, the default if you specify @option{-O} without
4466 an operand. A good compromise between code quality and compilation
4467 time.
4468
4469 @item n = 2
4470 Extensive optimization, may improve execution time, possibly at the cost of
4471 substantially increased compilation time.
4472
4473 @item n = 3
4474 Same as @option{-O2}, and also includes inline expansion for small subprograms
4475 in the same unit.
4476
4477 @item n = s
4478 Optimize space usage
4479 @end table
4480
4481 @noindent
4482 See also @ref{Optimization Levels}.
4483 @end ifclear
4484
4485 @ifset vms
4486 @item  /NOOPTIMIZE
4487 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4488 Equivalent to @option{/OPTIMIZE=NONE}.
4489 This is the default behavior in the absence of an @option{/OPTIMIZE}
4490 qualifier.
4491
4492 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4493 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4494 Selects the level of optimization for your program. The supported
4495 keywords are as follows:
4496 @table @code
4497 @item   ALL
4498 Perform most optimizations, including those that
4499 are expensive.
4500 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4501 without keyword options.
4502
4503 @item   NONE
4504 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4505
4506 @item SOME
4507 Perform some optimizations, but omit ones that are costly.
4508
4509 @item   DEVELOPMENT
4510 Same as @code{SOME}.
4511
4512 @item INLINING
4513 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4514 automatic inlining of small subprograms within a unit
4515
4516 @item   UNROLL_LOOPS
4517 Try to unroll loops. This keyword may be specified together with
4518 any keyword above other than @code{NONE}. Loop unrolling
4519 usually, but not always, improves the performance of programs.
4520
4521 @item SPACE
4522 Optimize space usage
4523 @end table
4524
4525 @noindent
4526 See also @ref{Optimization Levels}.
4527 @end ifset
4528
4529 @ifclear vms
4530 @item -pass-exit-codes
4531 @cindex @option{-pass-exit-codes} (@command{gcc})
4532 Catch exit codes from the compiler and use the most meaningful as
4533 exit status.
4534 @end ifclear
4535
4536 @item --RTS=@var{rts-path}
4537 @cindex @option{--RTS} (@command{gcc})
4538 Specifies the default location of the runtime library. Same meaning as the
4539 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4540
4541 @item ^-S^/ASM^
4542 @cindex @option{^-S^/ASM^} (@command{gcc})
4543 ^Used in place of @option{-c} to^Used to^
4544 cause the assembler source file to be
4545 generated, using @file{^.s^.S^} as the extension,
4546 instead of the object file.
4547 This may be useful if you need to examine the generated assembly code.
4548
4549 @item ^-fverbose-asm^/VERBOSE_ASM^
4550 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4551 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4552 to cause the generated assembly code file to be annotated with variable
4553 names, making it significantly easier to follow.
4554
4555 @item ^-v^/VERBOSE^
4556 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4557 Show commands generated by the @command{gcc} driver. Normally used only for
4558 debugging purposes or if you need to be sure what version of the
4559 compiler you are executing.
4560
4561 @ifclear vms
4562 @item -V @var{ver}
4563 @cindex @option{-V} (@command{gcc})
4564 Execute @var{ver} version of the compiler. This is the @command{gcc}
4565 version, not the GNAT version.
4566 @end ifclear
4567
4568 @item ^-w^/NO_BACK_END_WARNINGS^
4569 @cindex @option{-w} (@command{gcc})
4570 Turn off warnings generated by the back end of the compiler. Use of
4571 this switch also causes the default for front end warnings to be set
4572 to suppress (as though @option{-gnatws} had appeared at the start of
4573 the options).
4574
4575 @end table
4576
4577 @ifclear vms
4578 @c Combining qualifiers does not work on VMS
4579 You may combine a sequence of GNAT switches into a single switch. For
4580 example, the combined switch
4581
4582 @cindex Combining GNAT switches
4583 @smallexample
4584 -gnatofi3
4585 @end smallexample
4586
4587 @noindent
4588 is equivalent to specifying the following sequence of switches:
4589
4590 @smallexample
4591 -gnato -gnatf -gnati3
4592 @end smallexample
4593 @end ifclear
4594
4595 @noindent
4596 The following restrictions apply to the combination of switches
4597 in this manner:
4598
4599 @itemize @bullet
4600 @item
4601 The switch @option{-gnatc} if combined with other switches must come
4602 first in the string.
4603
4604 @item
4605 The switch @option{-gnats} if combined with other switches must come
4606 first in the string.
4607
4608 @item
4609 The switches
4610 ^^@option{/DISTRIBUTION_STUBS=},^
4611 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4612 switches, and only one of them may appear in the command line.
4613
4614 @item
4615 The switch @option{-gnat-p} may not be combined with any other switch.
4616
4617 @ifclear vms
4618 @item
4619 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4620 switch), then all further characters in the switch are interpreted
4621 as style modifiers (see description of @option{-gnaty}).
4622
4623 @item
4624 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4625 switch), then all further characters in the switch are interpreted
4626 as debug flags (see description of @option{-gnatd}).
4627
4628 @item
4629 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4630 switch), then all further characters in the switch are interpreted
4631 as warning mode modifiers (see description of @option{-gnatw}).
4632
4633 @item
4634 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4635 switch), then all further characters in the switch are interpreted
4636 as validity checking options (@pxref{Validity Checking}).
4637
4638 @item
4639 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4640 a combined list of options.
4641 @end ifclear
4642 @end itemize
4643
4644 @node Output and Error Message Control
4645 @subsection Output and Error Message Control
4646 @findex stderr
4647
4648 @noindent
4649 The standard default format for error messages is called ``brief format''.
4650 Brief format messages are written to @file{stderr} (the standard error
4651 file) and have the following form:
4652
4653 @smallexample
4654 e.adb:3:04: Incorrect spelling of keyword "function"
4655 e.adb:4:20: ";" should be "is"
4656 @end smallexample
4657
4658 @noindent
4659 The first integer after the file name is the line number in the file,
4660 and the second integer is the column number within the line.
4661 @ifclear vms
4662 @code{GPS} can parse the error messages
4663 and point to the referenced character.
4664 @end ifclear
4665 The following switches provide control over the error message
4666 format:
4667
4668 @table @option
4669 @c !sort!
4670 @item -gnatv
4671 @cindex @option{-gnatv} (@command{gcc})
4672 @findex stdout
4673 @ifclear vms
4674 The v stands for verbose.
4675 @end ifclear
4676 The effect of this setting is to write long-format error
4677 messages to @file{stdout} (the standard output file.
4678 The same program compiled with the
4679 @option{-gnatv} switch would generate:
4680
4681 @smallexample
4682 @cartouche
4683 3. funcion X (Q : Integer)
4684    |
4685 >>> Incorrect spelling of keyword "function"
4686 4. return Integer;
4687                  |
4688 >>> ";" should be "is"
4689 @end cartouche
4690 @end smallexample
4691
4692 @noindent
4693 The vertical bar indicates the location of the error, and the @samp{>>>}
4694 prefix can be used to search for error messages. When this switch is
4695 used the only source lines output are those with errors.
4696
4697 @item -gnatl
4698 @cindex @option{-gnatl} (@command{gcc})
4699 @ifclear vms
4700 The @code{l} stands for list.
4701 @end ifclear
4702 This switch causes a full listing of
4703 the file to be generated. In the case where a body is
4704 compiled, the corresponding spec is also listed, along
4705 with any subunits. Typical output from compiling a package
4706 body @file{p.adb} might look like:
4707
4708 @smallexample @c ada
4709 @cartouche
4710  Compiling: p.adb
4711
4712      1. package body p is
4713      2.    procedure a;
4714      3.    procedure a is separate;
4715      4. begin
4716      5.    null
4717                |
4718         >>> missing ";"
4719
4720      6. end;
4721
4722 Compiling: p.ads
4723
4724      1. package p is
4725      2.    pragma Elaborate_Body
4726                                 |
4727         >>> missing ";"
4728
4729      3. end p;
4730
4731 Compiling: p-a.adb
4732
4733      1. separate p
4734                 |
4735         >>> missing "("
4736
4737      2. procedure a is
4738      3. begin
4739      4.    null
4740                |
4741         >>> missing ";"
4742
4743      5. end;
4744 @end cartouche
4745 @end smallexample
4746
4747 @noindent
4748 @findex stderr
4749 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4750 standard output is redirected, a brief summary is written to
4751 @file{stderr} (standard error) giving the number of error messages and
4752 warning messages generated.
4753
4754 @item ^-gnatl^/OUTPUT_FILE^=file
4755 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4756 This has the same effect as @option{-gnatl} except that the output is
4757 written to a file instead of to standard output. If the given name
4758 @file{fname} does not start with a period, then it is the full name
4759 of the file to be written. If @file{fname} is an extension, it is
4760 appended to the name of the file being compiled. For example, if
4761 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4762 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4763
4764 @item -gnatU
4765 @cindex @option{-gnatU} (@command{gcc})
4766 This switch forces all error messages to be preceded by the unique
4767 string ``error:''. This means that error messages take a few more
4768 characters in space, but allows easy searching for and identification
4769 of error messages.
4770
4771 @item -gnatb
4772 @cindex @option{-gnatb} (@command{gcc})
4773 @ifclear vms
4774 The @code{b} stands for brief.
4775 @end ifclear
4776 This switch causes GNAT to generate the
4777 brief format error messages to @file{stderr} (the standard error
4778 file) as well as the verbose
4779 format message or full listing (which as usual is written to
4780 @file{stdout} (the standard output file).
4781
4782 @item -gnatm=@var{n}
4783 @cindex @option{-gnatm} (@command{gcc})
4784 @ifclear vms
4785 The @code{m} stands for maximum.
4786 @end ifclear
4787 @var{n} is a decimal integer in the
4788 range of 1 to 999999 and limits the number of error or warning
4789 messages to be generated. For example, using
4790 @option{-gnatm2} might yield
4791
4792 @smallexample
4793 e.adb:3:04: Incorrect spelling of keyword "function"
4794 e.adb:5:35: missing ".."
4795 fatal error: maximum number of errors detected
4796 compilation abandoned
4797 @end smallexample
4798
4799 @noindent
4800 The default setting if
4801 no switch is given is 9999. If the number of warnings reaches this
4802 limit, then a message is output and further warnings are suppressed,
4803 but the compilation is continued. If the number of error messages
4804 reaches this limit, then a message is output and the compilation
4805 is abandoned. A value of zero means that no limit applies.
4806
4807 @noindent
4808 Note that the equal sign is optional, so the switches
4809 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4810
4811 @item -gnatf
4812 @cindex @option{-gnatf} (@command{gcc})
4813 @cindex Error messages, suppressing
4814 @ifclear vms
4815 The @code{f} stands for full.
4816 @end ifclear
4817 Normally, the compiler suppresses error messages that are likely to be
4818 redundant. This switch causes all error
4819 messages to be generated. In particular, in the case of
4820 references to undefined variables. If a given variable is referenced
4821 several times, the normal format of messages is
4822 @smallexample
4823 e.adb:7:07: "V" is undefined (more references follow)
4824 @end smallexample
4825
4826 @noindent
4827 where the parenthetical comment warns that there are additional
4828 references to the variable @code{V}. Compiling the same program with the
4829 @option{-gnatf} switch yields
4830
4831 @smallexample
4832 e.adb:7:07: "V" is undefined
4833 e.adb:8:07: "V" is undefined
4834 e.adb:8:12: "V" is undefined
4835 e.adb:8:16: "V" is undefined
4836 e.adb:9:07: "V" is undefined
4837 e.adb:9:12: "V" is undefined
4838 @end smallexample
4839
4840 @noindent
4841 The @option{-gnatf} switch also generates additional information for
4842 some error messages.  Some examples are:
4843
4844 @itemize @bullet
4845 @item
4846 Details on possibly non-portable unchecked conversion
4847 @item
4848 List possible interpretations for ambiguous calls
4849 @item
4850 Additional details on incorrect parameters
4851 @end itemize
4852
4853 @item -gnatjnn
4854 @cindex @option{-gnatjnn} (@command{gcc})
4855 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4856 with continuation lines are treated as though the continuation lines were
4857 separate messages (and so a warning with two continuation lines counts as
4858 three warnings, and is listed as three separate messages).
4859
4860 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4861 messages are output in a different manner. A message and all its continuation
4862 lines are treated as a unit, and count as only one warning or message in the
4863 statistics totals. Furthermore, the message is reformatted so that no line
4864 is longer than nn characters.
4865
4866 @item -gnatq
4867 @cindex @option{-gnatq} (@command{gcc})
4868 @ifclear vms
4869 The @code{q} stands for quit (really ``don't quit'').
4870 @end ifclear
4871 In normal operation mode, the compiler first parses the program and
4872 determines if there are any syntax errors. If there are, appropriate
4873 error messages are generated and compilation is immediately terminated.
4874 This switch tells
4875 GNAT to continue with semantic analysis even if syntax errors have been
4876 found. This may enable the detection of more errors in a single run. On
4877 the other hand, the semantic analyzer is more likely to encounter some
4878 internal fatal error when given a syntactically invalid tree.
4879
4880 @item -gnatQ
4881 @cindex @option{-gnatQ} (@command{gcc})
4882 In normal operation mode, the @file{ALI} file is not generated if any
4883 illegalities are detected in the program. The use of @option{-gnatQ} forces
4884 generation of the @file{ALI} file. This file is marked as being in
4885 error, so it cannot be used for binding purposes, but it does contain
4886 reasonably complete cross-reference information, and thus may be useful
4887 for use by tools (e.g., semantic browsing tools or integrated development
4888 environments) that are driven from the @file{ALI} file. This switch
4889 implies @option{-gnatq}, since the semantic phase must be run to get a
4890 meaningful ALI file.
4891
4892 In addition, if @option{-gnatt} is also specified, then the tree file is
4893 generated even if there are illegalities. It may be useful in this case
4894 to also specify @option{-gnatq} to ensure that full semantic processing
4895 occurs. The resulting tree file can be processed by ASIS, for the purpose
4896 of providing partial information about illegal units, but if the error
4897 causes the tree to be badly malformed, then ASIS may crash during the
4898 analysis.
4899
4900 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4901 being in error, @command{gnatmake} will attempt to recompile the source when it
4902 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4903
4904 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4905 since ALI files are never generated if @option{-gnats} is set.
4906
4907 @end table
4908
4909 @node Warning Message Control
4910 @subsection Warning Message Control
4911 @cindex Warning messages
4912 @noindent
4913 In addition to error messages, which correspond to illegalities as defined
4914 in the Ada Reference Manual, the compiler detects two kinds of warning
4915 situations.
4916
4917 First, the compiler considers some constructs suspicious and generates a
4918 warning message to alert you to a possible error. Second, if the
4919 compiler detects a situation that is sure to raise an exception at
4920 run time, it generates a warning message. The following shows an example
4921 of warning messages:
4922 @smallexample
4923 e.adb:4:24: warning: creation of object may raise Storage_Error
4924 e.adb:10:17: warning: static value out of range
4925 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4926 @end smallexample
4927
4928 @noindent
4929 GNAT considers a large number of situations as appropriate
4930 for the generation of warning messages. As always, warnings are not
4931 definite indications of errors. For example, if you do an out-of-range
4932 assignment with the deliberate intention of raising a
4933 @code{Constraint_Error} exception, then the warning that may be
4934 issued does not indicate an error. Some of the situations for which GNAT
4935 issues warnings (at least some of the time) are given in the following
4936 list. This list is not complete, and new warnings are often added to
4937 subsequent versions of GNAT. The list is intended to give a general idea
4938 of the kinds of warnings that are generated.
4939
4940 @itemize @bullet
4941 @item
4942 Possible infinitely recursive calls
4943
4944 @item
4945 Out-of-range values being assigned
4946
4947 @item
4948 Possible order of elaboration problems
4949
4950 @item
4951 Assertions (pragma Assert) that are sure to fail
4952
4953 @item
4954 Unreachable code
4955
4956 @item
4957 Address clauses with possibly unaligned values, or where an attempt is
4958 made to overlay a smaller variable with a larger one.
4959
4960 @item
4961 Fixed-point type declarations with a null range
4962
4963 @item
4964 Direct_IO or Sequential_IO instantiated with a type that has access values
4965
4966 @item
4967 Variables that are never assigned a value
4968
4969 @item
4970 Variables that are referenced before being initialized
4971
4972 @item
4973 Task entries with no corresponding @code{accept} statement
4974
4975 @item
4976 Duplicate accepts for the same task entry in a @code{select}
4977
4978 @item
4979 Objects that take too much storage
4980
4981 @item
4982 Unchecked conversion between types of differing sizes
4983
4984 @item
4985 Missing @code{return} statement along some execution path in a function
4986
4987 @item
4988 Incorrect (unrecognized) pragmas
4989
4990 @item
4991 Incorrect external names
4992
4993 @item
4994 Allocation from empty storage pool
4995
4996 @item
4997 Potentially blocking operation in protected type
4998
4999 @item
5000 Suspicious parenthesization of expressions
5001
5002 @item
5003 Mismatching bounds in an aggregate
5004
5005 @item
5006 Attempt to return local value by reference
5007
5008 @item
5009 Premature instantiation of a generic body
5010
5011 @item
5012 Attempt to pack aliased components
5013
5014 @item
5015 Out of bounds array subscripts
5016
5017 @item
5018 Wrong length on string assignment
5019
5020 @item
5021 Violations of style rules if style checking is enabled
5022
5023 @item
5024 Unused @code{with} clauses
5025
5026 @item
5027 @code{Bit_Order} usage that does not have any effect
5028
5029 @item
5030 @code{Standard.Duration} used to resolve universal fixed expression
5031
5032 @item
5033 Dereference of possibly null value
5034
5035 @item
5036 Declaration that is likely to cause storage error
5037
5038 @item
5039 Internal GNAT unit @code{with}'ed by application unit
5040
5041 @item
5042 Values known to be out of range at compile time
5043
5044 @item
5045 Unreferenced labels and variables
5046
5047 @item
5048 Address overlays that could clobber memory
5049
5050 @item
5051 Unexpected initialization when address clause present
5052
5053 @item
5054 Bad alignment for address clause
5055
5056 @item
5057 Useless type conversions
5058
5059 @item
5060 Redundant assignment statements and other redundant constructs
5061
5062 @item
5063 Useless exception handlers
5064
5065 @item
5066 Accidental hiding of name by child unit
5067
5068 @item
5069 Access before elaboration detected at compile time
5070
5071 @item
5072 A range in a @code{for} loop that is known to be null or might be null
5073
5074 @end itemize
5075
5076 @noindent
5077 The following section lists compiler switches that are available
5078 to control the handling of warning messages. It is also possible
5079 to exercise much finer control over what warnings are issued and
5080 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5081 gnat_rm, GNAT Reference manual}.
5082
5083 @table @option
5084 @c !sort!
5085 @item -gnatwa
5086 @emph{Activate most optional warnings.}
5087 @cindex @option{-gnatwa} (@command{gcc})
5088 This switch activates most optional warning messages.  See the remaining list
5089 in this section for details on optional warning messages that can be
5090 individually controlled.  The warnings that are not turned on by this
5091 switch are
5092 @option{-gnatwd} (implicit dereferencing),
5093 @option{-gnatwh} (hiding),
5094 @option{-gnatw.h} (holes (gaps) in record layouts)
5095 @option{-gnatw.i} (overlapping actuals),
5096 @option{-gnatwl} (elaboration warnings),
5097 @option{-gnatw.l} (inherited aspects),
5098 @option{-gnatw.o} (warn on values set by out parameters ignored),
5099 @option{-gnatwt} (tracking of deleted conditional code)
5100 and @option{-gnatw.u} (unordered enumeration),
5101 All other optional warnings are turned on.
5102
5103 @item -gnatwA
5104 @emph{Suppress all optional errors.}
5105 @cindex @option{-gnatwA} (@command{gcc})
5106 This switch suppresses all optional warning messages, see remaining list
5107 in this section for details on optional warning messages that can be
5108 individually controlled. Note that unlike switch @option{-gnatws}, the
5109 use of switch @option{-gnatwA} does not suppress warnings that are
5110 normally given unconditionally and cannot be individually controlled
5111 (for example, the warning about a missing exit path in a function).
5112 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5113 the use of switch @option{-gnatwA} can be individually turned back
5114 on. For example the use of switch @option{-gnatwA} followed by
5115 switch @option{-gnatwd} will suppress all optional warnings except
5116 the warnings for implicit dereferencing.
5117
5118 @item -gnatw.a
5119 @emph{Activate warnings on failing assertions.}
5120 @cindex @option{-gnatw.a} (@command{gcc})
5121 @cindex Assert failures
5122 This switch activates warnings for assertions where the compiler can tell at
5123 compile time that the assertion will fail. Note that this warning is given
5124 even if assertions are disabled. The default is that such warnings are
5125 generated.
5126
5127 @item -gnatw.A
5128 @emph{Suppress warnings on failing assertions.}
5129 @cindex @option{-gnatw.A} (@command{gcc})
5130 @cindex Assert failures
5131 This switch suppresses warnings for assertions where the compiler can tell at
5132 compile time that the assertion will fail.
5133
5134 @item -gnatwb
5135 @emph{Activate warnings on bad fixed values.}
5136 @cindex @option{-gnatwb} (@command{gcc})
5137 @cindex Bad fixed values
5138 @cindex Fixed-point Small value
5139 @cindex Small value
5140 This switch activates warnings for static fixed-point expressions whose
5141 value is not an exact multiple of Small. Such values are implementation
5142 dependent, since an implementation is free to choose either of the multiples
5143 that surround the value. GNAT always chooses the closer one, but this is not
5144 required behavior, and it is better to specify a value that is an exact
5145 multiple, ensuring predictable execution. The default is that such warnings
5146 are not generated.
5147
5148 @item -gnatwB
5149 @emph{Suppress warnings on bad fixed values.}
5150 @cindex @option{-gnatwB} (@command{gcc})
5151 This switch suppresses warnings for static fixed-point expressions whose
5152 value is not an exact multiple of Small.
5153
5154 @item -gnatw.b
5155 @emph{Activate warnings on biased representation.}
5156 @cindex @option{-gnatw.b} (@command{gcc})
5157 @cindex Biased representation
5158 This switch activates warnings when a size clause, value size clause, component
5159 clause, or component size clause forces the use of biased representation for an
5160 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5161 to represent 10/11). The default is that such warnings are generated.
5162
5163 @item -gnatw.B
5164 @emph{Suppress warnings on biased representation.}
5165 @cindex @option{-gnatwB} (@command{gcc})
5166 This switch suppresses warnings for representation clauses that force the use
5167 of biased representation.
5168
5169 @item -gnatwc
5170 @emph{Activate warnings on conditionals.}
5171 @cindex @option{-gnatwc} (@command{gcc})
5172 @cindex Conditionals, constant
5173 This switch activates warnings for conditional expressions used in
5174 tests that are known to be True or False at compile time. The default
5175 is that such warnings are not generated.
5176 Note that this warning does
5177 not get issued for the use of boolean variables or constants whose
5178 values are known at compile time, since this is a standard technique
5179 for conditional compilation in Ada, and this would generate too many
5180 false positive warnings.
5181
5182 This warning option also activates a special test for comparisons using
5183 the operators ``>='' and`` <=''.
5184 If the compiler can tell that only the equality condition is possible,
5185 then it will warn that the ``>'' or ``<'' part of the test
5186 is useless and that the operator could be replaced by ``=''.
5187 An example would be comparing a @code{Natural} variable <= 0.
5188
5189 This warning option also generates warnings if
5190 one or both tests is optimized away in a membership test for integer
5191 values if the result can be determined at compile time. Range tests on
5192 enumeration types are not included, since it is common for such tests
5193 to include an end point.
5194
5195 This warning can also be turned on using @option{-gnatwa}.
5196
5197 @item -gnatwC
5198 @emph{Suppress warnings on conditionals.}
5199 @cindex @option{-gnatwC} (@command{gcc})
5200 This switch suppresses warnings for conditional expressions used in
5201 tests that are known to be True or False at compile time.
5202
5203 @item -gnatw.c
5204 @emph{Activate warnings on missing component clauses.}
5205 @cindex @option{-gnatw.c} (@command{gcc})
5206 @cindex Component clause, missing
5207 This switch activates warnings for record components where a record
5208 representation clause is present and has component clauses for the
5209 majority, but not all, of the components. A warning is given for each
5210 component for which no component clause is present.
5211
5212 This warning can also be turned on using @option{-gnatwa}.
5213
5214 @item -gnatw.C
5215 @emph{Suppress warnings on missing component clauses.}
5216 @cindex @option{-gnatwC} (@command{gcc})
5217 This switch suppresses warnings for record components that are
5218 missing a component clause in the situation described above.
5219
5220 @item -gnatwd
5221 @emph{Activate warnings on implicit dereferencing.}
5222 @cindex @option{-gnatwd} (@command{gcc})
5223 If this switch is set, then the use of a prefix of an access type
5224 in an indexed component, slice, or selected component without an
5225 explicit @code{.all} will generate a warning. With this warning
5226 enabled, access checks occur only at points where an explicit
5227 @code{.all} appears in the source code (assuming no warnings are
5228 generated as a result of this switch). The default is that such
5229 warnings are not generated.
5230 Note that @option{-gnatwa} does not affect the setting of
5231 this warning option.
5232
5233 @item -gnatwD
5234 @emph{Suppress warnings on implicit dereferencing.}
5235 @cindex @option{-gnatwD} (@command{gcc})
5236 @cindex Implicit dereferencing
5237 @cindex Dereferencing, implicit
5238 This switch suppresses warnings for implicit dereferences in
5239 indexed components, slices, and selected components.
5240
5241 @item -gnatwe
5242 @emph{Treat warnings and style checks as errors.}
5243 @cindex @option{-gnatwe} (@command{gcc})
5244 @cindex Warnings, treat as error
5245 This switch causes warning messages and style check messages to be
5246 treated as errors.
5247 The warning string still appears, but the warning messages are counted
5248 as errors, and prevent the generation of an object file. Note that this
5249 is the only -gnatw switch that affects the handling of style check messages.
5250
5251 @item -gnatw.e
5252 @emph{Activate every optional warning}
5253 @cindex @option{-gnatw.e} (@command{gcc})
5254 @cindex Warnings, activate every optional warning
5255 This switch activates all optional warnings, including those which
5256 are not activated by @code{-gnatwa}. The use of this switch is not
5257 recommended for normal use. If you turn this switch on, it is almost
5258 certain that you will get large numbers of useless warnings. The
5259 warnings that are excluded from @code{-gnatwa} are typically highly
5260 specialized warnings that are suitable for use only in code that has
5261 been specifically designed according to specialized coding rules.
5262
5263 @item -gnatwf
5264 @emph{Activate warnings on unreferenced formals.}
5265 @cindex @option{-gnatwf} (@command{gcc})
5266 @cindex Formals, unreferenced
5267 This switch causes a warning to be generated if a formal parameter
5268 is not referenced in the body of the subprogram. This warning can
5269 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5270 default is that these warnings are not generated.
5271
5272 @item -gnatwF
5273 @emph{Suppress warnings on unreferenced formals.}
5274 @cindex @option{-gnatwF} (@command{gcc})
5275 This switch suppresses warnings for unreferenced formal
5276 parameters. Note that the
5277 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5278 effect of warning on unreferenced entities other than subprogram
5279 formals.
5280
5281 @item -gnatwg
5282 @emph{Activate warnings on unrecognized pragmas.}
5283 @cindex @option{-gnatwg} (@command{gcc})
5284 @cindex Pragmas, unrecognized
5285 This switch causes a warning to be generated if an unrecognized
5286 pragma is encountered. Apart from issuing this warning, the
5287 pragma is ignored and has no effect. This warning can
5288 also be turned on using @option{-gnatwa}. The default
5289 is that such warnings are issued (satisfying the Ada Reference
5290 Manual requirement that such warnings appear).
5291
5292 @item -gnatwG
5293 @emph{Suppress warnings on unrecognized pragmas.}
5294 @cindex @option{-gnatwG} (@command{gcc})
5295 This switch suppresses warnings for unrecognized pragmas.
5296
5297 @item -gnatwh
5298 @emph{Activate warnings on hiding.}
5299 @cindex @option{-gnatwh} (@command{gcc})
5300 @cindex Hiding of Declarations
5301 This switch activates warnings on hiding declarations.
5302 A declaration is considered hiding
5303 if it is for a non-overloadable entity, and it declares an entity with the
5304 same name as some other entity that is directly or use-visible. The default
5305 is that such warnings are not generated.
5306 Note that @option{-gnatwa} does not affect the setting of this warning option.
5307
5308 @item -gnatwH
5309 @emph{Suppress warnings on hiding.}
5310 @cindex @option{-gnatwH} (@command{gcc})
5311 This switch suppresses warnings on hiding declarations.
5312
5313 @item -gnatw.h
5314 @emph{Activate warnings on holes/gaps in records.}
5315 @cindex @option{-gnatw.h} (@command{gcc})
5316 @cindex Record Representation (gaps)
5317 This switch activates warnings on component clauses in record
5318 representation clauses that leave holes (gaps) in the record layout.
5319 If this warning option is active, then record representation clauses
5320 should specify a contiguous layout, adding unused fill fields if needed.
5321 Note that @option{-gnatwa} does not affect the setting of this warning option.
5322
5323 @item -gnatw.H
5324 @emph{Suppress warnings on holes/gaps in records.}
5325 @cindex @option{-gnatw.H} (@command{gcc})
5326 This switch suppresses warnings on component clauses in record
5327 representation clauses that leave holes (haps) in the record layout.
5328
5329 @item -gnatwi
5330 @emph{Activate warnings on implementation units.}
5331 @cindex @option{-gnatwi} (@command{gcc})
5332 This switch activates warnings for a @code{with} of an internal GNAT
5333 implementation unit, defined as any unit from the @code{Ada},
5334 @code{Interfaces}, @code{GNAT},
5335 ^^@code{DEC},^ or @code{System}
5336 hierarchies that is not
5337 documented in either the Ada Reference Manual or the GNAT
5338 Programmer's Reference Manual. Such units are intended only
5339 for internal implementation purposes and should not be @code{with}'ed
5340 by user programs. The default is that such warnings are generated
5341 This warning can also be turned on using @option{-gnatwa}.
5342
5343 @item -gnatwI
5344 @emph{Disable warnings on implementation units.}
5345 @cindex @option{-gnatwI} (@command{gcc})
5346 This switch disables warnings for a @code{with} of an internal GNAT
5347 implementation unit.
5348
5349 @item -gnatw.i
5350 @emph{Activate warnings on overlapping actuals.}
5351 @cindex @option{-gnatw.i} (@command{gcc})
5352 This switch enables a warning on statically detectable overlapping actuals in
5353 a subprogram call, when one of the actuals is an in-out parameter, and the
5354 types of the actuals are not by-copy types. The warning is off by default,
5355 and is not included under -gnatwa.
5356
5357 @item -gnatw.I
5358 @emph{Disable warnings on overlapping actuals.}
5359 @cindex @option{-gnatw.I} (@command{gcc})
5360 This switch disables warnings on overlapping actuals in a call..
5361
5362 @item -gnatwj
5363 @emph{Activate warnings on obsolescent features (Annex J).}
5364 @cindex @option{-gnatwj} (@command{gcc})
5365 @cindex Features, obsolescent
5366 @cindex Obsolescent features
5367 If this warning option is activated, then warnings are generated for
5368 calls to subprograms marked with @code{pragma Obsolescent} and
5369 for use of features in Annex J of the Ada Reference Manual. In the
5370 case of Annex J, not all features are flagged. In particular use
5371 of the renamed packages (like @code{Text_IO}) and use of package
5372 @code{ASCII} are not flagged, since these are very common and
5373 would generate many annoying positive warnings. The default is that
5374 such warnings are not generated. This warning is also turned on by
5375 the use of @option{-gnatwa}.
5376
5377 In addition to the above cases, warnings are also generated for
5378 GNAT features that have been provided in past versions but which
5379 have been superseded (typically by features in the new Ada standard).
5380 For example, @code{pragma Ravenscar} will be flagged since its
5381 function is replaced by @code{pragma Profile(Ravenscar)}.
5382
5383 Note that this warning option functions differently from the
5384 restriction @code{No_Obsolescent_Features} in two respects.
5385 First, the restriction applies only to annex J features.
5386 Second, the restriction does flag uses of package @code{ASCII}.
5387
5388 @item -gnatwJ
5389 @emph{Suppress warnings on obsolescent features (Annex J).}
5390 @cindex @option{-gnatwJ} (@command{gcc})
5391 This switch disables warnings on use of obsolescent features.
5392
5393 @item -gnatwk
5394 @emph{Activate warnings on variables that could be constants.}
5395 @cindex @option{-gnatwk} (@command{gcc})
5396 This switch activates warnings for variables that are initialized but
5397 never modified, and then could be declared constants. The default is that
5398 such warnings are not given.
5399 This warning can also be turned on using @option{-gnatwa}.
5400
5401 @item -gnatwK
5402 @emph{Suppress warnings on variables that could be constants.}
5403 @cindex @option{-gnatwK} (@command{gcc})
5404 This switch disables warnings on variables that could be declared constants.
5405
5406 @item -gnatwl
5407 @emph{Activate warnings for elaboration pragmas.}
5408 @cindex @option{-gnatwl} (@command{gcc})
5409 @cindex Elaboration, warnings
5410 This switch activates warnings on missing
5411 @code{Elaborate_All} and @code{Elaborate} pragmas.
5412 See the section in this guide on elaboration checking for details on
5413 when such pragmas should be used. In dynamic elaboration mode, this switch
5414 generations warnings about the need to add elaboration pragmas. Note however,
5415 that if you blindly follow these warnings, and add @code{Elaborate_All}
5416 warnings wherever they are recommended, you basically end up with the
5417 equivalent of the static elaboration model, which may not be what you want for
5418 legacy code for which the static model does not work.
5419
5420 For the static model, the messages generated are labeled "info:" (for
5421 information messages). They are not warnings to add elaboration pragmas,
5422 merely informational messages showing what implicit elaboration pragmas
5423 have been added, for use in analyzing elaboration circularity problems.
5424
5425 Warnings are also generated if you
5426 are using the static mode of elaboration, and a @code{pragma Elaborate}
5427 is encountered. The default is that such warnings
5428 are not generated.
5429 This warning is not automatically turned on by the use of @option{-gnatwa}.
5430
5431 @item -gnatwL
5432 @emph{Suppress warnings for elaboration pragmas.}
5433 @cindex @option{-gnatwL} (@command{gcc})
5434 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5435 See the section in this guide on elaboration checking for details on
5436 when such pragmas should be used.
5437
5438 @item -gnatw.l
5439 @emph{List inherited aspects.}
5440 @cindex @option{-gnatw.l} (@command{gcc})
5441 This switch causes the compiler to list inherited invariants,
5442 preconditions, and postconditions from Invariant'Class, Pre'Class, and
5443 Post'Class aspects. Also list inherited subtype predicates.
5444 These messages are not automatically turned on by the use of @option{-gnatwa}.
5445
5446 @item -gnatw.L
5447 @emph{Suppress listing of inherited aspects.}
5448 @cindex @option{-gnatw.L} (@command{gcc})
5449 This switch suppresses listing of inherited aspects.
5450
5451 @item -gnatwm
5452 @emph{Activate warnings on modified but unreferenced variables.}
5453 @cindex @option{-gnatwm} (@command{gcc})
5454 This switch activates warnings for variables that are assigned (using
5455 an initialization value or with one or more assignment statements) but
5456 whose value is never read. The warning is suppressed for volatile
5457 variables and also for variables that are renamings of other variables
5458 or for which an address clause is given.
5459 This warning can also be turned on using @option{-gnatwa}.
5460 The default is that these warnings are not given.
5461
5462 @item -gnatwM
5463 @emph{Disable warnings on modified but unreferenced variables.}
5464 @cindex @option{-gnatwM} (@command{gcc})
5465 This switch disables warnings for variables that are assigned or
5466 initialized, but never read.
5467
5468 @item -gnatw.m
5469 @emph{Activate warnings on suspicious modulus values.}
5470 @cindex @option{-gnatw.m} (@command{gcc})
5471 This switch activates warnings for modulus values that seem suspicious.
5472 The cases caught are where the size is the same as the modulus (e.g.
5473 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5474 with no size clause. The guess in both cases is that 2**x was intended
5475 rather than x. The default is that these warnings are given.
5476
5477 @item -gnatw.M
5478 @emph{Disable warnings on suspicious modulus values.}
5479 @cindex @option{-gnatw.M} (@command{gcc})
5480 This switch disables warnings for suspicious modulus values.
5481
5482 @item -gnatwn
5483 @emph{Set normal warnings mode.}
5484 @cindex @option{-gnatwn} (@command{gcc})
5485 This switch sets normal warning mode, in which enabled warnings are
5486 issued and treated as warnings rather than errors. This is the default
5487 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5488 an explicit @option{-gnatws} or
5489 @option{-gnatwe}. It also cancels the effect of the
5490 implicit @option{-gnatwe} that is activated by the
5491 use of @option{-gnatg}.
5492
5493 @item -gnatwo
5494 @emph{Activate warnings on address clause overlays.}
5495 @cindex @option{-gnatwo} (@command{gcc})
5496 @cindex Address Clauses, warnings
5497 This switch activates warnings for possibly unintended initialization
5498 effects of defining address clauses that cause one variable to overlap
5499 another. The default is that such warnings are generated.
5500 This warning can also be turned on using @option{-gnatwa}.
5501
5502 @item -gnatwO
5503 @emph{Suppress warnings on address clause overlays.}
5504 @cindex @option{-gnatwO} (@command{gcc})
5505 This switch suppresses warnings on possibly unintended initialization
5506 effects of defining address clauses that cause one variable to overlap
5507 another.
5508
5509 @item -gnatw.o
5510 @emph{Activate warnings on modified but unreferenced out parameters.}
5511 @cindex @option{-gnatw.o} (@command{gcc})
5512 This switch activates warnings for variables that are modified by using
5513 them as actuals for a call to a procedure with an out mode formal, where
5514 the resulting assigned value is never read. It is applicable in the case
5515 where there is more than one out mode formal. If there is only one out
5516 mode formal, the warning is issued by default (controlled by -gnatwu).
5517 The warning is suppressed for volatile
5518 variables and also for variables that are renamings of other variables
5519 or for which an address clause is given.
5520 The default is that these warnings are not given. Note that this warning
5521 is not included in -gnatwa, it must be activated explicitly.
5522
5523 @item -gnatw.O
5524 @emph{Disable warnings on modified but unreferenced out parameters.}
5525 @cindex @option{-gnatw.O} (@command{gcc})
5526 This switch suppresses warnings for variables that are modified by using
5527 them as actuals for a call to a procedure with an out mode formal, where
5528 the resulting assigned value is never read.
5529
5530 @item -gnatwp
5531 @emph{Activate warnings on ineffective pragma Inlines.}
5532 @cindex @option{-gnatwp} (@command{gcc})
5533 @cindex Inlining, warnings
5534 This switch activates warnings for failure of front end inlining
5535 (activated by @option{-gnatN}) to inline a particular call. There are
5536 many reasons for not being able to inline a call, including most
5537 commonly that the call is too complex to inline. The default is
5538 that such warnings are not given.
5539 This warning can also be turned on using @option{-gnatwa}.
5540 Warnings on ineffective inlining by the gcc back-end can be activated
5541 separately, using the gcc switch -Winline.
5542
5543 @item -gnatwP
5544 @emph{Suppress warnings on ineffective pragma Inlines.}
5545 @cindex @option{-gnatwP} (@command{gcc})
5546 This switch suppresses warnings on ineffective pragma Inlines. If the
5547 inlining mechanism cannot inline a call, it will simply ignore the
5548 request silently.
5549
5550 @item -gnatw.p
5551 @emph{Activate warnings on parameter ordering.}
5552 @cindex @option{-gnatw.p} (@command{gcc})
5553 @cindex Parameter order, warnings
5554 This switch activates warnings for cases of suspicious parameter
5555 ordering when the list of arguments are all simple identifiers that
5556 match the names of the formals, but are in a different order. The
5557 warning is suppressed if any use of named parameter notation is used,
5558 so this is the appropriate way to suppress a false positive (and
5559 serves to emphasize that the "misordering" is deliberate). The
5560 default is
5561 that such warnings are not given.
5562 This warning can also be turned on using @option{-gnatwa}.
5563
5564 @item -gnatw.P
5565 @emph{Suppress warnings on parameter ordering.}
5566 @cindex @option{-gnatw.P} (@command{gcc})
5567 This switch suppresses warnings on cases of suspicious parameter
5568 ordering.
5569
5570 @item -gnatwq
5571 @emph{Activate warnings on questionable missing parentheses.}
5572 @cindex @option{-gnatwq} (@command{gcc})
5573 @cindex Parentheses, warnings
5574 This switch activates warnings for cases where parentheses are not used and
5575 the result is potential ambiguity from a readers point of view. For example
5576 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5577 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5578 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5579 follow the rule of always parenthesizing to make the association clear, and
5580 this warning switch warns if such parentheses are not present. The default
5581 is that these warnings are given.
5582 This warning can also be turned on using @option{-gnatwa}.
5583
5584 @item -gnatwQ
5585 @emph{Suppress warnings on questionable missing parentheses.}
5586 @cindex @option{-gnatwQ} (@command{gcc})
5587 This switch suppresses warnings for cases where the association is not
5588 clear and the use of parentheses is preferred.
5589
5590 @item -gnatwr
5591 @emph{Activate warnings on redundant constructs.}
5592 @cindex @option{-gnatwr} (@command{gcc})
5593 This switch activates warnings for redundant constructs. The following
5594 is the current list of constructs regarded as redundant:
5595
5596 @itemize @bullet
5597 @item
5598 Assignment of an item to itself.
5599 @item
5600 Type conversion that converts an expression to its own type.
5601 @item
5602 Use of the attribute @code{Base} where @code{typ'Base} is the same
5603 as @code{typ}.
5604 @item
5605 Use of pragma @code{Pack} when all components are placed by a record
5606 representation clause.
5607 @item
5608 Exception handler containing only a reraise statement (raise with no
5609 operand) which has no effect.
5610 @item
5611 Use of the operator abs on an operand that is known at compile time
5612 to be non-negative
5613 @item
5614 Comparison of boolean expressions to an explicit True value.
5615 @end itemize
5616
5617 This warning can also be turned on using @option{-gnatwa}.
5618 The default is that warnings for redundant constructs are not given.
5619
5620 @item -gnatwR
5621 @emph{Suppress warnings on redundant constructs.}
5622 @cindex @option{-gnatwR} (@command{gcc})
5623 This switch suppresses warnings for redundant constructs.
5624
5625 @item -gnatw.r
5626 @emph{Activate warnings for object renaming function.}
5627 @cindex @option{-gnatw.r} (@command{gcc})
5628 This switch activates warnings for an object renaming that renames a
5629 function call, which is equivalent to a constant declaration (as
5630 opposed to renaming the function itself).  The default is that these
5631 warnings are given.  This warning can also be turned on using
5632 @option{-gnatwa}.
5633
5634 @item -gnatw.R
5635 @emph{Suppress warnings for object renaming function.}
5636 @cindex @option{-gnatwT} (@command{gcc})
5637 This switch suppresses warnings for object renaming function.
5638
5639 @item -gnatws
5640 @emph{Suppress all warnings.}
5641 @cindex @option{-gnatws} (@command{gcc})
5642 This switch completely suppresses the
5643 output of all warning messages from the GNAT front end, including
5644 both warnings that can be controlled by switches described in this
5645 section, and those that are normally given unconditionally. The
5646 effect of this suppress action can only be cancelled by a subsequent
5647 use of the switch @option{-gnatwn}.
5648
5649 Note that switch @option{-gnatws} does not suppress
5650 warnings from the @command{gcc} back end.
5651 To suppress these back end warnings as well, use the switch @option{-w}
5652 in addition to @option{-gnatws}. Also this switch has no effect on the
5653 handling of style check messages.
5654
5655 @item -gnatw.s
5656 @emph{Activate warnings on overridden size clauses.}
5657 @cindex @option{-gnatw.s} (@command{gcc})
5658 @cindex Record Representation (component sizes)
5659 This switch activates warnings on component clauses in record
5660 representation clauses where the length given overrides that
5661 specified by an explicit size clause for the component type. A
5662 warning is similarly given in the array case if a specified
5663 component size overrides an explicit size clause for the array
5664 component type.
5665 Note that @option{-gnatwa} does not affect the setting of this warning option.
5666
5667 @item -gnatw.S
5668 @emph{Suppress warnings on overridden size clauses.}
5669 @cindex @option{-gnatw.S} (@command{gcc})
5670 This switch suppresses warnings on component clauses in record
5671 representation clauses that override size clauses, and similar
5672 warnings when an array component size overrides a size clause.
5673
5674 @item -gnatwt
5675 @emph{Activate warnings for tracking of deleted conditional code.}
5676 @cindex @option{-gnatwt} (@command{gcc})
5677 @cindex Deactivated code, warnings
5678 @cindex Deleted code, warnings
5679 This switch activates warnings for tracking of code in conditionals (IF and
5680 CASE statements) that is detected to be dead code which cannot be executed, and
5681 which is removed by the front end. This warning is off by default, and is not
5682 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5683 useful for detecting deactivated code in certified applications.
5684
5685 @item -gnatwT
5686 @emph{Suppress warnings for tracking of deleted conditional code.}
5687 @cindex @option{-gnatwT} (@command{gcc})
5688 This switch suppresses warnings for tracking of deleted conditional code.
5689
5690 @item -gnatw.t
5691 @emph{Activate warnings on suspicious contracts.}
5692 @cindex @option{-gnatw.t} (@command{gcc})
5693 This switch activates warnings on suspicious postconditions (whether a
5694 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012). A
5695 function postcondition is suspicious when it does not mention the result
5696 of the function. A procedure postcondition is suspicious when it only
5697 refers to the pre-state of the procedure, because in that case it should
5698 rather be expressed as a precondition. The default is that such warnings
5699 are not generated. This warning can also be turned on using @option{-gnatwa}.
5700
5701 @item -gnatw.T
5702 @emph{Suppress warnings on suspicious contracts.}
5703 @cindex @option{-gnatw.T} (@command{gcc})
5704 This switch suppresses warnings on suspicious postconditions.
5705
5706 @item -gnatwu
5707 @emph{Activate warnings on unused entities.}
5708 @cindex @option{-gnatwu} (@command{gcc})
5709 This switch activates warnings to be generated for entities that
5710 are declared but not referenced, and for units that are @code{with}'ed
5711 and not
5712 referenced. In the case of packages, a warning is also generated if
5713 no entities in the package are referenced. This means that if a with'ed
5714 package is referenced but the only references are in @code{use}
5715 clauses or @code{renames}
5716 declarations, a warning is still generated. A warning is also generated
5717 for a generic package that is @code{with}'ed but never instantiated.
5718 In the case where a package or subprogram body is compiled, and there
5719 is a @code{with} on the corresponding spec
5720 that is only referenced in the body,
5721 a warning is also generated, noting that the
5722 @code{with} can be moved to the body. The default is that
5723 such warnings are not generated.
5724 This switch also activates warnings on unreferenced formals
5725 (it includes the effect of @option{-gnatwf}).
5726 This warning can also be turned on using @option{-gnatwa}.
5727
5728 @item -gnatwU
5729 @emph{Suppress warnings on unused entities.}
5730 @cindex @option{-gnatwU} (@command{gcc})
5731 This switch suppresses warnings for unused entities and packages.
5732 It also turns off warnings on unreferenced formals (and thus includes
5733 the effect of @option{-gnatwF}).
5734
5735 @item -gnatw.u
5736 @emph{Activate warnings on unordered enumeration types.}
5737 @cindex @option{-gnatw.u} (@command{gcc})
5738 This switch causes enumeration types to be considered as conceptually
5739 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5740 The effect is to generate warnings in clients that use explicit comparisons
5741 or subranges, since these constructs both treat objects of the type as
5742 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5743 which the type is declared, or its body or subunits.) Please refer to
5744 the description of pragma @code{Ordered} in the
5745 @cite{@value{EDITION} Reference Manual} for further details.
5746 The default is that such warnings are not generated.
5747 This warning is not automatically turned on by the use of @option{-gnatwa}.
5748
5749 @item -gnatw.U
5750 @emph{Deactivate warnings on unordered enumeration types.}
5751 @cindex @option{-gnatw.U} (@command{gcc})
5752 This switch causes all enumeration types to be considered as ordered, so
5753 that no warnings are given for comparisons or subranges for any type.
5754
5755 @item -gnatwv
5756 @emph{Activate warnings on unassigned variables.}
5757 @cindex @option{-gnatwv} (@command{gcc})
5758 @cindex Unassigned variable warnings
5759 This switch activates warnings for access to variables which
5760 may not be properly initialized. The default is that
5761 such warnings are generated.
5762 This warning can also be turned on using @option{-gnatwa}.
5763
5764 @item -gnatwV
5765 @emph{Suppress warnings on unassigned variables.}
5766 @cindex @option{-gnatwV} (@command{gcc})
5767 This switch suppresses warnings for access to variables which
5768 may not be properly initialized.
5769 For variables of a composite type, the warning can also be suppressed in
5770 Ada 2005 by using a default initialization with a box. For example, if
5771 Table is an array of records whose components are only partially uninitialized,
5772 then the following code:
5773
5774 @smallexample @c ada
5775    Tab : Table := (others => <>);
5776 @end smallexample
5777
5778 will suppress warnings on subsequent statements that access components
5779 of variable Tab.
5780
5781 @item -gnatww
5782 @emph{Activate warnings on wrong low bound assumption.}
5783 @cindex @option{-gnatww} (@command{gcc})
5784 @cindex String indexing warnings
5785 This switch activates warnings for indexing an unconstrained string parameter
5786 with a literal or S'Length. This is a case where the code is assuming that the
5787 low bound is one, which is in general not true (for example when a slice is
5788 passed). The default is that such warnings are generated.
5789 This warning can also be turned on using @option{-gnatwa}.
5790
5791 @item -gnatwW
5792 @emph{Suppress warnings on wrong low bound assumption.}
5793 @cindex @option{-gnatwW} (@command{gcc})
5794 This switch suppresses warnings for indexing an unconstrained string parameter
5795 with a literal or S'Length. Note that this warning can also be suppressed
5796 in a particular case by adding an
5797 assertion that the lower bound is 1,
5798 as shown in the following example.
5799
5800 @smallexample @c ada
5801    procedure K (S : String) is
5802       pragma Assert (S'First = 1);
5803       @dots{}
5804 @end smallexample
5805
5806 @item -gnatw.w
5807 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5808 @cindex @option{-gnatw.w} (@command{gcc})
5809 @cindex Warnings Off control
5810 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5811 where either the pragma is entirely useless (because it suppresses no
5812 warnings), or it could be replaced by @code{pragma Unreferenced} or
5813 @code{pragma Unmodified}. The default is that these warnings are not given.
5814 Note that this warning is not included in -gnatwa, it must be
5815 activated explicitly.
5816
5817 @item -gnatw.W
5818 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5819 @cindex @option{-gnatw.W} (@command{gcc})
5820 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5821
5822 @item -gnatwx
5823 @emph{Activate warnings on Export/Import pragmas.}
5824 @cindex @option{-gnatwx} (@command{gcc})
5825 @cindex Export/Import pragma warnings
5826 This switch activates warnings on Export/Import pragmas when
5827 the compiler detects a possible conflict between the Ada and
5828 foreign language calling sequences. For example, the use of
5829 default parameters in a convention C procedure is dubious
5830 because the C compiler cannot supply the proper default, so
5831 a warning is issued. The default is that such warnings are
5832 generated.
5833 This warning can also be turned on using @option{-gnatwa}.
5834
5835 @item -gnatwX
5836 @emph{Suppress warnings on Export/Import pragmas.}
5837 @cindex @option{-gnatwX} (@command{gcc})
5838 This switch suppresses warnings on Export/Import pragmas.
5839 The sense of this is that you are telling the compiler that
5840 you know what you are doing in writing the pragma, and it
5841 should not complain at you.
5842
5843 @item -gnatw.x
5844 @emph{Activate warnings for No_Exception_Propagation mode.}
5845 @cindex @option{-gnatwm} (@command{gcc})
5846 This switch activates warnings for exception usage when pragma Restrictions
5847 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5848 explicit exception raises which are not covered by a local handler, and for
5849 exception handlers which do not cover a local raise. The default is that these
5850 warnings are not given.
5851
5852 @item -gnatw.X
5853 @emph{Disable warnings for No_Exception_Propagation mode.}
5854 This switch disables warnings for exception usage when pragma Restrictions
5855 (No_Exception_Propagation) is in effect.
5856
5857 @item -gnatwy
5858 @emph{Activate warnings for Ada compatibility issues.}
5859 @cindex @option{-gnatwy} (@command{gcc})
5860 @cindex Ada compatibility issues warnings
5861 For the most part, newer versions of Ada are upwards compatible
5862 with older versions. For example, Ada 2005 programs will almost
5863 always work when compiled as Ada 2012.
5864 However there are some exceptions (for example the fact that
5865 @code{some} is now a reserved word in Ada 2012). This
5866 switch activates several warnings to help in identifying
5867 and correcting such incompatibilities. The default is that
5868 these warnings are generated. Note that at one point Ada 2005
5869 was called Ada 0Y, hence the choice of character.
5870 This warning can also be turned on using @option{-gnatwa}.
5871
5872 @item -gnatwY
5873 @emph{Disable warnings for Ada compatibility issues.}
5874 @cindex @option{-gnatwY} (@command{gcc})
5875 @cindex Ada compatibility issues warnings
5876 This switch suppresses the warnings intended to help in identifying
5877 incompatibilities between Ada language versions.
5878
5879 @item -gnatwz
5880 @emph{Activate warnings on unchecked conversions.}
5881 @cindex @option{-gnatwz} (@command{gcc})
5882 @cindex Unchecked_Conversion warnings
5883 This switch activates warnings for unchecked conversions
5884 where the types are known at compile time to have different
5885 sizes. The default
5886 is that such warnings are generated. Warnings are also
5887 generated for subprogram pointers with different conventions,
5888 and, on VMS only, for data pointers with different conventions.
5889 This warning can also be turned on using @option{-gnatwa}.
5890
5891 @item -gnatwZ
5892 @emph{Suppress warnings on unchecked conversions.}
5893 @cindex @option{-gnatwZ} (@command{gcc})
5894 This switch suppresses warnings for unchecked conversions
5895 where the types are known at compile time to have different
5896 sizes or conventions.
5897
5898 @item ^-Wunused^WARNINGS=UNUSED^
5899 @cindex @option{-Wunused}
5900 The warnings controlled by the @option{-gnatw} switch are generated by
5901 the front end of the compiler. The @option{GCC} back end can provide
5902 additional warnings and they are controlled by the @option{-W} switch.
5903 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5904 warnings for entities that are declared but not referenced.
5905
5906 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5907 @cindex @option{-Wuninitialized}
5908 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5909 the back end warning for uninitialized variables. This switch must be
5910 used in conjunction with an optimization level greater than zero.
5911
5912 @item -Wstack-usage=@var{len}
5913 @cindex @option{-Wstack-usage}
5914 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5915 See @ref{Static Stack Usage Analysis} for details.
5916
5917 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5918 @cindex @option{-Wall}
5919 This switch enables most warnings from the @option{GCC} back end.
5920 The code generator detects a number of warning situations that are missed
5921 by the @option{GNAT} front end, and this switch can be used to activate them.
5922 The use of this switch also sets the default front end warning mode to
5923 @option{-gnatwa}, that is, most front end warnings activated as well.
5924
5925 @item ^-w^/NO_BACK_END_WARNINGS^
5926 @cindex @option{-w}
5927 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5928 The use of this switch also sets the default front end warning mode to
5929 @option{-gnatws}, that is, front end warnings suppressed as well.
5930
5931 @end table
5932
5933 @noindent
5934 @ifclear vms
5935 A string of warning parameters can be used in the same parameter. For example:
5936
5937 @smallexample
5938 -gnatwaGe
5939 @end smallexample
5940
5941 @noindent
5942 will turn on all optional warnings except for unrecognized pragma warnings,
5943 and also specify that warnings should be treated as errors.
5944 @end ifclear
5945
5946 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5947
5948 @table @option
5949 @c !sort!
5950 @item -gnatwB
5951 @item -gnatw.b
5952 @item -gnatwC
5953 @item -gnatw.C
5954 @item -gnatwD
5955 @item -gnatwF
5956 @item -gnatwg
5957 @item -gnatwH
5958 @item -gnatwi
5959 @item -gnatw.I
5960 @item -gnatwJ
5961 @item -gnatwK
5962 @item -gnatwL
5963 @item -gnatw.L
5964 @item -gnatwM
5965 @item -gnatw.m
5966 @item -gnatwn
5967 @item -gnatwo
5968 @item -gnatw.O
5969 @item -gnatwP
5970 @item -gnatw.P
5971 @item -gnatwq
5972 @item -gnatwR
5973 @item -gnatw.R
5974 @item -gnatw.S
5975 @item -gnatwT
5976 @item -gnatw.T
5977 @item -gnatwU
5978 @item -gnatwv
5979 @item -gnatww
5980 @item -gnatw.W
5981 @item -gnatwx
5982 @item -gnatw.X
5983 @item -gnatwy
5984 @item -gnatwz
5985
5986 @end table
5987
5988 @node Debugging and Assertion Control
5989 @subsection Debugging and Assertion Control
5990
5991 @table @option
5992 @item -gnata
5993 @cindex @option{-gnata} (@command{gcc})
5994 @findex Assert
5995 @findex Debug
5996 @cindex Assertions
5997
5998 @noindent
5999 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6000 are ignored. This switch, where @samp{a} stands for assert, causes
6001 @code{Assert} and @code{Debug} pragmas to be activated.
6002
6003 The pragmas have the form:
6004
6005 @smallexample
6006 @cartouche
6007    @b{pragma} Assert (@var{Boolean-expression} @r{[},
6008                       @var{static-string-expression}@r{]})
6009    @b{pragma} Debug (@var{procedure call})
6010 @end cartouche
6011 @end smallexample
6012
6013 @noindent
6014 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6015 If the result is @code{True}, the pragma has no effect (other than
6016 possible side effects from evaluating the expression). If the result is
6017 @code{False}, the exception @code{Assert_Failure} declared in the package
6018 @code{System.Assertions} is
6019 raised (passing @var{static-string-expression}, if present, as the
6020 message associated with the exception). If no string expression is
6021 given the default is a string giving the file name and line number
6022 of the pragma.
6023
6024 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6025 @code{pragma Debug} may appear within a declaration sequence, allowing
6026 debugging procedures to be called between declarations.
6027
6028 @ifset vms
6029 @item /DEBUG@r{[}=debug-level@r{]}
6030 @itemx  /NODEBUG
6031 Specifies how much debugging information is to be included in
6032 the resulting object file where 'debug-level' is one of the following:
6033 @table @code
6034 @item   TRACEBACK
6035 Include both debugger symbol records and traceback
6036 the object file.
6037 This is the default setting.
6038 @item   ALL
6039 Include both debugger symbol records and traceback in
6040 object file.
6041 @item   NONE
6042 Excludes both debugger symbol records and traceback
6043 the object file. Same as /NODEBUG.
6044 @item   SYMBOLS
6045 Includes only debugger symbol records in the object
6046 file. Note that this doesn't include traceback information.
6047 @end table
6048 @end ifset
6049 @end table
6050
6051 @node Validity Checking
6052 @subsection Validity Checking
6053 @findex Validity Checking
6054
6055 @noindent
6056 The Ada Reference Manual defines the concept of invalid values (see
6057 RM 13.9.1). The primary source of invalid values is uninitialized
6058 variables. A scalar variable that is left uninitialized may contain
6059 an invalid value; the concept of invalid does not apply to access or
6060 composite types.
6061
6062 It is an error to read an invalid value, but the RM does not require
6063 run-time checks to detect such errors, except for some minimal
6064 checking to prevent erroneous execution (i.e. unpredictable
6065 behavior). This corresponds to the @option{-gnatVd} switch below,
6066 which is the default. For example, by default, if the expression of a
6067 case statement is invalid, it will raise Constraint_Error rather than
6068 causing a wild jump, and if an array index on the left-hand side of an
6069 assignment is invalid, it will raise Constraint_Error rather than
6070 overwriting an arbitrary memory location.
6071
6072 The @option{-gnatVa} may be used to enable additional validity checks,
6073 which are not required by the RM. These checks are often very
6074 expensive (which is why the RM does not require them). These checks
6075 are useful in tracking down uninitialized variables, but they are
6076 not usually recommended for production builds.
6077
6078 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6079 control; you can enable whichever validity checks you desire. However,
6080 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6081 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6082 sufficient for non-debugging use.
6083
6084 The @option{-gnatB} switch tells the compiler to assume that all
6085 values are valid (that is, within their declared subtype range)
6086 except in the context of a use of the Valid attribute. This means
6087 the compiler can generate more efficient code, since the range
6088 of values is better known at compile time. However, an uninitialized
6089 variable can cause wild jumps and memory corruption in this mode.
6090
6091 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6092 checking mode as described below.
6093 @ifclear vms
6094 The @code{x} argument is a string of letters that
6095 indicate validity checks that are performed or not performed in addition
6096 to the default checks required by Ada as described above.
6097 @end ifclear
6098 @ifset vms
6099 The options allowed for this qualifier
6100 indicate validity checks that are performed or not performed in addition
6101 to the default checks required by Ada as described above.
6102 @end ifset
6103
6104 @table @option
6105 @c !sort!
6106 @item -gnatVa
6107 @emph{All validity checks.}
6108 @cindex @option{-gnatVa} (@command{gcc})
6109 All validity checks are turned on.
6110 @ifclear vms
6111 That is, @option{-gnatVa} is
6112 equivalent to @option{gnatVcdfimorst}.
6113 @end ifclear
6114
6115 @item -gnatVc
6116 @emph{Validity checks for copies.}
6117 @cindex @option{-gnatVc} (@command{gcc})
6118 The right hand side of assignments, and the initializing values of
6119 object declarations are validity checked.
6120
6121 @item -gnatVd
6122 @emph{Default (RM) validity checks.}
6123 @cindex @option{-gnatVd} (@command{gcc})
6124 Some validity checks are done by default following normal Ada semantics
6125 (RM 13.9.1 (9-11)).
6126 A check is done in case statements that the expression is within the range
6127 of the subtype. If it is not, Constraint_Error is raised.
6128 For assignments to array components, a check is done that the expression used
6129 as index is within the range. If it is not, Constraint_Error is raised.
6130 Both these validity checks may be turned off using switch @option{-gnatVD}.
6131 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6132 switch @option{-gnatVd} will leave the checks turned on.
6133 Switch @option{-gnatVD} should be used only if you are sure that all such
6134 expressions have valid values. If you use this switch and invalid values
6135 are present, then the program is erroneous, and wild jumps or memory
6136 overwriting may occur.
6137
6138 @item -gnatVe
6139 @emph{Validity checks for elementary components.}
6140 @cindex @option{-gnatVe} (@command{gcc})
6141 In the absence of this switch, assignments to record or array components are
6142 not validity checked, even if validity checks for assignments generally
6143 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6144 require valid data, but assignment of individual components does. So for
6145 example, there is a difference between copying the elements of an array with a
6146 slice assignment, compared to assigning element by element in a loop. This
6147 switch allows you to turn off validity checking for components, even when they
6148 are assigned component by component.
6149
6150 @item -gnatVf
6151 @emph{Validity checks for floating-point values.}
6152 @cindex @option{-gnatVf} (@command{gcc})
6153 In the absence of this switch, validity checking occurs only for discrete
6154 values. If @option{-gnatVf} is specified, then validity checking also applies
6155 for floating-point values, and NaNs and infinities are considered invalid,
6156 as well as out of range values for constrained types. Note that this means
6157 that standard IEEE infinity mode is not allowed. The exact contexts
6158 in which floating-point values are checked depends on the setting of other
6159 options. For example,
6160 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6161 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6162 (the order does not matter) specifies that floating-point parameters of mode
6163 @code{in} should be validity checked.
6164
6165 @item -gnatVi
6166 @emph{Validity checks for @code{in} mode parameters}
6167 @cindex @option{-gnatVi} (@command{gcc})
6168 Arguments for parameters of mode @code{in} are validity checked in function
6169 and procedure calls at the point of call.
6170
6171 @item -gnatVm
6172 @emph{Validity checks for @code{in out} mode parameters.}
6173 @cindex @option{-gnatVm} (@command{gcc})
6174 Arguments for parameters of mode @code{in out} are validity checked in
6175 procedure calls at the point of call. The @code{'m'} here stands for
6176 modify, since this concerns parameters that can be modified by the call.
6177 Note that there is no specific option to test @code{out} parameters,
6178 but any reference within the subprogram will be tested in the usual
6179 manner, and if an invalid value is copied back, any reference to it
6180 will be subject to validity checking.
6181
6182 @item -gnatVn
6183 @emph{No validity checks.}
6184 @cindex @option{-gnatVn} (@command{gcc})
6185 This switch turns off all validity checking, including the default checking
6186 for case statements and left hand side subscripts. Note that the use of
6187 the switch @option{-gnatp} suppresses all run-time checks, including
6188 validity checks, and thus implies @option{-gnatVn}. When this switch
6189 is used, it cancels any other @option{-gnatV} previously issued.
6190
6191 @item -gnatVo
6192 @emph{Validity checks for operator and attribute operands.}
6193 @cindex @option{-gnatVo} (@command{gcc})
6194 Arguments for predefined operators and attributes are validity checked.
6195 This includes all operators in package @code{Standard},
6196 the shift operators defined as intrinsic in package @code{Interfaces}
6197 and operands for attributes such as @code{Pos}. Checks are also made
6198 on individual component values for composite comparisons, and on the
6199 expressions in type conversions and qualified expressions. Checks are
6200 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6201
6202 @item -gnatVp
6203 @emph{Validity checks for parameters.}
6204 @cindex @option{-gnatVp} (@command{gcc})
6205 This controls the treatment of parameters within a subprogram (as opposed
6206 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6207 of parameters on a call. If either of these call options is used, then
6208 normally an assumption is made within a subprogram that the input arguments
6209 have been validity checking at the point of call, and do not need checking
6210 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6211 is not made, and parameters are not assumed to be valid, so their validity
6212 will be checked (or rechecked) within the subprogram.
6213
6214 @item -gnatVr
6215 @emph{Validity checks for function returns.}
6216 @cindex @option{-gnatVr} (@command{gcc})
6217 The expression in @code{return} statements in functions is validity
6218 checked.
6219
6220 @item -gnatVs
6221 @emph{Validity checks for subscripts.}
6222 @cindex @option{-gnatVs} (@command{gcc})
6223 All subscripts expressions are checked for validity, whether they appear
6224 on the right side or left side (in default mode only left side subscripts
6225 are validity checked).
6226
6227 @item -gnatVt
6228 @emph{Validity checks for tests.}
6229 @cindex @option{-gnatVt} (@command{gcc})
6230 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6231 statements are checked, as well as guard expressions in entry calls.
6232
6233 @end table
6234
6235 @noindent
6236 The @option{-gnatV} switch may be followed by
6237 ^a string of letters^a list of options^
6238 to turn on a series of validity checking options.
6239 For example,
6240 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6241 specifies that in addition to the default validity checking, copies and
6242 function return expressions are to be validity checked.
6243 In order to make it easier
6244 to specify the desired combination of effects,
6245 @ifclear vms
6246 the upper case letters @code{CDFIMORST} may
6247 be used to turn off the corresponding lower case option.
6248 @end ifclear
6249 @ifset vms
6250 the prefix @code{NO} on an option turns off the corresponding validity
6251 checking:
6252 @itemize @bullet
6253 @item @code{NOCOPIES}
6254 @item @code{NODEFAULT}
6255 @item @code{NOFLOATS}
6256 @item @code{NOIN_PARAMS}
6257 @item @code{NOMOD_PARAMS}
6258 @item @code{NOOPERANDS}
6259 @item @code{NORETURNS}
6260 @item @code{NOSUBSCRIPTS}
6261 @item @code{NOTESTS}
6262 @end itemize
6263 @end ifset
6264 Thus
6265 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6266 turns on all validity checking options except for
6267 checking of @code{@b{in out}} procedure arguments.
6268
6269 The specification of additional validity checking generates extra code (and
6270 in the case of @option{-gnatVa} the code expansion can be substantial).
6271 However, these additional checks can be very useful in detecting
6272 uninitialized variables, incorrect use of unchecked conversion, and other
6273 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6274 is useful in conjunction with the extra validity checking, since this
6275 ensures that wherever possible uninitialized variables have invalid values.
6276
6277 See also the pragma @code{Validity_Checks} which allows modification of
6278 the validity checking mode at the program source level, and also allows for
6279 temporary disabling of validity checks.
6280
6281 @node Style Checking
6282 @subsection Style Checking
6283 @findex Style checking
6284
6285 @noindent
6286 The @option{-gnaty^x^(option,option,@dots{})^} switch
6287 @cindex @option{-gnaty} (@command{gcc})
6288 causes the compiler to
6289 enforce specified style rules. A limited set of style rules has been used
6290 in writing the GNAT sources themselves. This switch allows user programs
6291 to activate all or some of these checks. If the source program fails a
6292 specified style check, an appropriate message is given, preceded by
6293 the character sequence ``(style)''. This message does not prevent
6294 successful compilation (unless the @option{-gnatwe} switch is used).
6295
6296 Note that this is by no means intended to be a general facility for
6297 checking arbitrary coding standards. It is simply an embedding of the
6298 style rules we have chosen for the GNAT sources. If you are starting
6299 a project which does not have established style standards, you may
6300 find it useful to adopt the entire set of GNAT coding standards, or
6301 some subset of them. If you already have an established set of coding
6302 standards, then it may be that selected style checking options do
6303 indeed correspond to choices you have made, but for general checking
6304 of an existing set of coding rules, you should look to the gnatcheck
6305 tool, which is designed for that purpose.
6306
6307 @ifset vms
6308 @code{(option,option,@dots{})} is a sequence of keywords
6309 @end ifset
6310 @ifclear vms
6311 The string @var{x} is a sequence of letters or digits
6312 @end ifclear
6313 indicating the particular style
6314 checks to be performed. The following checks are defined:
6315
6316 @table @option
6317 @c !sort!
6318 @item 0-9
6319 @emph{Specify indentation level.}
6320 If a digit from 1-9 appears
6321 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6322 then proper indentation is checked, with the digit indicating the
6323 indentation level required. A value of zero turns off this style check.
6324 The general style of required indentation is as specified by
6325 the examples in the Ada Reference Manual. Full line comments must be
6326 aligned with the @code{--} starting on a column that is a multiple of
6327 the alignment level, or they may be aligned the same way as the following
6328 non-blank line (this is useful when full line comments appear in the middle
6329 of a statement.
6330
6331 @item ^a^ATTRIBUTE^
6332 @emph{Check attribute casing.}
6333 Attribute names, including the case of keywords such as @code{digits}
6334 used as attributes names, must be written in mixed case, that is, the
6335 initial letter and any letter following an underscore must be uppercase.
6336 All other letters must be lowercase.
6337
6338 @item ^A^ARRAY_INDEXES^
6339 @emph{Use of array index numbers in array attributes.}
6340 When using the array attributes First, Last, Range,
6341 or Length, the index number must be omitted for one-dimensional arrays
6342 and is required for multi-dimensional arrays.
6343
6344 @item ^b^BLANKS^
6345 @emph{Blanks not allowed at statement end.}
6346 Trailing blanks are not allowed at the end of statements. The purpose of this
6347 rule, together with h (no horizontal tabs), is to enforce a canonical format
6348 for the use of blanks to separate source tokens.
6349
6350 @item ^B^BOOLEAN_OPERATORS^
6351 @emph{Check Boolean operators.}
6352 The use of AND/OR operators is not permitted except in the cases of modular
6353 operands, array operands, and simple stand-alone boolean variables or
6354 boolean constants. In all other cases @code{and then}/@code{or else} are
6355 required.
6356
6357 @item ^c^COMMENTS^
6358 @emph{Check comments, double space.}
6359 Comments must meet the following set of rules:
6360
6361 @itemize @bullet
6362
6363 @item
6364 The ``@code{--}'' that starts the column must either start in column one,
6365 or else at least one blank must precede this sequence.
6366
6367 @item
6368 Comments that follow other tokens on a line must have at least one blank
6369 following the ``@code{--}'' at the start of the comment.
6370
6371 @item
6372 Full line comments must have at least two blanks following the
6373 ``@code{--}'' that starts the comment, with the following exceptions.
6374
6375 @item
6376 A line consisting only of the ``@code{--}'' characters, possibly preceded
6377 by blanks is permitted.
6378
6379 @item
6380 A comment starting with ``@code{--x}'' where @code{x} is a special character
6381 is permitted.
6382 This allows proper processing of the output generated by specialized tools
6383 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6384 annotation
6385 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6386 special character is defined as being in one of the ASCII ranges
6387 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6388 Note that this usage is not permitted
6389 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6390
6391 @item
6392 A line consisting entirely of minus signs, possibly preceded by blanks, is
6393 permitted. This allows the construction of box comments where lines of minus
6394 signs are used to form the top and bottom of the box.
6395
6396 @item
6397 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6398 least one blank follows the initial ``@code{--}''. Together with the preceding
6399 rule, this allows the construction of box comments, as shown in the following
6400 example:
6401 @smallexample
6402 ---------------------------
6403 -- This is a box comment --
6404 -- with two text lines.  --
6405 ---------------------------
6406 @end smallexample
6407 @end itemize
6408
6409 @item ^C^COMMENTS1^
6410 @emph{Check comments, single space.}
6411 This is identical to @code{^c^COMMENTS^} except that only one space
6412 is required following the @code{--} of a comment instead of two.
6413
6414 @item ^d^DOS_LINE_ENDINGS^
6415 @emph{Check no DOS line terminators present.}
6416 All lines must be terminated by a single ASCII.LF
6417 character (in particular the DOS line terminator sequence CR/LF is not
6418 allowed).
6419
6420 @item ^e^END^
6421 @emph{Check end/exit labels.}
6422 Optional labels on @code{end} statements ending subprograms and on
6423 @code{exit} statements exiting named loops, are required to be present.
6424
6425 @item ^f^VTABS^
6426 @emph{No form feeds or vertical tabs.}
6427 Neither form feeds nor vertical tab characters are permitted
6428 in the source text.
6429
6430 @item ^g^GNAT^
6431 @emph{GNAT style mode.}
6432 The set of style check switches is set to match that used by the GNAT sources.
6433 This may be useful when developing code that is eventually intended to be
6434 incorporated into GNAT. For further details, see GNAT sources.
6435
6436 @item ^h^HTABS^
6437 @emph{No horizontal tabs.}
6438 Horizontal tab characters are not permitted in the source text.
6439 Together with the b (no blanks at end of line) check, this
6440 enforces a canonical form for the use of blanks to separate
6441 source tokens.
6442
6443 @item ^i^IF_THEN^
6444 @emph{Check if-then layout.}
6445 The keyword @code{then} must appear either on the same
6446 line as corresponding @code{if}, or on a line on its own, lined
6447 up under the @code{if} with at least one non-blank line in between
6448 containing all or part of the condition to be tested.
6449
6450 @item ^I^IN_MODE^
6451 @emph{check mode IN keywords.}
6452 Mode @code{in} (the default mode) is not
6453 allowed to be given explicitly. @code{in out} is fine,
6454 but not @code{in} on its own.
6455
6456 @item ^k^KEYWORD^
6457 @emph{Check keyword casing.}
6458 All keywords must be in lower case (with the exception of keywords
6459 such as @code{digits} used as attribute names to which this check
6460 does not apply).
6461
6462 @item ^l^LAYOUT^
6463 @emph{Check layout.}
6464 Layout of statement and declaration constructs must follow the
6465 recommendations in the Ada Reference Manual, as indicated by the
6466 form of the syntax rules. For example an @code{else} keyword must
6467 be lined up with the corresponding @code{if} keyword.
6468
6469 There are two respects in which the style rule enforced by this check
6470 option are more liberal than those in the Ada Reference Manual. First
6471 in the case of record declarations, it is permissible to put the
6472 @code{record} keyword on the same line as the @code{type} keyword, and
6473 then the @code{end} in @code{end record} must line up under @code{type}.
6474 This is also permitted when the type declaration is split on two lines.
6475 For example, any of the following three layouts is acceptable:
6476
6477 @smallexample @c ada
6478 @cartouche
6479 type q is record
6480    a : integer;
6481    b : integer;
6482 end record;
6483
6484 type q is
6485    record
6486       a : integer;
6487       b : integer;
6488    end record;
6489
6490 type q is
6491    record
6492       a : integer;
6493       b : integer;
6494 end record;
6495
6496 @end cartouche
6497 @end smallexample
6498
6499 @noindent
6500 Second, in the case of a block statement, a permitted alternative
6501 is to put the block label on the same line as the @code{declare} or
6502 @code{begin} keyword, and then line the @code{end} keyword up under
6503 the block label. For example both the following are permitted:
6504
6505 @smallexample @c ada
6506 @cartouche
6507 Block : declare
6508    A : Integer := 3;
6509 begin
6510    Proc (A, A);
6511 end Block;
6512
6513 Block :
6514    declare
6515       A : Integer := 3;
6516    begin
6517       Proc (A, A);
6518    end Block;
6519 @end cartouche
6520 @end smallexample
6521
6522 @noindent
6523 The same alternative format is allowed for loops. For example, both of
6524 the following are permitted:
6525
6526 @smallexample @c ada
6527 @cartouche
6528 Clear : while J < 10 loop
6529    A (J) := 0;
6530 end loop Clear;
6531
6532 Clear :
6533    while J < 10 loop
6534       A (J) := 0;
6535    end loop Clear;
6536 @end cartouche
6537 @end smallexample
6538
6539 @item ^Lnnn^MAX_NESTING=nnn^
6540 @emph{Set maximum nesting level.}
6541 The maximum level of nesting of constructs (including subprograms, loops,
6542 blocks, packages, and conditionals) may not exceed the given value
6543 @option{nnn}. A value of zero disconnects this style check.
6544
6545 @item ^m^LINE_LENGTH^
6546 @emph{Check maximum line length.}
6547 The length of source lines must not exceed 79 characters, including
6548 any trailing blanks. The value of 79 allows convenient display on an
6549 80 character wide device or window, allowing for possible special
6550 treatment of 80 character lines. Note that this count is of
6551 characters in the source text. This means that a tab character counts
6552 as one character in this count but a wide character sequence counts as
6553 a single character (however many bytes are needed in the encoding).
6554
6555 @item ^Mnnn^MAX_LENGTH=nnn^
6556 @emph{Set maximum line length.}
6557 The length of lines must not exceed the
6558 given value @option{nnn}. The maximum value that can be specified is 32767.
6559
6560 @item ^n^STANDARD_CASING^
6561 @emph{Check casing of entities in Standard.}
6562 Any identifier from Standard must be cased
6563 to match the presentation in the Ada Reference Manual (for example,
6564 @code{Integer} and @code{ASCII.NUL}).
6565
6566 @item ^N^NONE^
6567 @emph{Turn off all style checks.}
6568 All style check options are turned off.
6569
6570 @item ^o^ORDERED_SUBPROGRAMS^
6571 @emph{Check order of subprogram bodies.}
6572 All subprogram bodies in a given scope
6573 (e.g.@: a package body) must be in alphabetical order. The ordering
6574 rule uses normal Ada rules for comparing strings, ignoring casing
6575 of letters, except that if there is a trailing numeric suffix, then
6576 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6577 before Junk10).
6578
6579 @item ^O^OVERRIDING_INDICATORS^
6580 @emph{Check that overriding subprograms are explicitly marked as such.}
6581 The declaration of a primitive operation of a type extension that overrides
6582 an inherited operation must carry an overriding indicator.
6583
6584 @item ^p^PRAGMA^
6585 @emph{Check pragma casing.}
6586 Pragma names must be written in mixed case, that is, the
6587 initial letter and any letter following an underscore must be uppercase.
6588 All other letters must be lowercase.
6589
6590 @item ^r^REFERENCES^
6591 @emph{Check references.}
6592 All identifier references must be cased in the same way as the
6593 corresponding declaration. No specific casing style is imposed on
6594 identifiers. The only requirement is for consistency of references
6595 with declarations.
6596
6597 @item ^s^SPECS^
6598 @emph{Check separate specs.}
6599 Separate declarations (``specs'') are required for subprograms (a
6600 body is not allowed to serve as its own declaration). The only
6601 exception is that parameterless library level procedures are
6602 not required to have a separate declaration. This exception covers
6603 the most frequent form of main program procedures.
6604
6605 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6606 @emph{Check no statements after @code{then}/@code{else}.}
6607 No statements are allowed
6608 on the same line as a @code{then} or @code{else} keyword following the
6609 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6610 affected, and a special exception allows a pragma to appear after @code{else}.
6611
6612 @item ^t^TOKEN^
6613 @emph{Check token spacing.}
6614 The following token spacing rules are enforced:
6615
6616 @itemize @bullet
6617
6618 @item
6619 The keywords @code{abs} and @code{not} must be followed by a space.
6620
6621 @item
6622 The token @code{=>} must be surrounded by spaces.
6623
6624 @item
6625 The token @code{<>} must be preceded by a space or a left parenthesis.
6626
6627 @item
6628 Binary operators other than @code{**} must be surrounded by spaces.
6629 There is no restriction on the layout of the @code{**} binary operator.
6630
6631 @item
6632 Colon must be surrounded by spaces.
6633
6634 @item
6635 Colon-equal (assignment, initialization) must be surrounded by spaces.
6636
6637 @item
6638 Comma must be the first non-blank character on the line, or be
6639 immediately preceded by a non-blank character, and must be followed
6640 by a space.
6641
6642 @item
6643 If the token preceding a left parenthesis ends with a letter or digit, then
6644 a space must separate the two tokens.
6645
6646 @item
6647 if the token following a right parenthesis starts with a letter or digit, then
6648 a space must separate the two tokens.
6649
6650 @item
6651 A right parenthesis must either be the first non-blank character on
6652 a line, or it must be preceded by a non-blank character.
6653
6654 @item
6655 A semicolon must not be preceded by a space, and must not be followed by
6656 a non-blank character.
6657
6658 @item
6659 A unary plus or minus may not be followed by a space.
6660
6661 @item
6662 A vertical bar must be surrounded by spaces.
6663 @end itemize
6664
6665 @item ^u^UNNECESSARY_BLANK_LINES^
6666 @emph{Check unnecessary blank lines.}
6667 Unnecessary blank lines are not allowed. A blank line is considered
6668 unnecessary if it appears at the end of the file, or if more than
6669 one blank line occurs in sequence.
6670
6671 @item ^x^XTRA_PARENS^
6672 @emph{Check extra parentheses.}
6673 Unnecessary extra level of parentheses (C-style) are not allowed
6674 around conditions in @code{if} statements, @code{while} statements and
6675 @code{exit} statements.
6676
6677 @item ^y^ALL_BUILTIN^
6678 @emph{Set all standard style check options}
6679 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6680 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6681 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6682 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6683
6684 @ifclear vms
6685 @item -
6686 @emph{Remove style check options}
6687 This causes any subsequent options in the string to act as canceling the
6688 corresponding style check option. To cancel maximum nesting level control,
6689 use @option{L} parameter witout any integer value after that, because any
6690 digit following @option{-} in the parameter string of the @option{-gnaty}
6691 option will be threated as canceling indentation check. The same is true
6692 for @option{M} parameter. @option{y} and @option{N} parameters are not
6693 allowed after @option{-}.
6694
6695 @item +
6696 This causes any subsequent options in the string to enable the corresponding
6697 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6698 if any.
6699 @end ifclear
6700
6701 @ifset vms
6702 @item NOxxx
6703 @emph{Removing style check options}
6704 If the name of a style check is preceded by @option{NO} then the corresponding
6705 style check is turned off. For example @option{NOCOMMENTS} turns off style
6706 checking for comments.
6707 @end ifset
6708 @end table
6709
6710 @noindent
6711 In the above rules, appearing in column one is always permitted, that is,
6712 counts as meeting either a requirement for a required preceding space,
6713 or as meeting a requirement for no preceding space.
6714
6715 Appearing at the end of a line is also always permitted, that is, counts
6716 as meeting either a requirement for a following space, or as meeting
6717 a requirement for no following space.
6718
6719 @noindent
6720 If any of these style rules is violated, a message is generated giving
6721 details on the violation. The initial characters of such messages are
6722 always ``@code{(style)}''. Note that these messages are treated as warning
6723 messages, so they normally do not prevent the generation of an object
6724 file. The @option{-gnatwe} switch can be used to treat warning messages,
6725 including style messages, as fatal errors.
6726
6727 The switch
6728 @ifclear vms
6729 @option{-gnaty} on its own (that is not
6730 followed by any letters or digits) is equivalent
6731 to the use of @option{-gnatyy} as described above, that is all
6732 built-in standard style check options are enabled.
6733
6734 @end ifclear
6735 @ifset vms
6736 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6737 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6738 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6739 @end ifset
6740
6741 The switch
6742 @ifclear vms
6743 @option{-gnatyN}
6744 @end ifclear
6745 @ifset vms
6746 /STYLE_CHECKS=NONE
6747 @end ifset
6748 clears any previously set style checks.
6749
6750 @node Run-Time Checks
6751 @subsection Run-Time Checks
6752 @cindex Division by zero
6753 @cindex Access before elaboration
6754 @cindex Checks, division by zero
6755 @cindex Checks, access before elaboration
6756 @cindex Checks, stack overflow checking
6757
6758 @noindent
6759 By default, the following checks are suppressed: integer overflow
6760 checks, stack overflow checks, and checks for access before
6761 elaboration on subprogram calls. All other checks, including range
6762 checks and array bounds checks, are turned on by default. The
6763 following @command{gcc} switches refine this default behavior.
6764
6765 @table @option
6766 @c !sort!
6767 @item -gnatp
6768 @cindex @option{-gnatp} (@command{gcc})
6769 @cindex Suppressing checks
6770 @cindex Checks, suppressing
6771 @findex Suppress
6772 This switch causes the unit to be compiled
6773 as though @code{pragma Suppress (All_checks)}
6774 had been present in the source. Validity checks are also eliminated (in
6775 other words @option{-gnatp} also implies @option{-gnatVn}.
6776 Use this switch to improve the performance
6777 of the code at the expense of safety in the presence of invalid data or
6778 program bugs.
6779
6780 Note that when checks are suppressed, the compiler is allowed, but not
6781 required, to omit the checking code. If the run-time cost of the
6782 checking code is zero or near-zero, the compiler will generate it even
6783 if checks are suppressed. In particular, if the compiler can prove
6784 that a certain check will necessarily fail, it will generate code to
6785 do an unconditional ``raise'', even if checks are suppressed. The
6786 compiler warns in this case. Another case in which checks may not be
6787 eliminated is when they are embedded in certain run time routines such
6788 as math library routines.
6789
6790 Of course, run-time checks are omitted whenever the compiler can prove
6791 that they will not fail, whether or not checks are suppressed.
6792
6793 Note that if you suppress a check that would have failed, program
6794 execution is erroneous, which means the behavior is totally
6795 unpredictable. The program might crash, or print wrong answers, or
6796 do anything else. It might even do exactly what you wanted it to do
6797 (and then it might start failing mysteriously next week or next
6798 year). The compiler will generate code based on the assumption that
6799 the condition being checked is true, which can result in disaster if
6800 that assumption is wrong.
6801
6802 The @option{-gnatp} switch has no effect if a subsequent
6803 @option{-gnat-p} switch appears.
6804
6805 @item -gnat-p
6806 @cindex @option{-gnat-p} (@command{gcc})
6807 @cindex Suppressing checks
6808 @cindex Checks, suppressing
6809 @findex Suppress
6810 This switch cancels the effect of a previous @option{gnatp} switch.
6811
6812 @item -gnato
6813 @cindex @option{-gnato} (@command{gcc})
6814 @cindex Overflow checks
6815 @cindex Check, overflow
6816 Enables overflow checking for integer operations.
6817 This causes GNAT to generate slower and larger executable
6818 programs by adding code to check for overflow (resulting in raising
6819 @code{Constraint_Error} as required by standard Ada
6820 semantics). These overflow checks correspond to situations in which
6821 the true value of the result of an operation may be outside the base
6822 range of the result type. The following example shows the distinction:
6823
6824 @smallexample @c ada
6825 X1 : Integer := "Integer'Last";
6826 X2 : Integer range 1 .. 5 := "5";
6827 X3 : Integer := "Integer'Last";
6828 X4 : Integer range 1 .. 5 := "5";
6829 F  : Float := "2.0E+20";
6830 @dots{}
6831 X1 := X1 + 1;
6832 X2 := X2 + 1;
6833 X3 := Integer (F);
6834 X4 := Integer (F);
6835 @end smallexample
6836
6837 @noindent
6838 Note that if explicit values are assigned at compile time, the
6839 compiler may be able to detect overflow at compile time, in which case
6840 no actual run-time checking code is required, and Constraint_Error
6841 will be raised unconditionally, with or without
6842 @option{-gnato}. That's why the assigned values in the above fragment
6843 are in quotes, the meaning is "assign a value not known to the
6844 compiler that happens to be equal to ...". The remaining discussion
6845 assumes that the compiler cannot detect the values at compile time.
6846
6847 Here the first addition results in a value that is outside the base range
6848 of Integer, and hence requires an overflow check for detection of the
6849 constraint error. Thus the first assignment to @code{X1} raises a
6850 @code{Constraint_Error} exception only if @option{-gnato} is set.
6851
6852 The second increment operation results in a violation of the explicit
6853 range constraint; such range checks are performed by default, and are
6854 unaffected by @option{-gnato}.
6855
6856 The two conversions of @code{F} both result in values that are outside
6857 the base range of type @code{Integer} and thus will raise
6858 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6859 The fact that the result of the second conversion is assigned to
6860 variable @code{X4} with a restricted range is irrelevant, since the problem
6861 is in the conversion, not the assignment.
6862
6863 Basically the rule is that in the default mode (@option{-gnato} not
6864 used), the generated code assures that all integer variables stay
6865 within their declared ranges, or within the base range if there is
6866 no declared range. This prevents any serious problems like indexes
6867 out of range for array operations.
6868
6869 What is not checked in default mode is an overflow that results in
6870 an in-range, but incorrect value. In the above example, the assignments
6871 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6872 range of the target variable, but the result is wrong in the sense that
6873 it is too large to be represented correctly. Typically the assignment
6874 to @code{X1} will result in wrap around to the largest negative number.
6875 The conversions of @code{F} will result in some @code{Integer} value
6876 and if that integer value is out of the @code{X4} range then the
6877 subsequent assignment would generate an exception.
6878
6879 @findex Machine_Overflows
6880 Note that the @option{-gnato} switch does not affect the code generated
6881 for any floating-point operations; it applies only to integer
6882 semantics).
6883 For floating-point, GNAT has the @code{Machine_Overflows}
6884 attribute set to @code{False} and the normal mode of operation is to
6885 generate IEEE NaN and infinite values on overflow or invalid operations
6886 (such as dividing 0.0 by 0.0).
6887
6888 The reason that we distinguish overflow checking from other kinds of
6889 range constraint checking is that a failure of an overflow check, unlike
6890 for example the failure of a range check, can result in an incorrect
6891 value, but cannot cause random memory destruction (like an out of range
6892 subscript), or a wild jump (from an out of range case value). Overflow
6893 checking is also quite expensive in time and space, since in general it
6894 requires the use of double length arithmetic.
6895
6896 Note again that @option{-gnato} is off by default, so overflow checking is
6897 not performed in default mode. This means that out of the box, with the
6898 default settings, GNAT does not do all the checks expected from the
6899 language description in the Ada Reference Manual. If you want all constraint
6900 checks to be performed, as described in this Manual, then you must
6901 explicitly use the -gnato switch either on the @command{gnatmake} or
6902 @command{gcc} command.
6903
6904 @item -gnatE
6905 @cindex @option{-gnatE} (@command{gcc})
6906 @cindex Elaboration checks
6907 @cindex Check, elaboration
6908 Enables dynamic checks for access-before-elaboration
6909 on subprogram calls and generic instantiations.
6910 Note that @option{-gnatE} is not necessary for safety, because in the
6911 default mode, GNAT ensures statically that the checks would not fail.
6912 For full details of the effect and use of this switch,
6913 @xref{Compiling Using gcc}.
6914
6915 @item -fstack-check
6916 @cindex @option{-fstack-check} (@command{gcc})
6917 @cindex Stack Overflow Checking
6918 @cindex Checks, stack overflow checking
6919 Activates stack overflow checking. For full details of the effect and use of
6920 this switch see @ref{Stack Overflow Checking}.
6921 @end table
6922
6923 @findex Unsuppress
6924 @noindent
6925 The setting of these switches only controls the default setting of the
6926 checks. You may modify them using either @code{Suppress} (to remove
6927 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6928 the program source.
6929
6930 @node Using gcc for Syntax Checking
6931 @subsection Using @command{gcc} for Syntax Checking
6932 @table @option
6933 @item -gnats
6934 @cindex @option{-gnats} (@command{gcc})
6935 @ifclear vms
6936
6937 @noindent
6938 The @code{s} stands for ``syntax''.
6939 @end ifclear
6940
6941 Run GNAT in syntax checking only mode. For
6942 example, the command
6943
6944 @smallexample
6945 $ gcc -c -gnats x.adb
6946 @end smallexample
6947
6948 @noindent
6949 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6950 series of files in a single command
6951 @ifclear vms
6952 , and can use wild cards to specify such a group of files.
6953 Note that you must specify the @option{-c} (compile
6954 only) flag in addition to the @option{-gnats} flag.
6955 @end ifclear
6956 .
6957 You may use other switches in conjunction with @option{-gnats}. In
6958 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6959 format of any generated error messages.
6960
6961 When the source file is empty or contains only empty lines and/or comments,
6962 the output is a warning:
6963
6964 @smallexample
6965 $ gcc -c -gnats -x ada toto.txt
6966 toto.txt:1:01: warning: empty file, contains no compilation units
6967 $
6968 @end smallexample
6969
6970 Otherwise, the output is simply the error messages, if any. No object file or
6971 ALI file is generated by a syntax-only compilation. Also, no units other
6972 than the one specified are accessed. For example, if a unit @code{X}
6973 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6974 check only mode does not access the source file containing unit
6975 @code{Y}.
6976
6977 @cindex Multiple units, syntax checking
6978 Normally, GNAT allows only a single unit in a source file. However, this
6979 restriction does not apply in syntax-check-only mode, and it is possible
6980 to check a file containing multiple compilation units concatenated
6981 together. This is primarily used by the @code{gnatchop} utility
6982 (@pxref{Renaming Files Using gnatchop}).
6983 @end table
6984
6985 @node Using gcc for Semantic Checking
6986 @subsection Using @command{gcc} for Semantic Checking
6987 @table @option
6988 @item -gnatc
6989 @cindex @option{-gnatc} (@command{gcc})
6990
6991 @ifclear vms
6992 @noindent
6993 The @code{c} stands for ``check''.
6994 @end ifclear
6995 Causes the compiler to operate in semantic check mode,
6996 with full checking for all illegalities specified in the
6997 Ada Reference Manual, but without generation of any object code
6998 (no object file is generated).
6999
7000 Because dependent files must be accessed, you must follow the GNAT
7001 semantic restrictions on file structuring to operate in this mode:
7002
7003 @itemize @bullet
7004 @item
7005 The needed source files must be accessible
7006 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7007
7008 @item
7009 Each file must contain only one compilation unit.
7010
7011 @item
7012 The file name and unit name must match (@pxref{File Naming Rules}).
7013 @end itemize
7014
7015 The output consists of error messages as appropriate. No object file is
7016 generated. An @file{ALI} file is generated for use in the context of
7017 cross-reference tools, but this file is marked as not being suitable
7018 for binding (since no object file is generated).
7019 The checking corresponds exactly to the notion of
7020 legality in the Ada Reference Manual.
7021
7022 Any unit can be compiled in semantics-checking-only mode, including
7023 units that would not normally be compiled (subunits,
7024 and specifications where a separate body is present).
7025 @end table
7026
7027 @node Compiling Different Versions of Ada
7028 @subsection Compiling Different Versions of Ada
7029
7030 @noindent
7031 The switches described in this section allow you to explicitly specify
7032 the version of the Ada language that your programs are written in.
7033 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7034 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7035 indicate Ada 83 compatibility mode.
7036
7037 @table @option
7038 @cindex Compatibility with Ada 83
7039
7040 @item -gnat83 (Ada 83 Compatibility Mode)
7041 @cindex @option{-gnat83} (@command{gcc})
7042 @cindex ACVC, Ada 83 tests
7043 @cindex Ada 83 mode
7044
7045 @noindent
7046 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7047 specifies that the program is to be compiled in Ada 83 mode. With
7048 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7049 semantics where this can be done easily.
7050 It is not possible to guarantee this switch does a perfect
7051 job; some subtle tests, such as are
7052 found in earlier ACVC tests (and that have been removed from the ACATS suite
7053 for Ada 95), might not compile correctly.
7054 Nevertheless, this switch may be useful in some circumstances, for example
7055 where, due to contractual reasons, existing code needs to be maintained
7056 using only Ada 83 features.
7057
7058 With few exceptions (most notably the need to use @code{<>} on
7059 @cindex Generic formal parameters
7060 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7061 reserved words, and the use of packages
7062 with optional bodies), it is not necessary to specify the
7063 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7064 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7065 a correct Ada 83 program is usually also a correct program
7066 in these later versions of the language standard.
7067 For further information, please refer to @ref{Compatibility and Porting Guide}.
7068
7069 @item -gnat95 (Ada 95 mode)
7070 @cindex @option{-gnat95} (@command{gcc})
7071 @cindex Ada 95 mode
7072
7073 @noindent
7074 This switch directs the compiler to implement the Ada 95 version of the
7075 language.
7076 Since Ada 95 is almost completely upwards
7077 compatible with Ada 83, Ada 83 programs may generally be compiled using
7078 this switch (see the description of the @option{-gnat83} switch for further
7079 information about Ada 83 mode).
7080 If an Ada 2005 program is compiled in Ada 95 mode,
7081 uses of the new Ada 2005 features will cause error
7082 messages or warnings.
7083
7084 This switch also can be used to cancel the effect of a previous
7085 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7086 switch earlier in the command line.
7087
7088 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7089 @cindex @option{-gnat05} (@command{gcc})
7090 @cindex @option{-gnat2005} (@command{gcc})
7091 @cindex Ada 2005 mode
7092
7093 @noindent
7094 This switch directs the compiler to implement the Ada 2005 version of the
7095 language, as documented in the official Ada standards document.
7096 Since Ada 2005 is almost completely upwards
7097 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7098 may generally be compiled using this switch (see the description of the
7099 @option{-gnat83} and @option{-gnat95} switches for further
7100 information).
7101
7102 @ifset PROEDITION
7103 Note that even though Ada 2005 is the current official version of the
7104 language, GNAT still compiles in Ada 95 mode by default, so if you are
7105 using Ada 2005 features in your program, you must use this switch (or
7106 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7107 @end ifset
7108
7109 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7110 @cindex @option{-gnat12} (@command{gcc})
7111 @cindex @option{-gnat2012} (@command{gcc})
7112 @cindex Ada 2012 mode
7113
7114 @noindent
7115 This switch directs the compiler to implement the Ada 2012 version of the
7116 language.
7117 Since Ada 2012 is almost completely upwards
7118 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7119 Ada 83 and Ada 95 programs
7120 may generally be compiled using this switch (see the description of the
7121 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7122 for further information).
7123
7124 For information about the approved ``Ada Issues'' that have been incorporated
7125 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7126 Included with GNAT releases is a file @file{features-ada12} that describes
7127 the set of implemented Ada 2012 features.
7128
7129 @item -gnatX (Enable GNAT Extensions)
7130 @cindex @option{-gnatX} (@command{gcc})
7131 @cindex Ada language extensions
7132 @cindex GNAT extensions
7133
7134 @noindent
7135 This switch directs the compiler to implement the latest version of the
7136 language (currently Ada 2012) and also to enable certain GNAT implementation
7137 extensions that are not part of any Ada standard. For a full list of these
7138 extensions, see the GNAT reference manual.
7139
7140 @end table
7141
7142 @node Character Set Control
7143 @subsection Character Set Control
7144 @table @option
7145 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7146 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7147
7148 @noindent
7149 Normally GNAT recognizes the Latin-1 character set in source program
7150 identifiers, as described in the Ada Reference Manual.
7151 This switch causes
7152 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7153 single character ^^or word^ indicating the character set, as follows:
7154
7155 @table @code
7156 @item 1
7157 ISO 8859-1 (Latin-1) identifiers
7158
7159 @item 2
7160 ISO 8859-2 (Latin-2) letters allowed in identifiers
7161
7162 @item 3
7163 ISO 8859-3 (Latin-3) letters allowed in identifiers
7164
7165 @item 4
7166 ISO 8859-4 (Latin-4) letters allowed in identifiers
7167
7168 @item 5
7169 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7170
7171 @item 9
7172 ISO 8859-15 (Latin-9) letters allowed in identifiers
7173
7174 @item ^p^PC^
7175 IBM PC letters (code page 437) allowed in identifiers
7176
7177 @item ^8^PC850^
7178 IBM PC letters (code page 850) allowed in identifiers
7179
7180 @item ^f^FULL_UPPER^
7181 Full upper-half codes allowed in identifiers
7182
7183 @item ^n^NO_UPPER^
7184 No upper-half codes allowed in identifiers
7185
7186 @item ^w^WIDE^
7187 Wide-character codes (that is, codes greater than 255)
7188 allowed in identifiers
7189 @end table
7190
7191 @xref{Foreign Language Representation}, for full details on the
7192 implementation of these character sets.
7193
7194 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7195 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7196 Specify the method of encoding for wide characters.
7197 @var{e} is one of the following:
7198
7199 @table @code
7200
7201 @item ^h^HEX^
7202 Hex encoding (brackets coding also recognized)
7203
7204 @item ^u^UPPER^
7205 Upper half encoding (brackets encoding also recognized)
7206
7207 @item ^s^SHIFT_JIS^
7208 Shift/JIS encoding (brackets encoding also recognized)
7209
7210 @item ^e^EUC^
7211 EUC encoding (brackets encoding also recognized)
7212
7213 @item ^8^UTF8^
7214 UTF-8 encoding (brackets encoding also recognized)
7215
7216 @item ^b^BRACKETS^
7217 Brackets encoding only (default value)
7218 @end table
7219 For full details on these encoding
7220 methods see @ref{Wide Character Encodings}.
7221 Note that brackets coding is always accepted, even if one of the other
7222 options is specified, so for example @option{-gnatW8} specifies that both
7223 brackets and UTF-8 encodings will be recognized. The units that are
7224 with'ed directly or indirectly will be scanned using the specified
7225 representation scheme, and so if one of the non-brackets scheme is
7226 used, it must be used consistently throughout the program. However,
7227 since brackets encoding is always recognized, it may be conveniently
7228 used in standard libraries, allowing these libraries to be used with
7229 any of the available coding schemes.
7230
7231 Note that brackets encoding only applies to program text. Within comments,
7232 brackets are considered to be normal graphic characters, and bracket sequences
7233 are never recognized as wide characters.
7234
7235 If no @option{-gnatW?} parameter is present, then the default
7236 representation is normally Brackets encoding only. However, if the
7237 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7238 byte order mark or BOM for UTF-8), then these three characters are
7239 skipped and the default representation for the file is set to UTF-8.
7240
7241 Note that the wide character representation that is specified (explicitly
7242 or by default) for the main program also acts as the default encoding used
7243 for Wide_Text_IO files if not specifically overridden by a WCEM form
7244 parameter.
7245
7246 @end table
7247
7248 When no @option{-gnatW?} is specified, then characters (other than wide
7249 characters represented using brackets notation) are treated as 8-bit
7250 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7251 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7252 characters in the range 16#00#..16#1F# are not accepted in program text
7253 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7254 in program text, but allowed and ignored in comments. Note in particular
7255 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7256 as an end of line in this default mode. If your source program contains
7257 instances of the NEL character used as a line terminator,
7258 you must use UTF-8 encoding for the whole
7259 source program. In default mode, all lines must be ended by a standard
7260 end of line sequence (CR, CR/LF, or LF).
7261
7262 Note that the convention of simply accepting all upper half characters in
7263 comments means that programs that use standard ASCII for program text, but
7264 UTF-8 encoding for comments are accepted in default mode, providing that the
7265 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7266 This is a common mode for many programs with foreign language comments.
7267
7268 @node File Naming Control
7269 @subsection File Naming Control
7270
7271 @table @option
7272 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7273 @cindex @option{-gnatk} (@command{gcc})
7274 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7275 1-999, indicates the maximum allowable length of a file name (not
7276 including the @file{.ads} or @file{.adb} extension). The default is not
7277 to enable file name krunching.
7278
7279 For the source file naming rules, @xref{File Naming Rules}.
7280 @end table
7281
7282 @node Subprogram Inlining Control
7283 @subsection Subprogram Inlining Control
7284
7285 @table @option
7286 @c !sort!
7287 @item -gnatn
7288 @cindex @option{-gnatn} (@command{gcc})
7289 @ifclear vms
7290 The @code{n} here is intended to suggest the first syllable of the
7291 word ``inline''.
7292 @end ifclear
7293 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7294 inlining to actually occur, optimization must be enabled. To enable
7295 inlining of subprograms specified by pragma @code{Inline},
7296 you must also specify this switch.
7297 In the absence of this switch, GNAT does not attempt
7298 inlining and does not need to access the bodies of
7299 subprograms for which @code{pragma Inline} is specified if they are not
7300 in the current unit.
7301
7302 If you specify this switch the compiler will access these bodies,
7303 creating an extra source dependency for the resulting object file, and
7304 where possible, the call will be inlined.
7305 For further details on when inlining is possible
7306 see @ref{Inlining of Subprograms}.
7307
7308 @item -gnatN
7309 @cindex @option{-gnatN} (@command{gcc})
7310 This switch activates front-end inlining which also
7311 generates additional dependencies.
7312
7313 When using a gcc-based back end (in practice this means using any version
7314 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7315 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7316 Historically front end inlining was more extensive than the gcc back end
7317 inlining, but that is no longer the case.
7318 @end table
7319
7320 @node Auxiliary Output Control
7321 @subsection Auxiliary Output Control
7322
7323 @table @option
7324 @item -gnatt
7325 @cindex @option{-gnatt} (@command{gcc})
7326 @cindex Writing internal trees
7327 @cindex Internal trees, writing to file
7328 Causes GNAT to write the internal tree for a unit to a file (with the
7329 extension @file{.adt}.
7330 This not normally required, but is used by separate analysis tools.
7331 Typically
7332 these tools do the necessary compilations automatically, so you should
7333 not have to specify this switch in normal operation.
7334 Note that the combination of switches @option{-gnatct}
7335 generates a tree in the form required by ASIS applications.
7336
7337 @item -gnatu
7338 @cindex @option{-gnatu} (@command{gcc})
7339 Print a list of units required by this compilation on @file{stdout}.
7340 The listing includes all units on which the unit being compiled depends
7341 either directly or indirectly.
7342
7343 @ifclear vms
7344 @item -pass-exit-codes
7345 @cindex @option{-pass-exit-codes} (@command{gcc})
7346 If this switch is not used, the exit code returned by @command{gcc} when
7347 compiling multiple files indicates whether all source files have
7348 been successfully used to generate object files or not.
7349
7350 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7351 exit status and allows an integrated development environment to better
7352 react to a compilation failure. Those exit status are:
7353
7354 @table @asis
7355 @item 5
7356 There was an error in at least one source file.
7357 @item 3
7358 At least one source file did not generate an object file.
7359 @item 2
7360 The compiler died unexpectedly (internal error for example).
7361 @item 0
7362 An object file has been generated for every source file.
7363 @end table
7364 @end ifclear
7365 @end table
7366
7367 @node Debugging Control
7368 @subsection Debugging Control
7369
7370 @table @option
7371 @c !sort!
7372 @cindex Debugging options
7373 @ifclear vms
7374 @item -gnatd@var{x}
7375 @cindex @option{-gnatd} (@command{gcc})
7376 Activate internal debugging switches. @var{x} is a letter or digit, or
7377 string of letters or digits, which specifies the type of debugging
7378 outputs desired. Normally these are used only for internal development
7379 or system debugging purposes. You can find full documentation for these
7380 switches in the body of the @code{Debug} unit in the compiler source
7381 file @file{debug.adb}.
7382 @end ifclear
7383
7384 @item -gnatG[=nn]
7385 @cindex @option{-gnatG} (@command{gcc})
7386 This switch causes the compiler to generate auxiliary output containing
7387 a pseudo-source listing of the generated expanded code. Like most Ada
7388 compilers, GNAT works by first transforming the high level Ada code into
7389 lower level constructs. For example, tasking operations are transformed
7390 into calls to the tasking run-time routines. A unique capability of GNAT
7391 is to list this expanded code in a form very close to normal Ada source.
7392 This is very useful in understanding the implications of various Ada
7393 usage on the efficiency of the generated code. There are many cases in
7394 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7395 generate a lot of run-time code. By using @option{-gnatG} you can identify
7396 these cases, and consider whether it may be desirable to modify the coding
7397 approach to improve efficiency.
7398
7399 The optional parameter @code{nn} if present after -gnatG specifies an
7400 alternative maximum line length that overrides the normal default of 72.
7401 This value is in the range 40-999999, values less than 40 being silently
7402 reset to 40. The equal sign is optional.
7403
7404 The format of the output is very similar to standard Ada source, and is
7405 easily understood by an Ada programmer. The following special syntactic
7406 additions correspond to low level features used in the generated code that
7407 do not have any exact analogies in pure Ada source form. The following
7408 is a partial list of these special constructions. See the spec
7409 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7410
7411 If the switch @option{-gnatL} is used in conjunction with
7412 @cindex @option{-gnatL} (@command{gcc})
7413 @option{-gnatG}, then the original source lines are interspersed
7414 in the expanded source (as comment lines with the original line number).
7415
7416 @table @code
7417 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7418 Shows the storage pool being used for an allocator.
7419
7420 @item at end @var{procedure-name};
7421 Shows the finalization (cleanup) procedure for a scope.
7422
7423 @item (if @var{expr} then @var{expr} else @var{expr})
7424 Conditional expression equivalent to the @code{x?y:z} construction in C.
7425
7426 @item @var{target}^^^(@var{source})
7427 A conversion with floating-point truncation instead of rounding.
7428
7429 @item @var{target}?(@var{source})
7430 A conversion that bypasses normal Ada semantic checking. In particular
7431 enumeration types and fixed-point types are treated simply as integers.
7432
7433 @item @var{target}?^^^(@var{source})
7434 Combines the above two cases.
7435
7436 @item @var{x} #/ @var{y}
7437 @itemx @var{x} #mod @var{y}
7438 @itemx @var{x} #* @var{y}
7439 @itemx @var{x} #rem @var{y}
7440 A division or multiplication of fixed-point values which are treated as
7441 integers without any kind of scaling.
7442
7443 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7444 Shows the storage pool associated with a @code{free} statement.
7445
7446 @item [subtype or type declaration]
7447 Used to list an equivalent declaration for an internally generated
7448 type that is referenced elsewhere in the listing.
7449
7450 @c @item freeze @var{type-name} @ovar{actions}
7451 @c Expanding @ovar macro inline (explanation in macro def comments)
7452 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7453 Shows the point at which @var{type-name} is frozen, with possible
7454 associated actions to be performed at the freeze point.
7455
7456 @item reference @var{itype}
7457 Reference (and hence definition) to internal type @var{itype}.
7458
7459 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7460 Intrinsic function call.
7461
7462 @item @var{label-name} : label
7463 Declaration of label @var{labelname}.
7464
7465 @item #$ @var{subprogram-name}
7466 An implicit call to a run-time support routine
7467 (to meet the requirement of H.3.1(9) in a
7468 convenient manner).
7469
7470 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7471 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7472 @var{expr}, but handled more efficiently).
7473
7474 @item [constraint_error]
7475 Raise the @code{Constraint_Error} exception.
7476
7477 @item @var{expression}'reference
7478 A pointer to the result of evaluating @var{expression}.
7479
7480 @item @var{target-type}!(@var{source-expression})
7481 An unchecked conversion of @var{source-expression} to @var{target-type}.
7482
7483 @item [@var{numerator}/@var{denominator}]
7484 Used to represent internal real literals (that) have no exact
7485 representation in base 2-16 (for example, the result of compile time
7486 evaluation of the expression 1.0/27.0).
7487 @end table
7488
7489 @item -gnatD[=nn]
7490 @cindex @option{-gnatD} (@command{gcc})
7491 When used in conjunction with @option{-gnatG}, this switch causes
7492 the expanded source, as described above for
7493 @option{-gnatG} to be written to files with names
7494 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7495 instead of to the standard output file. For
7496 example, if the source file name is @file{hello.adb}, then a file
7497 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7498 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7499 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7500 you to do source level debugging using the generated code which is
7501 sometimes useful for complex code, for example to find out exactly
7502 which part of a complex construction raised an exception. This switch
7503 also suppress generation of cross-reference information (see
7504 @option{-gnatx}) since otherwise the cross-reference information
7505 would refer to the @file{^.dg^.DG^} file, which would cause
7506 confusion since this is not the original source file.
7507
7508 Note that @option{-gnatD} actually implies @option{-gnatG}
7509 automatically, so it is not necessary to give both options.
7510 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7511
7512 If the switch @option{-gnatL} is used in conjunction with
7513 @cindex @option{-gnatL} (@command{gcc})
7514 @option{-gnatDG}, then the original source lines are interspersed
7515 in the expanded source (as comment lines with the original line number).
7516
7517 The optional parameter @code{nn} if present after -gnatD specifies an
7518 alternative maximum line length that overrides the normal default of 72.
7519 This value is in the range 40-999999, values less than 40 being silently
7520 reset to 40. The equal sign is optional.
7521
7522 @item -gnatr
7523 @cindex @option{-gnatr} (@command{gcc})
7524 @cindex pragma Restrictions
7525 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7526 so that violation of restrictions causes warnings rather than illegalities.
7527 This is useful during the development process when new restrictions are added
7528 or investigated. The switch also causes pragma Profile to be treated as
7529 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7530 restriction warnings rather than restrictions.
7531
7532 @ifclear vms
7533 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7534 @cindex @option{-gnatR} (@command{gcc})
7535 This switch controls output from the compiler of a listing showing
7536 representation information for declared types and objects. For
7537 @option{-gnatR0}, no information is output (equivalent to omitting
7538 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7539 so @option{-gnatR} with no parameter has the same effect), size and alignment
7540 information is listed for declared array and record types. For
7541 @option{-gnatR2}, size and alignment information is listed for all
7542 declared types and objects. Finally @option{-gnatR3} includes symbolic
7543 expressions for values that are computed at run time for
7544 variant records. These symbolic expressions have a mostly obvious
7545 format with #n being used to represent the value of the n'th
7546 discriminant. See source files @file{repinfo.ads/adb} in the
7547 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7548 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7549 the output is to a file with the name @file{^file.rep^file_REP^} where
7550 file is the name of the corresponding source file.
7551 @end ifclear
7552 @ifset vms
7553 @item /REPRESENTATION_INFO
7554 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7555 This qualifier controls output from the compiler of a listing showing
7556 representation information for declared types and objects. For
7557 @option{/REPRESENTATION_INFO=NONE}, no information is output
7558 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7559 @option{/REPRESENTATION_INFO} without option is equivalent to
7560 @option{/REPRESENTATION_INFO=ARRAYS}.
7561 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7562 information is listed for declared array and record types. For
7563 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7564 is listed for all expression information for values that are computed
7565 at run time for variant records. These symbolic expressions have a mostly
7566 obvious format with #n being used to represent the value of the n'th
7567 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7568 @code{GNAT} sources for full details on the format of
7569 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7570 If _FILE is added at the end of an option
7571 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7572 then the output is to a file with the name @file{file_REP} where
7573 file is the name of the corresponding source file.
7574 @end ifset
7575 Note that it is possible for record components to have zero size. In
7576 this case, the component clause uses an obvious extension of permitted
7577 Ada syntax, for example @code{at 0 range 0 .. -1}.
7578
7579 Representation information requires that code be generated (since it is the
7580 code generator that lays out complex data structures). If an attempt is made
7581 to output representation information when no code is generated, for example
7582 when a subunit is compiled on its own, then no information can be generated
7583 and the compiler outputs a message to this effect.
7584
7585 @item -gnatS
7586 @cindex @option{-gnatS} (@command{gcc})
7587 The use of the switch @option{-gnatS} for an
7588 Ada compilation will cause the compiler to output a
7589 representation of package Standard in a form very
7590 close to standard Ada. It is not quite possible to
7591 do this entirely in standard Ada (since new
7592 numeric base types cannot be created in standard
7593 Ada), but the output is easily
7594 readable to any Ada programmer, and is useful to
7595 determine the characteristics of target dependent
7596 types in package Standard.
7597
7598 @item -gnatx
7599 @cindex @option{-gnatx} (@command{gcc})
7600 Normally the compiler generates full cross-referencing information in
7601 the @file{ALI} file. This information is used by a number of tools,
7602 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7603 suppresses this information. This saves some space and may slightly
7604 speed up compilation, but means that these tools cannot be used.
7605 @end table
7606
7607 @node Exception Handling Control
7608 @subsection Exception Handling Control
7609
7610 @noindent
7611 GNAT uses two methods for handling exceptions at run-time. The
7612 @code{setjmp/longjmp} method saves the context when entering
7613 a frame with an exception handler. Then when an exception is
7614 raised, the context can be restored immediately, without the
7615 need for tracing stack frames. This method provides very fast
7616 exception propagation, but introduces significant overhead for
7617 the use of exception handlers, even if no exception is raised.
7618
7619 The other approach is called ``zero cost'' exception handling.
7620 With this method, the compiler builds static tables to describe
7621 the exception ranges. No dynamic code is required when entering
7622 a frame containing an exception handler. When an exception is
7623 raised, the tables are used to control a back trace of the
7624 subprogram invocation stack to locate the required exception
7625 handler. This method has considerably poorer performance for
7626 the propagation of exceptions, but there is no overhead for
7627 exception handlers if no exception is raised. Note that in this
7628 mode and in the context of mixed Ada and C/C++ programming,
7629 to propagate an exception through a C/C++ code, the C/C++ code
7630 must be compiled with the @option{-funwind-tables} GCC's
7631 option.
7632
7633 The following switches may be used to control which of the
7634 two exception handling methods is used.
7635
7636 @table @option
7637 @c !sort!
7638
7639 @item --RTS=sjlj
7640 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7641 This switch causes the setjmp/longjmp run-time (when available) to be used
7642 for exception handling. If the default
7643 mechanism for the target is zero cost exceptions, then
7644 this switch can be used to modify this default, and must be
7645 used for all units in the partition.
7646 This option is rarely used. One case in which it may be
7647 advantageous is if you have an application where exception
7648 raising is common and the overall performance of the
7649 application is improved by favoring exception propagation.
7650
7651 @item --RTS=zcx
7652 @cindex @option{--RTS=zcx} (@command{gnatmake})
7653 @cindex Zero Cost Exceptions
7654 This switch causes the zero cost approach to be used
7655 for exception handling. If this is the default mechanism for the
7656 target (see below), then this switch is unneeded. If the default
7657 mechanism for the target is setjmp/longjmp exceptions, then
7658 this switch can be used to modify this default, and must be
7659 used for all units in the partition.
7660 This option can only be used if the zero cost approach
7661 is available for the target in use, otherwise it will generate an error.
7662 @end table
7663
7664 @noindent
7665 The same option @option{--RTS} must be used both for @command{gcc}
7666 and @command{gnatbind}. Passing this option to @command{gnatmake}
7667 (@pxref{Switches for gnatmake}) will ensure the required consistency
7668 through the compilation and binding steps.
7669
7670 @node Units to Sources Mapping Files
7671 @subsection Units to Sources Mapping Files
7672
7673 @table @option
7674
7675 @item -gnatem=@var{path}
7676 @cindex @option{-gnatem} (@command{gcc})
7677 A mapping file is a way to communicate to the compiler two mappings:
7678 from unit names to file names (without any directory information) and from
7679 file names to path names (with full directory information). These mappings
7680 are used by the compiler to short-circuit the path search.
7681
7682 The use of mapping files is not required for correct operation of the
7683 compiler, but mapping files can improve efficiency, particularly when
7684 sources are read over a slow network connection. In normal operation,
7685 you need not be concerned with the format or use of mapping files,
7686 and the @option{-gnatem} switch is not a switch that you would use
7687 explicitly. It is intended primarily for use by automatic tools such as
7688 @command{gnatmake} running under the project file facility. The
7689 description here of the format of mapping files is provided
7690 for completeness and for possible use by other tools.
7691
7692 A mapping file is a sequence of sets of three lines. In each set, the
7693 first line is the unit name, in lower case, with @code{%s} appended
7694 for specs and @code{%b} appended for bodies; the second line is the
7695 file name; and the third line is the path name.
7696
7697 Example:
7698 @smallexample
7699    main%b
7700    main.2.ada
7701    /gnat/project1/sources/main.2.ada
7702 @end smallexample
7703
7704 When the switch @option{-gnatem} is specified, the compiler will
7705 create in memory the two mappings from the specified file. If there is
7706 any problem (nonexistent file, truncated file or duplicate entries),
7707 no mapping will be created.
7708
7709 Several @option{-gnatem} switches may be specified; however, only the
7710 last one on the command line will be taken into account.
7711
7712 When using a project file, @command{gnatmake} creates a temporary
7713 mapping file and communicates it to the compiler using this switch.
7714
7715 @end table
7716
7717 @node Integrated Preprocessing
7718 @subsection Integrated Preprocessing
7719
7720 @noindent
7721 GNAT sources may be preprocessed immediately before compilation.
7722 In this case, the actual
7723 text of the source is not the text of the source file, but is derived from it
7724 through a process called preprocessing. Integrated preprocessing is specified
7725 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7726 indicates, through a text file, the preprocessing data to be used.
7727 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7728
7729 @noindent
7730 Note that when integrated preprocessing is used, the output from the
7731 preprocessor is not written to any external file. Instead it is passed
7732 internally to the compiler. If you need to preserve the result of
7733 preprocessing in a file, then you should use @command{gnatprep}
7734 to perform the desired preprocessing in stand-alone mode.
7735
7736 @noindent
7737 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7738 used when Integrated Preprocessing is used. The reason is that preprocessing
7739 with another Preprocessing Data file without changing the sources will
7740 not trigger recompilation without this switch.
7741
7742 @noindent
7743 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7744 always trigger recompilation for sources that are preprocessed,
7745 because @command{gnatmake} cannot compute the checksum of the source after
7746 preprocessing.
7747
7748 @noindent
7749 The actual preprocessing function is described in details in section
7750 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7751 preprocessing is triggered and parameterized.
7752
7753 @table @code
7754
7755 @item -gnatep=@var{file}
7756 @cindex @option{-gnatep} (@command{gcc})
7757 This switch indicates to the compiler the file name (without directory
7758 information) of the preprocessor data file to use. The preprocessor data file
7759 should be found in the source directories. Note that when the compiler is
7760 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7761 file, if the object directory is not also a source directory, the builder needs
7762 to be called with @option{-x}.
7763
7764 @noindent
7765 A preprocessing data file is a text file with significant lines indicating
7766 how should be preprocessed either a specific source or all sources not
7767 mentioned in other lines. A significant line is a nonempty, non-comment line.
7768 Comments are similar to Ada comments.
7769
7770 @noindent
7771 Each significant line starts with either a literal string or the character '*'.
7772 A literal string is the file name (without directory information) of the source
7773 to preprocess. A character '*' indicates the preprocessing for all the sources
7774 that are not specified explicitly on other lines (order of the lines is not
7775 significant). It is an error to have two lines with the same file name or two
7776 lines starting with the character '*'.
7777
7778 @noindent
7779 After the file name or the character '*', another optional literal string
7780 indicating the file name of the definition file to be used for preprocessing
7781 (@pxref{Form of Definitions File}). The definition files are found by the
7782 compiler in one of the source directories. In some cases, when compiling
7783 a source in a directory other than the current directory, if the definition
7784 file is in the current directory, it may be necessary to add the current
7785 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7786 the compiler would not find the definition file.
7787
7788 @noindent
7789 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7790 be found. Those ^switches^switches^ are:
7791
7792 @table @code
7793
7794 @item -b
7795 Causes both preprocessor lines and the lines deleted by
7796 preprocessing to be replaced by blank lines, preserving the line number.
7797 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7798 it cancels the effect of @option{-c}.
7799
7800 @item -c
7801 Causes both preprocessor lines and the lines deleted
7802 by preprocessing to be retained as comments marked
7803 with the special string ``@code{--! }''.
7804
7805 @item -Dsymbol=value
7806 Define or redefine a symbol, associated with value. A symbol is an Ada
7807 identifier, or an Ada reserved word, with the exception of @code{if},
7808 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7809 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7810 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7811 same name defined in a definition file.
7812
7813 @item -s
7814 Causes a sorted list of symbol names and values to be
7815 listed on the standard output file.
7816
7817 @item -u
7818 Causes undefined symbols to be treated as having the value @code{FALSE}
7819 in the context
7820 of a preprocessor test. In the absence of this option, an undefined symbol in
7821 a @code{#if} or @code{#elsif} test will be treated as an error.
7822
7823 @end table
7824
7825 @noindent
7826 Examples of valid lines in a preprocessor data file:
7827
7828 @smallexample
7829   "toto.adb"  "prep.def" -u
7830   --  preprocess "toto.adb", using definition file "prep.def",
7831   --  undefined symbol are False.
7832
7833   * -c -DVERSION=V101
7834   --  preprocess all other sources without a definition file;
7835   --  suppressed lined are commented; symbol VERSION has the value V101.
7836
7837   "titi.adb" "prep2.def" -s
7838   --  preprocess "titi.adb", using definition file "prep2.def";
7839   --  list all symbols with their values.
7840 @end smallexample
7841
7842 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7843 @cindex @option{-gnateD} (@command{gcc})
7844 Define or redefine a preprocessing symbol, associated with value. If no value
7845 is given on the command line, then the value of the symbol is @code{True}.
7846 A symbol is an identifier, following normal Ada (case-insensitive)
7847 rules for its syntax, and value is any sequence (including an empty sequence)
7848 of characters from the set (letters, digits, period, underline).
7849 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7850 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7851
7852 @noindent
7853 A symbol declared with this ^switch^switch^ on the command line replaces a
7854 symbol with the same name either in a definition file or specified with a
7855 ^switch^switch^ -D in the preprocessor data file.
7856
7857 @noindent
7858 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7859
7860 @item -gnateG
7861 When integrated preprocessing is performed and the preprocessor modifies
7862 the source text, write the result of this preprocessing into a file
7863 <source>^.prep^_prep^.
7864
7865 @end table
7866
7867 @node Code Generation Control
7868 @subsection Code Generation Control
7869
7870 @noindent
7871
7872 The GCC technology provides a wide range of target dependent
7873 @option{-m} switches for controlling
7874 details of code generation with respect to different versions of
7875 architectures. This includes variations in instruction sets (e.g.@:
7876 different members of the power pc family), and different requirements
7877 for optimal arrangement of instructions (e.g.@: different members of
7878 the x86 family). The list of available @option{-m} switches may be
7879 found in the GCC documentation.
7880
7881 Use of these @option{-m} switches may in some cases result in improved
7882 code performance.
7883
7884 The @value{EDITION} technology is tested and qualified without any
7885 @option{-m} switches,
7886 so generally the most reliable approach is to avoid the use of these
7887 switches. However, we generally expect most of these switches to work
7888 successfully with @value{EDITION}, and many customers have reported successful
7889 use of these options.
7890
7891 Our general advice is to avoid the use of @option{-m} switches unless
7892 special needs lead to requirements in this area. In particular,
7893 there is no point in using @option{-m} switches to improve performance
7894 unless you actually see a performance improvement.
7895
7896 @ifset vms
7897 @node Return Codes
7898 @subsection Return Codes
7899 @cindex Return Codes
7900 @cindex @option{/RETURN_CODES=VMS}
7901
7902 @noindent
7903 On VMS, GNAT compiled programs return POSIX-style codes by default,
7904 e.g.@: @option{/RETURN_CODES=POSIX}.
7905
7906 To enable VMS style return codes, use GNAT BIND and LINK with the option
7907 @option{/RETURN_CODES=VMS}. For example:
7908
7909 @smallexample
7910 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7911 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7912 @end smallexample
7913
7914 @noindent
7915 Programs built with /RETURN_CODES=VMS are suitable to be called in
7916 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7917 are suitable for spawning with appropriate GNAT RTL routines.
7918
7919 @end ifset
7920
7921 @node Search Paths and the Run-Time Library (RTL)
7922 @section Search Paths and the Run-Time Library (RTL)
7923
7924 @noindent
7925 With the GNAT source-based library system, the compiler must be able to
7926 find source files for units that are needed by the unit being compiled.
7927 Search paths are used to guide this process.
7928
7929 The compiler compiles one source file whose name must be given
7930 explicitly on the command line. In other words, no searching is done
7931 for this file. To find all other source files that are needed (the most
7932 common being the specs of units), the compiler examines the following
7933 directories, in the following order:
7934
7935 @enumerate
7936 @item
7937 The directory containing the source file of the main unit being compiled
7938 (the file name on the command line).
7939
7940 @item
7941 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7942 @command{gcc} command line, in the order given.
7943
7944 @item
7945 @findex ADA_PRJ_INCLUDE_FILE
7946 Each of the directories listed in the text file whose name is given
7947 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7948
7949 @noindent
7950 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7951 driver when project files are used. It should not normally be set
7952 by other means.
7953
7954 @item
7955 @findex ADA_INCLUDE_PATH
7956 Each of the directories listed in the value of the
7957 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7958 @ifclear vms
7959 Construct this value
7960 exactly as the @env{PATH} environment variable: a list of directory
7961 names separated by colons (semicolons when working with the NT version).
7962 @end ifclear
7963 @ifset vms
7964 Normally, define this value as a logical name containing a comma separated
7965 list of directory names.
7966
7967 This variable can also be defined by means of an environment string
7968 (an argument to the HP C exec* set of functions).
7969
7970 Logical Name:
7971 @smallexample
7972 DEFINE ANOTHER_PATH FOO:[BAG]
7973 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7974 @end smallexample
7975
7976 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7977 first, followed by the standard Ada
7978 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7979 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7980 (Text_IO, Sequential_IO, etc)
7981 instead of the standard Ada packages. Thus, in order to get the standard Ada
7982 packages by default, ADA_INCLUDE_PATH must be redefined.
7983 @end ifset
7984
7985 @item
7986 The content of the @file{ada_source_path} file which is part of the GNAT
7987 installation tree and is used to store standard libraries such as the
7988 GNAT Run Time Library (RTL) source files.
7989 @ifclear vms
7990 @ref{Installing a library}
7991 @end ifclear
7992 @end enumerate
7993
7994 @noindent
7995 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7996 inhibits the use of the directory
7997 containing the source file named in the command line. You can still
7998 have this directory on your search path, but in this case it must be
7999 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8000
8001 Specifying the switch @option{-nostdinc}
8002 inhibits the search of the default location for the GNAT Run Time
8003 Library (RTL) source files.
8004
8005 The compiler outputs its object files and ALI files in the current
8006 working directory.
8007 @ifclear vms
8008 Caution: The object file can be redirected with the @option{-o} switch;
8009 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8010 so the @file{ALI} file will not go to the right place. Therefore, you should
8011 avoid using the @option{-o} switch.
8012 @end ifclear
8013
8014 @findex System.IO
8015 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8016 children make up the GNAT RTL, together with the simple @code{System.IO}
8017 package used in the @code{"Hello World"} example. The sources for these units
8018 are needed by the compiler and are kept together in one directory. Not
8019 all of the bodies are needed, but all of the sources are kept together
8020 anyway. In a normal installation, you need not specify these directory
8021 names when compiling or binding. Either the environment variables or
8022 the built-in defaults cause these files to be found.
8023
8024 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8025 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8026 consisting of child units of @code{GNAT}. This is a collection of generally
8027 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8028 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8029
8030 Besides simplifying access to the RTL, a major use of search paths is
8031 in compiling sources from multiple directories. This can make
8032 development environments much more flexible.
8033
8034 @node Order of Compilation Issues
8035 @section Order of Compilation Issues
8036
8037 @noindent
8038 If, in our earlier example, there was a spec for the @code{hello}
8039 procedure, it would be contained in the file @file{hello.ads}; yet this
8040 file would not have to be explicitly compiled. This is the result of the
8041 model we chose to implement library management. Some of the consequences
8042 of this model are as follows:
8043
8044 @itemize @bullet
8045 @item
8046 There is no point in compiling specs (except for package
8047 specs with no bodies) because these are compiled as needed by clients. If
8048 you attempt a useless compilation, you will receive an error message.
8049 It is also useless to compile subunits because they are compiled as needed
8050 by the parent.
8051
8052 @item
8053 There are no order of compilation requirements: performing a
8054 compilation never obsoletes anything. The only way you can obsolete
8055 something and require recompilations is to modify one of the
8056 source files on which it depends.
8057
8058 @item
8059 There is no library as such, apart from the ALI files
8060 (@pxref{The Ada Library Information Files}, for information on the format
8061 of these files). For now we find it convenient to create separate ALI files,
8062 but eventually the information therein may be incorporated into the object
8063 file directly.
8064
8065 @item
8066 When you compile a unit, the source files for the specs of all units
8067 that it @code{with}'s, all its subunits, and the bodies of any generics it
8068 instantiates must be available (reachable by the search-paths mechanism
8069 described above), or you will receive a fatal error message.
8070 @end itemize
8071
8072 @node Examples
8073 @section Examples
8074
8075 @noindent
8076 The following are some typical Ada compilation command line examples:
8077
8078 @table @code
8079 @item $ gcc -c xyz.adb
8080 Compile body in file @file{xyz.adb} with all default options.
8081
8082 @ifclear vms
8083 @item $ gcc -c -O2 -gnata xyz-def.adb
8084 @end ifclear
8085 @ifset vms
8086 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8087 @end ifset
8088
8089 Compile the child unit package in file @file{xyz-def.adb} with extensive
8090 optimizations, and pragma @code{Assert}/@code{Debug} statements
8091 enabled.
8092
8093 @item $ gcc -c -gnatc abc-def.adb
8094 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8095 mode.
8096 @end table
8097
8098 @node Binding Using gnatbind
8099 @chapter Binding Using @code{gnatbind}
8100 @findex gnatbind
8101
8102 @menu
8103 * Running gnatbind::
8104 * Switches for gnatbind::
8105 * Command-Line Access::
8106 * Search Paths for gnatbind::
8107 * Examples of gnatbind Usage::
8108 @end menu
8109
8110 @noindent
8111 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8112 to bind compiled GNAT objects.
8113
8114 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8115 driver (see @ref{The GNAT Driver and Project Files}).
8116
8117 The @code{gnatbind} program performs four separate functions:
8118
8119 @enumerate
8120 @item
8121 Checks that a program is consistent, in accordance with the rules in
8122 Chapter 10 of the Ada Reference Manual. In particular, error
8123 messages are generated if a program uses inconsistent versions of a
8124 given unit.
8125
8126 @item
8127 Checks that an acceptable order of elaboration exists for the program
8128 and issues an error message if it cannot find an order of elaboration
8129 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8130
8131 @item
8132 Generates a main program incorporating the given elaboration order.
8133 This program is a small Ada package (body and spec) that
8134 must be subsequently compiled
8135 using the GNAT compiler. The necessary compilation step is usually
8136 performed automatically by @command{gnatlink}. The two most important
8137 functions of this program
8138 are to call the elaboration routines of units in an appropriate order
8139 and to call the main program.
8140
8141 @item
8142 Determines the set of object files required by the given main program.
8143 This information is output in the forms of comments in the generated program,
8144 to be read by the @command{gnatlink} utility used to link the Ada application.
8145 @end enumerate
8146
8147 @node Running gnatbind
8148 @section Running @code{gnatbind}
8149
8150 @noindent
8151 The form of the @code{gnatbind} command is
8152
8153 @smallexample
8154 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8155 @c Expanding @ovar macro inline (explanation in macro def comments)
8156 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8157 @end smallexample
8158
8159 @noindent
8160 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8161 unit body. @code{gnatbind} constructs an Ada
8162 package in two files whose names are
8163 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8164 For example, if given the
8165 parameter @file{hello.ali}, for a main program contained in file
8166 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8167 and @file{b~hello.adb}.
8168
8169 When doing consistency checking, the binder takes into consideration
8170 any source files it can locate. For example, if the binder determines
8171 that the given main program requires the package @code{Pack}, whose
8172 @file{.ALI}
8173 file is @file{pack.ali} and whose corresponding source spec file is
8174 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8175 (using the same search path conventions as previously described for the
8176 @command{gcc} command). If it can locate this source file, it checks that
8177 the time stamps
8178 or source checksums of the source and its references to in @file{ALI} files
8179 match. In other words, any @file{ALI} files that mentions this spec must have
8180 resulted from compiling this version of the source file (or in the case
8181 where the source checksums match, a version close enough that the
8182 difference does not matter).
8183
8184 @cindex Source files, use by binder
8185 The effect of this consistency checking, which includes source files, is
8186 that the binder ensures that the program is consistent with the latest
8187 version of the source files that can be located at bind time. Editing a
8188 source file without compiling files that depend on the source file cause
8189 error messages to be generated by the binder.
8190
8191 For example, suppose you have a main program @file{hello.adb} and a
8192 package @code{P}, from file @file{p.ads} and you perform the following
8193 steps:
8194
8195 @enumerate
8196 @item
8197 Enter @code{gcc -c hello.adb} to compile the main program.
8198
8199 @item
8200 Enter @code{gcc -c p.ads} to compile package @code{P}.
8201
8202 @item
8203 Edit file @file{p.ads}.
8204
8205 @item
8206 Enter @code{gnatbind hello}.
8207 @end enumerate
8208
8209 @noindent
8210 At this point, the file @file{p.ali} contains an out-of-date time stamp
8211 because the file @file{p.ads} has been edited. The attempt at binding
8212 fails, and the binder generates the following error messages:
8213
8214 @smallexample
8215 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8216 error: "p.ads" has been modified and must be recompiled
8217 @end smallexample
8218
8219 @noindent
8220 Now both files must be recompiled as indicated, and then the bind can
8221 succeed, generating a main program. You need not normally be concerned
8222 with the contents of this file, but for reference purposes a sample
8223 binder output file is given in @ref{Example of Binder Output File}.
8224
8225 In most normal usage, the default mode of @command{gnatbind} which is to
8226 generate the main package in Ada, as described in the previous section.
8227 In particular, this means that any Ada programmer can read and understand
8228 the generated main program. It can also be debugged just like any other
8229 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8230 @command{gnatbind} and @command{gnatlink}.
8231
8232 @node Switches for gnatbind
8233 @section Switches for @command{gnatbind}
8234
8235 @noindent
8236 The following switches are available with @code{gnatbind}; details will
8237 be presented in subsequent sections.
8238
8239 @menu
8240 * Consistency-Checking Modes::
8241 * Binder Error Message Control::
8242 * Elaboration Control::
8243 * Output Control::
8244 * Dynamic Allocation Control::
8245 * Binding with Non-Ada Main Programs::
8246 * Binding Programs with No Main Subprogram::
8247 @end menu
8248
8249 @table @option
8250 @c !sort!
8251
8252 @item --version
8253 @cindex @option{--version} @command{gnatbind}
8254 Display Copyright and version, then exit disregarding all other options.
8255
8256 @item --help
8257 @cindex @option{--help} @command{gnatbind}
8258 If @option{--version} was not used, display usage, then exit disregarding
8259 all other options.
8260
8261 @item -a
8262 @cindex @option{-a} @command{gnatbind}
8263 Indicates that, if supported by the platform, the adainit procedure should
8264 be treated as an initialisation routine by the linker (a constructor). This
8265 is intended to be used by the Project Manager to automatically initialize
8266 shared Stand-Alone Libraries.
8267
8268 @item ^-aO^/OBJECT_SEARCH^
8269 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8270 Specify directory to be searched for ALI files.
8271
8272 @item ^-aI^/SOURCE_SEARCH^
8273 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8274 Specify directory to be searched for source file.
8275
8276 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8277 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8278 Output ALI list (to standard output or to the named file).
8279
8280 @item ^-b^/REPORT_ERRORS=BRIEF^
8281 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8282 Generate brief messages to @file{stderr} even if verbose mode set.
8283
8284 @item ^-c^/NOOUTPUT^
8285 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8286 Check only, no generation of binder output file.
8287
8288 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8289 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8290 This switch can be used to change the default task stack size value
8291 to a specified size @var{nn}, which is expressed in bytes by default, or
8292 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8293 with @var{m}.
8294 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8295 in effect, to completing all task specs with
8296 @smallexample @c ada
8297    pragma Storage_Size (nn);
8298 @end smallexample
8299 When they do not already have such a pragma.
8300
8301 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8302 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8303 This switch can be used to change the default secondary stack size value
8304 to a specified size @var{nn}, which is expressed in bytes by default, or
8305 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8306 with @var{m}.
8307
8308 The secondary stack is used to deal with functions that return a variable
8309 sized result, for example a function returning an unconstrained
8310 String. There are two ways in which this secondary stack is allocated.
8311
8312 For most targets, the secondary stack is growing on demand and is allocated
8313 as a chain of blocks in the heap. The -D option is not very
8314 relevant. It only give some control over the size of the allocated
8315 blocks (whose size is the minimum of the default secondary stack size value,
8316 and the actual size needed for the current allocation request).
8317
8318 For certain targets, notably VxWorks 653,
8319 the secondary stack is allocated by carving off a fixed ratio chunk of the
8320 primary task stack. The -D option is used to define the
8321 size of the environment task's secondary stack.
8322
8323 @item ^-e^/ELABORATION_DEPENDENCIES^
8324 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8325 Output complete list of elaboration-order dependencies.
8326
8327 @item ^-E^/STORE_TRACEBACKS^
8328 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8329 Store tracebacks in exception occurrences when the target supports it.
8330 @ignore
8331 @c The following may get moved to an appendix
8332 This option is currently supported on the following targets:
8333 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8334 @end ignore
8335 See also the packages @code{GNAT.Traceback} and
8336 @code{GNAT.Traceback.Symbolic} for more information.
8337 @ifclear vms
8338 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8339 @command{gcc} option.
8340 @end ifclear
8341
8342 @item ^-F^/FORCE_ELABS_FLAGS^
8343 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8344 Force the checks of elaboration flags. @command{gnatbind} does not normally
8345 generate checks of elaboration flags for the main executable, except when
8346 a Stand-Alone Library is used. However, there are cases when this cannot be
8347 detected by gnatbind. An example is importing an interface of a Stand-Alone
8348 Library through a pragma Import and only specifying through a linker switch
8349 this Stand-Alone Library. This switch is used to guarantee that elaboration
8350 flag checks are generated.
8351
8352 @item ^-h^/HELP^
8353 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8354 Output usage (help) information
8355
8356 @item ^-H32^/32_MALLOC^
8357 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8358 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8359 For further details see @ref{Dynamic Allocation Control}.
8360
8361 @item ^-H64^/64_MALLOC^
8362 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8363 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8364 @cindex @code{__gnat_malloc}
8365 For further details see @ref{Dynamic Allocation Control}.
8366
8367 @item ^-I^/SEARCH^
8368 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8369 Specify directory to be searched for source and ALI files.
8370
8371 @item ^-I-^/NOCURRENT_DIRECTORY^
8372 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8373 Do not look for sources in the current directory where @code{gnatbind} was
8374 invoked, and do not look for ALI files in the directory containing the
8375 ALI file named in the @code{gnatbind} command line.
8376
8377 @item ^-l^/ORDER_OF_ELABORATION^
8378 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8379 Output chosen elaboration order.
8380
8381 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8382 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8383 Bind the units for library building. In this case the adainit and
8384 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8385 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8386 ^@var{xxx}final^@var{XXX}FINAL^.
8387 Implies ^-n^/NOCOMPILE^.
8388 @ifclear vms
8389 (@xref{GNAT and Libraries}, for more details.)
8390 @end ifclear
8391 @ifset vms
8392 On OpenVMS, these init and final procedures are exported in uppercase
8393 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8394 the init procedure will be "TOTOINIT" and the exported name of the final
8395 procedure will be "TOTOFINAL".
8396 @end ifset
8397
8398 @item ^-Mxyz^/RENAME_MAIN=xyz^
8399 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8400 Rename generated main program from main to xyz. This option is
8401 supported on cross environments only.
8402
8403 @item ^-m^/ERROR_LIMIT=^@var{n}
8404 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8405 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8406 in the range 1..999999. The default value if no switch is
8407 given is 9999. If the number of warnings reaches this limit, then a
8408 message is output and further warnings are suppressed, the bind
8409 continues in this case. If the number of errors reaches this
8410 limit, then a message is output and the bind is abandoned.
8411 A value of zero means that no limit is enforced. The equal
8412 sign is optional.
8413
8414 @ifset unw
8415 Furthermore, under Windows, the sources pointed to by the libraries path
8416 set in the registry are not searched for.
8417 @end ifset
8418
8419 @item ^-n^/NOMAIN^
8420 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8421 No main program.
8422
8423 @item -nostdinc
8424 @cindex @option{-nostdinc} (@command{gnatbind})
8425 Do not look for sources in the system default directory.
8426
8427 @item -nostdlib
8428 @cindex @option{-nostdlib} (@command{gnatbind})
8429 Do not look for library files in the system default directory.
8430
8431 @item --RTS=@var{rts-path}
8432 @cindex @option{--RTS} (@code{gnatbind})
8433 Specifies the default location of the runtime library. Same meaning as the
8434 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8435
8436 @item ^-o ^/OUTPUT=^@var{file}
8437 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8438 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8439 Note that if this option is used, then linking must be done manually,
8440 gnatlink cannot be used.
8441
8442 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8443 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8444 Output object list (to standard output or to the named file).
8445
8446 @item ^-p^/PESSIMISTIC_ELABORATION^
8447 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8448 Pessimistic (worst-case) elaboration order
8449
8450 @item ^-P^-P^
8451 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8452 Generate binder file suitable for CodePeer.
8453
8454 @item ^-R^-R^
8455 @cindex @option{^-R^-R^} (@command{gnatbind})
8456 Output closure source list.
8457
8458 @item ^-s^/READ_SOURCES=ALL^
8459 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8460 Require all source files to be present.
8461
8462 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8463 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8464 Specifies the value to be used when detecting uninitialized scalar
8465 objects with pragma Initialize_Scalars.
8466 The @var{xxx} ^string specified with the switch^option^ may be either
8467 @itemize @bullet
8468 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8469 @item ``@option{^lo^LOW^}'' for the lowest possible value
8470 @item ``@option{^hi^HIGH^}'' for the highest possible value
8471 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8472 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8473 @end itemize
8474
8475 In addition, you can specify @option{-Sev} to indicate that the value is
8476 to be set at run time. In this case, the program will look for an environment
8477 @cindex GNAT_INIT_SCALARS
8478 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8479 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8480 If no environment variable is found, or if it does not have a valid value,
8481 then the default is @option{in} (invalid values).
8482
8483 @ifclear vms
8484 @item -static
8485 @cindex @option{-static} (@code{gnatbind})
8486 Link against a static GNAT run time.
8487
8488 @item -shared
8489 @cindex @option{-shared} (@code{gnatbind})
8490 Link against a shared GNAT run time when available.
8491 @end ifclear
8492
8493 @item ^-t^/NOTIME_STAMP_CHECK^
8494 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8495 Tolerate time stamp and other consistency errors
8496
8497 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8498 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8499 Set the time slice value to @var{n} milliseconds. If the system supports
8500 the specification of a specific time slice value, then the indicated value
8501 is used. If the system does not support specific time slice values, but
8502 does support some general notion of round-robin scheduling, then any
8503 nonzero value will activate round-robin scheduling.
8504
8505 A value of zero is treated specially. It turns off time
8506 slicing, and in addition, indicates to the tasking run time that the
8507 semantics should match as closely as possible the Annex D
8508 requirements of the Ada RM, and in particular sets the default
8509 scheduling policy to @code{FIFO_Within_Priorities}.
8510
8511 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8512 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8513 Enable dynamic stack usage, with @var{n} results stored and displayed
8514 at program termination. A result is generated when a task
8515 terminates. Results that can't be stored are displayed on the fly, at
8516 task termination. This option is currently not supported on Itanium
8517 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8518
8519 @item ^-v^/REPORT_ERRORS=VERBOSE^
8520 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8521 Verbose mode. Write error messages, header, summary output to
8522 @file{stdout}.
8523
8524 @ifclear vms
8525 @item -w@var{x}
8526 @cindex @option{-w} (@code{gnatbind})
8527 Warning mode (@var{x}=s/e for suppress/treat as error)
8528 @end ifclear
8529
8530 @ifset vms
8531 @item /WARNINGS=NORMAL
8532 @cindex @option{/WARNINGS} (@code{gnatbind})
8533 Normal warnings mode. Warnings are issued but ignored
8534
8535 @item /WARNINGS=SUPPRESS
8536 @cindex @option{/WARNINGS} (@code{gnatbind})
8537 All warning messages are suppressed
8538
8539 @item /WARNINGS=ERROR
8540 @cindex @option{/WARNINGS} (@code{gnatbind})
8541 Warning messages are treated as fatal errors
8542 @end ifset
8543
8544 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8545 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8546 Override default wide character encoding for standard Text_IO files.
8547
8548 @item ^-x^/READ_SOURCES=NONE^
8549 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8550 Exclude source files (check object consistency only).
8551
8552 @ifset vms
8553 @item /READ_SOURCES=AVAILABLE
8554 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8555 Default mode, in which sources are checked for consistency only if
8556 they are available.
8557 @end ifset
8558
8559 @item ^-y^/ENABLE_LEAP_SECONDS^
8560 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8561 Enable leap seconds support in @code{Ada.Calendar} and its children.
8562
8563 @item ^-z^/ZERO_MAIN^
8564 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8565 No main subprogram.
8566 @end table
8567
8568 @ifclear vms
8569 @noindent
8570 You may obtain this listing of switches by running @code{gnatbind} with
8571 no arguments.
8572 @end ifclear
8573
8574 @node Consistency-Checking Modes
8575 @subsection Consistency-Checking Modes
8576
8577 @noindent
8578 As described earlier, by default @code{gnatbind} checks
8579 that object files are consistent with one another and are consistent
8580 with any source files it can locate. The following switches control binder
8581 access to sources.
8582
8583 @table @option
8584 @c !sort!
8585 @item ^-s^/READ_SOURCES=ALL^
8586 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8587 Require source files to be present. In this mode, the binder must be
8588 able to locate all source files that are referenced, in order to check
8589 their consistency. In normal mode, if a source file cannot be located it
8590 is simply ignored. If you specify this switch, a missing source
8591 file is an error.
8592
8593 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8594 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8595 Override default wide character encoding for standard Text_IO files.
8596 Normally the default wide character encoding method used for standard
8597 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8598 the main source input (see description of switch
8599 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8600 use of this switch for the binder (which has the same set of
8601 possible arguments) overrides this default as specified.
8602
8603 @item ^-x^/READ_SOURCES=NONE^
8604 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8605 Exclude source files. In this mode, the binder only checks that ALI
8606 files are consistent with one another. Source files are not accessed.
8607 The binder runs faster in this mode, and there is still a guarantee that
8608 the resulting program is self-consistent.
8609 If a source file has been edited since it was last compiled, and you
8610 specify this switch, the binder will not detect that the object
8611 file is out of date with respect to the source file. Note that this is the
8612 mode that is automatically used by @command{gnatmake} because in this
8613 case the checking against sources has already been performed by
8614 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8615
8616 @ifset vms
8617 @item /READ_SOURCES=AVAILABLE
8618 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8619 This is the default mode in which source files are checked if they are
8620 available, and ignored if they are not available.
8621 @end ifset
8622 @end table
8623
8624 @node Binder Error Message Control
8625 @subsection Binder Error Message Control
8626
8627 @noindent
8628 The following switches provide control over the generation of error
8629 messages from the binder:
8630
8631 @table @option
8632 @c !sort!
8633 @item ^-v^/REPORT_ERRORS=VERBOSE^
8634 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8635 Verbose mode. In the normal mode, brief error messages are generated to
8636 @file{stderr}. If this switch is present, a header is written
8637 to @file{stdout} and any error messages are directed to @file{stdout}.
8638 All that is written to @file{stderr} is a brief summary message.
8639
8640 @item ^-b^/REPORT_ERRORS=BRIEF^
8641 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8642 Generate brief error messages to @file{stderr} even if verbose mode is
8643 specified. This is relevant only when used with the
8644 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8645
8646 @ifclear vms
8647 @item -m@var{n}
8648 @cindex @option{-m} (@code{gnatbind})
8649 Limits the number of error messages to @var{n}, a decimal integer in the
8650 range 1-999. The binder terminates immediately if this limit is reached.
8651
8652 @item -M@var{xxx}
8653 @cindex @option{-M} (@code{gnatbind})
8654 Renames the generated main program from @code{main} to @code{xxx}.
8655 This is useful in the case of some cross-building environments, where
8656 the actual main program is separate from the one generated
8657 by @code{gnatbind}.
8658 @end ifclear
8659
8660 @item ^-ws^/WARNINGS=SUPPRESS^
8661 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8662 @cindex Warnings
8663 Suppress all warning messages.
8664
8665 @item ^-we^/WARNINGS=ERROR^
8666 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8667 Treat any warning messages as fatal errors.
8668
8669 @ifset vms
8670 @item /WARNINGS=NORMAL
8671 Standard mode with warnings generated, but warnings do not get treated
8672 as errors.
8673 @end ifset
8674
8675 @item ^-t^/NOTIME_STAMP_CHECK^
8676 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8677 @cindex Time stamp checks, in binder
8678 @cindex Binder consistency checks
8679 @cindex Consistency checks, in binder
8680 The binder performs a number of consistency checks including:
8681
8682 @itemize @bullet
8683 @item
8684 Check that time stamps of a given source unit are consistent
8685 @item
8686 Check that checksums of a given source unit are consistent
8687 @item
8688 Check that consistent versions of @code{GNAT} were used for compilation
8689 @item
8690 Check consistency of configuration pragmas as required
8691 @end itemize
8692
8693 @noindent
8694 Normally failure of such checks, in accordance with the consistency
8695 requirements of the Ada Reference Manual, causes error messages to be
8696 generated which abort the binder and prevent the output of a binder
8697 file and subsequent link to obtain an executable.
8698
8699 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8700 into warnings, so that
8701 binding and linking can continue to completion even in the presence of such
8702 errors. The result may be a failed link (due to missing symbols), or a
8703 non-functional executable which has undefined semantics.
8704 @emph{This means that
8705 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8706 with extreme care.}
8707 @end table
8708
8709 @node Elaboration Control
8710 @subsection Elaboration Control
8711
8712 @noindent
8713 The following switches provide additional control over the elaboration
8714 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8715
8716 @table @option
8717 @item ^-p^/PESSIMISTIC_ELABORATION^
8718 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8719 Normally the binder attempts to choose an elaboration order that is
8720 likely to minimize the likelihood of an elaboration order error resulting
8721 in raising a @code{Program_Error} exception. This switch reverses the
8722 action of the binder, and requests that it deliberately choose an order
8723 that is likely to maximize the likelihood of an elaboration error.
8724 This is useful in ensuring portability and avoiding dependence on
8725 accidental fortuitous elaboration ordering.
8726
8727 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8728 switch if dynamic
8729 elaboration checking is used (@option{-gnatE} switch used for compilation).
8730 This is because in the default static elaboration mode, all necessary
8731 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8732 These implicit pragmas are still respected by the binder in
8733 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8734 safe elaboration order is assured.
8735
8736 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8737 production use; it is more for debugging/experimental use.
8738 @end table
8739
8740 @node Output Control
8741 @subsection Output Control
8742
8743 @noindent
8744 The following switches allow additional control over the output
8745 generated by the binder.
8746
8747 @table @option
8748 @c !sort!
8749
8750 @item ^-c^/NOOUTPUT^
8751 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8752 Check only. Do not generate the binder output file. In this mode the
8753 binder performs all error checks but does not generate an output file.
8754
8755 @item ^-e^/ELABORATION_DEPENDENCIES^
8756 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8757 Output complete list of elaboration-order dependencies, showing the
8758 reason for each dependency. This output can be rather extensive but may
8759 be useful in diagnosing problems with elaboration order. The output is
8760 written to @file{stdout}.
8761
8762 @item ^-h^/HELP^
8763 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8764 Output usage information. The output is written to @file{stdout}.
8765
8766 @item ^-K^/LINKER_OPTION_LIST^
8767 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8768 Output linker options to @file{stdout}. Includes library search paths,
8769 contents of pragmas Ident and Linker_Options, and libraries added
8770 by @code{gnatbind}.
8771
8772 @item ^-l^/ORDER_OF_ELABORATION^
8773 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8774 Output chosen elaboration order. The output is written to @file{stdout}.
8775
8776 @item ^-O^/OBJECT_LIST^
8777 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8778 Output full names of all the object files that must be linked to provide
8779 the Ada component of the program. The output is written to @file{stdout}.
8780 This list includes the files explicitly supplied and referenced by the user
8781 as well as implicitly referenced run-time unit files. The latter are
8782 omitted if the corresponding units reside in shared libraries. The
8783 directory names for the run-time units depend on the system configuration.
8784
8785 @item ^-o ^/OUTPUT=^@var{file}
8786 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8787 Set name of output file to @var{file} instead of the normal
8788 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8789 binder generated body filename.
8790 Note that if this option is used, then linking must be done manually.
8791 It is not possible to use gnatlink in this case, since it cannot locate
8792 the binder file.
8793
8794 @item ^-r^/RESTRICTION_LIST^
8795 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8796 Generate list of @code{pragma Restrictions} that could be applied to
8797 the current unit. This is useful for code audit purposes, and also may
8798 be used to improve code generation in some cases.
8799
8800 @end table
8801
8802 @node Dynamic Allocation Control
8803 @subsection Dynamic Allocation Control
8804
8805 @noindent
8806 The heap control switches -- @option{-H32} and @option{-H64} --
8807 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8808 They only affect compiler-generated allocations via @code{__gnat_malloc};
8809 explicit calls to @code{malloc} and related functions from the C
8810 run-time library are unaffected.
8811
8812 @table @option
8813 @item -H32
8814 Allocate memory on 32-bit heap
8815
8816 @item -H64
8817 Allocate memory on 64-bit heap.  This is the default
8818 unless explicitly overridden by a @code{'Size} clause on the access type.
8819 @end table
8820
8821 @ifset vms
8822 @noindent
8823 See also @ref{Access types and 32/64-bit allocation}.
8824 @end ifset
8825 @ifclear vms
8826 @noindent
8827 These switches are only effective on VMS platforms.
8828 @end ifclear
8829
8830
8831 @node Binding with Non-Ada Main Programs
8832 @subsection Binding with Non-Ada Main Programs
8833
8834 @noindent
8835 In our description so far we have assumed that the main
8836 program is in Ada, and that the task of the binder is to generate a
8837 corresponding function @code{main} that invokes this Ada main
8838 program. GNAT also supports the building of executable programs where
8839 the main program is not in Ada, but some of the called routines are
8840 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8841 The following switch is used in this situation:
8842
8843 @table @option
8844 @item ^-n^/NOMAIN^
8845 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8846 No main program. The main program is not in Ada.
8847 @end table
8848
8849 @noindent
8850 In this case, most of the functions of the binder are still required,
8851 but instead of generating a main program, the binder generates a file
8852 containing the following callable routines:
8853
8854 @table @code
8855 @item adainit
8856 @findex adainit
8857 You must call this routine to initialize the Ada part of the program by
8858 calling the necessary elaboration routines. A call to @code{adainit} is
8859 required before the first call to an Ada subprogram.
8860
8861 Note that it is assumed that the basic execution environment must be setup
8862 to be appropriate for Ada execution at the point where the first Ada
8863 subprogram is called. In particular, if the Ada code will do any
8864 floating-point operations, then the FPU must be setup in an appropriate
8865 manner. For the case of the x86, for example, full precision mode is
8866 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8867 that the FPU is in the right state.
8868
8869 @item adafinal
8870 @findex adafinal
8871 You must call this routine to perform any library-level finalization
8872 required by the Ada subprograms. A call to @code{adafinal} is required
8873 after the last call to an Ada subprogram, and before the program
8874 terminates.
8875 @end table
8876
8877 @noindent
8878 If the @option{^-n^/NOMAIN^} switch
8879 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8880 @cindex Binder, multiple input files
8881 is given, more than one ALI file may appear on
8882 the command line for @code{gnatbind}. The normal @dfn{closure}
8883 calculation is performed for each of the specified units. Calculating
8884 the closure means finding out the set of units involved by tracing
8885 @code{with} references. The reason it is necessary to be able to
8886 specify more than one ALI file is that a given program may invoke two or
8887 more quite separate groups of Ada units.
8888
8889 The binder takes the name of its output file from the last specified ALI
8890 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8891 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8892 The output is an Ada unit in source form that can be compiled with GNAT.
8893 This compilation occurs automatically as part of the @command{gnatlink}
8894 processing.
8895
8896 Currently the GNAT run time requires a FPU using 80 bits mode
8897 precision. Under targets where this is not the default it is required to
8898 call GNAT.Float_Control.Reset before using floating point numbers (this
8899 include float computation, float input and output) in the Ada code. A
8900 side effect is that this could be the wrong mode for the foreign code
8901 where floating point computation could be broken after this call.
8902
8903 @node Binding Programs with No Main Subprogram
8904 @subsection Binding Programs with No Main Subprogram
8905
8906 @noindent
8907 It is possible to have an Ada program which does not have a main
8908 subprogram. This program will call the elaboration routines of all the
8909 packages, then the finalization routines.
8910
8911 The following switch is used to bind programs organized in this manner:
8912
8913 @table @option
8914 @item ^-z^/ZERO_MAIN^
8915 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8916 Normally the binder checks that the unit name given on the command line
8917 corresponds to a suitable main subprogram. When this switch is used,
8918 a list of ALI files can be given, and the execution of the program
8919 consists of elaboration of these units in an appropriate order. Note
8920 that the default wide character encoding method for standard Text_IO
8921 files is always set to Brackets if this switch is set (you can use
8922 the binder switch
8923 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8924 @end table
8925
8926 @node Command-Line Access
8927 @section Command-Line Access
8928
8929 @noindent
8930 The package @code{Ada.Command_Line} provides access to the command-line
8931 arguments and program name. In order for this interface to operate
8932 correctly, the two variables
8933
8934 @smallexample
8935 @group
8936 int gnat_argc;
8937 char **gnat_argv;
8938 @end group
8939 @end smallexample
8940
8941 @noindent
8942 @findex gnat_argv
8943 @findex gnat_argc
8944 are declared in one of the GNAT library routines. These variables must
8945 be set from the actual @code{argc} and @code{argv} values passed to the
8946 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8947 generates the C main program to automatically set these variables.
8948 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8949 set these variables. If they are not set, the procedures in
8950 @code{Ada.Command_Line} will not be available, and any attempt to use
8951 them will raise @code{Constraint_Error}. If command line access is
8952 required, your main program must set @code{gnat_argc} and
8953 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8954 it.
8955
8956 @node Search Paths for gnatbind
8957 @section Search Paths for @code{gnatbind}
8958
8959 @noindent
8960 The binder takes the name of an ALI file as its argument and needs to
8961 locate source files as well as other ALI files to verify object consistency.
8962
8963 For source files, it follows exactly the same search rules as @command{gcc}
8964 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8965 directories searched are:
8966
8967 @enumerate
8968 @item
8969 The directory containing the ALI file named in the command line, unless
8970 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8971
8972 @item
8973 All directories specified by @option{^-I^/SEARCH^}
8974 switches on the @code{gnatbind}
8975 command line, in the order given.
8976
8977 @item
8978 @findex ADA_PRJ_OBJECTS_FILE
8979 Each of the directories listed in the text file whose name is given
8980 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8981
8982 @noindent
8983 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8984 driver when project files are used. It should not normally be set
8985 by other means.
8986
8987 @item
8988 @findex ADA_OBJECTS_PATH
8989 Each of the directories listed in the value of the
8990 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8991 @ifset unw
8992 Construct this value
8993 exactly as the @env{PATH} environment variable: a list of directory
8994 names separated by colons (semicolons when working with the NT version
8995 of GNAT).
8996 @end ifset
8997 @ifset vms
8998 Normally, define this value as a logical name containing a comma separated
8999 list of directory names.
9000
9001 This variable can also be defined by means of an environment string
9002 (an argument to the HP C exec* set of functions).
9003
9004 Logical Name:
9005 @smallexample
9006 DEFINE ANOTHER_PATH FOO:[BAG]
9007 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9008 @end smallexample
9009
9010 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9011 first, followed by the standard Ada
9012 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9013 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9014 (Text_IO, Sequential_IO, etc)
9015 instead of the standard Ada packages. Thus, in order to get the standard Ada
9016 packages by default, ADA_OBJECTS_PATH must be redefined.
9017 @end ifset
9018
9019 @item
9020 The content of the @file{ada_object_path} file which is part of the GNAT
9021 installation tree and is used to store standard libraries such as the
9022 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9023 specified.
9024 @ifclear vms
9025 @ref{Installing a library}
9026 @end ifclear
9027 @end enumerate
9028
9029 @noindent
9030 In the binder the switch @option{^-I^/SEARCH^}
9031 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9032 is used to specify both source and
9033 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9034 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9035 instead if you want to specify
9036 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9037 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9038 if you want to specify library paths
9039 only. This means that for the binder
9040 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9041 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9042 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9043 The binder generates the bind file (a C language source file) in the
9044 current working directory.
9045
9046 @findex Ada
9047 @findex System
9048 @findex Interfaces
9049 @findex GNAT
9050 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9051 children make up the GNAT Run-Time Library, together with the package
9052 GNAT and its children, which contain a set of useful additional
9053 library functions provided by GNAT. The sources for these units are
9054 needed by the compiler and are kept together in one directory. The ALI
9055 files and object files generated by compiling the RTL are needed by the
9056 binder and the linker and are kept together in one directory, typically
9057 different from the directory containing the sources. In a normal
9058 installation, you need not specify these directory names when compiling
9059 or binding. Either the environment variables or the built-in defaults
9060 cause these files to be found.
9061
9062 Besides simplifying access to the RTL, a major use of search paths is
9063 in compiling sources from multiple directories. This can make
9064 development environments much more flexible.
9065
9066 @node Examples of gnatbind Usage
9067 @section Examples of @code{gnatbind} Usage
9068
9069 @noindent
9070 This section contains a number of examples of using the GNAT binding
9071 utility @code{gnatbind}.
9072
9073 @table @code
9074 @item gnatbind hello
9075 The main program @code{Hello} (source program in @file{hello.adb}) is
9076 bound using the standard switch settings. The generated main program is
9077 @file{b~hello.adb}. This is the normal, default use of the binder.
9078
9079 @ifclear vms
9080 @item gnatbind hello -o mainprog.adb
9081 @end ifclear
9082 @ifset vms
9083 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9084 @end ifset
9085 The main program @code{Hello} (source program in @file{hello.adb}) is
9086 bound using the standard switch settings. The generated main program is
9087 @file{mainprog.adb} with the associated spec in
9088 @file{mainprog.ads}. Note that you must specify the body here not the
9089 spec. Note that if this option is used, then linking must be done manually,
9090 since gnatlink will not be able to find the generated file.
9091 @end table
9092
9093 @c ------------------------------------
9094 @node Linking Using gnatlink
9095 @chapter Linking Using @command{gnatlink}
9096 @c ------------------------------------
9097 @findex gnatlink
9098
9099 @noindent
9100 This chapter discusses @command{gnatlink}, a tool that links
9101 an Ada program and builds an executable file. This utility
9102 invokes the system linker ^(via the @command{gcc} command)^^
9103 with a correct list of object files and library references.
9104 @command{gnatlink} automatically determines the list of files and
9105 references for the Ada part of a program. It uses the binder file
9106 generated by the @command{gnatbind} to determine this list.
9107
9108 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9109 driver (see @ref{The GNAT Driver and Project Files}).
9110
9111 @menu
9112 * Running gnatlink::
9113 * Switches for gnatlink::
9114 @end menu
9115
9116 @node Running gnatlink
9117 @section Running @command{gnatlink}
9118
9119 @noindent
9120 The form of the @command{gnatlink} command is
9121
9122 @smallexample
9123 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9124 @c            @ovar{non-Ada objects} @ovar{linker options}
9125 @c Expanding @ovar macro inline (explanation in macro def comments)
9126 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9127            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9128
9129 @end smallexample
9130
9131 @noindent
9132 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9133 non-Ada objects
9134 or linker options) may be in any order, provided that no non-Ada object may
9135 be mistaken for a main @file{ALI} file.
9136 Any file name @file{F} without the @file{.ali}
9137 extension will be taken as the main @file{ALI} file if a file exists
9138 whose name is the concatenation of @file{F} and @file{.ali}.
9139
9140 @noindent
9141 @file{@var{mainprog}.ali} references the ALI file of the main program.
9142 The @file{.ali} extension of this file can be omitted. From this
9143 reference, @command{gnatlink} locates the corresponding binder file
9144 @file{b~@var{mainprog}.adb} and, using the information in this file along
9145 with the list of non-Ada objects and linker options, constructs a
9146 linker command file to create the executable.
9147
9148 The arguments other than the @command{gnatlink} switches and the main
9149 @file{ALI} file are passed to the linker uninterpreted.
9150 They typically include the names of
9151 object files for units written in other languages than Ada and any library
9152 references required to resolve references in any of these foreign language
9153 units, or in @code{Import} pragmas in any Ada units.
9154
9155 @var{linker options} is an optional list of linker specific
9156 switches.
9157 The default linker called by gnatlink is @command{gcc} which in
9158 turn calls the appropriate system linker.
9159
9160 One useful option for the linker is @option{-s}: it reduces the size of the
9161 executable by removing all symbol table and relocation information from the
9162 executable.
9163
9164 Standard options for the linker such as @option{-lmy_lib} or
9165 @option{-Ldir} can be added as is.
9166 For options that are not recognized by
9167 @command{gcc} as linker options, use the @command{gcc} switches
9168 @option{-Xlinker} or @option{-Wl,}.
9169
9170 Refer to the GCC documentation for
9171 details.
9172
9173 Here is an example showing how to generate a linker map:
9174
9175 @smallexample
9176 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9177 @end smallexample
9178
9179 Using @var{linker options} it is possible to set the program stack and
9180 heap size.
9181 @ifset unw
9182 See @ref{Setting Stack Size from gnatlink} and
9183 @ref{Setting Heap Size from gnatlink}.
9184 @end ifset
9185
9186 @command{gnatlink} determines the list of objects required by the Ada
9187 program and prepends them to the list of objects passed to the linker.
9188 @command{gnatlink} also gathers any arguments set by the use of
9189 @code{pragma Linker_Options} and adds them to the list of arguments
9190 presented to the linker.
9191
9192 @ifset vms
9193 @command{gnatlink} accepts the following types of extra files on the command
9194 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9195 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9196 handled according to their extension.
9197 @end ifset
9198
9199 @node Switches for gnatlink
9200 @section Switches for @command{gnatlink}
9201
9202 @noindent
9203 The following switches are available with the @command{gnatlink} utility:
9204
9205 @table @option
9206 @c !sort!
9207
9208 @item --version
9209 @cindex @option{--version} @command{gnatlink}
9210 Display Copyright and version, then exit disregarding all other options.
9211
9212 @item --help
9213 @cindex @option{--help} @command{gnatlink}
9214 If @option{--version} was not used, display usage, then exit disregarding
9215 all other options.
9216
9217 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9218 @cindex Command line length
9219 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9220 On some targets, the command line length is limited, and @command{gnatlink}
9221 will generate a separate file for the linker if the list of object files
9222 is too long.
9223 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9224 to be generated even if
9225 the limit is not exceeded. This is useful in some cases to deal with
9226 special situations where the command line length is exceeded.
9227
9228 @item ^-g^/DEBUG^
9229 @cindex Debugging information, including
9230 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9231 The option to include debugging information causes the Ada bind file (in
9232 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9233 @option{^-g^/DEBUG^}.
9234 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9235 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9236 Without @option{^-g^/DEBUG^}, the binder removes these files by
9237 default. The same procedure apply if a C bind file was generated using
9238 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9239 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9240
9241 @item ^-n^/NOCOMPILE^
9242 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9243 Do not compile the file generated by the binder. This may be used when
9244 a link is rerun with different options, but there is no need to recompile
9245 the binder file.
9246
9247 @item ^-v^/VERBOSE^
9248 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9249 Causes additional information to be output, including a full list of the
9250 included object files. This switch option is most useful when you want
9251 to see what set of object files are being used in the link step.
9252
9253 @item ^-v -v^/VERBOSE/VERBOSE^
9254 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9255 Very verbose mode. Requests that the compiler operate in verbose mode when
9256 it compiles the binder file, and that the system linker run in verbose mode.
9257
9258 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9259 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9260 @var{exec-name} specifies an alternate name for the generated
9261 executable program. If this switch is omitted, the executable has the same
9262 name as the main unit. For example, @code{gnatlink try.ali} creates
9263 an executable called @file{^try^TRY.EXE^}.
9264
9265 @ifclear vms
9266 @item -b @var{target}
9267 @cindex @option{-b} (@command{gnatlink})
9268 Compile your program to run on @var{target}, which is the name of a
9269 system configuration. You must have a GNAT cross-compiler built if
9270 @var{target} is not the same as your host system.
9271
9272 @item -B@var{dir}
9273 @cindex @option{-B} (@command{gnatlink})
9274 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9275 from @var{dir} instead of the default location. Only use this switch
9276 when multiple versions of the GNAT compiler are available.
9277 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9278 for further details. You would normally use the @option{-b} or
9279 @option{-V} switch instead.
9280
9281 @item -M
9282 When linking an executable, create a map file. The name of the map file
9283 has the same name as the executable with extension ".map".
9284
9285 @item -M=mapfile
9286 When linking an executable, create a map file. The name of the map file is
9287 "mapfile".
9288
9289 @item --GCC=@var{compiler_name}
9290 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9291 Program used for compiling the binder file. The default is
9292 @command{gcc}. You need to use quotes around @var{compiler_name} if
9293 @code{compiler_name} contains spaces or other separator characters.
9294 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9295 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9296 inserted after your command name. Thus in the above example the compiler
9297 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9298 A limitation of this syntax is that the name and path name of the executable
9299 itself must not include any embedded spaces. If the compiler executable is
9300 different from the default one (gcc or <prefix>-gcc), then the back-end
9301 switches in the ALI file are not used to compile the binder generated source.
9302 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9303 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9304 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9305 is taken into account. However, all the additional switches are also taken
9306 into account. Thus,
9307 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9308 @option{--GCC="bar -x -y -z -t"}.
9309
9310 @item --LINK=@var{name}
9311 @cindex @option{--LINK=} (@command{gnatlink})
9312 @var{name} is the name of the linker to be invoked. This is especially
9313 useful in mixed language programs since languages such as C++ require
9314 their own linker to be used. When this switch is omitted, the default
9315 name for the linker is @command{gcc}. When this switch is used, the
9316 specified linker is called instead of @command{gcc} with exactly the same
9317 parameters that would have been passed to @command{gcc} so if the desired
9318 linker requires different parameters it is necessary to use a wrapper
9319 script that massages the parameters before invoking the real linker. It
9320 may be useful to control the exact invocation by using the verbose
9321 switch.
9322
9323 @end ifclear
9324
9325 @ifset vms
9326 @item /DEBUG=TRACEBACK
9327 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9328 This qualifier causes sufficient information to be included in the
9329 executable file to allow a traceback, but does not include the full
9330 symbol information needed by the debugger.
9331
9332 @item /IDENTIFICATION="<string>"
9333 @code{"<string>"} specifies the string to be stored in the image file
9334 identification field in the image header.
9335 It overrides any pragma @code{Ident} specified string.
9336
9337 @item /NOINHIBIT-EXEC
9338 Generate the executable file even if there are linker warnings.
9339
9340 @item /NOSTART_FILES
9341 Don't link in the object file containing the ``main'' transfer address.
9342 Used when linking with a foreign language main program compiled with an
9343 HP compiler.
9344
9345 @item /STATIC
9346 Prefer linking with object libraries over sharable images, even without
9347 /DEBUG.
9348 @end ifset
9349
9350 @end table
9351
9352 @node The GNAT Make Program gnatmake
9353 @chapter The GNAT Make Program @command{gnatmake}
9354 @findex gnatmake
9355
9356 @menu
9357 * Running gnatmake::
9358 * Switches for gnatmake::
9359 * Mode Switches for gnatmake::
9360 * Notes on the Command Line::
9361 * How gnatmake Works::
9362 * Examples of gnatmake Usage::
9363 @end menu
9364 @noindent
9365 A typical development cycle when working on an Ada program consists of
9366 the following steps:
9367
9368 @enumerate
9369 @item
9370 Edit some sources to fix bugs.
9371
9372 @item
9373 Add enhancements.
9374
9375 @item
9376 Compile all sources affected.
9377
9378 @item
9379 Rebind and relink.
9380
9381 @item
9382 Test.
9383 @end enumerate
9384
9385 @noindent
9386 The third step can be tricky, because not only do the modified files
9387 @cindex Dependency rules
9388 have to be compiled, but any files depending on these files must also be
9389 recompiled. The dependency rules in Ada can be quite complex, especially
9390 in the presence of overloading, @code{use} clauses, generics and inlined
9391 subprograms.
9392
9393 @command{gnatmake} automatically takes care of the third and fourth steps
9394 of this process. It determines which sources need to be compiled,
9395 compiles them, and binds and links the resulting object files.
9396
9397 Unlike some other Ada make programs, the dependencies are always
9398 accurately recomputed from the new sources. The source based approach of
9399 the GNAT compilation model makes this possible. This means that if
9400 changes to the source program cause corresponding changes in
9401 dependencies, they will always be tracked exactly correctly by
9402 @command{gnatmake}.
9403
9404 @node Running gnatmake
9405 @section Running @command{gnatmake}
9406
9407 @noindent
9408 The usual form of the @command{gnatmake} command is
9409
9410 @smallexample
9411 @c $ gnatmake @ovar{switches} @var{file_name}
9412 @c       @ovar{file_names} @ovar{mode_switches}
9413 @c Expanding @ovar macro inline (explanation in macro def comments)
9414 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9415       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9416 @end smallexample
9417
9418 @noindent
9419 The only required argument is one @var{file_name}, which specifies
9420 a compilation unit that is a main program. Several @var{file_names} can be
9421 specified: this will result in several executables being built.
9422 If @code{switches} are present, they can be placed before the first
9423 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9424 If @var{mode_switches} are present, they must always be placed after
9425 the last @var{file_name} and all @code{switches}.
9426
9427 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9428 extension may be omitted from the @var{file_name} arguments. However, if
9429 you are using non-standard extensions, then it is required that the
9430 extension be given. A relative or absolute directory path can be
9431 specified in a @var{file_name}, in which case, the input source file will
9432 be searched for in the specified directory only. Otherwise, the input
9433 source file will first be searched in the directory where
9434 @command{gnatmake} was invoked and if it is not found, it will be search on
9435 the source path of the compiler as described in
9436 @ref{Search Paths and the Run-Time Library (RTL)}.
9437
9438 All @command{gnatmake} output (except when you specify
9439 @option{^-M^/DEPENDENCIES_LIST^}) is to
9440 @file{stderr}. The output produced by the
9441 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9442 @file{stdout}.
9443
9444 @node Switches for gnatmake
9445 @section Switches for @command{gnatmake}
9446
9447 @noindent
9448 You may specify any of the following switches to @command{gnatmake}:
9449
9450 @table @option
9451 @c !sort!
9452
9453 @item --version
9454 @cindex @option{--version} @command{gnatmake}
9455 Display Copyright and version, then exit disregarding all other options.
9456
9457 @item --help
9458 @cindex @option{--help} @command{gnatmake}
9459 If @option{--version} was not used, display usage, then exit disregarding
9460 all other options.
9461
9462 @ifclear vms
9463 @item --GCC=@var{compiler_name}
9464 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9465 Program used for compiling. The default is `@command{gcc}'. You need to use
9466 quotes around @var{compiler_name} if @code{compiler_name} contains
9467 spaces or other separator characters. As an example @option{--GCC="foo -x
9468 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9469 compiler. A limitation of this syntax is that the name and path name of
9470 the executable itself must not include any embedded spaces. Note that
9471 switch @option{-c} is always inserted after your command name. Thus in the
9472 above example the compiler command that will be used by @command{gnatmake}
9473 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9474 used, only the last @var{compiler_name} is taken into account. However,
9475 all the additional switches are also taken into account. Thus,
9476 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9477 @option{--GCC="bar -x -y -z -t"}.
9478
9479 @item --GNATBIND=@var{binder_name}
9480 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9481 Program used for binding. The default is `@code{gnatbind}'. You need to
9482 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9483 or other separator characters. As an example @option{--GNATBIND="bar -x
9484 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9485 binder. Binder switches that are normally appended by @command{gnatmake}
9486 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9487 A limitation of this syntax is that the name and path name of the executable
9488 itself must not include any embedded spaces.
9489
9490 @item --GNATLINK=@var{linker_name}
9491 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9492 Program used for linking. The default is `@command{gnatlink}'. You need to
9493 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9494 or other separator characters. As an example @option{--GNATLINK="lan -x
9495 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9496 linker. Linker switches that are normally appended by @command{gnatmake} to
9497 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9498 A limitation of this syntax is that the name and path name of the executable
9499 itself must not include any embedded spaces.
9500
9501 @end ifclear
9502
9503 @item ^--subdirs^/SUBDIRS^=subdir
9504 Actual object directory of each project file is the subdirectory subdir of the
9505 object directory specified or defaulted in the project file.
9506
9507 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9508 Disallow simultaneous compilations in the same object directory when
9509 project files are used.
9510
9511 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9512 By default, shared library projects are not allowed to import static library
9513 projects. When this switch is used on the command line, this restriction is
9514 relaxed.
9515
9516 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9517 Specify a source info file. This switch is active only when project files
9518 are used. If the source info file is specified as a relative path, then it is
9519 relative to the object directory of the main project. If the source info file
9520 does not exist, then after the Project Manager has successfully parsed and
9521 processed the project files and found the sources, it creates the source info
9522 file. If the source info file already exists and can be read successfully,
9523 then the Project Manager will get all the needed information about the sources
9524 from the source info file and will not look for them. This reduces the time
9525 to process the project files, especially when looking for sources that take a
9526 long time. If the source info file exists but cannot be parsed successfully,
9527 the Project Manager will attempt to recreate it. If the Project Manager fails
9528 to create the source info file, a message is issued, but gnatmake does not
9529 fail. @command{gnatmake} "trusts" the source info file. This means that
9530 if the source files have changed (addition, deletion, moving to a different
9531 source directory), then the source info file need to be deleted and recreated.
9532
9533 @ifclear vms
9534 @item --create-map-file
9535 When linking an executable, create a map file. The name of the map file
9536 has the same name as the executable with extension ".map".
9537
9538 @item --create-map-file=mapfile
9539 When linking an executable, create a map file. The name of the map file is
9540 "mapfile".
9541
9542 @end ifclear
9543
9544 @item ^-a^/ALL_FILES^
9545 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9546 Consider all files in the make process, even the GNAT internal system
9547 files (for example, the predefined Ada library files), as well as any
9548 locked files. Locked files are files whose ALI file is write-protected.
9549 By default,
9550 @command{gnatmake} does not check these files,
9551 because the assumption is that the GNAT internal files are properly up
9552 to date, and also that any write protected ALI files have been properly
9553 installed. Note that if there is an installation problem, such that one
9554 of these files is not up to date, it will be properly caught by the
9555 binder.
9556 You may have to specify this switch if you are working on GNAT
9557 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9558 in conjunction with @option{^-f^/FORCE_COMPILE^}
9559 if you need to recompile an entire application,
9560 including run-time files, using special configuration pragmas,
9561 such as a @code{Normalize_Scalars} pragma.
9562
9563 By default
9564 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9565 internal files with
9566 @ifclear vms
9567 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9568 @end ifclear
9569 @ifset vms
9570 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9571 @end ifset
9572
9573 @item ^-b^/ACTIONS=BIND^
9574 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9575 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9576 compilation and binding, but no link.
9577 Can be combined with @option{^-l^/ACTIONS=LINK^}
9578 to do binding and linking. When not combined with
9579 @option{^-c^/ACTIONS=COMPILE^}
9580 all the units in the closure of the main program must have been previously
9581 compiled and must be up to date. The root unit specified by @var{file_name}
9582 may be given without extension, with the source extension or, if no GNAT
9583 Project File is specified, with the ALI file extension.
9584
9585 @item ^-c^/ACTIONS=COMPILE^
9586 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9587 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9588 is also specified. Do not perform linking, except if both
9589 @option{^-b^/ACTIONS=BIND^} and
9590 @option{^-l^/ACTIONS=LINK^} are also specified.
9591 If the root unit specified by @var{file_name} is not a main unit, this is the
9592 default. Otherwise @command{gnatmake} will attempt binding and linking
9593 unless all objects are up to date and the executable is more recent than
9594 the objects.
9595
9596 @item ^-C^/MAPPING^
9597 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9598 Use a temporary mapping file. A mapping file is a way to communicate
9599 to the compiler two mappings: from unit names to file names (without
9600 any directory information) and from file names to path names (with
9601 full directory information). A mapping file can make the compiler's
9602 file searches faster, especially if there are many source directories,
9603 or the sources are read over a slow network connection. If
9604 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9605 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9606 is initially populated based on the project file. If
9607 @option{^-C^/MAPPING^} is used without
9608 @option{^-P^/PROJECT_FILE^},
9609 the mapping file is initially empty. Each invocation of the compiler
9610 will add any newly accessed sources to the mapping file.
9611
9612 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9613 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9614 Use a specific mapping file. The file, specified as a path name (absolute or
9615 relative) by this switch, should already exist, otherwise the switch is
9616 ineffective. The specified mapping file will be communicated to the compiler.
9617 This switch is not compatible with a project file
9618 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9619 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9620
9621 @item ^-d^/DISPLAY_PROGRESS^
9622 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9623 Display progress for each source, up to date or not, as a single line
9624
9625 @smallexample
9626 completed x out of y (zz%)
9627 @end smallexample
9628
9629 If the file needs to be compiled this is displayed after the invocation of
9630 the compiler. These lines are displayed even in quiet output mode.
9631
9632 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9633 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9634 Put all object files and ALI file in directory @var{dir}.
9635 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9636 and ALI files go in the current working directory.
9637
9638 This switch cannot be used when using a project file.
9639
9640 @item -eInnn
9641 @cindex @option{-eI} (@command{gnatmake})
9642 Indicates that the main source is a multi-unit source and the rank of the unit
9643 in the source file is nnn. nnn needs to be a positive number and a valid
9644 index in the source. This switch cannot be used when @command{gnatmake} is
9645 invoked for several mains.
9646
9647 @ifclear vms
9648 @item -eL
9649 @cindex @option{-eL} (@command{gnatmake})
9650 @cindex symbolic links
9651 Follow all symbolic links when processing project files.
9652 This should be used if your project uses symbolic links for files or
9653 directories, but is not needed in other cases.
9654
9655 @cindex naming scheme
9656 This also assumes that no directory matches the naming scheme for files (for
9657 instance that you do not have a directory called "sources.ads" when using the
9658 default GNAT naming scheme).
9659
9660 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9661 save a lot of system calls (several per source file and object file), which
9662 can result in a significant speed up to load and manipulate a project file,
9663 especially when using source files from a remote system.
9664
9665 @end ifclear
9666
9667 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9668 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9669 Output the commands for the compiler, the binder and the linker
9670 on ^standard output^SYS$OUTPUT^,
9671 instead of ^standard error^SYS$ERROR^.
9672
9673 @item ^-f^/FORCE_COMPILE^
9674 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9675 Force recompilations. Recompile all sources, even though some object
9676 files may be up to date, but don't recompile predefined or GNAT internal
9677 files or locked files (files with a write-protected ALI file),
9678 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9679
9680 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9681 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9682 When using project files, if some errors or warnings are detected during
9683 parsing and verbose mode is not in effect (no use of switch
9684 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9685 file, rather than its simple file name.
9686
9687 @item ^-g^/DEBUG^
9688 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9689 Enable debugging. This switch is simply passed to the compiler and to the
9690 linker.
9691
9692 @item ^-i^/IN_PLACE^
9693 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9694 In normal mode, @command{gnatmake} compiles all object files and ALI files
9695 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9696 then instead object files and ALI files that already exist are overwritten
9697 in place. This means that once a large project is organized into separate
9698 directories in the desired manner, then @command{gnatmake} will automatically
9699 maintain and update this organization. If no ALI files are found on the
9700 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9701 the new object and ALI files are created in the
9702 directory containing the source being compiled. If another organization
9703 is desired, where objects and sources are kept in different directories,
9704 a useful technique is to create dummy ALI files in the desired directories.
9705 When detecting such a dummy file, @command{gnatmake} will be forced to
9706 recompile the corresponding source file, and it will be put the resulting
9707 object and ALI files in the directory where it found the dummy file.
9708
9709 @item ^-j^/PROCESSES=^@var{n}
9710 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9711 @cindex Parallel make
9712 Use @var{n} processes to carry out the (re)compilations. On a
9713 multiprocessor machine compilations will occur in parallel. In the
9714 event of compilation errors, messages from various compilations might
9715 get interspersed (but @command{gnatmake} will give you the full ordered
9716 list of failing compiles at the end). If this is problematic, rerun
9717 the make process with n set to 1 to get a clean list of messages.
9718
9719 @item ^-k^/CONTINUE_ON_ERROR^
9720 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9721 Keep going. Continue as much as possible after a compilation error. To
9722 ease the programmer's task in case of compilation errors, the list of
9723 sources for which the compile fails is given when @command{gnatmake}
9724 terminates.
9725
9726 If @command{gnatmake} is invoked with several @file{file_names} and with this
9727 switch, if there are compilation errors when building an executable,
9728 @command{gnatmake} will not attempt to build the following executables.
9729
9730 @item ^-l^/ACTIONS=LINK^
9731 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9732 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9733 and linking. Linking will not be performed if combined with
9734 @option{^-c^/ACTIONS=COMPILE^}
9735 but not with @option{^-b^/ACTIONS=BIND^}.
9736 When not combined with @option{^-b^/ACTIONS=BIND^}
9737 all the units in the closure of the main program must have been previously
9738 compiled and must be up to date, and the main program needs to have been bound.
9739 The root unit specified by @var{file_name}
9740 may be given without extension, with the source extension or, if no GNAT
9741 Project File is specified, with the ALI file extension.
9742
9743 @item ^-m^/MINIMAL_RECOMPILATION^
9744 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9745 Specify that the minimum necessary amount of recompilations
9746 be performed. In this mode @command{gnatmake} ignores time
9747 stamp differences when the only
9748 modifications to a source file consist in adding/removing comments,
9749 empty lines, spaces or tabs. This means that if you have changed the
9750 comments in a source file or have simply reformatted it, using this
9751 switch will tell @command{gnatmake} not to recompile files that depend on it
9752 (provided other sources on which these files depend have undergone no
9753 semantic modifications). Note that the debugging information may be
9754 out of date with respect to the sources if the @option{-m} switch causes
9755 a compilation to be switched, so the use of this switch represents a
9756 trade-off between compilation time and accurate debugging information.
9757
9758 @item ^-M^/DEPENDENCIES_LIST^
9759 @cindex Dependencies, producing list
9760 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9761 Check if all objects are up to date. If they are, output the object
9762 dependences to @file{stdout} in a form that can be directly exploited in
9763 a @file{Makefile}. By default, each source file is prefixed with its
9764 (relative or absolute) directory name. This name is whatever you
9765 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9766 and @option{^-I^/SEARCH^} switches. If you use
9767 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9768 @option{^-q^/QUIET^}
9769 (see below), only the source file names,
9770 without relative paths, are output. If you just specify the
9771 @option{^-M^/DEPENDENCIES_LIST^}
9772 switch, dependencies of the GNAT internal system files are omitted. This
9773 is typically what you want. If you also specify
9774 the @option{^-a^/ALL_FILES^} switch,
9775 dependencies of the GNAT internal files are also listed. Note that
9776 dependencies of the objects in external Ada libraries (see switch
9777 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9778 are never reported.
9779
9780 @item ^-n^/DO_OBJECT_CHECK^
9781 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9782 Don't compile, bind, or link. Checks if all objects are up to date.
9783 If they are not, the full name of the first file that needs to be
9784 recompiled is printed.
9785 Repeated use of this option, followed by compiling the indicated source
9786 file, will eventually result in recompiling all required units.
9787
9788 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9789 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9790 Output executable name. The name of the final executable program will be
9791 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9792 name for the executable will be the name of the input file in appropriate form
9793 for an executable file on the host system.
9794
9795 This switch cannot be used when invoking @command{gnatmake} with several
9796 @file{file_names}.
9797
9798 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9799 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9800 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9801 automatically missing object directories, library directories and exec
9802 directories.
9803
9804 @item ^-P^/PROJECT_FILE=^@var{project}
9805 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9806 Use project file @var{project}. Only one such switch can be used.
9807 @xref{gnatmake and Project Files}.
9808
9809 @item ^-q^/QUIET^
9810 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9811 Quiet. When this flag is not set, the commands carried out by
9812 @command{gnatmake} are displayed.
9813
9814 @item ^-s^/SWITCH_CHECK/^
9815 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9816 Recompile if compiler switches have changed since last compilation.
9817 All compiler switches but -I and -o are taken into account in the
9818 following way:
9819 orders between different ``first letter'' switches are ignored, but
9820 orders between same switches are taken into account. For example,
9821 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9822 is equivalent to @option{-O -g}.
9823
9824 This switch is recommended when Integrated Preprocessing is used.
9825
9826 @item ^-u^/UNIQUE^
9827 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9828 Unique. Recompile at most the main files. It implies -c. Combined with
9829 -f, it is equivalent to calling the compiler directly. Note that using
9830 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9831 (@pxref{Project Files and Main Subprograms}).
9832
9833 @item ^-U^/ALL_PROJECTS^
9834 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9835 When used without a project file or with one or several mains on the command
9836 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9837 on the command line, all sources of all project files are checked and compiled
9838 if not up to date, and libraries are rebuilt, if necessary.
9839
9840 @item ^-v^/REASONS^
9841 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9842 Verbose. Display the reason for all recompilations @command{gnatmake}
9843 decides are necessary, with the highest verbosity level.
9844
9845 @item ^-vl^/LOW_VERBOSITY^
9846 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9847 Verbosity level Low. Display fewer lines than in verbosity Medium.
9848
9849 @item ^-vm^/MEDIUM_VERBOSITY^
9850 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9851 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9852
9853 @item ^-vh^/HIGH_VERBOSITY^
9854 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9855 Verbosity level High. Equivalent to ^-v^/REASONS^.
9856
9857 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9858 Indicate the verbosity of the parsing of GNAT project files.
9859 @xref{Switches Related to Project Files}.
9860
9861 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9862 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9863 Indicate that sources that are not part of any Project File may be compiled.
9864 Normally, when using Project Files, only sources that are part of a Project
9865 File may be compile. When this switch is used, a source outside of all Project
9866 Files may be compiled. The ALI file and the object file will be put in the
9867 object directory of the main Project. The compilation switches used will only
9868 be those specified on the command line. Even when
9869 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9870 command line need to be sources of a project file.
9871
9872 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9873 Indicate that external variable @var{name} has the value @var{value}.
9874 The Project Manager will use this value for occurrences of
9875 @code{external(name)} when parsing the project file.
9876 @xref{Switches Related to Project Files}.
9877
9878 @item ^-z^/NOMAIN^
9879 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9880 No main subprogram. Bind and link the program even if the unit name
9881 given on the command line is a package name. The resulting executable
9882 will execute the elaboration routines of the package and its closure,
9883 then the finalization routines.
9884
9885 @end table
9886
9887 @table @asis
9888 @item @command{gcc} @asis{switches}
9889 @ifclear vms
9890 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9891 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9892 @end ifclear
9893 @ifset vms
9894 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9895 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9896 automatically treated as a compiler switch, and passed on to all
9897 compilations that are carried out.
9898 @end ifset
9899 @end table
9900
9901 @noindent
9902 Source and library search path switches:
9903
9904 @table @option
9905 @c !sort!
9906 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9907 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9908 When looking for source files also look in directory @var{dir}.
9909 The order in which source files search is undertaken is
9910 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9911
9912 @item ^-aL^/SKIP_MISSING=^@var{dir}
9913 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9914 Consider @var{dir} as being an externally provided Ada library.
9915 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9916 files have been located in directory @var{dir}. This allows you to have
9917 missing bodies for the units in @var{dir} and to ignore out of date bodies
9918 for the same units. You still need to specify
9919 the location of the specs for these units by using the switches
9920 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9921 or @option{^-I^/SEARCH=^@var{dir}}.
9922 Note: this switch is provided for compatibility with previous versions
9923 of @command{gnatmake}. The easier method of causing standard libraries
9924 to be excluded from consideration is to write-protect the corresponding
9925 ALI files.
9926
9927 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9928 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9929 When searching for library and object files, look in directory
9930 @var{dir}. The order in which library files are searched is described in
9931 @ref{Search Paths for gnatbind}.
9932
9933 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9934 @cindex Search paths, for @command{gnatmake}
9935 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9936 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9937 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9938
9939 @item ^-I^/SEARCH=^@var{dir}
9940 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9941 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9942 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9943
9944 @item ^-I-^/NOCURRENT_DIRECTORY^
9945 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9946 @cindex Source files, suppressing search
9947 Do not look for source files in the directory containing the source
9948 file named in the command line.
9949 Do not look for ALI or object files in the directory
9950 where @command{gnatmake} was invoked.
9951
9952 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9953 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9954 @cindex Linker libraries
9955 Add directory @var{dir} to the list of directories in which the linker
9956 will search for libraries. This is equivalent to
9957 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9958 @ifclear vms
9959 Furthermore, under Windows, the sources pointed to by the libraries path
9960 set in the registry are not searched for.
9961 @end ifclear
9962
9963 @item -nostdinc
9964 @cindex @option{-nostdinc} (@command{gnatmake})
9965 Do not look for source files in the system default directory.
9966
9967 @item -nostdlib
9968 @cindex @option{-nostdlib} (@command{gnatmake})
9969 Do not look for library files in the system default directory.
9970
9971 @item --RTS=@var{rts-path}
9972 @cindex @option{--RTS} (@command{gnatmake})
9973 Specifies the default location of the runtime library. GNAT looks for the
9974 runtime
9975 in the following directories, and stops as soon as a valid runtime is found
9976 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9977 @file{ada_object_path} present):
9978
9979 @itemize @bullet
9980 @item <current directory>/$rts_path
9981
9982 @item <default-search-dir>/$rts_path
9983
9984 @item <default-search-dir>/rts-$rts_path
9985 @end itemize
9986
9987 @noindent
9988 The selected path is handled like a normal RTS path.
9989
9990 @end table
9991
9992 @node Mode Switches for gnatmake
9993 @section Mode Switches for @command{gnatmake}
9994
9995 @noindent
9996 The mode switches (referred to as @code{mode_switches}) allow the
9997 inclusion of switches that are to be passed to the compiler itself, the
9998 binder or the linker. The effect of a mode switch is to cause all
9999 subsequent switches up to the end of the switch list, or up to the next
10000 mode switch, to be interpreted as switches to be passed on to the
10001 designated component of GNAT.
10002
10003 @table @option
10004 @c !sort!
10005 @item -cargs @var{switches}
10006 @cindex @option{-cargs} (@command{gnatmake})
10007 Compiler switches. Here @var{switches} is a list of switches
10008 that are valid switches for @command{gcc}. They will be passed on to
10009 all compile steps performed by @command{gnatmake}.
10010
10011 @item -bargs @var{switches}
10012 @cindex @option{-bargs} (@command{gnatmake})
10013 Binder switches. Here @var{switches} is a list of switches
10014 that are valid switches for @code{gnatbind}. They will be passed on to
10015 all bind steps performed by @command{gnatmake}.
10016
10017 @item -largs @var{switches}
10018 @cindex @option{-largs} (@command{gnatmake})
10019 Linker switches. Here @var{switches} is a list of switches
10020 that are valid switches for @command{gnatlink}. They will be passed on to
10021 all link steps performed by @command{gnatmake}.
10022
10023 @item -margs @var{switches}
10024 @cindex @option{-margs} (@command{gnatmake})
10025 Make switches. The switches are directly interpreted by @command{gnatmake},
10026 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10027 or @option{-largs}.
10028 @end table
10029
10030 @node Notes on the Command Line
10031 @section Notes on the Command Line
10032
10033 @noindent
10034 This section contains some additional useful notes on the operation
10035 of the @command{gnatmake} command.
10036
10037 @itemize @bullet
10038 @item
10039 @cindex Recompilation, by @command{gnatmake}
10040 If @command{gnatmake} finds no ALI files, it recompiles the main program
10041 and all other units required by the main program.
10042 This means that @command{gnatmake}
10043 can be used for the initial compile, as well as during subsequent steps of
10044 the development cycle.
10045
10046 @item
10047 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10048 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10049 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10050 warning.
10051
10052 @item
10053 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10054 is used to specify both source and
10055 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10056 instead if you just want to specify
10057 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10058 if you want to specify library paths
10059 only.
10060
10061 @item
10062 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10063 This may conveniently be used to exclude standard libraries from
10064 consideration and in particular it means that the use of the
10065 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10066 unless @option{^-a^/ALL_FILES^} is also specified.
10067
10068 @item
10069 @command{gnatmake} has been designed to make the use of Ada libraries
10070 particularly convenient. Assume you have an Ada library organized
10071 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10072 of your Ada compilation units,
10073 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10074 specs of these units, but no bodies. Then to compile a unit
10075 stored in @code{main.adb}, which uses this Ada library you would just type
10076
10077 @smallexample
10078 @ifclear vms
10079 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10080 @end ifclear
10081 @ifset vms
10082 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10083            /SKIP_MISSING=@i{[OBJ_DIR]} main
10084 @end ifset
10085 @end smallexample
10086
10087 @item
10088 Using @command{gnatmake} along with the
10089 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10090 switch provides a mechanism for avoiding unnecessary recompilations. Using
10091 this switch,
10092 you can update the comments/format of your
10093 source files without having to recompile everything. Note, however, that
10094 adding or deleting lines in a source files may render its debugging
10095 info obsolete. If the file in question is a spec, the impact is rather
10096 limited, as that debugging info will only be useful during the
10097 elaboration phase of your program. For bodies the impact can be more
10098 significant. In all events, your debugger will warn you if a source file
10099 is more recent than the corresponding object, and alert you to the fact
10100 that the debugging information may be out of date.
10101 @end itemize
10102
10103 @node How gnatmake Works
10104 @section How @command{gnatmake} Works
10105
10106 @noindent
10107 Generally @command{gnatmake} automatically performs all necessary
10108 recompilations and you don't need to worry about how it works. However,
10109 it may be useful to have some basic understanding of the @command{gnatmake}
10110 approach and in particular to understand how it uses the results of
10111 previous compilations without incorrectly depending on them.
10112
10113 First a definition: an object file is considered @dfn{up to date} if the
10114 corresponding ALI file exists and if all the source files listed in the
10115 dependency section of this ALI file have time stamps matching those in
10116 the ALI file. This means that neither the source file itself nor any
10117 files that it depends on have been modified, and hence there is no need
10118 to recompile this file.
10119
10120 @command{gnatmake} works by first checking if the specified main unit is up
10121 to date. If so, no compilations are required for the main unit. If not,
10122 @command{gnatmake} compiles the main program to build a new ALI file that
10123 reflects the latest sources. Then the ALI file of the main unit is
10124 examined to find all the source files on which the main program depends,
10125 and @command{gnatmake} recursively applies the above procedure on all these
10126 files.
10127
10128 This process ensures that @command{gnatmake} only trusts the dependencies
10129 in an existing ALI file if they are known to be correct. Otherwise it
10130 always recompiles to determine a new, guaranteed accurate set of
10131 dependencies. As a result the program is compiled ``upside down'' from what may
10132 be more familiar as the required order of compilation in some other Ada
10133 systems. In particular, clients are compiled before the units on which
10134 they depend. The ability of GNAT to compile in any order is critical in
10135 allowing an order of compilation to be chosen that guarantees that
10136 @command{gnatmake} will recompute a correct set of new dependencies if
10137 necessary.
10138
10139 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10140 imported by several of the executables, it will be recompiled at most once.
10141
10142 Note: when using non-standard naming conventions
10143 (@pxref{Using Other File Names}), changing through a configuration pragmas
10144 file the version of a source and invoking @command{gnatmake} to recompile may
10145 have no effect, if the previous version of the source is still accessible
10146 by @command{gnatmake}. It may be necessary to use the switch
10147 ^-f^/FORCE_COMPILE^.
10148
10149 @node Examples of gnatmake Usage
10150 @section Examples of @command{gnatmake} Usage
10151
10152 @table @code
10153 @item gnatmake hello.adb
10154 Compile all files necessary to bind and link the main program
10155 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10156 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10157
10158 @item gnatmake main1 main2 main3
10159 Compile all files necessary to bind and link the main programs
10160 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10161 (containing unit @code{Main2}) and @file{main3.adb}
10162 (containing unit @code{Main3}) and bind and link the resulting object files
10163 to generate three executable files @file{^main1^MAIN1.EXE^},
10164 @file{^main2^MAIN2.EXE^}
10165 and @file{^main3^MAIN3.EXE^}.
10166
10167 @ifclear vms
10168 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10169 @end ifclear
10170
10171 @ifset vms
10172 @item gnatmake Main_Unit /QUIET
10173 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10174 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10175 @end ifset
10176 Compile all files necessary to bind and link the main program unit
10177 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10178 be done with optimization level 2 and the order of elaboration will be
10179 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10180 displaying commands it is executing.
10181 @end table
10182
10183 @c *************************
10184 @node Improving Performance
10185 @chapter Improving Performance
10186 @cindex Improving performance
10187
10188 @noindent
10189 This chapter presents several topics related to program performance.
10190 It first describes some of the tradeoffs that need to be considered
10191 and some of the techniques for making your program run faster.
10192 It then documents the @command{gnatelim} tool and unused subprogram/data
10193 elimination feature, which can reduce the size of program executables.
10194
10195 @ifnottex
10196 @menu
10197 * Performance Considerations::
10198 * Text_IO Suggestions::
10199 * Reducing Size of Ada Executables with gnatelim::
10200 * Reducing Size of Executables with unused subprogram/data elimination::
10201 @end menu
10202 @end ifnottex
10203
10204 @c *****************************
10205 @node Performance Considerations
10206 @section Performance Considerations
10207
10208 @noindent
10209 The GNAT system provides a number of options that allow a trade-off
10210 between
10211
10212 @itemize @bullet
10213 @item
10214 performance of the generated code
10215
10216 @item
10217 speed of compilation
10218
10219 @item
10220 minimization of dependences and recompilation
10221
10222 @item
10223 the degree of run-time checking.
10224 @end itemize
10225
10226 @noindent
10227 The defaults (if no options are selected) aim at improving the speed
10228 of compilation and minimizing dependences, at the expense of performance
10229 of the generated code:
10230
10231 @itemize @bullet
10232 @item
10233 no optimization
10234
10235 @item
10236 no inlining of subprogram calls
10237
10238 @item
10239 all run-time checks enabled except overflow and elaboration checks
10240 @end itemize
10241
10242 @noindent
10243 These options are suitable for most program development purposes. This
10244 chapter describes how you can modify these choices, and also provides
10245 some guidelines on debugging optimized code.
10246
10247 @menu
10248 * Controlling Run-Time Checks::
10249 * Use of Restrictions::
10250 * Optimization Levels::
10251 * Debugging Optimized Code::
10252 * Inlining of Subprograms::
10253 * Vectorization of loops::
10254 * Other Optimization Switches::
10255 * Optimization and Strict Aliasing::
10256
10257 @ifset vms
10258 * Coverage Analysis::
10259 @end ifset
10260 @end menu
10261
10262 @node Controlling Run-Time Checks
10263 @subsection Controlling Run-Time Checks
10264
10265 @noindent
10266 By default, GNAT generates all run-time checks, except integer overflow
10267 checks, stack overflow checks, and checks for access before elaboration on
10268 subprogram calls. The latter are not required in default mode, because all
10269 necessary checking is done at compile time.
10270 @cindex @option{-gnatp} (@command{gcc})
10271 @cindex @option{-gnato} (@command{gcc})
10272 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10273 be modified. @xref{Run-Time Checks}.
10274
10275 Our experience is that the default is suitable for most development
10276 purposes.
10277
10278 We treat integer overflow specially because these
10279 are quite expensive and in our experience are not as important as other
10280 run-time checks in the development process. Note that division by zero
10281 is not considered an overflow check, and divide by zero checks are
10282 generated where required by default.
10283
10284 Elaboration checks are off by default, and also not needed by default, since
10285 GNAT uses a static elaboration analysis approach that avoids the need for
10286 run-time checking. This manual contains a full chapter discussing the issue
10287 of elaboration checks, and if the default is not satisfactory for your use,
10288 you should read this chapter.
10289
10290 For validity checks, the minimal checks required by the Ada Reference
10291 Manual (for case statements and assignments to array elements) are on
10292 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10293 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10294 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10295 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10296 are also suppressed entirely if @option{-gnatp} is used.
10297
10298 @cindex Overflow checks
10299 @cindex Checks, overflow
10300 @findex Suppress
10301 @findex Unsuppress
10302 @cindex pragma Suppress
10303 @cindex pragma Unsuppress
10304 Note that the setting of the switches controls the default setting of
10305 the checks. They may be modified using either @code{pragma Suppress} (to
10306 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10307 checks) in the program source.
10308
10309 @node Use of Restrictions
10310 @subsection Use of Restrictions
10311
10312 @noindent
10313 The use of pragma Restrictions allows you to control which features are
10314 permitted in your program. Apart from the obvious point that if you avoid
10315 relatively expensive features like finalization (enforceable by the use
10316 of pragma Restrictions (No_Finalization), the use of this pragma does not
10317 affect the generated code in most cases.
10318
10319 One notable exception to this rule is that the possibility of task abort
10320 results in some distributed overhead, particularly if finalization or
10321 exception handlers are used. The reason is that certain sections of code
10322 have to be marked as non-abortable.
10323
10324 If you use neither the @code{abort} statement, nor asynchronous transfer
10325 of control (@code{select @dots{} then abort}), then this distributed overhead
10326 is removed, which may have a general positive effect in improving
10327 overall performance.  Especially code involving frequent use of tasking
10328 constructs and controlled types will show much improved performance.
10329 The relevant restrictions pragmas are
10330
10331 @smallexample @c ada
10332    pragma Restrictions (No_Abort_Statements);
10333    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10334 @end smallexample
10335
10336 @noindent
10337 It is recommended that these restriction pragmas be used if possible. Note
10338 that this also means that you can write code without worrying about the
10339 possibility of an immediate abort at any point.
10340
10341 @node Optimization Levels
10342 @subsection Optimization Levels
10343 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10344
10345 @noindent
10346 Without any optimization ^option,^qualifier,^
10347 the compiler's goal is to reduce the cost of
10348 compilation and to make debugging produce the expected results.
10349 Statements are independent: if you stop the program with a breakpoint between
10350 statements, you can then assign a new value to any variable or change
10351 the program counter to any other statement in the subprogram and get exactly
10352 the results you would expect from the source code.
10353
10354 Turning on optimization makes the compiler attempt to improve the
10355 performance and/or code size at the expense of compilation time and
10356 possibly the ability to debug the program.
10357
10358 If you use multiple
10359 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10360 the last such option is the one that is effective.
10361
10362 @noindent
10363 The default is optimization off. This results in the fastest compile
10364 times, but GNAT makes absolutely no attempt to optimize, and the
10365 generated programs are considerably larger and slower than when
10366 optimization is enabled. You can use the
10367 @ifclear vms
10368 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10369 @option{-O2}, @option{-O3}, and @option{-Os})
10370 @end ifclear
10371 @ifset vms
10372 @code{OPTIMIZE} qualifier
10373 @end ifset
10374 to @command{gcc} to control the optimization level:
10375
10376 @table @option
10377 @item ^-O0^/OPTIMIZE=NONE^
10378 No optimization (the default);
10379 generates unoptimized code but has
10380 the fastest compilation time.
10381
10382 Note that many other compilers do fairly extensive optimization
10383 even if ``no optimization'' is specified. With gcc, it is
10384 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10385 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10386 really does mean no optimization at all. This difference between
10387 gcc and other compilers should be kept in mind when doing
10388 performance comparisons.
10389
10390 @item ^-O1^/OPTIMIZE=SOME^
10391 Moderate optimization;
10392 optimizes reasonably well but does not
10393 degrade compilation time significantly.
10394
10395 @item ^-O2^/OPTIMIZE=ALL^
10396 @ifset vms
10397 @itemx /OPTIMIZE=DEVELOPMENT
10398 @end ifset
10399 Full optimization;
10400 generates highly optimized code and has
10401 the slowest compilation time.
10402
10403 @item ^-O3^/OPTIMIZE=INLINING^
10404 Full optimization as in @option{-O2};
10405 also uses more aggressive automatic inlining of subprograms within a unit
10406 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10407
10408 @item ^-Os^/OPTIMIZE=SPACE^
10409 Optimize space usage (code and data) of resulting program.
10410 @end table
10411
10412 @noindent
10413 Higher optimization levels perform more global transformations on the
10414 program and apply more expensive analysis algorithms in order to generate
10415 faster and more compact code. The price in compilation time, and the
10416 resulting improvement in execution time,
10417 both depend on the particular application and the hardware environment.
10418 You should experiment to find the best level for your application.
10419
10420 Since the precise set of optimizations done at each level will vary from
10421 release to release (and sometime from target to target), it is best to think
10422 of the optimization settings in general terms.
10423 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10424 the GNU Compiler Collection (GCC)}, for details about
10425 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10426 individually enable or disable specific optimizations.
10427
10428 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10429 been tested extensively at all optimization levels. There are some bugs
10430 which appear only with optimization turned on, but there have also been
10431 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10432 level of optimization does not improve the reliability of the code
10433 generator, which in practice is highly reliable at all optimization
10434 levels.
10435
10436 Note regarding the use of @option{-O3}: The use of this optimization level
10437 is generally discouraged with GNAT, since it often results in larger
10438 executables which may run more slowly. See further discussion of this point
10439 in @ref{Inlining of Subprograms}.
10440
10441 @node Debugging Optimized Code
10442 @subsection Debugging Optimized Code
10443 @cindex Debugging optimized code
10444 @cindex Optimization and debugging
10445
10446 @noindent
10447 Although it is possible to do a reasonable amount of debugging at
10448 @ifclear vms
10449 nonzero optimization levels,
10450 the higher the level the more likely that
10451 @end ifclear
10452 @ifset vms
10453 @option{/OPTIMIZE} settings other than @code{NONE},
10454 such settings will make it more likely that
10455 @end ifset
10456 source-level constructs will have been eliminated by optimization.
10457 For example, if a loop is strength-reduced, the loop
10458 control variable may be completely eliminated and thus cannot be
10459 displayed in the debugger.
10460 This can only happen at @option{-O2} or @option{-O3}.
10461 Explicit temporary variables that you code might be eliminated at
10462 ^level^setting^ @option{-O1} or higher.
10463
10464 The use of the @option{^-g^/DEBUG^} switch,
10465 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10466 which is needed for source-level debugging,
10467 affects the size of the program executable on disk,
10468 and indeed the debugging information can be quite large.
10469 However, it has no effect on the generated code (and thus does not
10470 degrade performance)
10471
10472 Since the compiler generates debugging tables for a compilation unit before
10473 it performs optimizations, the optimizing transformations may invalidate some
10474 of the debugging data.  You therefore need to anticipate certain
10475 anomalous situations that may arise while debugging optimized code.
10476 These are the most common cases:
10477
10478 @enumerate
10479 @item
10480 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10481 commands show
10482 the PC bouncing back and forth in the code.  This may result from any of
10483 the following optimizations:
10484
10485 @itemize @bullet
10486 @item
10487 @i{Common subexpression elimination:} using a single instance of code for a
10488 quantity that the source computes several times.  As a result you
10489 may not be able to stop on what looks like a statement.
10490
10491 @item
10492 @i{Invariant code motion:} moving an expression that does not change within a
10493 loop, to the beginning of the loop.
10494
10495 @item
10496 @i{Instruction scheduling:} moving instructions so as to
10497 overlap loads and stores (typically) with other code, or in
10498 general to move computations of values closer to their uses. Often
10499 this causes you to pass an assignment statement without the assignment
10500 happening and then later bounce back to the statement when the
10501 value is actually needed.  Placing a breakpoint on a line of code
10502 and then stepping over it may, therefore, not always cause all the
10503 expected side-effects.
10504 @end itemize
10505
10506 @item
10507 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10508 two identical pieces of code are merged and the program counter suddenly
10509 jumps to a statement that is not supposed to be executed, simply because
10510 it (and the code following) translates to the same thing as the code
10511 that @emph{was} supposed to be executed.  This effect is typically seen in
10512 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10513 a @code{break} in a C @code{^switch^switch^} statement.
10514
10515 @item
10516 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10517 There are various reasons for this effect:
10518
10519 @itemize @bullet
10520 @item
10521 In a subprogram prologue, a parameter may not yet have been moved to its
10522 ``home''.
10523
10524 @item
10525 A variable may be dead, and its register re-used.  This is
10526 probably the most common cause.
10527
10528 @item
10529 As mentioned above, the assignment of a value to a variable may
10530 have been moved.
10531
10532 @item
10533 A variable may be eliminated entirely by value propagation or
10534 other means.  In this case, GCC may incorrectly generate debugging
10535 information for the variable
10536 @end itemize
10537
10538 @noindent
10539 In general, when an unexpected value appears for a local variable or parameter
10540 you should first ascertain if that value was actually computed by
10541 your program, as opposed to being incorrectly reported by the debugger.
10542 Record fields or
10543 array elements in an object designated by an access value
10544 are generally less of a problem, once you have ascertained that the access
10545 value is sensible.
10546 Typically, this means checking variables in the preceding code and in the
10547 calling subprogram to verify that the value observed is explainable from other
10548 values (one must apply the procedure recursively to those
10549 other values); or re-running the code and stopping a little earlier
10550 (perhaps before the call) and stepping to better see how the variable obtained
10551 the value in question; or continuing to step @emph{from} the point of the
10552 strange value to see if code motion had simply moved the variable's
10553 assignments later.
10554 @end enumerate
10555
10556 @noindent
10557 In light of such anomalies, a recommended technique is to use @option{-O0}
10558 early in the software development cycle, when extensive debugging capabilities
10559 are most needed, and then move to @option{-O1} and later @option{-O2} as
10560 the debugger becomes less critical.
10561 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10562 a release management issue.
10563 @ifclear vms
10564 Note that if you use @option{-g} you can then use the @command{strip} program
10565 on the resulting executable,
10566 which removes both debugging information and global symbols.
10567 @end ifclear
10568
10569 @node Inlining of Subprograms
10570 @subsection Inlining of Subprograms
10571
10572 @noindent
10573 A call to a subprogram in the current unit is inlined if all the
10574 following conditions are met:
10575
10576 @itemize @bullet
10577 @item
10578 The optimization level is at least @option{-O1}.
10579
10580 @item
10581 The called subprogram is suitable for inlining: It must be small enough
10582 and not contain something that @command{gcc} cannot support in inlined
10583 subprograms.
10584
10585 @item
10586 @cindex pragma Inline
10587 @findex Inline
10588 Any one of the following applies: @code{pragma Inline} is applied to the
10589 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10590 subprogram is local to the unit and called once from within it; the
10591 subprogram is small and optimization level @option{-O2} is specified;
10592 optimization level @option{-O3}) is specified.
10593 @end itemize
10594
10595 @noindent
10596 Calls to subprograms in @code{with}'ed units are normally not inlined.
10597 To achieve actual inlining (that is, replacement of the call by the code
10598 in the body of the subprogram), the following conditions must all be true.
10599
10600 @itemize @bullet
10601 @item
10602 The optimization level is at least @option{-O1}.
10603
10604 @item
10605 The called subprogram is suitable for inlining: It must be small enough
10606 and not contain something that @command{gcc} cannot support in inlined
10607 subprograms.
10608
10609 @item
10610 The call appears in a body (not in a package spec).
10611
10612 @item
10613 There is a @code{pragma Inline} for the subprogram.
10614
10615 @item
10616 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10617 @end itemize
10618
10619 Even if all these conditions are met, it may not be possible for
10620 the compiler to inline the call, due to the length of the body,
10621 or features in the body that make it impossible for the compiler
10622 to do the inlining.
10623
10624 Note that specifying the @option{-gnatn} switch causes additional
10625 compilation dependencies. Consider the following:
10626
10627 @smallexample @c ada
10628 @cartouche
10629 package R is
10630    procedure Q;
10631    pragma Inline (Q);
10632 end R;
10633 package body R is
10634    @dots{}
10635 end R;
10636
10637 with R;
10638 procedure Main is
10639 begin
10640    @dots{}
10641    R.Q;
10642 end Main;
10643 @end cartouche
10644 @end smallexample
10645
10646 @noindent
10647 With the default behavior (no @option{-gnatn} switch specified), the
10648 compilation of the @code{Main} procedure depends only on its own source,
10649 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10650 means that editing the body of @code{R} does not require recompiling
10651 @code{Main}.
10652
10653 On the other hand, the call @code{R.Q} is not inlined under these
10654 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10655 is compiled, the call will be inlined if the body of @code{Q} is small
10656 enough, but now @code{Main} depends on the body of @code{R} in
10657 @file{r.adb} as well as on the spec. This means that if this body is edited,
10658 the main program must be recompiled. Note that this extra dependency
10659 occurs whether or not the call is in fact inlined by @command{gcc}.
10660
10661 The use of front end inlining with @option{-gnatN} generates similar
10662 additional dependencies.
10663
10664 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10665 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10666 can be used to prevent
10667 all inlining. This switch overrides all other conditions and ensures
10668 that no inlining occurs. The extra dependences resulting from
10669 @option{-gnatn} will still be active, even if
10670 this switch is used to suppress the resulting inlining actions.
10671
10672 @cindex @option{-fno-inline-functions} (@command{gcc})
10673 Note: The @option{-fno-inline-functions} switch can be used to prevent
10674 automatic inlining of subprograms if @option{-O3} is used.
10675
10676 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10677 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10678 automatic inlining of small subprograms if @option{-O2} is used.
10679
10680 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10681 Note: The @option{-fno-inline-functions-called-once} switch
10682 can be used to prevent inlining of subprograms local to the unit
10683 and called once from within it if @option{-O1} is used.
10684
10685 Note regarding the use of @option{-O3}: There is no difference in inlining
10686 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10687 pragma @code{Inline} assuming the use of @option{-gnatn}
10688 or @option{-gnatN} (the switches that activate inlining). If you have used
10689 pragma @code{Inline} in appropriate cases, then it is usually much better
10690 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10691 in this case only has the effect of inlining subprograms you did not
10692 think should be inlined. We often find that the use of @option{-O3} slows
10693 down code by performing excessive inlining, leading to increased instruction
10694 cache pressure from the increased code size. So the bottom line here is
10695 that you should not automatically assume that @option{-O3} is better than
10696 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10697 it actually improves performance.
10698
10699 @node Vectorization of loops
10700 @subsection Vectorization of loops
10701 @cindex Optimization Switches
10702
10703 You can take advantage of the auto-vectorizer present in the @command{gcc}
10704 back end to vectorize loops with GNAT.  The corresponding command line switch
10705 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10706 and other aggressive optimizations helpful for vectorization also are enabled
10707 by default at this level, using @option{-O3} directly is recommended.
10708
10709 You also need to make sure that the target architecture features a supported
10710 SIMD instruction set.  For example, for the x86 architecture, you should at
10711 least specify @option{-msse2} to get significant vectorization (but you don't
10712 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10713 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10714
10715 The preferred loop form for vectorization is the @code{for} iteration scheme.
10716 Loops with a @code{while} iteration scheme can also be vectorized if they are
10717 very simple, but the vectorizer will quickly give up otherwise.  With either
10718 iteration scheme, the flow of control must be straight, in particular no
10719 @code{exit} statement may appear in the loop body.  The loop may however
10720 contain a single nested loop, if it can be vectorized when considered alone:
10721
10722 @smallexample @c ada
10723 @cartouche
10724    A : array (1..4, 1..4) of Long_Float;
10725    S : array (1..4) of Long_Float;
10726
10727    procedure Sum is
10728    begin
10729       for I in A'Range(1) loop
10730          for J in A'Range(2) loop
10731             S (I) := S (I) + A (I, J);
10732          end loop;
10733       end loop;
10734    end Sum;
10735 @end cartouche
10736 @end smallexample
10737
10738 The vectorizable operations depend on the targeted SIMD instruction set, but
10739 the adding and some of the multiplying operators are generally supported, as
10740 well as the logical operators for modular types.  Note that, in the former
10741 case, enabling overflow checks, for example with @option{-gnato}, totally
10742 disables vectorization.  The other checks are not supposed to have the same
10743 definitive effect, although compiling with @option{-gnatp} might well reveal
10744 cases where some checks do thwart vectorization.
10745
10746 Type conversions may also prevent vectorization if they involve semantics that
10747 are not directly supported by the code generator or the SIMD instruction set.
10748 A typical example is direct conversion from floating-point to integer types.
10749 The solution in this case is to use the following idiom:
10750
10751 @smallexample @c ada
10752    Integer (S'Truncation (F))
10753 @end smallexample
10754
10755 @noindent
10756 if @code{S} is the subtype of floating-point object @code{F}.
10757
10758 In most cases, the vectorizable loops are loops that iterate over arrays.
10759 All kinds of array types are supported, i.e. constrained array types with
10760 static bounds:
10761
10762 @smallexample @c ada
10763    type Array_Type is array (1 .. 4) of Long_Float;
10764 @end smallexample
10765
10766 @noindent
10767 constrained array types with dynamic bounds:
10768
10769 @smallexample @c ada
10770    type Array_Type is array (1 .. Q.N) of Long_Float;
10771
10772    type Array_Type is array (Q.K .. 4) of Long_Float;
10773
10774    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10775 @end smallexample
10776
10777 @noindent
10778 or unconstrained array types:
10779
10780 @smallexample @c ada
10781   type Array_Type is array (Positive range <>) of Long_Float;
10782 @end smallexample
10783
10784 @noindent
10785 The quality of the generated code decreases when the dynamic aspect of the
10786 array type increases, the worst code being generated for unconstrained array
10787 types.  This is so because, the less information the compiler has about the
10788 bounds of the array, the more fallback code it needs to generate in order to
10789 fix things up at run time.
10790
10791 You can obtain information about the vectorization performed by the compiler
10792 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10793 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10794 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10795
10796 @node Other Optimization Switches
10797 @subsection Other Optimization Switches
10798 @cindex Optimization Switches
10799
10800 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10801 @command{gcc} optimization switches are potentially usable. These switches
10802 have not been extensively tested with GNAT but can generally be expected
10803 to work. Examples of switches in this category are @option{-funroll-loops}
10804 and the various target-specific @option{-m} options (in particular, it has
10805 been observed that @option{-march=xxx} can significantly improve performance
10806 on appropriate machines). For full details of these switches, see
10807 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10808 the GNU Compiler Collection (GCC)}.
10809
10810 @node Optimization and Strict Aliasing
10811 @subsection Optimization and Strict Aliasing
10812 @cindex Aliasing
10813 @cindex Strict Aliasing
10814 @cindex No_Strict_Aliasing
10815
10816 @noindent
10817 The strong typing capabilities of Ada allow an optimizer to generate
10818 efficient code in situations where other languages would be forced to
10819 make worst case assumptions preventing such optimizations. Consider
10820 the following example:
10821
10822 @smallexample @c ada
10823 @cartouche
10824 procedure R is
10825    type Int1 is new Integer;
10826    type Int2 is new Integer;
10827    type Int1A is access Int1;
10828    type Int2A is access Int2;
10829    Int1V : Int1A;
10830    Int2V : Int2A;
10831    @dots{}
10832
10833 begin
10834    @dots{}
10835    for J in Data'Range loop
10836       if Data (J) = Int1V.all then
10837          Int2V.all := Int2V.all + 1;
10838       end if;
10839    end loop;
10840    @dots{}
10841 end R;
10842 @end cartouche
10843 @end smallexample
10844
10845 @noindent
10846 In this example, since the variable @code{Int1V} can only access objects
10847 of type @code{Int1}, and @code{Int2V} can only access objects of type
10848 @code{Int2}, there is no possibility that the assignment to
10849 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10850 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10851 for all iterations of the loop and avoid the extra memory reference
10852 required to dereference it each time through the loop.
10853
10854 This kind of optimization, called strict aliasing analysis, is
10855 triggered by specifying an optimization level of @option{-O2} or
10856 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10857 when access values are involved.
10858
10859 However, although this optimization is always correct in terms of
10860 the formal semantics of the Ada Reference Manual, difficulties can
10861 arise if features like @code{Unchecked_Conversion} are used to break
10862 the typing system. Consider the following complete program example:
10863
10864 @smallexample @c ada
10865 @cartouche
10866 package p1 is
10867    type int1 is new integer;
10868    type int2 is new integer;
10869    type a1 is access int1;
10870    type a2 is access int2;
10871 end p1;
10872
10873 with p1; use p1;
10874 package p2 is
10875    function to_a2 (Input : a1) return a2;
10876 end p2;
10877
10878 with Unchecked_Conversion;
10879 package body p2 is
10880    function to_a2 (Input : a1) return a2 is
10881       function to_a2u is
10882         new Unchecked_Conversion (a1, a2);
10883    begin
10884       return to_a2u (Input);
10885    end to_a2;
10886 end p2;
10887
10888 with p2; use p2;
10889 with p1; use p1;
10890 with Text_IO; use Text_IO;
10891 procedure m is
10892    v1 : a1 := new int1;
10893    v2 : a2 := to_a2 (v1);
10894 begin
10895    v1.all := 1;
10896    v2.all := 0;
10897    put_line (int1'image (v1.all));
10898 end;
10899 @end cartouche
10900 @end smallexample
10901
10902 @noindent
10903 This program prints out 0 in @option{-O0} or @option{-O1}
10904 mode, but it prints out 1 in @option{-O2} mode. That's
10905 because in strict aliasing mode, the compiler can and
10906 does assume that the assignment to @code{v2.all} could not
10907 affect the value of @code{v1.all}, since different types
10908 are involved.
10909
10910 This behavior is not a case of non-conformance with the standard, since
10911 the Ada RM specifies that an unchecked conversion where the resulting
10912 bit pattern is not a correct value of the target type can result in an
10913 abnormal value and attempting to reference an abnormal value makes the
10914 execution of a program erroneous.  That's the case here since the result
10915 does not point to an object of type @code{int2}.  This means that the
10916 effect is entirely unpredictable.
10917
10918 However, although that explanation may satisfy a language
10919 lawyer, in practice an applications programmer expects an
10920 unchecked conversion involving pointers to create true
10921 aliases and the behavior of printing 1 seems plain wrong.
10922 In this case, the strict aliasing optimization is unwelcome.
10923
10924 Indeed the compiler recognizes this possibility, and the
10925 unchecked conversion generates a warning:
10926
10927 @smallexample
10928 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10929 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10930 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10931 @end smallexample
10932
10933 @noindent
10934 Unfortunately the problem is recognized when compiling the body of
10935 package @code{p2}, but the actual "bad" code is generated while
10936 compiling the body of @code{m} and this latter compilation does not see
10937 the suspicious @code{Unchecked_Conversion}.
10938
10939 As implied by the warning message, there are approaches you can use to
10940 avoid the unwanted strict aliasing optimization in a case like this.
10941
10942 One possibility is to simply avoid the use of @option{-O2}, but
10943 that is a bit drastic, since it throws away a number of useful
10944 optimizations that do not involve strict aliasing assumptions.
10945
10946 A less drastic approach is to compile the program using the
10947 option @option{-fno-strict-aliasing}. Actually it is only the
10948 unit containing the dereferencing of the suspicious pointer
10949 that needs to be compiled. So in this case, if we compile
10950 unit @code{m} with this switch, then we get the expected
10951 value of zero printed. Analyzing which units might need
10952 the switch can be painful, so a more reasonable approach
10953 is to compile the entire program with options @option{-O2}
10954 and @option{-fno-strict-aliasing}. If the performance is
10955 satisfactory with this combination of options, then the
10956 advantage is that the entire issue of possible "wrong"
10957 optimization due to strict aliasing is avoided.
10958
10959 To avoid the use of compiler switches, the configuration
10960 pragma @code{No_Strict_Aliasing} with no parameters may be
10961 used to specify that for all access types, the strict
10962 aliasing optimization should be suppressed.
10963
10964 However, these approaches are still overkill, in that they causes
10965 all manipulations of all access values to be deoptimized. A more
10966 refined approach is to concentrate attention on the specific
10967 access type identified as problematic.
10968
10969 First, if a careful analysis of uses of the pointer shows
10970 that there are no possible problematic references, then
10971 the warning can be suppressed by bracketing the
10972 instantiation of @code{Unchecked_Conversion} to turn
10973 the warning off:
10974
10975 @smallexample @c ada
10976    pragma Warnings (Off);
10977    function to_a2u is
10978      new Unchecked_Conversion (a1, a2);
10979    pragma Warnings (On);
10980 @end smallexample
10981
10982 @noindent
10983 Of course that approach is not appropriate for this particular
10984 example, since indeed there is a problematic reference. In this
10985 case we can take one of two other approaches.
10986
10987 The first possibility is to move the instantiation of unchecked
10988 conversion to the unit in which the type is declared. In
10989 this example, we would move the instantiation of
10990 @code{Unchecked_Conversion} from the body of package
10991 @code{p2} to the spec of package @code{p1}. Now the
10992 warning disappears. That's because any use of the
10993 access type knows there is a suspicious unchecked
10994 conversion, and the strict aliasing optimization
10995 is automatically suppressed for the type.
10996
10997 If it is not practical to move the unchecked conversion to the same unit
10998 in which the destination access type is declared (perhaps because the
10999 source type is not visible in that unit), you may use pragma
11000 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11001 same declarative sequence as the declaration of the access type:
11002
11003 @smallexample @c ada
11004    type a2 is access int2;
11005    pragma No_Strict_Aliasing (a2);
11006 @end smallexample
11007
11008 @noindent
11009 Here again, the compiler now knows that the strict aliasing optimization
11010 should be suppressed for any reference to type @code{a2} and the
11011 expected behavior is obtained.
11012
11013 Finally, note that although the compiler can generate warnings for
11014 simple cases of unchecked conversions, there are tricker and more
11015 indirect ways of creating type incorrect aliases which the compiler
11016 cannot detect. Examples are the use of address overlays and unchecked
11017 conversions involving composite types containing access types as
11018 components. In such cases, no warnings are generated, but there can
11019 still be aliasing problems. One safe coding practice is to forbid the
11020 use of address clauses for type overlaying, and to allow unchecked
11021 conversion only for primitive types. This is not really a significant
11022 restriction since any possible desired effect can be achieved by
11023 unchecked conversion of access values.
11024
11025 The aliasing analysis done in strict aliasing mode can certainly
11026 have significant benefits. We have seen cases of large scale
11027 application code where the time is increased by up to 5% by turning
11028 this optimization off. If you have code that includes significant
11029 usage of unchecked conversion, you might want to just stick with
11030 @option{-O1} and avoid the entire issue. If you get adequate
11031 performance at this level of optimization level, that's probably
11032 the safest approach. If tests show that you really need higher
11033 levels of optimization, then you can experiment with @option{-O2}
11034 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11035 has on size and speed of the code. If you really need to use
11036 @option{-O2} with strict aliasing in effect, then you should
11037 review any uses of unchecked conversion of access types,
11038 particularly if you are getting the warnings described above.
11039
11040 @ifset vms
11041 @node Coverage Analysis
11042 @subsection Coverage Analysis
11043
11044 @noindent
11045 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11046 the user to determine the distribution of execution time across a program,
11047 @pxref{Profiling} for details of usage.
11048 @end ifset
11049
11050
11051 @node Text_IO Suggestions
11052 @section @code{Text_IO} Suggestions
11053 @cindex @code{Text_IO} and performance
11054
11055 @noindent
11056 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11057 the requirement of maintaining page and line counts. If performance
11058 is critical, a recommendation is to use @code{Stream_IO} instead of
11059 @code{Text_IO} for volume output, since this package has less overhead.
11060
11061 If @code{Text_IO} must be used, note that by default output to the standard
11062 output and standard error files is unbuffered (this provides better
11063 behavior when output statements are used for debugging, or if the
11064 progress of a program is observed by tracking the output, e.g. by
11065 using the Unix @command{tail -f} command to watch redirected output.
11066
11067 If you are generating large volumes of output with @code{Text_IO} and
11068 performance is an important factor, use a designated file instead
11069 of the standard output file, or change the standard output file to
11070 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11071
11072
11073
11074 @node Reducing Size of Ada Executables with gnatelim
11075 @section Reducing Size of Ada Executables with @code{gnatelim}
11076 @findex gnatelim
11077
11078 @noindent
11079 This section describes @command{gnatelim}, a tool which detects unused
11080 subprograms and helps the compiler to create a smaller executable for your
11081 program.
11082
11083 @menu
11084 * About gnatelim::
11085 * Running gnatelim::
11086 * Processing Precompiled Libraries::
11087 * Correcting the List of Eliminate Pragmas::
11088 * Making Your Executables Smaller::
11089 * Summary of the gnatelim Usage Cycle::
11090 @end menu
11091
11092 @node About gnatelim
11093 @subsection About @code{gnatelim}
11094
11095 @noindent
11096 When a program shares a set of Ada
11097 packages with other programs, it may happen that this program uses
11098 only a fraction of the subprograms defined in these packages. The code
11099 created for these unused subprograms increases the size of the executable.
11100
11101 @code{gnatelim} tracks unused subprograms in an Ada program and
11102 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11103 subprograms that are declared but never called. By placing the list of
11104 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11105 recompiling your program, you may decrease the size of its executable,
11106 because the compiler will not generate the code for 'eliminated' subprograms.
11107 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11108 information about this pragma.
11109
11110 @code{gnatelim} needs as its input data the name of the main subprogram.
11111
11112 If a set of source files is specified as @code{gnatelim} arguments, it
11113 treats these files as a complete set of sources making up a program to
11114 analyse, and analyses only these sources.
11115
11116 After a full successful build of the main subprogram @code{gnatelim} can be
11117 called without  specifying sources to analyse, in this case it computes
11118 the source closure of the main unit from the @file{ALI} files.
11119
11120 The following command will create the set of @file{ALI} files needed for
11121 @code{gnatelim}:
11122
11123 @smallexample
11124 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11125 @end smallexample
11126
11127 Note that @code{gnatelim} does not need object files.
11128
11129 @node Running gnatelim
11130 @subsection Running @code{gnatelim}
11131
11132 @noindent
11133 @code{gnatelim} has the following command-line interface:
11134
11135 @smallexample
11136 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11137 @end smallexample
11138
11139 @noindent
11140 @var{main_unit_name} should be a name of a source file that contains the main
11141 subprogram of a program (partition).
11142
11143 Each @var{filename} is the name (including the extension) of a source
11144 file to process. ``Wildcards'' are allowed, and
11145 the file name may contain path information.
11146
11147 @samp{@var{gcc_switches}} is a list of switches for
11148 @command{gcc}. They will be passed on to all compiler invocations made by
11149 @command{gnatelim} to generate the ASIS trees. Here you can provide
11150 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11151 use the @option{-gnatec} switch to set the configuration file,
11152 use the @option{-gnat05} switch if sources should be compiled in
11153 Ada 2005 mode etc.
11154
11155 @code{gnatelim} has the following switches:
11156
11157 @table @option
11158 @c !sort!
11159 @item ^-files^/FILES^=@var{filename}
11160 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11161 Take the argument source files from the specified file. This file should be an
11162 ordinary text file containing file names separated by spaces or
11163 line breaks. You can use this switch more than once in the same call to
11164 @command{gnatelim}. You also can combine this switch with
11165 an explicit list of files.
11166
11167 @item ^-log^/LOG^
11168 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11169 Duplicate all the output sent to @file{stderr} into a log file. The log file
11170 is named @file{gnatelim.log} and is located in the current directory.
11171
11172 @item ^-log^/LOGFILE^=@var{filename}
11173 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11174 Duplicate all the output sent to @file{stderr} into a specified log file.
11175
11176 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11177 @item ^--no-elim-dispatch^/NO_DISPATCH^
11178 Do not generate pragmas for dispatching operations.
11179
11180 @item ^--ignore^/IGNORE^=@var{filename}
11181 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11182 Do not generate pragmas for subprograms declared in the sources
11183 listed in a specified file
11184
11185 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11186 @item ^-o^/OUTPUT^=@var{report_file}
11187 Put @command{gnatelim} output into a specified file. If this file already exists,
11188 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11189 into @file{stderr}
11190
11191 @item ^-q^/QUIET^
11192 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11193 Quiet mode: by default @code{gnatelim} outputs to the standard error
11194 stream the number of program units left to be processed. This option turns
11195 this trace off.
11196
11197 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11198 @item ^-t^/TIME^
11199 Print out execution time.
11200
11201 @item ^-v^/VERBOSE^
11202 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11203 Verbose mode: @code{gnatelim} version information is printed as Ada
11204 comments to the standard output stream. Also, in addition to the number of
11205 program units left @code{gnatelim} will output the name of the current unit
11206 being processed.
11207
11208 @item ^-wq^/WARNINGS=QUIET^
11209 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11210 Quiet warning mode - some warnings are suppressed. In particular warnings that
11211 indicate that the analysed set of sources is incomplete to make up a
11212 partition and that some subprogram bodies are missing are not generated.
11213 @end table
11214
11215 @noindent
11216 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11217 driver (see @ref{The GNAT Driver and Project Files}).
11218
11219 @node Processing Precompiled Libraries
11220 @subsection Processing Precompiled Libraries
11221
11222 @noindent
11223 If some program uses a precompiled Ada library, it can be processed by
11224 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11225 Eliminate pragma for a subprogram if the body of this subprogram has not
11226 been analysed, this is a typical case for subprograms from precompiled
11227 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11228 warnings about missing source files and non-analyzed subprogram bodies
11229 that can be generated when processing precompiled Ada libraries.
11230
11231 @node Correcting the List of Eliminate Pragmas
11232 @subsection Correcting the List of Eliminate Pragmas
11233
11234 @noindent
11235 In some rare cases @code{gnatelim} may try to eliminate
11236 subprograms that are actually called in the program. In this case, the
11237 compiler will generate an error message of the form:
11238
11239 @smallexample
11240 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11241 @end smallexample
11242
11243 @noindent
11244 You will need to manually remove the wrong @code{Eliminate} pragmas from
11245 the configuration file indicated in the error message. You should recompile
11246 your program from scratch after that, because you need a consistent
11247 configuration file(s) during the entire compilation.
11248
11249 @node Making Your Executables Smaller
11250 @subsection Making Your Executables Smaller
11251
11252 @noindent
11253 In order to get a smaller executable for your program you now have to
11254 recompile the program completely with the configuration file containing
11255 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11256 @file{gnat.adc} file located in your current directory, just do:
11257
11258 @smallexample
11259 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11260 @end smallexample
11261
11262 @noindent
11263 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11264 recompile everything
11265 with the set of pragmas @code{Eliminate} that you have obtained with
11266 @command{gnatelim}).
11267
11268 Be aware that the set of @code{Eliminate} pragmas is specific to each
11269 program. It is not recommended to merge sets of @code{Eliminate}
11270 pragmas created for different programs in one configuration file.
11271
11272 @node Summary of the gnatelim Usage Cycle
11273 @subsection Summary of the @code{gnatelim} Usage Cycle
11274
11275 @noindent
11276 Here is a quick summary of the steps to be taken in order to reduce
11277 the size of your executables with @code{gnatelim}. You may use
11278 other GNAT options to control the optimization level,
11279 to produce the debugging information, to set search path, etc.
11280
11281 @enumerate
11282 @item
11283 Create a complete set of @file{ALI} files (if the program has not been
11284 built already)
11285
11286 @smallexample
11287 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11288 @end smallexample
11289
11290 @item
11291 Generate a list of @code{Eliminate} pragmas in default configuration file
11292 @file{gnat.adc} in the current directory
11293 @smallexample
11294 @ifset vms
11295 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11296 @end ifset
11297 @ifclear vms
11298 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11299 @end ifclear
11300 @end smallexample
11301
11302 @item
11303 Recompile the application
11304
11305 @smallexample
11306 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11307 @end smallexample
11308
11309 @end enumerate
11310
11311 @node Reducing Size of Executables with unused subprogram/data elimination
11312 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11313 @findex unused subprogram/data elimination
11314
11315 @noindent
11316 This section describes how you can eliminate unused subprograms and data from
11317 your executable just by setting options at compilation time.
11318
11319 @menu
11320 * About unused subprogram/data elimination::
11321 * Compilation options::
11322 * Example of unused subprogram/data elimination::
11323 @end menu
11324
11325 @node About unused subprogram/data elimination
11326 @subsection About unused subprogram/data elimination
11327
11328 @noindent
11329 By default, an executable contains all code and data of its composing objects
11330 (directly linked or coming from statically linked libraries), even data or code
11331 never used by this executable.
11332
11333 This feature will allow you to eliminate such unused code from your
11334 executable, making it smaller (in disk and in memory).
11335
11336 This functionality is available on all Linux platforms except for the IA-64
11337 architecture and on all cross platforms using the ELF binary file format.
11338 In both cases GNU binutils version 2.16 or later are required to enable it.
11339
11340 @node Compilation options
11341 @subsection Compilation options
11342
11343 @noindent
11344 The operation of eliminating the unused code and data from the final executable
11345 is directly performed by the linker.
11346
11347 In order to do this, it has to work with objects compiled with the
11348 following options:
11349 @option{-ffunction-sections} @option{-fdata-sections}.
11350 @cindex @option{-ffunction-sections} (@command{gcc})
11351 @cindex @option{-fdata-sections} (@command{gcc})
11352 These options are usable with C and Ada files.
11353 They will place respectively each
11354 function or data in a separate section in the resulting object file.
11355
11356 Once the objects and static libraries are created with these options, the
11357 linker can perform the dead code elimination. You can do this by setting
11358 the @option{-Wl,--gc-sections} option to gcc command or in the
11359 @option{-largs} section of @command{gnatmake}. This will perform a
11360 garbage collection of code and data never referenced.
11361
11362 If the linker performs a partial link (@option{-r} ld linker option), then you
11363 will need to provide one or several entry point using the
11364 @option{-e} / @option{--entry} ld option.
11365
11366 Note that objects compiled without the @option{-ffunction-sections} and
11367 @option{-fdata-sections} options can still be linked with the executable.
11368 However, no dead code elimination will be performed on those objects (they will
11369 be linked as is).
11370
11371 The GNAT static library is now compiled with -ffunction-sections and
11372 -fdata-sections on some platforms. This allows you to eliminate the unused code
11373 and data of the GNAT library from your executable.
11374
11375 @node Example of unused subprogram/data elimination
11376 @subsection Example of unused subprogram/data elimination
11377
11378 @noindent
11379 Here is a simple example:
11380
11381 @smallexample @c ada
11382 with Aux;
11383
11384 procedure Test is
11385 begin
11386    Aux.Used (10);
11387 end Test;
11388
11389 package Aux is
11390    Used_Data   : Integer;
11391    Unused_Data : Integer;
11392
11393    procedure Used   (Data : Integer);
11394    procedure Unused (Data : Integer);
11395 end Aux;
11396
11397 package body Aux is
11398    procedure Used (Data : Integer) is
11399    begin
11400       Used_Data := Data;
11401    end Used;
11402
11403    procedure Unused (Data : Integer) is
11404    begin
11405       Unused_Data := Data;
11406    end Unused;
11407 end Aux;
11408 @end smallexample
11409
11410 @noindent
11411 @code{Unused} and @code{Unused_Data} are never referenced in this code
11412 excerpt, and hence they may be safely removed from the final executable.
11413
11414 @smallexample
11415 $ gnatmake test
11416
11417 $ nm test | grep used
11418 020015f0 T aux__unused
11419 02005d88 B aux__unused_data
11420 020015cc T aux__used
11421 02005d84 B aux__used_data
11422
11423 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11424      -largs -Wl,--gc-sections
11425
11426 $ nm test | grep used
11427 02005350 T aux__used
11428 0201ffe0 B aux__used_data
11429 @end smallexample
11430
11431 @noindent
11432 It can be observed that the procedure @code{Unused} and the object
11433 @code{Unused_Data} are removed by the linker when using the
11434 appropriate options.
11435
11436 @c ********************************
11437 @node Renaming Files Using gnatchop
11438 @chapter Renaming Files Using @code{gnatchop}
11439 @findex gnatchop
11440
11441 @noindent
11442 This chapter discusses how to handle files with multiple units by using
11443 the @code{gnatchop} utility. This utility is also useful in renaming
11444 files to meet the standard GNAT default file naming conventions.
11445
11446 @menu
11447 * Handling Files with Multiple Units::
11448 * Operating gnatchop in Compilation Mode::
11449 * Command Line for gnatchop::
11450 * Switches for gnatchop::
11451 * Examples of gnatchop Usage::
11452 @end menu
11453
11454 @node Handling Files with Multiple Units
11455 @section Handling Files with Multiple Units
11456
11457 @noindent
11458 The basic compilation model of GNAT requires that a file submitted to the
11459 compiler have only one unit and there be a strict correspondence
11460 between the file name and the unit name.
11461
11462 The @code{gnatchop} utility allows both of these rules to be relaxed,
11463 allowing GNAT to process files which contain multiple compilation units
11464 and files with arbitrary file names. @code{gnatchop}
11465 reads the specified file and generates one or more output files,
11466 containing one unit per file. The unit and the file name correspond,
11467 as required by GNAT.
11468
11469 If you want to permanently restructure a set of ``foreign'' files so that
11470 they match the GNAT rules, and do the remaining development using the
11471 GNAT structure, you can simply use @command{gnatchop} once, generate the
11472 new set of files and work with them from that point on.
11473
11474 Alternatively, if you want to keep your files in the ``foreign'' format,
11475 perhaps to maintain compatibility with some other Ada compilation
11476 system, you can set up a procedure where you use @command{gnatchop} each
11477 time you compile, regarding the source files that it writes as temporary
11478 files that you throw away.
11479
11480 Note that if your file containing multiple units starts with a byte order
11481 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11482 will each start with a copy of this BOM, meaning that they can be compiled
11483 automatically in UTF-8 mode without needing to specify an explicit encoding.
11484
11485 @node Operating gnatchop in Compilation Mode
11486 @section Operating gnatchop in Compilation Mode
11487
11488 @noindent
11489 The basic function of @code{gnatchop} is to take a file with multiple units
11490 and split it into separate files. The boundary between files is reasonably
11491 clear, except for the issue of comments and pragmas. In default mode, the
11492 rule is that any pragmas between units belong to the previous unit, except
11493 that configuration pragmas always belong to the following unit. Any comments
11494 belong to the following unit. These rules
11495 almost always result in the right choice of
11496 the split point without needing to mark it explicitly and most users will
11497 find this default to be what they want. In this default mode it is incorrect to
11498 submit a file containing only configuration pragmas, or one that ends in
11499 configuration pragmas, to @code{gnatchop}.
11500
11501 However, using a special option to activate ``compilation mode'',
11502 @code{gnatchop}
11503 can perform another function, which is to provide exactly the semantics
11504 required by the RM for handling of configuration pragmas in a compilation.
11505 In the absence of configuration pragmas (at the main file level), this
11506 option has no effect, but it causes such configuration pragmas to be handled
11507 in a quite different manner.
11508
11509 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11510 only configuration pragmas, then this file is appended to the
11511 @file{gnat.adc} file in the current directory. This behavior provides
11512 the required behavior described in the RM for the actions to be taken
11513 on submitting such a file to the compiler, namely that these pragmas
11514 should apply to all subsequent compilations in the same compilation
11515 environment. Using GNAT, the current directory, possibly containing a
11516 @file{gnat.adc} file is the representation
11517 of a compilation environment. For more information on the
11518 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11519
11520 Second, in compilation mode, if @code{gnatchop}
11521 is given a file that starts with
11522 configuration pragmas, and contains one or more units, then these
11523 configuration pragmas are prepended to each of the chopped files. This
11524 behavior provides the required behavior described in the RM for the
11525 actions to be taken on compiling such a file, namely that the pragmas
11526 apply to all units in the compilation, but not to subsequently compiled
11527 units.
11528
11529 Finally, if configuration pragmas appear between units, they are appended
11530 to the previous unit. This results in the previous unit being illegal,
11531 since the compiler does not accept configuration pragmas that follow
11532 a unit. This provides the required RM behavior that forbids configuration
11533 pragmas other than those preceding the first compilation unit of a
11534 compilation.
11535
11536 For most purposes, @code{gnatchop} will be used in default mode. The
11537 compilation mode described above is used only if you need exactly
11538 accurate behavior with respect to compilations, and you have files
11539 that contain multiple units and configuration pragmas. In this
11540 circumstance the use of @code{gnatchop} with the compilation mode
11541 switch provides the required behavior, and is for example the mode
11542 in which GNAT processes the ACVC tests.
11543
11544 @node Command Line for gnatchop
11545 @section Command Line for @code{gnatchop}
11546
11547 @noindent
11548 The @code{gnatchop} command has the form:
11549
11550 @smallexample
11551 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11552 @c      @ovar{directory}
11553 @c Expanding @ovar macro inline (explanation in macro def comments)
11554 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11555       @r{[}@var{directory}@r{]}
11556 @end smallexample
11557
11558 @noindent
11559 The only required argument is the file name of the file to be chopped.
11560 There are no restrictions on the form of this file name. The file itself
11561 contains one or more Ada units, in normal GNAT format, concatenated
11562 together. As shown, more than one file may be presented to be chopped.
11563
11564 When run in default mode, @code{gnatchop} generates one output file in
11565 the current directory for each unit in each of the files.
11566
11567 @var{directory}, if specified, gives the name of the directory to which
11568 the output files will be written. If it is not specified, all files are
11569 written to the current directory.
11570
11571 For example, given a
11572 file called @file{hellofiles} containing
11573
11574 @smallexample @c ada
11575 @group
11576 @cartouche
11577 procedure hello;
11578
11579 with Text_IO; use Text_IO;
11580 procedure hello is
11581 begin
11582    Put_Line ("Hello");
11583 end hello;
11584 @end cartouche
11585 @end group
11586 @end smallexample
11587
11588 @noindent
11589 the command
11590
11591 @smallexample
11592 $ gnatchop ^hellofiles^HELLOFILES.^
11593 @end smallexample
11594
11595 @noindent
11596 generates two files in the current directory, one called
11597 @file{hello.ads} containing the single line that is the procedure spec,
11598 and the other called @file{hello.adb} containing the remaining text. The
11599 original file is not affected. The generated files can be compiled in
11600 the normal manner.
11601
11602 @noindent
11603 When gnatchop is invoked on a file that is empty or that contains only empty
11604 lines and/or comments, gnatchop will not fail, but will not produce any
11605 new sources.
11606
11607 For example, given a
11608 file called @file{toto.txt} containing
11609
11610 @smallexample @c ada
11611 @group
11612 @cartouche
11613 --  Just a comment
11614 @end cartouche
11615 @end group
11616 @end smallexample
11617
11618 @noindent
11619 the command
11620
11621 @smallexample
11622 $ gnatchop ^toto.txt^TOT.TXT^
11623 @end smallexample
11624
11625 @noindent
11626 will not produce any new file and will result in the following warnings:
11627
11628 @smallexample
11629 toto.txt:1:01: warning: empty file, contains no compilation units
11630 no compilation units found
11631 no source files written
11632 @end smallexample
11633
11634 @node Switches for gnatchop
11635 @section Switches for @code{gnatchop}
11636
11637 @noindent
11638 @command{gnatchop} recognizes the following switches:
11639
11640 @table @option
11641 @c !sort!
11642
11643 @item --version
11644 @cindex @option{--version} @command{gnatchop}
11645 Display Copyright and version, then exit disregarding all other options.
11646
11647 @item --help
11648 @cindex @option{--help} @command{gnatchop}
11649 If @option{--version} was not used, display usage, then exit disregarding
11650 all other options.
11651
11652 @item ^-c^/COMPILATION^
11653 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11654 Causes @code{gnatchop} to operate in compilation mode, in which
11655 configuration pragmas are handled according to strict RM rules. See
11656 previous section for a full description of this mode.
11657
11658 @ifclear vms
11659 @item -gnat@var{xxx}
11660 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11661 used to parse the given file. Not all @var{xxx} options make sense,
11662 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11663 process a source file that uses Latin-2 coding for identifiers.
11664 @end ifclear
11665
11666 @item ^-h^/HELP^
11667 Causes @code{gnatchop} to generate a brief help summary to the standard
11668 output file showing usage information.
11669
11670 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11671 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11672 Limit generated file names to the specified number @code{mm}
11673 of characters.
11674 This is useful if the
11675 resulting set of files is required to be interoperable with systems
11676 which limit the length of file names.
11677 @ifset vms
11678 If no value is given, or
11679 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11680 a default of 39, suitable for OpenVMS Alpha
11681 Systems, is assumed
11682 @end ifset
11683 @ifclear vms
11684 No space is allowed between the @option{-k} and the numeric value. The numeric
11685 value may be omitted in which case a default of @option{-k8},
11686 suitable for use
11687 with DOS-like file systems, is used. If no @option{-k} switch
11688 is present then
11689 there is no limit on the length of file names.
11690 @end ifclear
11691
11692 @item ^-p^/PRESERVE^
11693 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11694 Causes the file ^modification^creation^ time stamp of the input file to be
11695 preserved and used for the time stamp of the output file(s). This may be
11696 useful for preserving coherency of time stamps in an environment where
11697 @code{gnatchop} is used as part of a standard build process.
11698
11699 @item ^-q^/QUIET^
11700 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11701 Causes output of informational messages indicating the set of generated
11702 files to be suppressed. Warnings and error messages are unaffected.
11703
11704 @item ^-r^/REFERENCE^
11705 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11706 @findex Source_Reference
11707 Generate @code{Source_Reference} pragmas. Use this switch if the output
11708 files are regarded as temporary and development is to be done in terms
11709 of the original unchopped file. This switch causes
11710 @code{Source_Reference} pragmas to be inserted into each of the
11711 generated files to refers back to the original file name and line number.
11712 The result is that all error messages refer back to the original
11713 unchopped file.
11714 In addition, the debugging information placed into the object file (when
11715 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11716 specified)
11717 also refers back to this original file so that tools like profilers and
11718 debuggers will give information in terms of the original unchopped file.
11719
11720 If the original file to be chopped itself contains
11721 a @code{Source_Reference}
11722 pragma referencing a third file, then gnatchop respects
11723 this pragma, and the generated @code{Source_Reference} pragmas
11724 in the chopped file refer to the original file, with appropriate
11725 line numbers. This is particularly useful when @code{gnatchop}
11726 is used in conjunction with @code{gnatprep} to compile files that
11727 contain preprocessing statements and multiple units.
11728
11729 @item ^-v^/VERBOSE^
11730 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11731 Causes @code{gnatchop} to operate in verbose mode. The version
11732 number and copyright notice are output, as well as exact copies of
11733 the gnat1 commands spawned to obtain the chop control information.
11734
11735 @item ^-w^/OVERWRITE^
11736 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11737 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11738 fatal error if there is already a file with the same name as a
11739 file it would otherwise output, in other words if the files to be
11740 chopped contain duplicated units. This switch bypasses this
11741 check, and causes all but the last instance of such duplicated
11742 units to be skipped.
11743
11744 @ifclear vms
11745 @item --GCC=@var{xxxx}
11746 @cindex @option{--GCC=} (@code{gnatchop})
11747 Specify the path of the GNAT parser to be used. When this switch is used,
11748 no attempt is made to add the prefix to the GNAT parser executable.
11749 @end ifclear
11750 @end table
11751
11752 @node Examples of gnatchop Usage
11753 @section Examples of @code{gnatchop} Usage
11754
11755 @table @code
11756 @ifset vms
11757 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11758 @end ifset
11759 @ifclear vms
11760 @item gnatchop -w hello_s.ada prerelease/files
11761 @end ifclear
11762
11763 Chops the source file @file{hello_s.ada}. The output files will be
11764 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11765 overwriting any
11766 files with matching names in that directory (no files in the current
11767 directory are modified).
11768
11769 @item gnatchop ^archive^ARCHIVE.^
11770 Chops the source file @file{^archive^ARCHIVE.^}
11771 into the current directory. One
11772 useful application of @code{gnatchop} is in sending sets of sources
11773 around, for example in email messages. The required sources are simply
11774 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11775 command), and then
11776 @command{gnatchop} is used at the other end to reconstitute the original
11777 file names.
11778
11779 @item gnatchop file1 file2 file3 direc
11780 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11781 the resulting files in the directory @file{direc}. Note that if any units
11782 occur more than once anywhere within this set of files, an error message
11783 is generated, and no files are written. To override this check, use the
11784 @option{^-w^/OVERWRITE^} switch,
11785 in which case the last occurrence in the last file will
11786 be the one that is output, and earlier duplicate occurrences for a given
11787 unit will be skipped.
11788 @end table
11789
11790 @node Configuration Pragmas
11791 @chapter Configuration Pragmas
11792 @cindex Configuration pragmas
11793 @cindex Pragmas, configuration
11794
11795 @noindent
11796 Configuration pragmas include those pragmas described as
11797 such in the Ada Reference Manual, as well as
11798 implementation-dependent pragmas that are configuration pragmas.
11799 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11800 for details on these additional GNAT-specific configuration pragmas.
11801 Most notably, the pragma @code{Source_File_Name}, which allows
11802 specifying non-default names for source files, is a configuration
11803 pragma. The following is a complete list of configuration pragmas
11804 recognized by GNAT:
11805
11806 @smallexample
11807    Ada_83
11808    Ada_95
11809    Ada_05
11810    Ada_2005
11811    Ada_12
11812    Ada_2012
11813    Annotate
11814    Assertion_Policy
11815    Assume_No_Invalid_Values
11816    C_Pass_By_Copy
11817    Check_Name
11818    Check_Policy
11819    Compile_Time_Error
11820    Compile_Time_Warning
11821    Compiler_Unit
11822    Component_Alignment
11823    Convention_Identifier
11824    Debug_Policy
11825    Detect_Blocking
11826    Default_Storage_Pool
11827    Discard_Names
11828    Elaboration_Checks
11829    Eliminate
11830    Extend_System
11831    Extensions_Allowed
11832    External_Name_Casing
11833    Fast_Math
11834    Favor_Top_Level
11835    Float_Representation
11836    Implicit_Packing
11837    Initialize_Scalars
11838    Interrupt_State
11839    License
11840    Locking_Policy
11841    Long_Float
11842    No_Run_Time
11843    No_Strict_Aliasing
11844    Normalize_Scalars
11845    Optimize_Alignment
11846    Persistent_BSS
11847    Polling
11848    Priority_Specific_Dispatching
11849    Profile
11850    Profile_Warnings
11851    Propagate_Exceptions
11852    Queuing_Policy
11853    Ravenscar
11854    Restricted_Run_Time
11855    Restrictions
11856    Restrictions_Warnings
11857    Reviewable
11858    Short_Circuit_And_Or
11859    Source_File_Name
11860    Source_File_Name_Project
11861    Style_Checks
11862    Suppress
11863    Suppress_Exception_Locations
11864    Task_Dispatching_Policy
11865    Universal_Data
11866    Unsuppress
11867    Use_VADS_Size
11868    Validity_Checks
11869    Warnings
11870    Wide_Character_Encoding
11871
11872 @end smallexample
11873
11874 @menu
11875 * Handling of Configuration Pragmas::
11876 * The Configuration Pragmas Files::
11877 @end menu
11878
11879 @node Handling of Configuration Pragmas
11880 @section Handling of Configuration Pragmas
11881
11882 Configuration pragmas may either appear at the start of a compilation
11883 unit, or they can appear in a configuration pragma file to apply to
11884 all compilations performed in a given compilation environment.
11885
11886 GNAT also provides the @code{gnatchop} utility to provide an automatic
11887 way to handle configuration pragmas following the semantics for
11888 compilations (that is, files with multiple units), described in the RM.
11889 See @ref{Operating gnatchop in Compilation Mode} for details.
11890 However, for most purposes, it will be more convenient to edit the
11891 @file{gnat.adc} file that contains configuration pragmas directly,
11892 as described in the following section.
11893
11894 In the case of @code{Restrictions} pragmas appearing as configuration
11895 pragmas in individual compilation units, the exact handling depends on
11896 the type of restriction.
11897
11898 Restrictions that require partition-wide consistency (like
11899 @code{No_Tasking}) are
11900 recognized wherever they appear
11901 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11902 unit. This makes sense since the binder will in any case insist on seeing
11903 consistent use, so any unit not conforming to any restrictions that are
11904 anywhere in the partition will be rejected, and you might as well find
11905 that out at compile time rather than at bind time.
11906
11907 For restrictions that do not require partition-wide consistency, e.g.
11908 SPARK or No_Implementation_Attributes, in general the restriction applies
11909 only to the unit in which the pragma appears, and not to any other units.
11910
11911 The exception is No_Elaboration_Code which always applies to the entire
11912 object file from a compilation, i.e. to the body, spec, and all subunits.
11913 This restriction can be specified in a configuration pragma file, or it
11914 can be on the body and/or the spec (in eithe case it applies to all the
11915 relevant units). It can appear on a subunit only if it has previously
11916 appeared in the body of spec.
11917
11918 @node The Configuration Pragmas Files
11919 @section The Configuration Pragmas Files
11920 @cindex @file{gnat.adc}
11921
11922 @noindent
11923 In GNAT a compilation environment is defined by the current
11924 directory at the time that a compile command is given. This current
11925 directory is searched for a file whose name is @file{gnat.adc}. If
11926 this file is present, it is expected to contain one or more
11927 configuration pragmas that will be applied to the current compilation.
11928 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11929 considered.
11930
11931 Configuration pragmas may be entered into the @file{gnat.adc} file
11932 either by running @code{gnatchop} on a source file that consists only of
11933 configuration pragmas, or more conveniently  by
11934 direct editing of the @file{gnat.adc} file, which is a standard format
11935 source file.
11936
11937 In addition to @file{gnat.adc}, additional files containing configuration
11938 pragmas may be applied to the current compilation using the switch
11939 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11940 contains only configuration pragmas. These configuration pragmas are
11941 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11942 is present and switch @option{-gnatA} is not used).
11943
11944 It is allowed to specify several switches @option{-gnatec}, all of which
11945 will be taken into account.
11946
11947 If you are using project file, a separate mechanism is provided using
11948 project attributes, see @ref{Specifying Configuration Pragmas} for more
11949 details.
11950
11951 @ifset vms
11952 Of special interest to GNAT OpenVMS Alpha is the following
11953 configuration pragma:
11954
11955 @smallexample @c ada
11956 @cartouche
11957 pragma Extend_System (Aux_DEC);
11958 @end cartouche
11959 @end smallexample
11960
11961 @noindent
11962 In the presence of this pragma, GNAT adds to the definition of the
11963 predefined package SYSTEM all the additional types and subprograms that are
11964 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11965 @end ifset
11966
11967 @node Handling Arbitrary File Naming Conventions Using gnatname
11968 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11969 @cindex Arbitrary File Naming Conventions
11970
11971 @menu
11972 * Arbitrary File Naming Conventions::
11973 * Running gnatname::
11974 * Switches for gnatname::
11975 * Examples of gnatname Usage::
11976 @end menu
11977
11978 @node Arbitrary File Naming Conventions
11979 @section Arbitrary File Naming Conventions
11980
11981 @noindent
11982 The GNAT compiler must be able to know the source file name of a compilation
11983 unit.  When using the standard GNAT default file naming conventions
11984 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11985 does not need additional information.
11986
11987 @noindent
11988 When the source file names do not follow the standard GNAT default file naming
11989 conventions, the GNAT compiler must be given additional information through
11990 a configuration pragmas file (@pxref{Configuration Pragmas})
11991 or a project file.
11992 When the non-standard file naming conventions are well-defined,
11993 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11994 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11995 if the file naming conventions are irregular or arbitrary, a number
11996 of pragma @code{Source_File_Name} for individual compilation units
11997 must be defined.
11998 To help maintain the correspondence between compilation unit names and
11999 source file names within the compiler,
12000 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12001 set of files.
12002
12003 @node Running gnatname
12004 @section Running @code{gnatname}
12005
12006 @noindent
12007 The usual form of the @code{gnatname} command is
12008
12009 @smallexample
12010 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12011 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12012 @c Expanding @ovar macro inline (explanation in macro def comments)
12013 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12014       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12015 @end smallexample
12016
12017 @noindent
12018 All of the arguments are optional. If invoked without any argument,
12019 @code{gnatname} will display its usage.
12020
12021 @noindent
12022 When used with at least one naming pattern, @code{gnatname} will attempt to
12023 find all the compilation units in files that follow at least one of the
12024 naming patterns. To find these compilation units,
12025 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12026 regular files.
12027
12028 @noindent
12029 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12030 Each Naming Pattern is enclosed between double quotes (or single
12031 quotes on Windows).
12032 A Naming Pattern is a regular expression similar to the wildcard patterns
12033 used in file names by the Unix shells or the DOS prompt.
12034
12035 @noindent
12036 @code{gnatname} may be called with several sections of directories/patterns.
12037 Sections are separated by switch @code{--and}. In each section, there must be
12038 at least one pattern. If no directory is specified in a section, the current
12039 directory (or the project directory is @code{-P} is used) is implied.
12040 The options other that the directory switches and the patterns apply globally
12041 even if they are in different sections.
12042
12043 @noindent
12044 Examples of Naming Patterns are
12045
12046 @smallexample
12047    "*.[12].ada"
12048    "*.ad[sb]*"
12049    "body_*"    "spec_*"
12050 @end smallexample
12051
12052 @noindent
12053 For a more complete description of the syntax of Naming Patterns,
12054 see the second kind of regular expressions described in @file{g-regexp.ads}
12055 (the ``Glob'' regular expressions).
12056
12057 @noindent
12058 When invoked with no switch @code{-P}, @code{gnatname} will create a
12059 configuration pragmas file @file{gnat.adc} in the current working directory,
12060 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12061 unit.
12062
12063 @node Switches for gnatname
12064 @section Switches for @code{gnatname}
12065
12066 @noindent
12067 Switches for @code{gnatname} must precede any specified Naming Pattern.
12068
12069 @noindent
12070 You may specify any of the following switches to @code{gnatname}:
12071
12072 @table @option
12073 @c !sort!
12074
12075 @item --version
12076 @cindex @option{--version} @command{gnatname}
12077 Display Copyright and version, then exit disregarding all other options.
12078
12079 @item --help
12080 @cindex @option{--help} @command{gnatname}
12081 If @option{--version} was not used, display usage, then exit disregarding
12082 all other options.
12083
12084 @item --and
12085 Start another section of directories/patterns.
12086
12087 @item ^-c^/CONFIG_FILE=^@file{file}
12088 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12089 Create a configuration pragmas file @file{file} (instead of the default
12090 @file{gnat.adc}).
12091 @ifclear vms
12092 There may be zero, one or more space between @option{-c} and
12093 @file{file}.
12094 @end ifclear
12095 @file{file} may include directory information. @file{file} must be
12096 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12097 When a switch @option{^-c^/CONFIG_FILE^} is
12098 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12099
12100 @item ^-d^/SOURCE_DIRS=^@file{dir}
12101 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12102 Look for source files in directory @file{dir}. There may be zero, one or more
12103 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12104 When a switch @option{^-d^/SOURCE_DIRS^}
12105 is specified, the current working directory will not be searched for source
12106 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12107 or @option{^-D^/DIR_FILES^} switch.
12108 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12109 If @file{dir} is a relative path, it is relative to the directory of
12110 the configuration pragmas file specified with switch
12111 @option{^-c^/CONFIG_FILE^},
12112 or to the directory of the project file specified with switch
12113 @option{^-P^/PROJECT_FILE^} or,
12114 if neither switch @option{^-c^/CONFIG_FILE^}
12115 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12116 current working directory. The directory
12117 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12118
12119 @item ^-D^/DIRS_FILE=^@file{file}
12120 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12121 Look for source files in all directories listed in text file @file{file}.
12122 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12123 and @file{file}.
12124 @file{file} must be an existing, readable text file.
12125 Each nonempty line in @file{file} must be a directory.
12126 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12127 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12128 @file{file}.
12129
12130 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12131 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12132 Foreign patterns. Using this switch, it is possible to add sources of languages
12133 other than Ada to the list of sources of a project file.
12134 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12135 For example,
12136 @smallexample
12137 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12138 @end smallexample
12139 @noindent
12140 will look for Ada units in all files with the @file{.ada} extension,
12141 and will add to the list of file for project @file{prj.gpr} the C files
12142 with extension @file{.^c^C^}.
12143
12144 @item ^-h^/HELP^
12145 @cindex @option{^-h^/HELP^} (@code{gnatname})
12146 Output usage (help) information. The output is written to @file{stdout}.
12147
12148 @item ^-P^/PROJECT_FILE=^@file{proj}
12149 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12150 Create or update project file @file{proj}. There may be zero, one or more space
12151 between @option{-P} and @file{proj}. @file{proj} may include directory
12152 information. @file{proj} must be writable.
12153 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12154 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12155 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12156
12157 @item ^-v^/VERBOSE^
12158 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12159 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12160 This includes name of the file written, the name of the directories to search
12161 and, for each file in those directories whose name matches at least one of
12162 the Naming Patterns, an indication of whether the file contains a unit,
12163 and if so the name of the unit.
12164
12165 @item ^-v -v^/VERBOSE /VERBOSE^
12166 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12167 Very Verbose mode. In addition to the output produced in verbose mode,
12168 for each file in the searched directories whose name matches none of
12169 the Naming Patterns, an indication is given that there is no match.
12170
12171 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12172 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12173 Excluded patterns. Using this switch, it is possible to exclude some files
12174 that would match the name patterns. For example,
12175 @smallexample
12176 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12177 @end smallexample
12178 @noindent
12179 will look for Ada units in all files with the @file{.ada} extension,
12180 except those whose names end with @file{_nt.ada}.
12181
12182 @end table
12183
12184 @node Examples of gnatname Usage
12185 @section Examples of @code{gnatname} Usage
12186
12187 @ifset vms
12188 @smallexample
12189 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12190 @end smallexample
12191 @end ifset
12192
12193 @ifclear vms
12194 @smallexample
12195 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12196 @end smallexample
12197 @end ifclear
12198
12199 @noindent
12200 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12201 and be writable. In addition, the directory
12202 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12203 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12204
12205 @ifclear vms
12206 Note the optional spaces after @option{-c} and @option{-d}.
12207 @end ifclear
12208
12209 @smallexample
12210 @ifclear vms
12211 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12212   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12213 @end ifclear
12214 @ifset vms
12215 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12216   /EXCLUDED_PATTERN=*_nt_body.ada
12217   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12218   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12219 @end ifset
12220 @end smallexample
12221
12222 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12223 even in conjunction with one or several switches
12224 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12225 are used in this example.
12226
12227 @c *****************************************
12228 @c * G N A T  P r o j e c t  M a n a g e r *
12229 @c *****************************************
12230
12231 @c ------ macros for projects.texi
12232 @c These macros are needed when building the gprbuild documentation, but
12233 @c should have no effect in the gnat user's guide
12234
12235 @macro CODESAMPLE{TXT}
12236 @smallexample
12237 @group
12238 \TXT\
12239 @end group
12240 @end smallexample
12241 @end macro
12242
12243 @macro PROJECTFILE{TXT}
12244 @CODESAMPLE{\TXT\}
12245 @end macro
12246
12247 @c simulates a newline when in a @CODESAMPLE
12248 @macro NL{}
12249 @end macro
12250
12251 @macro TIP{TXT}
12252 @quotation
12253 @noindent
12254 \TXT\
12255 @end quotation
12256 @end macro
12257
12258 @macro TIPHTML{TXT}
12259 \TXT\
12260 @end macro
12261
12262 @macro IMPORTANT{TXT}
12263 @quotation
12264 @noindent
12265 \TXT\
12266 @end quotation
12267
12268 @end macro
12269
12270 @macro NOTE{TXT}
12271 @quotation
12272 @noindent
12273 \TXT\
12274 @end quotation
12275 @end macro
12276
12277 @include projects.texi
12278
12279 @c *****************************************
12280 @c * Cross-referencing tools
12281 @c *****************************************
12282
12283 @node The Cross-Referencing Tools gnatxref and gnatfind
12284 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12285 @findex gnatxref
12286 @findex gnatfind
12287
12288 @noindent
12289 The compiler generates cross-referencing information (unless
12290 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12291 This information indicates where in the source each entity is declared and
12292 referenced. Note that entities in package Standard are not included, but
12293 entities in all other predefined units are included in the output.
12294
12295 Before using any of these two tools, you need to compile successfully your
12296 application, so that GNAT gets a chance to generate the cross-referencing
12297 information.
12298
12299 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12300 information to provide the user with the capability to easily locate the
12301 declaration and references to an entity. These tools are quite similar,
12302 the difference being that @code{gnatfind} is intended for locating
12303 definitions and/or references to a specified entity or entities, whereas
12304 @code{gnatxref} is oriented to generating a full report of all
12305 cross-references.
12306
12307 To use these tools, you must not compile your application using the
12308 @option{-gnatx} switch on the @command{gnatmake} command line
12309 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12310 information will not be generated.
12311
12312 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12313 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12314
12315 @menu
12316 * Switches for gnatxref::
12317 * Switches for gnatfind::
12318 * Project Files for gnatxref and gnatfind::
12319 * Regular Expressions in gnatfind and gnatxref::
12320 * Examples of gnatxref Usage::
12321 * Examples of gnatfind Usage::
12322 @end menu
12323
12324 @node Switches for gnatxref
12325 @section @code{gnatxref} Switches
12326
12327 @noindent
12328 The command invocation for @code{gnatxref} is:
12329 @smallexample
12330 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12331 @c Expanding @ovar macro inline (explanation in macro def comments)
12332 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12333 @end smallexample
12334
12335 @noindent
12336 where
12337
12338 @table @var
12339 @item sourcefile1
12340 @itemx sourcefile2
12341 identifies the source files for which a report is to be generated. The
12342 ``with''ed units will be processed too. You must provide at least one file.
12343
12344 These file names are considered to be regular expressions, so for instance
12345 specifying @file{source*.adb} is the same as giving every file in the current
12346 directory whose name starts with @file{source} and whose extension is
12347 @file{adb}.
12348
12349 You shouldn't specify any directory name, just base names. @command{gnatxref}
12350 and @command{gnatfind} will be able to locate these files by themselves using
12351 the source path. If you specify directories, no result is produced.
12352
12353 @end table
12354
12355 @noindent
12356 The switches can be:
12357 @table @option
12358 @c !sort!
12359 @item --version
12360 @cindex @option{--version} @command{gnatxref}
12361 Display Copyright and version, then exit disregarding all other options.
12362
12363 @item --help
12364 @cindex @option{--help} @command{gnatxref}
12365 If @option{--version} was not used, display usage, then exit disregarding
12366 all other options.
12367
12368 @item ^-a^/ALL_FILES^
12369 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12370 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12371 the read-only files found in the library search path. Otherwise, these files
12372 will be ignored. This option can be used to protect Gnat sources or your own
12373 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12374 much faster, and their output much smaller. Read-only here refers to access
12375 or permissions status in the file system for the current user.
12376
12377 @item -aIDIR
12378 @cindex @option{-aIDIR} (@command{gnatxref})
12379 When looking for source files also look in directory DIR. The order in which
12380 source file search is undertaken is the same as for @command{gnatmake}.
12381
12382 @item -aODIR
12383 @cindex @option{-aODIR} (@command{gnatxref})
12384 When searching for library and object files, look in directory
12385 DIR. The order in which library files are searched is the same as for
12386 @command{gnatmake}.
12387
12388 @item -nostdinc
12389 @cindex @option{-nostdinc} (@command{gnatxref})
12390 Do not look for sources in the system default directory.
12391
12392 @item -nostdlib
12393 @cindex @option{-nostdlib} (@command{gnatxref})
12394 Do not look for library files in the system default directory.
12395
12396 @item --ext=@var{extension}
12397 @cindex @option{--ext} (@command{gnatxref})
12398 Specify an alternate ali file extension. The default is @code{ali} and other
12399 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12400 switch. Note that if this switch overrides the default, which means that only
12401 the new extension will be considered.
12402
12403 @item --RTS=@var{rts-path}
12404 @cindex @option{--RTS} (@command{gnatxref})
12405 Specifies the default location of the runtime library. Same meaning as the
12406 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12407
12408 @item ^-d^/DERIVED_TYPES^
12409 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12410 If this switch is set @code{gnatxref} will output the parent type
12411 reference for each matching derived types.
12412
12413 @item ^-f^/FULL_PATHNAME^
12414 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12415 If this switch is set, the output file names will be preceded by their
12416 directory (if the file was found in the search path). If this switch is
12417 not set, the directory will not be printed.
12418
12419 @item ^-g^/IGNORE_LOCALS^
12420 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12421 If this switch is set, information is output only for library-level
12422 entities, ignoring local entities. The use of this switch may accelerate
12423 @code{gnatfind} and @code{gnatxref}.
12424
12425 @item -IDIR
12426 @cindex @option{-IDIR} (@command{gnatxref})
12427 Equivalent to @samp{-aODIR -aIDIR}.
12428
12429 @item -pFILE
12430 @cindex @option{-pFILE} (@command{gnatxref})
12431 Specify a project file to use @xref{GNAT Project Manager}.
12432 If you need to use the @file{.gpr}
12433 project files, you should use gnatxref through the GNAT driver
12434 (@command{gnat xref -Pproject}).
12435
12436 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12437 project file in the current directory.
12438
12439 If a project file is either specified or found by the tools, then the content
12440 of the source directory and object directory lines are added as if they
12441 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12442 and @samp{^-aO^OBJECT_SEARCH^}.
12443 @item ^-u^/UNUSED^
12444 Output only unused symbols. This may be really useful if you give your
12445 main compilation unit on the command line, as @code{gnatxref} will then
12446 display every unused entity and 'with'ed package.
12447
12448 @ifclear vms
12449 @item -v
12450 Instead of producing the default output, @code{gnatxref} will generate a
12451 @file{tags} file that can be used by vi. For examples how to use this
12452 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12453 to the standard output, thus you will have to redirect it to a file.
12454 @end ifclear
12455
12456 @end table
12457
12458 @noindent
12459 All these switches may be in any order on the command line, and may even
12460 appear after the file names. They need not be separated by spaces, thus
12461 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12462 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12463
12464 @node Switches for gnatfind
12465 @section @code{gnatfind} Switches
12466
12467 @noindent
12468 The command line for @code{gnatfind} is:
12469
12470 @smallexample
12471 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12472 @c       @r{[}@var{file1} @var{file2} @dots{}]
12473 @c Expanding @ovar macro inline (explanation in macro def comments)
12474 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12475       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12476 @end smallexample
12477
12478 @noindent
12479 where
12480
12481 @table @var
12482 @item pattern
12483 An entity will be output only if it matches the regular expression found
12484 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12485
12486 Omitting the pattern is equivalent to specifying @samp{*}, which
12487 will match any entity. Note that if you do not provide a pattern, you
12488 have to provide both a sourcefile and a line.
12489
12490 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12491 for matching purposes. At the current time there is no support for
12492 8-bit codes other than Latin-1, or for wide characters in identifiers.
12493
12494 @item sourcefile
12495 @code{gnatfind} will look for references, bodies or declarations
12496 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12497 and column @var{column}. See @ref{Examples of gnatfind Usage}
12498 for syntax examples.
12499
12500 @item line
12501 is a decimal integer identifying the line number containing
12502 the reference to the entity (or entities) to be located.
12503
12504 @item column
12505 is a decimal integer identifying the exact location on the
12506 line of the first character of the identifier for the
12507 entity reference. Columns are numbered from 1.
12508
12509 @item file1 file2 @dots{}
12510 The search will be restricted to these source files. If none are given, then
12511 the search will be done for every library file in the search path.
12512 These file must appear only after the pattern or sourcefile.
12513
12514 These file names are considered to be regular expressions, so for instance
12515 specifying @file{source*.adb} is the same as giving every file in the current
12516 directory whose name starts with @file{source} and whose extension is
12517 @file{adb}.
12518
12519 The location of the spec of the entity will always be displayed, even if it
12520 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12521 occurrences of the entity in the separate units of the ones given on the
12522 command line will also be displayed.
12523
12524 Note that if you specify at least one file in this part, @code{gnatfind} may
12525 sometimes not be able to find the body of the subprograms.
12526
12527 @end table
12528
12529 @noindent
12530 At least one of 'sourcefile' or 'pattern' has to be present on
12531 the command line.
12532
12533 The following switches are available:
12534 @table @option
12535 @c !sort!
12536
12537 @cindex @option{--version} @command{gnatfind}
12538 Display Copyright and version, then exit disregarding all other options.
12539
12540 @item --help
12541 @cindex @option{--help} @command{gnatfind}
12542 If @option{--version} was not used, display usage, then exit disregarding
12543 all other options.
12544
12545 @item ^-a^/ALL_FILES^
12546 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12547 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12548 the read-only files found in the library search path. Otherwise, these files
12549 will be ignored. This option can be used to protect Gnat sources or your own
12550 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12551 much faster, and their output much smaller. Read-only here refers to access
12552 or permission status in the file system for the current user.
12553
12554 @item -aIDIR
12555 @cindex @option{-aIDIR} (@command{gnatfind})
12556 When looking for source files also look in directory DIR. The order in which
12557 source file search is undertaken is the same as for @command{gnatmake}.
12558
12559 @item -aODIR
12560 @cindex @option{-aODIR} (@command{gnatfind})
12561 When searching for library and object files, look in directory
12562 DIR. The order in which library files are searched is the same as for
12563 @command{gnatmake}.
12564
12565 @item -nostdinc
12566 @cindex @option{-nostdinc} (@command{gnatfind})
12567 Do not look for sources in the system default directory.
12568
12569 @item -nostdlib
12570 @cindex @option{-nostdlib} (@command{gnatfind})
12571 Do not look for library files in the system default directory.
12572
12573 @item --ext=@var{extension}
12574 @cindex @option{--ext} (@command{gnatfind})
12575 Specify an alternate ali file extension. The default is @code{ali} and other
12576 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12577 switch. Note that if this switch overrides the default, which means that only
12578 the new extension will be considered.
12579
12580 @item --RTS=@var{rts-path}
12581 @cindex @option{--RTS} (@command{gnatfind})
12582 Specifies the default location of the runtime library. Same meaning as the
12583 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12584
12585 @item ^-d^/DERIVED_TYPE_INFORMATION^
12586 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12587 If this switch is set, then @code{gnatfind} will output the parent type
12588 reference for each matching derived types.
12589
12590 @item ^-e^/EXPRESSIONS^
12591 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12592 By default, @code{gnatfind} accept the simple regular expression set for
12593 @samp{pattern}. If this switch is set, then the pattern will be
12594 considered as full Unix-style regular expression.
12595
12596 @item ^-f^/FULL_PATHNAME^
12597 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12598 If this switch is set, the output file names will be preceded by their
12599 directory (if the file was found in the search path). If this switch is
12600 not set, the directory will not be printed.
12601
12602 @item ^-g^/IGNORE_LOCALS^
12603 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12604 If this switch is set, information is output only for library-level
12605 entities, ignoring local entities. The use of this switch may accelerate
12606 @code{gnatfind} and @code{gnatxref}.
12607
12608 @item -IDIR
12609 @cindex @option{-IDIR} (@command{gnatfind})
12610 Equivalent to @samp{-aODIR -aIDIR}.
12611
12612 @item -pFILE
12613 @cindex @option{-pFILE} (@command{gnatfind})
12614 Specify a project file (@pxref{GNAT Project Manager}) to use.
12615 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12616 project file in the current directory.
12617
12618 If a project file is either specified or found by the tools, then the content
12619 of the source directory and object directory lines are added as if they
12620 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12621 @samp{^-aO^/OBJECT_SEARCH^}.
12622
12623 @item ^-r^/REFERENCES^
12624 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12625 By default, @code{gnatfind} will output only the information about the
12626 declaration, body or type completion of the entities. If this switch is
12627 set, the @code{gnatfind} will locate every reference to the entities in
12628 the files specified on the command line (or in every file in the search
12629 path if no file is given on the command line).
12630
12631 @item ^-s^/PRINT_LINES^
12632 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12633 If this switch is set, then @code{gnatfind} will output the content
12634 of the Ada source file lines were the entity was found.
12635
12636 @item ^-t^/TYPE_HIERARCHY^
12637 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12638 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12639 the specified type. It act like -d option but recursively from parent
12640 type to parent type. When this switch is set it is not possible to
12641 specify more than one file.
12642
12643 @end table
12644
12645 @noindent
12646 All these switches may be in any order on the command line, and may even
12647 appear after the file names. They need not be separated by spaces, thus
12648 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12649 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12650
12651 As stated previously, gnatfind will search in every directory in the
12652 search path. You can force it to look only in the current directory if
12653 you specify @code{*} at the end of the command line.
12654
12655 @node Project Files for gnatxref and gnatfind
12656 @section Project Files for @command{gnatxref} and @command{gnatfind}
12657
12658 @noindent
12659 Project files allow a programmer to specify how to compile its
12660 application, where to find sources, etc.  These files are used
12661 @ifclear vms
12662 primarily by GPS, but they can also be used
12663 @end ifclear
12664 by the two tools
12665 @code{gnatxref} and @code{gnatfind}.
12666
12667 A project file name must end with @file{.gpr}. If a single one is
12668 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12669 extract the information from it. If multiple project files are found, none of
12670 them is read, and you have to use the @samp{-p} switch to specify the one
12671 you want to use.
12672
12673 The following lines can be included, even though most of them have default
12674 values which can be used in most cases.
12675 The lines can be entered in any order in the file.
12676 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12677 each line. If you have multiple instances, only the last one is taken into
12678 account.
12679
12680 @table @code
12681 @item src_dir=DIR
12682 [default: @code{"^./^[]^"}]
12683 specifies a directory where to look for source files. Multiple @code{src_dir}
12684 lines can be specified and they will be searched in the order they
12685 are specified.
12686
12687 @item obj_dir=DIR
12688 [default: @code{"^./^[]^"}]
12689 specifies a directory where to look for object and library files. Multiple
12690 @code{obj_dir} lines can be specified, and they will be searched in the order
12691 they are specified
12692
12693 @item comp_opt=SWITCHES
12694 [default: @code{""}]
12695 creates a variable which can be referred to subsequently by using
12696 the @code{$@{comp_opt@}} notation. This is intended to store the default
12697 switches given to @command{gnatmake} and @command{gcc}.
12698
12699 @item bind_opt=SWITCHES
12700 [default: @code{""}]
12701 creates a variable which can be referred to subsequently by using
12702 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12703 switches given to @command{gnatbind}.
12704
12705 @item link_opt=SWITCHES
12706 [default: @code{""}]
12707 creates a variable which can be referred to subsequently by using
12708 the @samp{$@{link_opt@}} notation. This is intended to store the default
12709 switches given to @command{gnatlink}.
12710
12711 @item main=EXECUTABLE
12712 [default: @code{""}]
12713 specifies the name of the executable for the application. This variable can
12714 be referred to in the following lines by using the @samp{$@{main@}} notation.
12715
12716 @ifset vms
12717 @item comp_cmd=COMMAND
12718 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12719 @end ifset
12720 @ifclear vms
12721 @item comp_cmd=COMMAND
12722 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12723 @end ifclear
12724 specifies the command used to compile a single file in the application.
12725
12726 @ifset vms
12727 @item make_cmd=COMMAND
12728 [default: @code{"GNAT MAKE $@{main@}
12729 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12730 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12731 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12732 @end ifset
12733 @ifclear vms
12734 @item make_cmd=COMMAND
12735 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12736 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12737 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12738 @end ifclear
12739 specifies the command used to recompile the whole application.
12740
12741 @item run_cmd=COMMAND
12742 [default: @code{"$@{main@}"}]
12743 specifies the command used to run the application.
12744
12745 @item debug_cmd=COMMAND
12746 [default: @code{"gdb $@{main@}"}]
12747 specifies the command used to debug the application
12748
12749 @end table
12750
12751 @noindent
12752 @command{gnatxref} and @command{gnatfind} only take into account the
12753 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12754
12755 @node Regular Expressions in gnatfind and gnatxref
12756 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12757
12758 @noindent
12759 As specified in the section about @command{gnatfind}, the pattern can be a
12760 regular expression. Actually, there are to set of regular expressions
12761 which are recognized by the program:
12762
12763 @table @code
12764 @item globbing patterns
12765 These are the most usual regular expression. They are the same that you
12766 generally used in a Unix shell command line, or in a DOS session.
12767
12768 Here is a more formal grammar:
12769 @smallexample
12770 @group
12771 @iftex
12772 @leftskip=.5cm
12773 @end iftex
12774 regexp ::= term
12775 term   ::= elmt            -- matches elmt
12776 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12777 term   ::= *               -- any string of 0 or more characters
12778 term   ::= ?               -- matches any character
12779 term   ::= [char @{char@}]   -- matches any character listed
12780 term   ::= [char - char]   -- matches any character in range
12781 @end group
12782 @end smallexample
12783
12784 @item full regular expression
12785 The second set of regular expressions is much more powerful. This is the
12786 type of regular expressions recognized by utilities such a @file{grep}.
12787
12788 The following is the form of a regular expression, expressed in Ada
12789 reference manual style BNF is as follows
12790
12791 @smallexample
12792 @iftex
12793 @leftskip=.5cm
12794 @end iftex
12795 @group
12796 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12797
12798 term ::= item @{item@}       -- concatenation (item then item)
12799
12800 item ::= elmt              -- match elmt
12801 item ::= elmt *            -- zero or more elmt's
12802 item ::= elmt +            -- one or more elmt's
12803 item ::= elmt ?            -- matches elmt or nothing
12804 @end group
12805 @group
12806 elmt ::= nschar            -- matches given character
12807 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12808 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12809 elmt ::= [char - char]     -- matches chars in given range
12810 elmt ::= \ char            -- matches given character
12811 elmt ::= .                 -- matches any single character
12812 elmt ::= ( regexp )        -- parens used for grouping
12813
12814 char ::= any character, including special characters
12815 nschar ::= any character except ()[].*+?^^^
12816 @end group
12817 @end smallexample
12818
12819 Following are a few examples:
12820
12821 @table @samp
12822 @item abcde|fghi
12823 will match any of the two strings @samp{abcde} and @samp{fghi},
12824
12825 @item abc*d
12826 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12827 @samp{abcccd}, and so on,
12828
12829 @item [a-z]+
12830 will match any string which has only lowercase characters in it (and at
12831 least one character.
12832
12833 @end table
12834 @end table
12835
12836 @node Examples of gnatxref Usage
12837 @section Examples of @code{gnatxref} Usage
12838
12839 @subsection General Usage
12840
12841 @noindent
12842 For the following examples, we will consider the following units:
12843
12844 @smallexample @c ada
12845 @group
12846 @cartouche
12847 main.ads:
12848 1: with Bar;
12849 2: package Main is
12850 3:     procedure Foo (B : in Integer);
12851 4:     C : Integer;
12852 5: private
12853 6:     D : Integer;
12854 7: end Main;
12855
12856 main.adb:
12857 1: package body Main is
12858 2:     procedure Foo (B : in Integer) is
12859 3:     begin
12860 4:        C := B;
12861 5:        D := B;
12862 6:        Bar.Print (B);
12863 7:        Bar.Print (C);
12864 8:     end Foo;
12865 9: end Main;
12866
12867 bar.ads:
12868 1: package Bar is
12869 2:     procedure Print (B : Integer);
12870 3: end bar;
12871 @end cartouche
12872 @end group
12873 @end smallexample
12874
12875 @table @code
12876
12877 @noindent
12878 The first thing to do is to recompile your application (for instance, in
12879 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12880 the cross-referencing information.
12881 You can then issue any of the following commands:
12882
12883 @item gnatxref main.adb
12884 @code{gnatxref} generates cross-reference information for main.adb
12885 and every unit 'with'ed by main.adb.
12886
12887 The output would be:
12888 @smallexample
12889 @iftex
12890 @leftskip=0cm
12891 @end iftex
12892 B                                                      Type: Integer
12893   Decl: bar.ads           2:22
12894 B                                                      Type: Integer
12895   Decl: main.ads          3:20
12896   Body: main.adb          2:20
12897   Ref:  main.adb          4:13     5:13     6:19
12898 Bar                                                    Type: Unit
12899   Decl: bar.ads           1:9
12900   Ref:  main.adb          6:8      7:8
12901        main.ads           1:6
12902 C                                                      Type: Integer
12903   Decl: main.ads          4:5
12904   Modi: main.adb          4:8
12905   Ref:  main.adb          7:19
12906 D                                                      Type: Integer
12907   Decl: main.ads          6:5
12908   Modi: main.adb          5:8
12909 Foo                                                    Type: Unit
12910   Decl: main.ads          3:15
12911   Body: main.adb          2:15
12912 Main                                                    Type: Unit
12913   Decl: main.ads          2:9
12914   Body: main.adb          1:14
12915 Print                                                   Type: Unit
12916   Decl: bar.ads           2:15
12917   Ref:  main.adb          6:12     7:12
12918 @end smallexample
12919
12920 @noindent
12921 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12922 its body is in main.adb, line 1, column 14 and is not referenced any where.
12923
12924 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12925 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12926
12927 @item gnatxref package1.adb package2.ads
12928 @code{gnatxref} will generates cross-reference information for
12929 package1.adb, package2.ads and any other package 'with'ed by any
12930 of these.
12931
12932 @end table
12933
12934 @ifclear vms
12935 @subsection Using gnatxref with vi
12936
12937 @code{gnatxref} can generate a tags file output, which can be used
12938 directly from @command{vi}. Note that the standard version of @command{vi}
12939 will not work properly with overloaded symbols. Consider using another
12940 free implementation of @command{vi}, such as @command{vim}.
12941
12942 @smallexample
12943 $ gnatxref -v gnatfind.adb > tags
12944 @end smallexample
12945
12946 @noindent
12947 will generate the tags file for @code{gnatfind} itself (if the sources
12948 are in the search path!).
12949
12950 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12951 (replacing @var{entity} by whatever you are looking for), and vi will
12952 display a new file with the corresponding declaration of entity.
12953 @end ifclear
12954
12955 @node Examples of gnatfind Usage
12956 @section Examples of @code{gnatfind} Usage
12957
12958 @table @code
12959
12960 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12961 Find declarations for all entities xyz referenced at least once in
12962 main.adb. The references are search in every library file in the search
12963 path.
12964
12965 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12966 switch is set)
12967
12968 The output will look like:
12969 @smallexample
12970 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12971 ^directory/^[directory]^main.adb:24:10: xyz <= body
12972 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12973 @end smallexample
12974
12975 @noindent
12976 that is to say, one of the entities xyz found in main.adb is declared at
12977 line 12 of main.ads (and its body is in main.adb), and another one is
12978 declared at line 45 of foo.ads
12979
12980 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12981 This is the same command as the previous one, instead @code{gnatfind} will
12982 display the content of the Ada source file lines.
12983
12984 The output will look like:
12985
12986 @smallexample
12987 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12988    procedure xyz;
12989 ^directory/^[directory]^main.adb:24:10: xyz <= body
12990    procedure xyz is
12991 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12992    xyz : Integer;
12993 @end smallexample
12994
12995 @noindent
12996 This can make it easier to find exactly the location your are looking
12997 for.
12998
12999 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13000 Find references to all entities containing an x that are
13001 referenced on line 123 of main.ads.
13002 The references will be searched only in main.ads and foo.adb.
13003
13004 @item gnatfind main.ads:123
13005 Find declarations and bodies for all entities that are referenced on
13006 line 123 of main.ads.
13007
13008 This is the same as @code{gnatfind "*":main.adb:123}.
13009
13010 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13011 Find the declaration for the entity referenced at column 45 in
13012 line 123 of file main.adb in directory mydir. Note that it
13013 is usual to omit the identifier name when the column is given,
13014 since the column position identifies a unique reference.
13015
13016 The column has to be the beginning of the identifier, and should not
13017 point to any character in the middle of the identifier.
13018
13019 @end table
13020
13021 @c *********************************
13022 @node The GNAT Pretty-Printer gnatpp
13023 @chapter The GNAT Pretty-Printer @command{gnatpp}
13024 @findex gnatpp
13025 @cindex Pretty-Printer
13026
13027 @noindent
13028 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13029 for source reformatting / pretty-printing.
13030 It takes an Ada source file as input and generates a reformatted
13031 version as output.
13032 You can specify various style directives via switches; e.g.,
13033 identifier case conventions, rules of indentation, and comment layout.
13034
13035 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13036 tree for the input source and thus requires the input to be syntactically and
13037 semantically legal.
13038 If this condition is not met, @command{gnatpp} will terminate with an
13039 error message; no output file will be generated.
13040
13041 If the source files presented to @command{gnatpp} contain
13042 preprocessing directives, then the output file will
13043 correspond to the generated source after all
13044 preprocessing is carried out. There is no way
13045 using @command{gnatpp} to obtain pretty printed files that
13046 include the preprocessing directives.
13047
13048 If the compilation unit
13049 contained in the input source depends semantically upon units located
13050 outside the current directory, you have to provide the source search path
13051 when invoking @command{gnatpp}, if these units are contained in files with
13052 names that do not follow the GNAT file naming rules, you have to provide
13053 the configuration file describing the corresponding naming scheme;
13054 see the description of the @command{gnatpp}
13055 switches below. Another possibility is to use a project file and to
13056 call @command{gnatpp} through the @command{gnat} driver
13057 (see @ref{The GNAT Driver and Project Files}).
13058
13059 The @command{gnatpp} command has the form
13060
13061 @smallexample
13062 @c $ gnatpp @ovar{switches} @var{filename}
13063 @c Expanding @ovar macro inline (explanation in macro def comments)
13064 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13065 @end smallexample
13066
13067 @noindent
13068 where
13069 @itemize @bullet
13070 @item
13071 @var{switches} is an optional sequence of switches defining such properties as
13072 the formatting rules, the source search path, and the destination for the
13073 output source file
13074
13075 @item
13076 @var{filename} is the name (including the extension) of the source file to
13077 reformat; ``wildcards'' or several file names on the same gnatpp command are
13078 allowed.  The file name may contain path information; it does not have to
13079 follow the GNAT file naming rules
13080
13081 @item
13082 @samp{@var{gcc_switches}} is a list of switches for
13083 @command{gcc}. They will be passed on to all compiler invocations made by
13084 @command{gnatelim} to generate the ASIS trees. Here you can provide
13085 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13086 use the @option{-gnatec} switch to set the configuration file,
13087 use the @option{-gnat05} switch if sources should be compiled in
13088 Ada 2005 mode  etc.
13089 @end itemize
13090
13091 @menu
13092 * Switches for gnatpp::
13093 * Formatting Rules::
13094 @end menu
13095
13096 @node Switches for gnatpp
13097 @section Switches for @command{gnatpp}
13098
13099 @noindent
13100 The following subsections describe the various switches accepted by
13101 @command{gnatpp}, organized by category.
13102
13103 @ifclear vms
13104 You specify a switch by supplying a name and generally also a value.
13105 In many cases the values for a switch with a given name are incompatible with
13106 each other
13107 (for example the switch that controls the casing of a reserved word may have
13108 exactly one value: upper case, lower case, or
13109 mixed case) and thus exactly one such switch can be in effect for an
13110 invocation of @command{gnatpp}.
13111 If more than one is supplied, the last one is used.
13112 However, some values for the same switch are mutually compatible.
13113 You may supply several such switches to @command{gnatpp}, but then
13114 each must be specified in full, with both the name and the value.
13115 Abbreviated forms (the name appearing once, followed by each value) are
13116 not permitted.
13117 For example, to set
13118 the alignment of the assignment delimiter both in declarations and in
13119 assignment statements, you must write @option{-A2A3}
13120 (or @option{-A2 -A3}), but not @option{-A23}.
13121 @end ifclear
13122
13123 @ifset vms
13124 In many cases the set of options for a given qualifier are incompatible with
13125 each other (for example the qualifier that controls the casing of a reserved
13126 word may have exactly one option, which specifies either upper case, lower
13127 case, or mixed case), and thus exactly one such option can be in effect for
13128 an invocation of @command{gnatpp}.
13129 If more than one is supplied, the last one is used.
13130 However, some qualifiers have options that are mutually compatible,
13131 and then you may then supply several such options when invoking
13132 @command{gnatpp}.
13133 @end ifset
13134
13135 In most cases, it is obvious whether or not the
13136 ^values for a switch with a given name^options for a given qualifier^
13137 are compatible with each other.
13138 When the semantics might not be evident, the summaries below explicitly
13139 indicate the effect.
13140
13141 @menu
13142 * Alignment Control::
13143 * Casing Control::
13144 * Construct Layout Control::
13145 * General Text Layout Control::
13146 * Other Formatting Options::
13147 * Setting the Source Search Path::
13148 * Output File Control::
13149 * Other gnatpp Switches::
13150 @end menu
13151
13152 @node Alignment Control
13153 @subsection Alignment Control
13154 @cindex Alignment control in @command{gnatpp}
13155
13156 @noindent
13157 Programs can be easier to read if certain constructs are vertically aligned.
13158 By default all alignments are set ON.
13159 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13160 OFF, and then use one or more of the other
13161 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13162 to activate alignment for specific constructs.
13163
13164 @table @option
13165 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13166
13167 @ifset vms
13168 @item /ALIGN=ON
13169 Set all alignments to ON
13170 @end ifset
13171
13172 @item ^-A0^/ALIGN=OFF^
13173 Set all alignments to OFF
13174
13175 @item ^-A1^/ALIGN=COLONS^
13176 Align @code{:} in declarations
13177
13178 @item ^-A2^/ALIGN=DECLARATIONS^
13179 Align @code{:=} in initializations in declarations
13180
13181 @item ^-A3^/ALIGN=STATEMENTS^
13182 Align @code{:=} in assignment statements
13183
13184 @item ^-A4^/ALIGN=ARROWS^
13185 Align @code{=>} in associations
13186
13187 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13188 Align @code{at} keywords in the component clauses in record
13189 representation clauses
13190 @end table
13191
13192 @noindent
13193 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13194 is allowed.
13195
13196 @node Casing Control
13197 @subsection Casing Control
13198 @cindex Casing control in @command{gnatpp}
13199
13200 @noindent
13201 @command{gnatpp} allows you to specify the casing for reserved words,
13202 pragma names, attribute designators and identifiers.
13203 For identifiers you may define a
13204 general rule for name casing but also override this rule
13205 via a set of dictionary files.
13206
13207 Three types of casing are supported: lower case, upper case, and mixed case.
13208 Lower and upper case are self-explanatory (but since some letters in
13209 Latin1 and other GNAT-supported character sets
13210 exist only in lower-case form, an upper case conversion will have no
13211 effect on them.)
13212 ``Mixed case'' means that the first letter, and also each letter immediately
13213 following an underscore, are converted to their uppercase forms;
13214 all the other letters are converted to their lowercase forms.
13215
13216 @table @option
13217 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13218 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13219 Attribute designators are lower case
13220
13221 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13222 Attribute designators are upper case
13223
13224 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13225 Attribute designators are mixed case (this is the default)
13226
13227 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13228 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13229 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13230 lower case (this is the default)
13231
13232 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13233 Keywords are upper case
13234
13235 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13236 @item ^-nD^/NAME_CASING=AS_DECLARED^
13237 Name casing for defining occurrences are as they appear in the source file
13238 (this is the default)
13239
13240 @item ^-nU^/NAME_CASING=UPPER_CASE^
13241 Names are in upper case
13242
13243 @item ^-nL^/NAME_CASING=LOWER_CASE^
13244 Names are in lower case
13245
13246 @item ^-nM^/NAME_CASING=MIXED_CASE^
13247 Names are in mixed case
13248
13249 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13250 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13251 Enumeration literal casing for defining occurrences are as they appear in the
13252 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13253
13254 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13255 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13256 setting.
13257
13258 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13259 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13260 setting.
13261
13262 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13263 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13264 setting.
13265
13266 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13267 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13268 Names introduced by type and subtype declarations are always
13269 cased as they appear in the declaration in the source file.
13270 Overrides ^-n^/NAME_CASING^ casing setting.
13271
13272 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13273 Names introduced by type and subtype declarations are always in
13274 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13275
13276 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13277 Names introduced by type and subtype declarations are always in
13278 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13279
13280 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13281 Names introduced by type and subtype declarations are always in
13282 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13283
13284 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13285 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13286 Pragma names are lower case
13287
13288 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13289 Pragma names are upper case
13290
13291 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13292 Pragma names are mixed case (this is the default)
13293
13294 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13295 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13296 Use @var{file} as a @emph{dictionary file} that defines
13297 the casing for a set of specified names,
13298 thereby overriding the effect on these names by
13299 any explicit or implicit
13300 ^-n^/NAME_CASING^ switch.
13301 To supply more than one dictionary file,
13302 use ^several @option{-D} switches^a list of files as options^.
13303
13304 @noindent
13305 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13306 to define the casing for the Ada predefined names and
13307 the names declared in the GNAT libraries.
13308
13309 @item ^-D-^/SPECIFIC_CASING^
13310 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13311 Do not use the default dictionary file;
13312 instead, use the casing
13313 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13314 dictionary file(s)
13315 @end table
13316
13317 @noindent
13318 The structure of a dictionary file, and details on the conventions
13319 used in the default dictionary file, are defined in @ref{Name Casing}.
13320
13321 The @option{^-D-^/SPECIFIC_CASING^} and
13322 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13323 compatible.
13324
13325 @node Construct Layout Control
13326 @subsection Construct Layout Control
13327 @cindex Layout control in @command{gnatpp}
13328
13329 @noindent
13330 This group of @command{gnatpp} switches controls the layout of comments and
13331 complex syntactic constructs.  See @ref{Formatting Comments} for details
13332 on their effect.
13333
13334 @table @option
13335 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13336 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13337 All the comments remain unchanged
13338
13339 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13340 GNAT-style comment line indentation (this is the default).
13341
13342 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13343 Reference-manual comment line indentation.
13344
13345 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13346 GNAT-style comment beginning
13347
13348 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13349 Reformat comment blocks
13350
13351 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13352 Keep unchanged special form comments
13353
13354 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13355 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13356 GNAT-style layout (this is the default)
13357
13358 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13359 Compact layout
13360
13361 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13362 Uncompact layout
13363
13364 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13365 @item ^-N^/NOTABS^
13366 All the VT characters are removed from the comment text. All the HT characters
13367 are expanded with the sequences of space characters to get to the next tab
13368 stops.
13369
13370 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13371 @item ^--no-separate-is^/NO_SEPARATE_IS^
13372 Do not place the keyword @code{is} on a separate line in a subprogram body in
13373 case if the spec occupies more then one line.
13374
13375 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13376 @item ^--separate-label^/SEPARATE_LABEL^
13377 Place statement label(s) on a separate line, with the following statement
13378 on the next line.
13379
13380 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13381 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13382 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13383 keyword @code{then} in IF statements on a separate line.
13384
13385 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13386 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13387 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13388 keyword @code{then} in IF statements on a separate line. This option is
13389 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13390
13391 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13392 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13393 Start each USE clause in a context clause from a separate line.
13394
13395 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13396 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13397 Use a separate line for a loop or block statement name, but do not use an extra
13398 indentation level for the statement itself.
13399
13400 @end table
13401
13402 @ifclear vms
13403 @noindent
13404 The @option{-c1} and @option{-c2} switches are incompatible.
13405 The @option{-c3} and @option{-c4} switches are compatible with each other and
13406 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13407 the other comment formatting switches.
13408
13409 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13410 @end ifclear
13411
13412 @ifset vms
13413 @noindent
13414 For the @option{/COMMENTS_LAYOUT} qualifier:
13415 @itemize @bullet
13416 @item
13417 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13418 @item
13419 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13420 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13421 @end itemize
13422
13423 @noindent
13424 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13425 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13426 @end ifset
13427
13428 @node General Text Layout Control
13429 @subsection General Text Layout Control
13430
13431 @noindent
13432 These switches allow control over line length and indentation.
13433
13434 @table @option
13435 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13436 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13437 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13438
13439 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13440 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13441 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13442
13443 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13444 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13445 Indentation level for continuation lines (relative to the line being
13446 continued), @var{nnn} from 1@dots{}9.
13447 The default
13448 value is one less then the (normal) indentation level, unless the
13449 indentation is set to 1 (in which case the default value for continuation
13450 line indentation is also 1)
13451 @end table
13452
13453 @node Other Formatting Options
13454 @subsection Other Formatting Options
13455
13456 @noindent
13457 These switches control the inclusion of missing end/exit labels, and
13458 the indentation level in @b{case} statements.
13459
13460 @table @option
13461 @item ^-e^/NO_MISSED_LABELS^
13462 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13463 Do not insert missing end/exit labels. An end label is the name of
13464 a construct that may optionally be repeated at the end of the
13465 construct's declaration;
13466 e.g., the names of packages, subprograms, and tasks.
13467 An exit label is the name of a loop that may appear as target
13468 of an exit statement within the loop.
13469 By default, @command{gnatpp} inserts these end/exit labels when
13470 they are absent from the original source. This option suppresses such
13471 insertion, so that the formatted source reflects the original.
13472
13473 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13474 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13475 Insert a Form Feed character after a pragma Page.
13476
13477 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13478 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13479 Do not use an additional indentation level for @b{case} alternatives
13480 and variants if there are @var{nnn} or more (the default
13481 value is 10).
13482 If @var{nnn} is 0, an additional indentation level is
13483 used for @b{case} alternatives and variants regardless of their number.
13484
13485 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13486 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13487 If the number of parameter associations is greater than @var{nnn} and if at
13488 least one association uses named notation, start each association from
13489 a new line. If @var{nnn} is 0, no check for the number of associations
13490 is made, this is the default.
13491
13492 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13493 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13494 If the number of parameter specifications is greater than @var{nnn}
13495 (or equal to @var{nnn} in case of a function), start each specification from
13496 a new line. The default for @var{nnn} is 3.
13497 @end table
13498
13499 @node Setting the Source Search Path
13500 @subsection Setting the Source Search Path
13501
13502 @noindent
13503 To define the search path for the input source file, @command{gnatpp}
13504 uses the same switches as the GNAT compiler, with the same effects.
13505
13506 @table @option
13507 @item ^-I^/SEARCH=^@var{dir}
13508 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13509 The same as the corresponding gcc switch
13510
13511 @item ^-I-^/NOCURRENT_DIRECTORY^
13512 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13513 The same as the corresponding gcc switch
13514
13515 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13516 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13517 The same as the corresponding gcc switch
13518
13519 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13520 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13521 The same as the corresponding gcc switch
13522
13523 @end table
13524
13525 @node Output File Control
13526 @subsection Output File Control
13527
13528 @noindent
13529 By default the output is sent to the file whose name is obtained by appending
13530 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13531 (if the file with this name already exists, it is unconditionally overwritten).
13532 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13533 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13534 as output file.
13535 The output may be redirected by the following switches:
13536
13537 @table @option
13538 @item ^-pipe^/STANDARD_OUTPUT^
13539 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13540 Send the output to @code{Standard_Output}
13541
13542 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13543 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13544 Write the output into @var{output_file}.
13545 If @var{output_file} already exists, @command{gnatpp} terminates without
13546 reading or processing the input file.
13547
13548 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13549 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13550 Write the output into @var{output_file}, overwriting the existing file
13551 (if one is present).
13552
13553 @item ^-r^/REPLACE^
13554 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13555 Replace the input source file with the reformatted output, and copy the
13556 original input source into the file whose name is obtained by appending the
13557 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13558 If a file with this name already exists, @command{gnatpp} terminates without
13559 reading or processing the input file.
13560
13561 @item ^-rf^/OVERRIDING_REPLACE^
13562 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13563 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13564 already exists, it is overwritten.
13565
13566 @item ^-rnb^/REPLACE_NO_BACKUP^
13567 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13568 Replace the input source file with the reformatted output without
13569 creating any backup copy of the input source.
13570
13571 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13572 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13573 Specifies the format of the reformatted output file. The @var{xxx}
13574 ^string specified with the switch^option^ may be either
13575 @itemize @bullet
13576 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13577 @item ``@option{^crlf^CRLF^}''
13578 the same as @option{^crlf^CRLF^}
13579 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13580 @item ``@option{^lf^LF^}''
13581 the same as @option{^unix^UNIX^}
13582 @end itemize
13583
13584 @item ^-W^/RESULT_ENCODING=^@var{e}
13585 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13586 Specify the wide character encoding method used to write the code in the
13587 result file
13588 @var{e} is one of the following:
13589
13590 @itemize @bullet
13591
13592 @item ^h^HEX^
13593 Hex encoding
13594
13595 @item ^u^UPPER^
13596 Upper half encoding
13597
13598 @item ^s^SHIFT_JIS^
13599 Shift/JIS encoding
13600
13601 @item ^e^EUC^
13602 EUC encoding
13603
13604 @item ^8^UTF8^
13605 UTF-8 encoding
13606
13607 @item ^b^BRACKETS^
13608 Brackets encoding (default value)
13609 @end itemize
13610
13611 @end table
13612
13613 @noindent
13614 Options @option{^-pipe^/STANDARD_OUTPUT^},
13615 @option{^-o^/OUTPUT^} and
13616 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13617 contains only one file to reformat.
13618 Option
13619 @option{^--eol^/END_OF_LINE^}
13620 and
13621 @option{^-W^/RESULT_ENCODING^}
13622 cannot be used together
13623 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13624
13625 @node Other gnatpp Switches
13626 @subsection Other @code{gnatpp} Switches
13627
13628 @noindent
13629 The additional @command{gnatpp} switches are defined in this subsection.
13630
13631 @table @option
13632 @item ^-files @var{filename}^/FILES=@var{filename}^
13633 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13634 Take the argument source files from the specified file. This file should be an
13635 ordinary text file containing file names separated by spaces or
13636 line breaks. You can use this switch more than once in the same call to
13637 @command{gnatpp}. You also can combine this switch with an explicit list of
13638 files.
13639
13640 @item ^-v^/VERBOSE^
13641 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13642 Verbose mode;
13643 @command{gnatpp} generates version information and then
13644 a trace of the actions it takes to produce or obtain the ASIS tree.
13645
13646 @item ^-w^/WARNINGS^
13647 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13648 Warning mode;
13649 @command{gnatpp} generates a warning whenever it cannot provide
13650 a required layout in the result source.
13651 @end table
13652
13653 @node Formatting Rules
13654 @section Formatting Rules
13655
13656 @noindent
13657 The following subsections show how @command{gnatpp} treats ``white space'',
13658 comments, program layout, and name casing.
13659 They provide the detailed descriptions of the switches shown above.
13660
13661 @menu
13662 * White Space and Empty Lines::
13663 * Formatting Comments::
13664 * Construct Layout::
13665 * Name Casing::
13666 @end menu
13667
13668 @node White Space and Empty Lines
13669 @subsection White Space and Empty Lines
13670
13671 @noindent
13672 @command{gnatpp} does not have an option to control space characters.
13673 It will add or remove spaces according to the style illustrated by the
13674 examples in the @cite{Ada Reference Manual}.
13675
13676 The only format effectors
13677 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13678 that will appear in the output file are platform-specific line breaks,
13679 and also format effectors within (but not at the end of) comments.
13680 In particular, each horizontal tab character that is not inside
13681 a comment will be treated as a space and thus will appear in the
13682 output file as zero or more spaces depending on
13683 the reformatting of the line in which it appears.
13684 The only exception is a Form Feed character, which is inserted after a
13685 pragma @code{Page} when @option{-ff} is set.
13686
13687 The output file will contain no lines with trailing ``white space'' (spaces,
13688 format effectors).
13689
13690 Empty lines in the original source are preserved
13691 only if they separate declarations or statements.
13692 In such contexts, a
13693 sequence of two or more empty lines is replaced by exactly one empty line.
13694 Note that a blank line will be removed if it separates two ``comment blocks''
13695 (a comment block is a sequence of whole-line comments).
13696 In order to preserve a visual separation between comment blocks, use an
13697 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13698 Likewise, if for some reason you wish to have a sequence of empty lines,
13699 use a sequence of empty comments instead.
13700
13701 @node Formatting Comments
13702 @subsection Formatting Comments
13703
13704 @noindent
13705 Comments in Ada code are of two kinds:
13706 @itemize @bullet
13707 @item
13708 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13709 ``white space'') on a line
13710
13711 @item
13712 an @emph{end-of-line comment}, which follows some other Ada lexical element
13713 on the same line.
13714 @end itemize
13715
13716 @noindent
13717 The indentation of a whole-line comment is that of either
13718 the preceding or following line in
13719 the formatted source, depending on switch settings as will be described below.
13720
13721 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13722 between the end of the preceding Ada lexical element and the beginning
13723 of the comment as appear in the original source,
13724 unless either the comment has to be split to
13725 satisfy the line length limitation, or else the next line contains a
13726 whole line comment that is considered a continuation of this end-of-line
13727 comment (because it starts at the same position).
13728 In the latter two
13729 cases, the start of the end-of-line comment is moved right to the nearest
13730 multiple of the indentation level.
13731 This may result in a ``line overflow'' (the right-shifted comment extending
13732 beyond the maximum line length), in which case the comment is split as
13733 described below.
13734
13735 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13736 (GNAT-style comment line indentation)
13737 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13738 (reference-manual comment line indentation).
13739 With reference-manual style, a whole-line comment is indented as if it
13740 were a declaration or statement at the same place
13741 (i.e., according to the indentation of the preceding line(s)).
13742 With GNAT style, a whole-line comment that is immediately followed by an
13743 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13744 word @b{begin}, is indented based on the construct that follows it.
13745
13746 For example:
13747 @smallexample @c ada
13748 @cartouche
13749 if A then
13750     null;
13751        -- some comment
13752 else
13753    null;
13754 end if;
13755 @end cartouche
13756 @end smallexample
13757
13758 @noindent
13759 Reference-manual indentation produces:
13760
13761 @smallexample @c ada
13762 @cartouche
13763 if A then
13764    null;
13765    --  some comment
13766 else
13767    null;
13768 end if;
13769 @end cartouche
13770 @end smallexample
13771
13772 @noindent
13773 while GNAT-style indentation produces:
13774
13775 @smallexample @c ada
13776 @cartouche
13777 if A then
13778    null;
13779 --  some comment
13780 else
13781    null;
13782 end if;
13783 @end cartouche
13784 @end smallexample
13785
13786 @noindent
13787 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13788 (GNAT style comment beginning) has the following
13789 effect:
13790
13791 @itemize @bullet
13792 @item
13793 For each whole-line comment that does not end with two hyphens,
13794 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13795 to ensure that there are at least two spaces between these hyphens and the
13796 first non-blank character of the comment.
13797 @end itemize
13798
13799 @noindent
13800 For an end-of-line comment, if in the original source the next line is a
13801 whole-line comment that starts at the same position
13802 as the end-of-line comment,
13803 then the whole-line comment (and all whole-line comments
13804 that follow it and that start at the same position)
13805 will start at this position in the output file.
13806
13807 @noindent
13808 That is, if in the original source we have:
13809
13810 @smallexample @c ada
13811 @cartouche
13812 begin
13813 A := B + C;            --  B must be in the range Low1..High1
13814                        --  C must be in the range Low2..High2
13815              --B+C will be in the range Low1+Low2..High1+High2
13816 X := X + 1;
13817 @end cartouche
13818 @end smallexample
13819
13820 @noindent
13821 Then in the formatted source we get
13822
13823 @smallexample @c ada
13824 @cartouche
13825 begin
13826    A := B + C;            --  B must be in the range Low1..High1
13827                           --  C must be in the range Low2..High2
13828    --  B+C will be in the range Low1+Low2..High1+High2
13829    X := X + 1;
13830 @end cartouche
13831 @end smallexample
13832
13833 @noindent
13834 A comment that exceeds the line length limit will be split.
13835 Unless switch
13836 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13837 the line belongs to a reformattable block, splitting the line generates a
13838 @command{gnatpp} warning.
13839 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13840 comments may be reformatted in typical
13841 word processor style (that is, moving words between lines and putting as
13842 many words in a line as possible).
13843
13844 @noindent
13845 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13846 that has a special format (that is, a character that is neither a letter nor digit
13847 not white space nor line break immediately following the leading @code{--} of
13848 the comment) should be without any change moved from the argument source
13849 into reformatted source. This switch allows to preserve comments that are used
13850 as a special marks in the code (e.g.@: SPARK annotation).
13851
13852 @node Construct Layout
13853 @subsection Construct Layout
13854
13855 @noindent
13856 In several cases the suggested layout in the Ada Reference Manual includes
13857 an extra level of indentation that many programmers prefer to avoid. The
13858 affected cases include:
13859
13860 @itemize @bullet
13861
13862 @item Record type declaration (RM 3.8)
13863
13864 @item Record representation clause (RM 13.5.1)
13865
13866 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13867
13868 @item Block statement in case if a block has a statement identifier (RM 5.6)
13869 @end itemize
13870
13871 @noindent
13872 In compact mode (when GNAT style layout or compact layout is set),
13873 the pretty printer uses one level of indentation instead
13874 of two. This is achieved in the record definition and record representation
13875 clause cases by putting the @code{record} keyword on the same line as the
13876 start of the declaration or representation clause, and in the block and loop
13877 case by putting the block or loop header on the same line as the statement
13878 identifier.
13879
13880 @noindent
13881 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13882 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13883 layout on the one hand, and uncompact layout
13884 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13885 can be illustrated by the following examples:
13886
13887 @iftex
13888 @cartouche
13889 @multitable @columnfractions .5 .5
13890 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13891
13892 @item
13893 @smallexample @c ada
13894 type q is record
13895    a : integer;
13896    b : integer;
13897 end record;
13898 @end smallexample
13899 @tab
13900 @smallexample @c ada
13901 type q is
13902    record
13903       a : integer;
13904       b : integer;
13905    end record;
13906 @end smallexample
13907
13908 @item
13909 @smallexample @c ada
13910 for q use record
13911    a at 0 range  0 .. 31;
13912    b at 4 range  0 .. 31;
13913 end record;
13914 @end smallexample
13915 @tab
13916 @smallexample @c ada
13917 for q use
13918    record
13919       a at 0 range  0 .. 31;
13920       b at 4 range  0 .. 31;
13921    end record;
13922 @end smallexample
13923
13924 @item
13925 @smallexample @c ada
13926 Block : declare
13927    A : Integer := 3;
13928 begin
13929    Proc (A, A);
13930 end Block;
13931 @end smallexample
13932 @tab
13933 @smallexample @c ada
13934 Block :
13935    declare
13936       A : Integer := 3;
13937    begin
13938       Proc (A, A);
13939    end Block;
13940 @end smallexample
13941
13942 @item
13943 @smallexample @c ada
13944 Clear : for J in 1 .. 10 loop
13945    A (J) := 0;
13946 end loop Clear;
13947 @end smallexample
13948 @tab
13949 @smallexample @c ada
13950 Clear :
13951    for J in 1 .. 10 loop
13952       A (J) := 0;
13953    end loop Clear;
13954 @end smallexample
13955 @end multitable
13956 @end cartouche
13957 @end iftex
13958
13959 @ifnottex
13960 @smallexample
13961 @cartouche
13962 GNAT style, compact layout              Uncompact layout
13963
13964 type q is record                        type q is
13965    a : integer;                            record
13966    b : integer;                               a : integer;
13967 end record;                                   b : integer;
13968                                            end record;
13969
13970 for q use record                        for q use
13971    a at 0 range  0 .. 31;                  record
13972    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13973 end record;                                   b at 4 range  0 .. 31;
13974                                            end record;
13975
13976 Block : declare                         Block :
13977    A : Integer := 3;                       declare
13978 begin                                         A : Integer := 3;
13979    Proc (A, A);                            begin
13980 end Block;                                    Proc (A, A);
13981                                            end Block;
13982
13983 Clear : for J in 1 .. 10 loop           Clear :
13984    A (J) := 0;                             for J in 1 .. 10 loop
13985 end loop Clear;                               A (J) := 0;
13986                                            end loop Clear;
13987 @end cartouche
13988 @end smallexample
13989 @end ifnottex
13990
13991 @noindent
13992 A further difference between GNAT style layout and compact layout is that
13993 GNAT style layout inserts empty lines as separation for
13994 compound statements, return statements and bodies.
13995
13996 Note that the layout specified by
13997 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13998 for named block and loop statements overrides the layout defined by these
13999 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14000 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14001 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14002
14003 @node Name Casing
14004 @subsection Name Casing
14005
14006 @noindent
14007 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14008 the same casing as the corresponding defining identifier.
14009
14010 You control the casing for defining occurrences via the
14011 @option{^-n^/NAME_CASING^} switch.
14012 @ifclear vms
14013 With @option{-nD} (``as declared'', which is the default),
14014 @end ifclear
14015 @ifset vms
14016 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14017 @end ifset
14018 defining occurrences appear exactly as in the source file
14019 where they are declared.
14020 The other ^values for this switch^options for this qualifier^ ---
14021 @option{^-nU^UPPER_CASE^},
14022 @option{^-nL^LOWER_CASE^},
14023 @option{^-nM^MIXED_CASE^} ---
14024 result in
14025 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14026 If @command{gnatpp} changes the casing of a defining
14027 occurrence, it analogously changes the casing of all the
14028 usage occurrences of this name.
14029
14030 If the defining occurrence of a name is not in the source compilation unit
14031 currently being processed by @command{gnatpp}, the casing of each reference to
14032 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14033 switch (subject to the dictionary file mechanism described below).
14034 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14035 had affected the
14036 casing for the defining occurrence of the name.
14037
14038 Some names may need to be spelled with casing conventions that are not
14039 covered by the upper-, lower-, and mixed-case transformations.
14040 You can arrange correct casing by placing such names in a
14041 @emph{dictionary file},
14042 and then supplying a @option{^-D^/DICTIONARY^} switch.
14043 The casing of names from dictionary files overrides
14044 any @option{^-n^/NAME_CASING^} switch.
14045
14046 To handle the casing of Ada predefined names and the names from GNAT libraries,
14047 @command{gnatpp} assumes a default dictionary file.
14048 The name of each predefined entity is spelled with the same casing as is used
14049 for the entity in the @cite{Ada Reference Manual}.
14050 The name of each entity in the GNAT libraries is spelled with the same casing
14051 as is used in the declaration of that entity.
14052
14053 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14054 default dictionary file.
14055 Instead, the casing for predefined and GNAT-defined names will be established
14056 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14057 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14058 will appear as just shown,
14059 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14060 To ensure that even such names are rendered in uppercase,
14061 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14062 (or else, less conveniently, place these names in upper case in a dictionary
14063 file).
14064
14065 A dictionary file is
14066 a plain text file; each line in this file can be either a blank line
14067 (containing only space characters and ASCII.HT characters), an Ada comment
14068 line, or the specification of exactly one @emph{casing schema}.
14069
14070 A casing schema is a string that has the following syntax:
14071
14072 @smallexample
14073 @cartouche
14074   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14075
14076   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14077 @end cartouche
14078 @end smallexample
14079
14080 @noindent
14081 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14082 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14083
14084 The casing schema string can be followed by white space and/or an Ada-style
14085 comment; any amount of white space is allowed before the string.
14086
14087 If a dictionary file is passed as
14088 @ifclear vms
14089 the value of a @option{-D@var{file}} switch
14090 @end ifclear
14091 @ifset vms
14092 an option to the @option{/DICTIONARY} qualifier
14093 @end ifset
14094 then for every
14095 simple name and every identifier, @command{gnatpp} checks if the dictionary
14096 defines the casing for the name or for some of its parts (the term ``subword''
14097 is used below to denote the part of a name which is delimited by ``_'' or by
14098 the beginning or end of the word and which does not contain any ``_'' inside):
14099
14100 @itemize @bullet
14101 @item
14102 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14103 the casing defined by the dictionary; no subwords are checked for this word
14104
14105 @item
14106 for every subword @command{gnatpp} checks if the dictionary contains the
14107 corresponding string of the form @code{*@var{simple_identifier}*},
14108 and if it does, the casing of this @var{simple_identifier} is used
14109 for this subword
14110
14111 @item
14112 if the whole name does not contain any ``_'' inside, and if for this name
14113 the dictionary contains two entries - one of the form @var{identifier},
14114 and another - of the form *@var{simple_identifier}*, then the first one
14115 is applied to define the casing of this name
14116
14117 @item
14118 if more than one dictionary file is passed as @command{gnatpp} switches, each
14119 dictionary adds new casing exceptions and overrides all the existing casing
14120 exceptions set by the previous dictionaries
14121
14122 @item
14123 when @command{gnatpp} checks if the word or subword is in the dictionary,
14124 this check is not case sensitive
14125 @end itemize
14126
14127 @noindent
14128 For example, suppose we have the following source to reformat:
14129
14130 @smallexample @c ada
14131 @cartouche
14132 procedure test is
14133    name1 : integer := 1;
14134    name4_name3_name2 : integer := 2;
14135    name2_name3_name4 : Boolean;
14136    name1_var : Float;
14137 begin
14138    name2_name3_name4 := name4_name3_name2 > name1;
14139 end;
14140 @end cartouche
14141 @end smallexample
14142
14143 @noindent
14144 And suppose we have two dictionaries:
14145
14146 @smallexample
14147 @cartouche
14148 @i{dict1:}
14149    NAME1
14150    *NaMe3*
14151    *Name1*
14152 @end cartouche
14153
14154 @cartouche
14155 @i{dict2:}
14156   *NAME3*
14157 @end cartouche
14158 @end smallexample
14159
14160 @noindent
14161 If @command{gnatpp} is called with the following switches:
14162
14163 @smallexample
14164 @ifclear vms
14165 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14166 @end ifclear
14167 @ifset vms
14168 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14169 @end ifset
14170 @end smallexample
14171
14172 @noindent
14173 then we will get the following name casing in the @command{gnatpp} output:
14174
14175 @smallexample @c ada
14176 @cartouche
14177 procedure Test is
14178    NAME1             : Integer := 1;
14179    Name4_NAME3_Name2 : Integer := 2;
14180    Name2_NAME3_Name4 : Boolean;
14181    Name1_Var         : Float;
14182 begin
14183    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14184 end Test;
14185 @end cartouche
14186 @end smallexample
14187
14188 @c *********************************
14189 @node The GNAT Metric Tool gnatmetric
14190 @chapter The GNAT Metric Tool @command{gnatmetric}
14191 @findex gnatmetric
14192 @cindex Metric tool
14193
14194 @noindent
14195 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14196 for computing various program metrics.
14197 It takes an Ada source file as input and generates a file containing the
14198 metrics data as output. Various switches control which
14199 metrics are computed and output.
14200
14201 @command{gnatmetric} generates and uses the ASIS
14202 tree for the input source and thus requires the input to be syntactically and
14203 semantically legal.
14204 If this condition is not met, @command{gnatmetric} will generate
14205 an error message; no metric information for this file will be
14206 computed and reported.
14207
14208 If the compilation unit contained in the input source depends semantically
14209 upon units in files located outside the current directory, you have to provide
14210 the source search path when invoking @command{gnatmetric}.
14211 If it depends semantically upon units that are contained
14212 in files with names that do not follow the GNAT file naming rules, you have to
14213 provide the configuration file describing the corresponding naming scheme (see
14214 the description of the @command{gnatmetric} switches below.)
14215 Alternatively, you may use a project file and invoke @command{gnatmetric}
14216 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14217
14218 The @command{gnatmetric} command has the form
14219
14220 @smallexample
14221 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14222 @c Expanding @ovar macro inline (explanation in macro def comments)
14223 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14224 @end smallexample
14225
14226 @noindent
14227 where
14228 @itemize @bullet
14229 @item
14230 @var{switches} specify the metrics to compute and define the destination for
14231 the output
14232
14233 @item
14234 Each @var{filename} is the name (including the extension) of a source
14235 file to process. ``Wildcards'' are allowed, and
14236 the file name may contain path information.
14237 If no @var{filename} is supplied, then the @var{switches} list must contain
14238 at least one
14239 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14240 Including both a @option{-files} switch and one or more
14241 @var{filename} arguments is permitted.
14242
14243 @item
14244 @samp{@var{gcc_switches}} is a list of switches for
14245 @command{gcc}. They will be passed on to all compiler invocations made by
14246 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14247 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14248 and use the @option{-gnatec} switch to set the configuration file,
14249 use the @option{-gnat05} switch if sources should be compiled in
14250 Ada 2005 mode etc.
14251 @end itemize
14252
14253 @menu
14254 * Switches for gnatmetric::
14255 @end menu
14256
14257 @node Switches for gnatmetric
14258 @section Switches for @command{gnatmetric}
14259
14260 @noindent
14261 The following subsections describe the various switches accepted by
14262 @command{gnatmetric}, organized by category.
14263
14264 @menu
14265 * Output Files Control::
14266 * Disable Metrics For Local Units::
14267 * Specifying a set of metrics to compute::
14268 * Other gnatmetric Switches::
14269 * Generate project-wide metrics::
14270 @end menu
14271
14272 @node Output Files Control
14273 @subsection Output File Control
14274 @cindex Output file control in @command{gnatmetric}
14275
14276 @noindent
14277 @command{gnatmetric} has two output formats. It can generate a
14278 textual (human-readable) form, and also XML. By default only textual
14279 output is generated.
14280
14281 When generating the output in textual form, @command{gnatmetric} creates
14282 for each Ada source file a corresponding text file
14283 containing the computed metrics, except for the case when the set of metrics
14284 specified by gnatmetric parameters consists only of metrics that are computed
14285 for the whole set of analyzed sources, but not for each Ada source.
14286 By default, this file is placed in the same directory as where the source
14287 file is located, and its name is obtained
14288 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14289 input file.
14290
14291 All the output information generated in XML format is placed in a single
14292 file. By default this file is placed in the current directory and has the
14293 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14294
14295 Some of the computed metrics are summed over the units passed to
14296 @command{gnatmetric}; for example, the total number of lines of code.
14297 By default this information is sent to @file{stdout}, but a file
14298 can be specified with the @option{-og} switch.
14299
14300 The following switches control the @command{gnatmetric} output:
14301
14302 @table @option
14303 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14304 @item ^-x^/XML^
14305 Generate the XML output
14306
14307 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14308 @item ^-xs^/XSD^
14309 Generate the XML output and the XML schema file that describes the structure
14310 of the XML metric report, this schema is assigned to the XML file. The schema
14311 file has the same name as the XML output file with @file{.xml} suffix replaced
14312 with @file{.xsd}
14313
14314 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14315 @item ^-nt^/NO_TEXT^
14316 Do not generate the output in text form (implies @option{^-x^/XML^})
14317
14318 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14319 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14320 Put text files with detailed metrics into @var{output_dir}
14321
14322 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14323 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14324 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14325 in the name of the output file.
14326
14327 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14328 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14329 Put global metrics into @var{file_name}
14330
14331 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14332 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14333 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14334
14335 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14336 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14337 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14338 output includes the name(s) of the Ada source file(s) from which the metrics
14339 are computed.  By default each name includes the absolute path. The
14340 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14341 to exclude all directory information from the file names that are output.)
14342
14343 @end table
14344
14345 @node Disable Metrics For Local Units
14346 @subsection Disable Metrics For Local Units
14347 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14348
14349 @noindent
14350 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14351 one compilation
14352 unit per one source file. It computes line metrics for the whole source
14353 file, and it also computes syntax
14354 and complexity metrics for the file's outermost unit.
14355
14356 By default, @command{gnatmetric} will also compute all metrics for certain
14357 kinds of locally declared program units:
14358
14359 @itemize @bullet
14360 @item
14361 subprogram (and generic subprogram) bodies;
14362
14363 @item
14364 package (and generic package) specs and bodies;
14365
14366 @item
14367 task object and type specifications and bodies;
14368
14369 @item
14370 protected object and type specifications and bodies.
14371 @end itemize
14372
14373 @noindent
14374 These kinds of entities will be referred to as
14375 @emph{eligible local program units}, or simply @emph{eligible local units},
14376 @cindex Eligible local unit (for @command{gnatmetric})
14377 in the discussion below.
14378
14379 Note that a subprogram declaration, generic instantiation,
14380 or renaming declaration only receives metrics
14381 computation when it appear as the outermost entity
14382 in a source file.
14383
14384 Suppression of metrics computation for eligible local units can be
14385 obtained via the following switch:
14386
14387 @table @option
14388 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14389 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14390 Do not compute detailed metrics for eligible local program units
14391
14392 @end table
14393
14394 @node Specifying a set of metrics to compute
14395 @subsection Specifying a set of metrics to compute
14396
14397 @noindent
14398 By default all the metrics are computed and reported. The switches
14399 described in this subsection allow you to control, on an individual
14400 basis, whether metrics are computed and
14401 reported. If at least one positive metric
14402 switch is specified (that is, a switch that defines that a given
14403 metric or set of metrics is to be computed), then only
14404 explicitly specified metrics are reported.
14405
14406 @menu
14407 * Line Metrics Control::
14408 * Syntax Metrics Control::
14409 * Complexity Metrics Control::
14410 * Coupling Metrics Control::
14411 @end menu
14412
14413 @node Line Metrics Control
14414 @subsubsection Line Metrics Control
14415 @cindex Line metrics control in @command{gnatmetric}
14416
14417 @noindent
14418 For any (legal) source file, and for each of its
14419 eligible local program units, @command{gnatmetric} computes the following
14420 metrics:
14421
14422 @itemize @bullet
14423 @item
14424 the total number of lines;
14425
14426 @item
14427 the total number of code lines (i.e., non-blank lines that are not comments)
14428
14429 @item
14430 the number of comment lines
14431
14432 @item
14433 the number of code lines containing end-of-line comments;
14434
14435 @item
14436 the comment percentage: the ratio between the number of lines that contain
14437 comments and the number of all non-blank lines, expressed as a percentage;
14438
14439 @item
14440 the number of empty lines and lines containing only space characters and/or
14441 format effectors (blank lines)
14442
14443 @item
14444 the average number of code lines in subprogram bodies, task bodies, entry
14445 bodies and statement sequences in package bodies (this metric is only computed
14446 across the whole set of the analyzed units)
14447
14448 @end itemize
14449
14450 @noindent
14451 @command{gnatmetric} sums the values of the line metrics for all the
14452 files being processed and then generates the cumulative results. The tool
14453 also computes for all the files being processed the average number of code
14454 lines in bodies.
14455
14456 You can use the following switches to select the specific line metrics
14457 to be computed and reported.
14458
14459 @table @option
14460 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14461
14462 @ifclear vms
14463 @cindex @option{--no-lines@var{x}}
14464 @end ifclear
14465
14466 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14467 Report all the line metrics
14468
14469 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14470 Do not report any of line metrics
14471
14472 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14473 Report the number of all lines
14474
14475 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14476 Do not report the number of all lines
14477
14478 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14479 Report the number of code lines
14480
14481 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14482 Do not report the number of code lines
14483
14484 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14485 Report the number of comment lines
14486
14487 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14488 Do not report the number of comment lines
14489
14490 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14491 Report the number of code lines containing
14492 end-of-line comments
14493
14494 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14495 Do not report the number of code lines containing
14496 end-of-line comments
14497
14498 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14499 Report the comment percentage in the program text
14500
14501 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14502 Do not report the comment percentage in the program text
14503
14504 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14505 Report the number of blank lines
14506
14507 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14508 Do not report the number of blank lines
14509
14510 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14511 Report the average number of code lines in subprogram bodies, task bodies,
14512 entry bodies and statement sequences in package bodies. The metric is computed
14513 and reported for the whole set of processed Ada sources only.
14514
14515 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14516 Do not report the average number of code lines in subprogram bodies,
14517 task bodies, entry bodies and statement sequences in package bodies.
14518
14519 @end table
14520
14521 @node Syntax Metrics Control
14522 @subsubsection Syntax Metrics Control
14523 @cindex Syntax metrics control in @command{gnatmetric}
14524
14525 @noindent
14526 @command{gnatmetric} computes various syntactic metrics for the
14527 outermost unit and for each eligible local unit:
14528
14529 @table @emph
14530 @item LSLOC (``Logical Source Lines Of Code'')
14531 The total number of declarations and the total number of statements. Note
14532 that the definition of declarations is the one given in the reference
14533 manual:
14534
14535 @noindent
14536 ``Each of the following is defined to be a declaration: any basic_declaration;
14537 an enumeration_literal_specification; a discriminant_specification;
14538 a component_declaration; a loop_parameter_specification; a
14539 parameter_specification; a subprogram_body; an entry_declaration;
14540 an entry_index_specification; a choice_parameter_specification;
14541 a generic_formal_parameter_declaration.''
14542
14543 This means for example that each enumeration literal adds one to the count,
14544 as well as each subprogram parameter.
14545
14546 Thus the results from this metric will be significantly greater than might
14547 be expected from a naive view of counting semicolons.
14548
14549 @item Maximal static nesting level of inner program units
14550 According to
14551 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14552 package, a task unit, a protected unit, a
14553 protected entry, a generic unit, or an explicitly declared subprogram other
14554 than an enumeration literal.''
14555
14556 @item Maximal nesting level of composite syntactic constructs
14557 This corresponds to the notion of the
14558 maximum nesting level in the GNAT built-in style checks
14559 (@pxref{Style Checking})
14560 @end table
14561
14562 @noindent
14563 For the outermost unit in the file, @command{gnatmetric} additionally computes
14564 the following metrics:
14565
14566 @table @emph
14567 @item Public subprograms
14568 This metric is computed for package specs. It is the
14569 number of subprograms and generic subprograms declared in the visible
14570 part (including the visible part of nested packages, protected objects, and
14571 protected types).
14572
14573 @item All subprograms
14574 This metric is computed for bodies and subunits. The
14575 metric is equal to a total number of subprogram bodies in the compilation
14576 unit.
14577 Neither generic instantiations nor renamings-as-a-body nor body stubs
14578 are counted. Any subprogram body is counted, independently of its nesting
14579 level and enclosing constructs. Generic bodies and bodies of protected
14580 subprograms are counted in the same way as ``usual'' subprogram bodies.
14581
14582 @item Public types
14583 This metric is computed for package specs and
14584 generic package declarations. It is the total number of types
14585 that can be referenced from outside this compilation unit, plus the
14586 number of types from all the visible parts of all the visible generic
14587 packages. Generic formal types are not counted.  Only types, not subtypes,
14588 are included.
14589
14590 @noindent
14591 Along with the total number of public types, the following
14592 types are counted and reported separately:
14593
14594 @itemize @bullet
14595 @item
14596 Abstract types
14597
14598 @item
14599 Root tagged types (abstract, non-abstract, private, non-private). Type
14600 extensions are @emph{not} counted
14601
14602 @item
14603 Private types (including private extensions)
14604
14605 @item
14606 Task types
14607
14608 @item
14609 Protected types
14610
14611 @end itemize
14612
14613 @item All types
14614 This metric is computed for any compilation unit. It is equal to the total
14615 number of the declarations of different types given in the compilation unit.
14616 The private and the corresponding full type declaration are counted as one
14617 type declaration. Incomplete type declarations and generic formal types
14618 are not counted.
14619 No distinction is made among different kinds of types (abstract,
14620 private etc.); the total number of types is computed and reported.
14621
14622 @end table
14623
14624 @noindent
14625 By default, all the syntax metrics are computed and reported. You can use the
14626 following switches to select specific syntax metrics.
14627
14628 @table @option
14629
14630 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14631
14632 @ifclear vms
14633 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14634 @end ifclear
14635
14636 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14637 Report all the syntax metrics
14638
14639 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14640 Do not report any of syntax metrics
14641
14642 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14643 Report the total number of declarations
14644
14645 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14646 Do not report the total number of declarations
14647
14648 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14649 Report the total number of statements
14650
14651 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14652 Do not report the total number of statements
14653
14654 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14655 Report the number of public subprograms in a compilation unit
14656
14657 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14658 Do not report the number of public subprograms in a compilation unit
14659
14660 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14661 Report the number of all the subprograms in a compilation unit
14662
14663 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14664 Do not report the number of all the subprograms in a compilation unit
14665
14666 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14667 Report the number of public types in a compilation unit
14668
14669 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14670 Do not report the number of public types in a compilation unit
14671
14672 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14673 Report the number of all the types in a compilation unit
14674
14675 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14676 Do not report the number of all the types in a compilation unit
14677
14678 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14679 Report the maximal program unit nesting level
14680
14681 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14682 Do not report the maximal program unit nesting level
14683
14684 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14685 Report the maximal construct nesting level
14686
14687 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14688 Do not report the maximal construct nesting level
14689
14690 @end table
14691
14692 @node Complexity Metrics Control
14693 @subsubsection Complexity Metrics Control
14694 @cindex Complexity metrics control in @command{gnatmetric}
14695
14696 @noindent
14697 For a program unit that is an executable body (a subprogram body (including
14698 generic bodies), task body, entry body or a package body containing
14699 its own statement sequence) @command{gnatmetric} computes the following
14700 complexity metrics:
14701
14702 @itemize @bullet
14703 @item
14704 McCabe cyclomatic complexity;
14705
14706 @item
14707 McCabe essential complexity;
14708
14709 @item
14710 maximal loop nesting level;
14711
14712 @item
14713 extra exit points (for subprograms);
14714 @end itemize
14715
14716 @noindent
14717 The McCabe cyclomatic complexity metric is defined
14718 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14719
14720 According to McCabe, both control statements and short-circuit control forms
14721 should be taken into account when computing cyclomatic complexity. For each
14722 body, we compute three metric values:
14723
14724 @itemize @bullet
14725 @item
14726 the complexity introduced by control
14727 statements only, without taking into account short-circuit forms,
14728
14729 @item
14730 the complexity introduced by short-circuit control forms only, and
14731
14732 @item
14733 the total
14734 cyclomatic complexity, which is the sum of these two values.
14735 @end itemize
14736
14737 @noindent
14738
14739 The origin of cyclomatic complexity metric is the need to estimate the number
14740 of independent paths in the control flow graph that in turn gives the number
14741 of tests needed to satisfy paths coverage testing completeness criterion.
14742 Considered from the testing point of view, a static Ada @code{loop} (that is,
14743 the @code{loop} statement having static subtype in loop parameter
14744 specification) does not add to cyclomatic complexity. By providing
14745 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14746 may specify that such loops should not be counted when computing the
14747 cyclomatic complexity metric
14748
14749 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14750 counted for the code that is reduced by excluding all the pure structural Ada
14751 control statements. An compound statement is considered as a non-structural
14752 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14753 or if it contains a @code{goto} statement that transfers the control outside
14754 the operator. A selective accept statement with @code{terminate} alternative
14755 is considered as non-structural statement. When computing this metric,
14756 @code{exit} statements are treated in the same way as @code{goto}
14757 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14758
14759 The Ada essential complexity metric defined here is intended to quantify
14760 the extent to which the software is unstructured. It is adapted from
14761 the McCabe essential complexity metric defined in
14762 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14763 suitable for typical Ada usage. For example, short circuit forms
14764 are not penalized as unstructured in the Ada essential complexity metric.
14765
14766 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14767 the code in the exception handlers and in all the nested program units.
14768
14769 By default, all the complexity metrics are computed and reported.
14770 For more fine-grained control you can use
14771 the following switches:
14772
14773 @table @option
14774 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14775
14776 @ifclear vms
14777 @cindex @option{--no-complexity@var{x}}
14778 @end ifclear
14779
14780 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14781 Report all the complexity metrics
14782
14783 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14784 Do not report any of complexity metrics
14785
14786 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14787 Report the McCabe Cyclomatic Complexity
14788
14789 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14790 Do not report the McCabe Cyclomatic Complexity
14791
14792 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14793 Report the Essential Complexity
14794
14795 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14796 Do not report the Essential Complexity
14797
14798 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14799 Report maximal loop nesting level
14800
14801 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14802 Do not report maximal loop nesting level
14803
14804 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14805 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14806 task bodies, entry bodies and statement sequences in package bodies.
14807 The metric is computed and reported for whole set of processed Ada sources
14808 only.
14809
14810 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14811 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14812 bodies, task bodies, entry bodies and statement sequences in package bodies
14813
14814 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14815 @item ^-ne^/NO_EXITS_AS_GOTOS^
14816 Do not consider @code{exit} statements as @code{goto}s when
14817 computing Essential Complexity
14818
14819 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14820 @item ^--no-static-loop^/NO_STATIC_LOOP^
14821 Do not consider static loops when computing cyclomatic complexity
14822
14823 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14824 Report the extra exit points for subprogram bodies. As an exit point, this
14825 metric counts @code{return} statements and raise statements in case when the
14826 raised exception is not handled in the same body. In case of a function this
14827 metric subtracts 1 from the number of exit points, because a function body
14828 must contain at least one @code{return} statement.
14829
14830 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14831 Do not report the extra exit points for subprogram bodies
14832 @end table
14833
14834
14835 @node Coupling Metrics Control
14836 @subsubsection Coupling Metrics Control
14837 @cindex Coupling metrics control in @command{gnatmetric}
14838
14839 @noindent
14840 @cindex Coupling metrics (in in @command{gnatmetric})
14841 Coupling metrics measure the dependencies between a given entity and other
14842 entities the program consists of. The goal of these metrics is to estimate the
14843 stability of the whole program considered as the collection of entities
14844 (modules, classes etc.).
14845
14846 Gnatmetric computes the following coupling metrics:
14847
14848 @itemize @bullet
14849
14850 @item
14851 @emph{object-oriented coupling} - for classes in traditional object-oriented
14852 sense;
14853
14854 @item
14855 @emph{unit coupling} - for all the program units making up a program;
14856
14857 @item
14858 @emph{control coupling} - this metric counts dependencies between a unit and
14859 only those units that define subprograms;
14860 @end itemize
14861
14862 @noindent
14863 Two kinds of coupling metrics are computed:
14864
14865 @table @asis
14866 @item fan-out coupling (efferent coupling)
14867 @cindex fan-out coupling
14868 @cindex efferent coupling
14869 the number of entities the given entity depends upon. It
14870 estimates in what extent the given entity depends on the changes in
14871 ``external world''
14872
14873 @item fan-in coupling (afferent coupling)
14874 @cindex fan-in coupling
14875 @cindex afferent coupling
14876 the number of entities that depend on a given entity.
14877 It estimates in what extent the ``external world'' depends on the changes in a
14878 given entity
14879 @end table
14880
14881 @noindent
14882
14883 Object-oriented coupling metrics are metrics that measure the dependencies
14884 between a given class (or a group of classes) and the other classes in the
14885 program. In this subsection the term ``class'' is used in its traditional
14886 object-oriented programming sense (an instantiable module that contains data
14887 and/or method members). A @emph{category} (of classes) is a group of closely
14888 related classes that are reused and/or modified together.
14889
14890 A class @code{K}'s fan-out coupling is the number of classes
14891 that @code{K} depends upon.
14892 A category's fan-out coupling is the number of classes outside the
14893 category that the classes inside the category depend upon.
14894
14895 A class @code{K}'s fan-in coupling is the number of classes
14896 that depend upon @code{K}.
14897 A category's fan-in coupling is the number of classes outside the
14898 category that depend on classes belonging to the category.
14899
14900 Ada's implementation of the object-oriented paradigm does not use the
14901 traditional class notion, so the definition of the coupling
14902 metrics for Ada maps the class and class category notions
14903 onto Ada constructs.
14904
14905 For the coupling metrics, several kinds of modules -- a library package,
14906 a library generic package, and a library generic package instantiation --
14907 that define a tagged type or an interface type are
14908 considered to be a class. A category consists of a library package (or
14909 a library generic package) that defines a tagged or an interface type,
14910 together with all its descendant (generic) packages that define tagged
14911 or interface types. That is a
14912 category is an Ada hierarchy of library-level program units. So class coupling
14913 in case of Ada is called as tagged coupling, and category coupling - as
14914 hierarchy coupling.
14915
14916 For any package counted as a class, its body and subunits (if any) are
14917 considered together with its spec when counting the dependencies, and coupling
14918 metrics are reported for spec units only. For dependencies between classes,
14919 the Ada semantic dependencies are considered. For object-oriented coupling
14920 metrics, only dependencies on units that are considered as classes, are
14921 considered.
14922
14923 For unit and control coupling also not compilation units but program units are
14924 counted. That is, for a package, its spec, its body and its subunits (if any)
14925 are considered as making up one unit, and the dependencies that are counted
14926 are the dependencies of all these compilation units collected together as
14927 the dependencies as a (whole) unit. And metrics are reported for spec
14928 compilation units only (or for a subprogram body unit in case if there is no
14929 separate spec for the given subprogram).
14930
14931 For unit coupling, dependencies between all kinds of program units are
14932 considered. For control coupling, for each unit the dependencies of this unit
14933 upon units that define subprograms are counted, so control fan-out coupling
14934 is reported for all units, but control fan-in coupling - only for the units
14935 that define subprograms.
14936
14937
14938
14939
14940
14941
14942 When computing coupling metrics, @command{gnatmetric} counts only
14943 dependencies between units that are arguments of the gnatmetric call.
14944 Coupling metrics are program-wide (or project-wide) metrics, so to
14945 get a valid result, you should call @command{gnatmetric} for
14946 the whole set of sources that make up your program. It can be done
14947 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14948 option (see @ref{The GNAT Driver and Project Files} for details).
14949
14950 By default, all the coupling metrics are disabled. You can use the following
14951 switches to specify the coupling metrics to be computed and reported:
14952
14953 @table @option
14954
14955 @ifclear vms
14956 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14957 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14958 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14959 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14960 @end ifclear
14961
14962 @ifset vms
14963 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14964 @end ifset
14965
14966 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14967 Report all the coupling metrics
14968
14969 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14970 Report tagged (class) fan-out coupling
14971
14972 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14973 Report tagged (class) fan-in coupling
14974
14975 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14976 Report hierarchy (category) fan-out coupling
14977
14978 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14979 Report hierarchy (category) fan-in coupling
14980
14981 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14982 Report unit fan-out coupling
14983
14984 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14985 Report unit fan-in coupling
14986
14987 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14988 Report control fan-out coupling
14989
14990 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14991 Report control fan-in coupling
14992 @end table
14993
14994 @node Other gnatmetric Switches
14995 @subsection Other @code{gnatmetric} Switches
14996
14997 @noindent
14998 Additional @command{gnatmetric} switches are as follows:
14999
15000 @table @option
15001 @item ^-files @var{filename}^/FILES=@var{filename}^
15002 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15003 Take the argument source files from the specified file. This file should be an
15004 ordinary text file containing file names separated by spaces or
15005 line breaks. You can use this switch more than once in the same call to
15006 @command{gnatmetric}. You also can combine this switch with
15007 an explicit list of files.
15008
15009 @item ^-v^/VERBOSE^
15010 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15011 Verbose mode;
15012 @command{gnatmetric} generates version information and then
15013 a trace of sources being processed.
15014
15015 @item ^-q^/QUIET^
15016 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15017 Quiet mode.
15018 @end table
15019
15020 @node Generate project-wide metrics
15021 @subsection Generate project-wide metrics
15022
15023 In order to compute metrics on all units of a given project, you can use
15024 the @command{gnat} driver along with the @option{-P} option:
15025 @smallexample
15026    gnat metric -Pproj
15027 @end smallexample
15028
15029 @noindent
15030 If the project @code{proj} depends upon other projects, you can compute
15031 the metrics on the project closure using the @option{-U} option:
15032 @smallexample
15033    gnat metric -Pproj -U
15034 @end smallexample
15035
15036 @noindent
15037 Finally, if not all the units are relevant to a particular main
15038 program in the project closure, you can generate metrics for the set
15039 of units needed to create a given main program (unit closure) using
15040 the @option{-U} option followed by the name of the main unit:
15041 @smallexample
15042    gnat metric -Pproj -U main
15043 @end smallexample
15044
15045
15046 @c ***********************************
15047 @node File Name Krunching Using gnatkr
15048 @chapter File Name Krunching Using @code{gnatkr}
15049 @findex gnatkr
15050
15051 @noindent
15052 This chapter discusses the method used by the compiler to shorten
15053 the default file names chosen for Ada units so that they do not
15054 exceed the maximum length permitted. It also describes the
15055 @code{gnatkr} utility that can be used to determine the result of
15056 applying this shortening.
15057 @menu
15058 * About gnatkr::
15059 * Using gnatkr::
15060 * Krunching Method::
15061 * Examples of gnatkr Usage::
15062 @end menu
15063
15064 @node About gnatkr
15065 @section About @code{gnatkr}
15066
15067 @noindent
15068 The default file naming rule in GNAT
15069 is that the file name must be derived from
15070 the unit name. The exact default rule is as follows:
15071 @itemize @bullet
15072 @item
15073 Take the unit name and replace all dots by hyphens.
15074 @item
15075 If such a replacement occurs in the
15076 second character position of a name, and the first character is
15077 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15078 then replace the dot by the character
15079 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15080 instead of a minus.
15081 @end itemize
15082 The reason for this exception is to avoid clashes
15083 with the standard names for children of System, Ada, Interfaces,
15084 and GNAT, which use the prefixes
15085 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15086 respectively.
15087
15088 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15089 switch of the compiler activates a ``krunching''
15090 circuit that limits file names to nn characters (where nn is a decimal
15091 integer). For example, using OpenVMS,
15092 where the maximum file name length is
15093 39, the value of nn is usually set to 39, but if you want to generate
15094 a set of files that would be usable if ported to a system with some
15095 different maximum file length, then a different value can be specified.
15096 The default value of 39 for OpenVMS need not be specified.
15097
15098 The @code{gnatkr} utility can be used to determine the krunched name for
15099 a given file, when krunched to a specified maximum length.
15100
15101 @node Using gnatkr
15102 @section Using @code{gnatkr}
15103
15104 @noindent
15105 The @code{gnatkr} command has the form
15106
15107 @ifclear vms
15108 @smallexample
15109 @c $ gnatkr @var{name} @ovar{length}
15110 @c Expanding @ovar macro inline (explanation in macro def comments)
15111 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15112 @end smallexample
15113 @end ifclear
15114
15115 @ifset vms
15116 @smallexample
15117 $ gnatkr @var{name} /COUNT=nn
15118 @end smallexample
15119 @end ifset
15120
15121 @noindent
15122 @var{name} is the uncrunched file name, derived from the name of the unit
15123 in the standard manner described in the previous section (i.e., in particular
15124 all dots are replaced by hyphens). The file name may or may not have an
15125 extension (defined as a suffix of the form period followed by arbitrary
15126 characters other than period). If an extension is present then it will
15127 be preserved in the output. For example, when krunching @file{hellofile.ads}
15128 to eight characters, the result will be hellofil.ads.
15129
15130 Note: for compatibility with previous versions of @code{gnatkr} dots may
15131 appear in the name instead of hyphens, but the last dot will always be
15132 taken as the start of an extension. So if @code{gnatkr} is given an argument
15133 such as @file{Hello.World.adb} it will be treated exactly as if the first
15134 period had been a hyphen, and for example krunching to eight characters
15135 gives the result @file{hellworl.adb}.
15136
15137 Note that the result is always all lower case (except on OpenVMS where it is
15138 all upper case). Characters of the other case are folded as required.
15139
15140 @var{length} represents the length of the krunched name. The default
15141 when no argument is given is ^8^39^ characters. A length of zero stands for
15142 unlimited, in other words do not chop except for system files where the
15143 implied crunching length is always eight characters.
15144
15145 @noindent
15146 The output is the krunched name. The output has an extension only if the
15147 original argument was a file name with an extension.
15148
15149 @node Krunching Method
15150 @section Krunching Method
15151
15152 @noindent
15153 The initial file name is determined by the name of the unit that the file
15154 contains. The name is formed by taking the full expanded name of the
15155 unit and replacing the separating dots with hyphens and
15156 using ^lowercase^uppercase^
15157 for all letters, except that a hyphen in the second character position is
15158 replaced by a ^tilde^dollar sign^ if the first character is
15159 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15160 The extension is @code{.ads} for a
15161 spec and @code{.adb} for a body.
15162 Krunching does not affect the extension, but the file name is shortened to
15163 the specified length by following these rules:
15164
15165 @itemize @bullet
15166 @item
15167 The name is divided into segments separated by hyphens, tildes or
15168 underscores and all hyphens, tildes, and underscores are
15169 eliminated. If this leaves the name short enough, we are done.
15170
15171 @item
15172 If the name is too long, the longest segment is located (left-most
15173 if there are two of equal length), and shortened by dropping
15174 its last character. This is repeated until the name is short enough.
15175
15176 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15177 to fit the name into 8 characters as required by some operating systems.
15178
15179 @smallexample
15180 our-strings-wide_fixed 22
15181 our strings wide fixed 19
15182 our string  wide fixed 18
15183 our strin   wide fixed 17
15184 our stri    wide fixed 16
15185 our stri    wide fixe  15
15186 our str     wide fixe  14
15187 our str     wid  fixe  13
15188 our str     wid  fix   12
15189 ou  str     wid  fix   11
15190 ou  st      wid  fix   10
15191 ou  st      wi   fix   9
15192 ou  st      wi   fi    8
15193 Final file name: oustwifi.adb
15194 @end smallexample
15195
15196 @item
15197 The file names for all predefined units are always krunched to eight
15198 characters. The krunching of these predefined units uses the following
15199 special prefix replacements:
15200
15201 @table @file
15202 @item ada-
15203 replaced by @file{^a^A^-}
15204
15205 @item gnat-
15206 replaced by @file{^g^G^-}
15207
15208 @item interfaces-
15209 replaced by @file{^i^I^-}
15210
15211 @item system-
15212 replaced by @file{^s^S^-}
15213 @end table
15214
15215 These system files have a hyphen in the second character position. That
15216 is why normal user files replace such a character with a
15217 ^tilde^dollar sign^, to
15218 avoid confusion with system file names.
15219
15220 As an example of this special rule, consider
15221 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15222
15223 @smallexample
15224 ada-strings-wide_fixed 22
15225 a-  strings wide fixed 18
15226 a-  string  wide fixed 17
15227 a-  strin   wide fixed 16
15228 a-  stri    wide fixed 15
15229 a-  stri    wide fixe  14
15230 a-  str     wide fixe  13
15231 a-  str     wid  fixe  12
15232 a-  str     wid  fix   11
15233 a-  st      wid  fix   10
15234 a-  st      wi   fix   9
15235 a-  st      wi   fi    8
15236 Final file name: a-stwifi.adb
15237 @end smallexample
15238 @end itemize
15239
15240 Of course no file shortening algorithm can guarantee uniqueness over all
15241 possible unit names, and if file name krunching is used then it is your
15242 responsibility to ensure that no name clashes occur. The utility
15243 program @code{gnatkr} is supplied for conveniently determining the
15244 krunched name of a file.
15245
15246 @node Examples of gnatkr Usage
15247 @section Examples of @code{gnatkr} Usage
15248
15249 @smallexample
15250 @iftex
15251 @leftskip=0cm
15252 @end iftex
15253 @ifclear vms
15254 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15255 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15256 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15257 $ gnatkr grandparent-parent-child     --> grparchi
15258 @end ifclear
15259 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15260 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15261 @end smallexample
15262
15263 @node Preprocessing Using gnatprep
15264 @chapter Preprocessing Using @code{gnatprep}
15265 @findex gnatprep
15266
15267 @noindent
15268 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15269 preprocessing.
15270 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15271 special GNAT features.
15272 For further discussion of conditional compilation in general, see
15273 @ref{Conditional Compilation}.
15274
15275 @menu
15276 * Preprocessing Symbols::
15277 * Using gnatprep::
15278 * Switches for gnatprep::
15279 * Form of Definitions File::
15280 * Form of Input Text for gnatprep::
15281 @end menu
15282
15283 @node Preprocessing Symbols
15284 @section Preprocessing Symbols
15285
15286 @noindent
15287 Preprocessing symbols are defined in definition files and referred to in
15288 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15289 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15290 all characters need to be in the ASCII set (no accented letters).
15291
15292 @node Using gnatprep
15293 @section Using @code{gnatprep}
15294
15295 @noindent
15296 To call @code{gnatprep} use
15297
15298 @smallexample
15299 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15300 @c Expanding @ovar macro inline (explanation in macro def comments)
15301 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15302 @end smallexample
15303
15304 @noindent
15305 where
15306 @table @var
15307 @item switches
15308 is an optional sequence of switches as described in the next section.
15309
15310 @item infile
15311 is the full name of the input file, which is an Ada source
15312 file containing preprocessor directives.
15313
15314 @item outfile
15315 is the full name of the output file, which is an Ada source
15316 in standard Ada form. When used with GNAT, this file name will
15317 normally have an ads or adb suffix.
15318
15319 @item deffile
15320 is the full name of a text file containing definitions of
15321 preprocessing symbols to be referenced by the preprocessor. This argument is
15322 optional, and can be replaced by the use of the @option{-D} switch.
15323
15324 @end table
15325
15326 @node Switches for gnatprep
15327 @section Switches for @code{gnatprep}
15328
15329 @table @option
15330 @c !sort!
15331
15332 @item ^-b^/BLANK_LINES^
15333 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15334 Causes both preprocessor lines and the lines deleted by
15335 preprocessing to be replaced by blank lines in the output source file,
15336 preserving line numbers in the output file.
15337
15338 @item ^-c^/COMMENTS^
15339 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15340 Causes both preprocessor lines and the lines deleted
15341 by preprocessing to be retained in the output source as comments marked
15342 with the special string @code{"--! "}. This option will result in line numbers
15343 being preserved in the output file.
15344
15345 @item ^-C^/REPLACE_IN_COMMENTS^
15346 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15347 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15348 If this option is specified, then comments are scanned and any $symbol
15349 substitutions performed as in program text. This is particularly useful
15350 when structured comments are used (e.g., when writing programs in the
15351 SPARK dialect of Ada). Note that this switch is not available when
15352 doing integrated preprocessing (it would be useless in this context
15353 since comments are ignored by the compiler in any case).
15354
15355 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15356 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15357 Defines a new preprocessing symbol, associated with value. If no value is given
15358 on the command line, then symbol is considered to be @code{True}. This switch
15359 can be used in place of a definition file.
15360
15361 @ifset vms
15362 @item /REMOVE
15363 @cindex @option{/REMOVE} (@command{gnatprep})
15364 This is the default setting which causes lines deleted by preprocessing
15365 to be entirely removed from the output file.
15366 @end ifset
15367
15368 @item ^-r^/REFERENCE^
15369 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15370 Causes a @code{Source_Reference} pragma to be generated that
15371 references the original input file, so that error messages will use
15372 the file name of this original file. The use of this switch implies
15373 that preprocessor lines are not to be removed from the file, so its
15374 use will force @option{^-b^/BLANK_LINES^} mode if
15375 @option{^-c^/COMMENTS^}
15376 has not been specified explicitly.
15377
15378 Note that if the file to be preprocessed contains multiple units, then
15379 it will be necessary to @code{gnatchop} the output file from
15380 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15381 in the preprocessed file, it will be respected by
15382 @code{gnatchop ^-r^/REFERENCE^}
15383 so that the final chopped files will correctly refer to the original
15384 input source file for @code{gnatprep}.
15385
15386 @item ^-s^/SYMBOLS^
15387 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15388 Causes a sorted list of symbol names and values to be
15389 listed on the standard output file.
15390
15391 @item ^-u^/UNDEFINED^
15392 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15393 Causes undefined symbols to be treated as having the value FALSE in the context
15394 of a preprocessor test. In the absence of this option, an undefined symbol in
15395 a @code{#if} or @code{#elsif} test will be treated as an error.
15396
15397 @end table
15398
15399 @ifclear vms
15400 @noindent
15401 Note: if neither @option{-b} nor @option{-c} is present,
15402 then preprocessor lines and
15403 deleted lines are completely removed from the output, unless -r is
15404 specified, in which case -b is assumed.
15405 @end ifclear
15406
15407 @node Form of Definitions File
15408 @section Form of Definitions File
15409
15410 @noindent
15411 The definitions file contains lines of the form
15412
15413 @smallexample
15414 symbol := value
15415 @end smallexample
15416
15417 @noindent
15418 where symbol is a preprocessing symbol, and value is one of the following:
15419
15420 @itemize @bullet
15421 @item
15422 Empty, corresponding to a null substitution
15423 @item
15424 A string literal using normal Ada syntax
15425 @item
15426 Any sequence of characters from the set
15427 (letters, digits, period, underline).
15428 @end itemize
15429
15430 @noindent
15431 Comment lines may also appear in the definitions file, starting with
15432 the usual @code{--},
15433 and comments may be added to the definitions lines.
15434
15435 @node Form of Input Text for gnatprep
15436 @section Form of Input Text for @code{gnatprep}
15437
15438 @noindent
15439 The input text may contain preprocessor conditional inclusion lines,
15440 as well as general symbol substitution sequences.
15441
15442 The preprocessor conditional inclusion commands have the form
15443
15444 @smallexample
15445 @group
15446 @cartouche
15447 #if @i{expression} @r{[}then@r{]}
15448    lines
15449 #elsif @i{expression} @r{[}then@r{]}
15450    lines
15451 #elsif @i{expression} @r{[}then@r{]}
15452    lines
15453 @dots{}
15454 #else
15455    lines
15456 #end if;
15457 @end cartouche
15458 @end group
15459 @end smallexample
15460
15461 @noindent
15462 In this example, @i{expression} is defined by the following grammar:
15463 @smallexample
15464 @i{expression} ::=  <symbol>
15465 @i{expression} ::=  <symbol> = "<value>"
15466 @i{expression} ::=  <symbol> = <symbol>
15467 @i{expression} ::=  <symbol> 'Defined
15468 @i{expression} ::=  not @i{expression}
15469 @i{expression} ::=  @i{expression} and @i{expression}
15470 @i{expression} ::=  @i{expression} or @i{expression}
15471 @i{expression} ::=  @i{expression} and then @i{expression}
15472 @i{expression} ::=  @i{expression} or else @i{expression}
15473 @i{expression} ::=  ( @i{expression} )
15474 @end smallexample
15475
15476 The following restriction exists: it is not allowed to have "and" or "or"
15477 following "not" in the same expression without parentheses. For example, this
15478 is not allowed:
15479
15480 @smallexample
15481    not X or Y
15482 @end smallexample
15483
15484 This should be one of the following:
15485
15486 @smallexample
15487    (not X) or Y
15488    not (X or Y)
15489 @end smallexample
15490
15491 @noindent
15492 For the first test (@i{expression} ::= <symbol>) the symbol must have
15493 either the value true or false, that is to say the right-hand of the
15494 symbol definition must be one of the (case-insensitive) literals
15495 @code{True} or @code{False}. If the value is true, then the
15496 corresponding lines are included, and if the value is false, they are
15497 excluded.
15498
15499 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15500 the symbol has been defined in the definition file or by a @option{-D}
15501 switch on the command line. Otherwise, the test is false.
15502
15503 The equality tests are case insensitive, as are all the preprocessor lines.
15504
15505 If the symbol referenced is not defined in the symbol definitions file,
15506 then the effect depends on whether or not switch @option{-u}
15507 is specified. If so, then the symbol is treated as if it had the value
15508 false and the test fails. If this switch is not specified, then
15509 it is an error to reference an undefined symbol. It is also an error to
15510 reference a symbol that is defined with a value other than @code{True}
15511 or @code{False}.
15512
15513 The use of the @code{not} operator inverts the sense of this logical test.
15514 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15515 operators, without parentheses. For example, "if not X or Y then" is not
15516 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15517
15518 The @code{then} keyword is optional as shown
15519
15520 The @code{#} must be the first non-blank character on a line, but
15521 otherwise the format is free form. Spaces or tabs may appear between
15522 the @code{#} and the keyword. The keywords and the symbols are case
15523 insensitive as in normal Ada code. Comments may be used on a
15524 preprocessor line, but other than that, no other tokens may appear on a
15525 preprocessor line. Any number of @code{elsif} clauses can be present,
15526 including none at all. The @code{else} is optional, as in Ada.
15527
15528 The @code{#} marking the start of a preprocessor line must be the first
15529 non-blank character on the line, i.e., it must be preceded only by
15530 spaces or horizontal tabs.
15531
15532 Symbol substitution outside of preprocessor lines is obtained by using
15533 the sequence
15534
15535 @smallexample
15536 $symbol
15537 @end smallexample
15538
15539 @noindent
15540 anywhere within a source line, except in a comment or within a
15541 string literal. The identifier
15542 following the @code{$} must match one of the symbols defined in the symbol
15543 definition file, and the result is to substitute the value of the
15544 symbol in place of @code{$symbol} in the output file.
15545
15546 Note that although the substitution of strings within a string literal
15547 is not possible, it is possible to have a symbol whose defined value is
15548 a string literal. So instead of setting XYZ to @code{hello} and writing:
15549
15550 @smallexample
15551 Header : String := "$XYZ";
15552 @end smallexample
15553
15554 @noindent
15555 you should set XYZ to @code{"hello"} and write:
15556
15557 @smallexample
15558 Header : String := $XYZ;
15559 @end smallexample
15560
15561 @noindent
15562 and then the substitution will occur as desired.
15563
15564 @node The GNAT Library Browser gnatls
15565 @chapter The GNAT Library Browser @code{gnatls}
15566 @findex gnatls
15567 @cindex Library browser
15568
15569 @noindent
15570 @code{gnatls} is a tool that outputs information about compiled
15571 units. It gives the relationship between objects, unit names and source
15572 files. It can also be used to check the source dependencies of a unit
15573 as well as various characteristics.
15574
15575 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15576 driver (see @ref{The GNAT Driver and Project Files}).
15577
15578 @menu
15579 * Running gnatls::
15580 * Switches for gnatls::
15581 * Examples of gnatls Usage::
15582 @end menu
15583
15584 @node Running gnatls
15585 @section Running @code{gnatls}
15586
15587 @noindent
15588 The @code{gnatls} command has the form
15589
15590 @smallexample
15591 $ gnatls switches @var{object_or_ali_file}
15592 @end smallexample
15593
15594 @noindent
15595 The main argument is the list of object or @file{ali} files
15596 (@pxref{The Ada Library Information Files})
15597 for which information is requested.
15598
15599 In normal mode, without additional option, @code{gnatls} produces a
15600 four-column listing. Each line represents information for a specific
15601 object. The first column gives the full path of the object, the second
15602 column gives the name of the principal unit in this object, the third
15603 column gives the status of the source and the fourth column gives the
15604 full path of the source representing this unit.
15605 Here is a simple example of use:
15606
15607 @smallexample
15608 $ gnatls *.o
15609 ^./^[]^demo1.o            demo1            DIF demo1.adb
15610 ^./^[]^demo2.o            demo2             OK demo2.adb
15611 ^./^[]^hello.o            h1                OK hello.adb
15612 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15613 ^./^[]^instr.o            instr             OK instr.adb
15614 ^./^[]^tef.o              tef              DIF tef.adb
15615 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15616 ^./^[]^tgef.o             tgef             DIF tgef.adb
15617 @end smallexample
15618
15619 @noindent
15620 The first line can be interpreted as follows: the main unit which is
15621 contained in
15622 object file @file{demo1.o} is demo1, whose main source is in
15623 @file{demo1.adb}. Furthermore, the version of the source used for the
15624 compilation of demo1 has been modified (DIF). Each source file has a status
15625 qualifier which can be:
15626
15627 @table @code
15628 @item OK (unchanged)
15629 The version of the source file used for the compilation of the
15630 specified unit corresponds exactly to the actual source file.
15631
15632 @item MOK (slightly modified)
15633 The version of the source file used for the compilation of the
15634 specified unit differs from the actual source file but not enough to
15635 require recompilation. If you use gnatmake with the qualifier
15636 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15637 MOK will not be recompiled.
15638
15639 @item DIF (modified)
15640 No version of the source found on the path corresponds to the source
15641 used to build this object.
15642
15643 @item ??? (file not found)
15644 No source file was found for this unit.
15645
15646 @item HID (hidden,  unchanged version not first on PATH)
15647 The version of the source that corresponds exactly to the source used
15648 for compilation has been found on the path but it is hidden by another
15649 version of the same source that has been modified.
15650
15651 @end table
15652
15653 @node Switches for gnatls
15654 @section Switches for @code{gnatls}
15655
15656 @noindent
15657 @code{gnatls} recognizes the following switches:
15658
15659 @table @option
15660 @c !sort!
15661 @cindex @option{--version} @command{gnatls}
15662 Display Copyright and version, then exit disregarding all other options.
15663
15664 @item --help
15665 @cindex @option{--help} @command{gnatls}
15666 If @option{--version} was not used, display usage, then exit disregarding
15667 all other options.
15668
15669 @item ^-a^/ALL_UNITS^
15670 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15671 Consider all units, including those of the predefined Ada library.
15672 Especially useful with @option{^-d^/DEPENDENCIES^}.
15673
15674 @item ^-d^/DEPENDENCIES^
15675 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15676 List sources from which specified units depend on.
15677
15678 @item ^-h^/OUTPUT=OPTIONS^
15679 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15680 Output the list of options.
15681
15682 @item ^-o^/OUTPUT=OBJECTS^
15683 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15684 Only output information about object files.
15685
15686 @item ^-s^/OUTPUT=SOURCES^
15687 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15688 Only output information about source files.
15689
15690 @item ^-u^/OUTPUT=UNITS^
15691 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15692 Only output information about compilation units.
15693
15694 @item ^-files^/FILES^=@var{file}
15695 @cindex @option{^-files^/FILES^} (@code{gnatls})
15696 Take as arguments the files listed in text file @var{file}.
15697 Text file @var{file} may contain empty lines that are ignored.
15698 Each nonempty line should contain the name of an existing file.
15699 Several such switches may be specified simultaneously.
15700
15701 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15702 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15703 @itemx ^-I^/SEARCH=^@var{dir}
15704 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15705 @itemx -nostdinc
15706 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15707 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15708 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15709 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15710 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15711 flags (@pxref{Switches for gnatmake}).
15712
15713 @item --RTS=@var{rts-path}
15714 @cindex @option{--RTS} (@code{gnatls})
15715 Specifies the default location of the runtime library. Same meaning as the
15716 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15717
15718 @item ^-v^/OUTPUT=VERBOSE^
15719 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15720 Verbose mode. Output the complete source, object and project paths. Do not use
15721 the default column layout but instead use long format giving as much as
15722 information possible on each requested units, including special
15723 characteristics such as:
15724
15725 @table @code
15726 @item  Preelaborable
15727 The unit is preelaborable in the Ada sense.
15728
15729 @item No_Elab_Code
15730 No elaboration code has been produced by the compiler for this unit.
15731
15732 @item Pure
15733 The unit is pure in the Ada sense.
15734
15735 @item Elaborate_Body
15736 The unit contains a pragma Elaborate_Body.
15737
15738 @item Remote_Types
15739 The unit contains a pragma Remote_Types.
15740
15741 @item Shared_Passive
15742 The unit contains a pragma Shared_Passive.
15743
15744 @item Predefined
15745 This unit is part of the predefined environment and cannot be modified
15746 by the user.
15747
15748 @item Remote_Call_Interface
15749 The unit contains a pragma Remote_Call_Interface.
15750
15751 @end table
15752
15753 @end table
15754
15755 @node Examples of gnatls Usage
15756 @section Example of @code{gnatls} Usage
15757 @ifclear vms
15758
15759 @noindent
15760 Example of using the verbose switch. Note how the source and
15761 object paths are affected by the -I switch.
15762
15763 @smallexample
15764 $ gnatls -v -I.. demo1.o
15765
15766 GNATLS 5.03w (20041123-34)
15767 Copyright 1997-2004 Free Software Foundation, Inc.
15768
15769 Source Search Path:
15770    <Current_Directory>
15771    ../
15772    /home/comar/local/adainclude/
15773
15774 Object Search Path:
15775    <Current_Directory>
15776    ../
15777    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15778
15779 Project Search Path:
15780    <Current_Directory>
15781    /home/comar/local/lib/gnat/
15782
15783 ./demo1.o
15784    Unit =>
15785      Name   => demo1
15786      Kind   => subprogram body
15787      Flags  => No_Elab_Code
15788      Source => demo1.adb    modified
15789 @end smallexample
15790
15791 @noindent
15792 The following is an example of use of the dependency list.
15793 Note the use of the -s switch
15794 which gives a straight list of source files. This can be useful for
15795 building specialized scripts.
15796
15797 @smallexample
15798 $ gnatls -d demo2.o
15799 ./demo2.o   demo2        OK demo2.adb
15800                          OK gen_list.ads
15801                          OK gen_list.adb
15802                          OK instr.ads
15803                          OK instr-child.ads
15804
15805 $ gnatls -d -s -a demo1.o
15806 demo1.adb
15807 /home/comar/local/adainclude/ada.ads
15808 /home/comar/local/adainclude/a-finali.ads
15809 /home/comar/local/adainclude/a-filico.ads
15810 /home/comar/local/adainclude/a-stream.ads
15811 /home/comar/local/adainclude/a-tags.ads
15812 gen_list.ads
15813 gen_list.adb
15814 /home/comar/local/adainclude/gnat.ads
15815 /home/comar/local/adainclude/g-io.ads
15816 instr.ads
15817 /home/comar/local/adainclude/system.ads
15818 /home/comar/local/adainclude/s-exctab.ads
15819 /home/comar/local/adainclude/s-finimp.ads
15820 /home/comar/local/adainclude/s-finroo.ads
15821 /home/comar/local/adainclude/s-secsta.ads
15822 /home/comar/local/adainclude/s-stalib.ads
15823 /home/comar/local/adainclude/s-stoele.ads
15824 /home/comar/local/adainclude/s-stratt.ads
15825 /home/comar/local/adainclude/s-tasoli.ads
15826 /home/comar/local/adainclude/s-unstyp.ads
15827 /home/comar/local/adainclude/unchconv.ads
15828 @end smallexample
15829 @end ifclear
15830
15831 @ifset vms
15832 @smallexample
15833 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15834
15835 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15836 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15840 demo1.adb
15841 gen_list.ads
15842 gen_list.adb
15843 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15844 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15845 instr.ads
15846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15857 @end smallexample
15858 @end ifset
15859
15860 @node Cleaning Up Using gnatclean
15861 @chapter Cleaning Up Using @code{gnatclean}
15862 @findex gnatclean
15863 @cindex Cleaning tool
15864
15865 @noindent
15866 @code{gnatclean} is a tool that allows the deletion of files produced by the
15867 compiler, binder and linker, including ALI files, object files, tree files,
15868 expanded source files, library files, interface copy source files, binder
15869 generated files and executable files.
15870
15871 @menu
15872 * Running gnatclean::
15873 * Switches for gnatclean::
15874 @c * Examples of gnatclean Usage::
15875 @end menu
15876
15877 @node Running gnatclean
15878 @section Running @code{gnatclean}
15879
15880 @noindent
15881 The @code{gnatclean} command has the form:
15882
15883 @smallexample
15884 $ gnatclean switches @var{names}
15885 @end smallexample
15886
15887 @noindent
15888 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15889 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15890 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15891
15892 @noindent
15893 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15894 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15895 the linker. In informative-only mode, specified by switch
15896 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15897 normal mode is listed, but no file is actually deleted.
15898
15899 @node Switches for gnatclean
15900 @section Switches for @code{gnatclean}
15901
15902 @noindent
15903 @code{gnatclean} recognizes the following switches:
15904
15905 @table @option
15906 @c !sort!
15907 @cindex @option{--version} @command{gnatclean}
15908 Display Copyright and version, then exit disregarding all other options.
15909
15910 @item --help
15911 @cindex @option{--help} @command{gnatclean}
15912 If @option{--version} was not used, display usage, then exit disregarding
15913 all other options.
15914
15915 @item ^--subdirs^/SUBDIRS^=subdir
15916 Actual object directory of each project file is the subdirectory subdir of the
15917 object directory specified or defaulted in the project file.
15918
15919 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15920 By default, shared library projects are not allowed to import static library
15921 projects. When this switch is used on the command line, this restriction is
15922 relaxed.
15923
15924 @item ^-c^/COMPILER_FILES_ONLY^
15925 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15926 Only attempt to delete the files produced by the compiler, not those produced
15927 by the binder or the linker. The files that are not to be deleted are library
15928 files, interface copy files, binder generated files and executable files.
15929
15930 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15931 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15932 Indicate that ALI and object files should normally be found in directory
15933 @var{dir}.
15934
15935 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15936 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15937 When using project files, if some errors or warnings are detected during
15938 parsing and verbose mode is not in effect (no use of switch
15939 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15940 file, rather than its simple file name.
15941
15942 @item ^-h^/HELP^
15943 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15944 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15945
15946 @item ^-n^/NODELETE^
15947 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15948 Informative-only mode. Do not delete any files. Output the list of the files
15949 that would have been deleted if this switch was not specified.
15950
15951 @item ^-P^/PROJECT_FILE=^@var{project}
15952 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15953 Use project file @var{project}. Only one such switch can be used.
15954 When cleaning a project file, the files produced by the compilation of the
15955 immediate sources or inherited sources of the project files are to be
15956 deleted. This is not depending on the presence or not of executable names
15957 on the command line.
15958
15959 @item ^-q^/QUIET^
15960 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15961 Quiet output. If there are no errors, do not output anything, except in
15962 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15963 (switch ^-n^/NODELETE^).
15964
15965 @item ^-r^/RECURSIVE^
15966 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15967 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15968 clean all imported and extended project files, recursively. If this switch
15969 is not specified, only the files related to the main project file are to be
15970 deleted. This switch has no effect if no project file is specified.
15971
15972 @item ^-v^/VERBOSE^
15973 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15974 Verbose mode.
15975
15976 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15977 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15978 Indicates the verbosity of the parsing of GNAT project files.
15979 @xref{Switches Related to Project Files}.
15980
15981 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15982 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15983 Indicates that external variable @var{name} has the value @var{value}.
15984 The Project Manager will use this value for occurrences of
15985 @code{external(name)} when parsing the project file.
15986 @xref{Switches Related to Project Files}.
15987
15988 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15989 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15990 When searching for ALI and object files, look in directory
15991 @var{dir}.
15992
15993 @item ^-I^/SEARCH=^@var{dir}
15994 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15995 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15996
15997 @item ^-I-^/NOCURRENT_DIRECTORY^
15998 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15999 @cindex Source files, suppressing search
16000 Do not look for ALI or object files in the directory
16001 where @code{gnatclean} was invoked.
16002
16003 @end table
16004
16005 @c @node Examples of gnatclean Usage
16006 @c @section Examples of @code{gnatclean} Usage
16007
16008 @ifclear vms
16009 @node GNAT and Libraries
16010 @chapter GNAT and Libraries
16011 @cindex Library, building, installing, using
16012
16013 @noindent
16014 This chapter describes how to build and use libraries with GNAT, and also shows
16015 how to recompile the GNAT run-time library. You should be familiar with the
16016 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16017 chapter.
16018
16019 @menu
16020 * Introduction to Libraries in GNAT::
16021 * General Ada Libraries::
16022 * Stand-alone Ada Libraries::
16023 * Rebuilding the GNAT Run-Time Library::
16024 @end menu
16025
16026 @node Introduction to Libraries in GNAT
16027 @section Introduction to Libraries in GNAT
16028
16029 @noindent
16030 A library is, conceptually, a collection of objects which does not have its
16031 own main thread of execution, but rather provides certain services to the
16032 applications that use it. A library can be either statically linked with the
16033 application, in which case its code is directly included in the application,
16034 or, on platforms that support it, be dynamically linked, in which case
16035 its code is shared by all applications making use of this library.
16036
16037 GNAT supports both types of libraries.
16038 In the static case, the compiled code can be provided in different ways. The
16039 simplest approach is to provide directly the set of objects resulting from
16040 compilation of the library source files. Alternatively, you can group the
16041 objects into an archive using whatever commands are provided by the operating
16042 system. For the latter case, the objects are grouped into a shared library.
16043
16044 In the GNAT environment, a library has three types of components:
16045 @itemize @bullet
16046 @item
16047 Source files.
16048 @item
16049 @file{ALI} files.
16050 @xref{The Ada Library Information Files}.
16051 @item
16052 Object files, an archive or a shared library.
16053 @end itemize
16054
16055 @noindent
16056 A GNAT library may expose all its source files, which is useful for
16057 documentation purposes. Alternatively, it may expose only the units needed by
16058 an external user to make use of the library. That is to say, the specs
16059 reflecting the library services along with all the units needed to compile
16060 those specs, which can include generic bodies or any body implementing an
16061 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16062 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16063
16064 All compilation units comprising an application, including those in a library,
16065 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16066 computes the elaboration order from the @file{ALI} files and this is why they
16067 constitute a mandatory part of GNAT libraries.
16068 @emph{Stand-alone libraries} are the exception to this rule because a specific
16069 library elaboration routine is produced independently of the application(s)
16070 using the library.
16071
16072 @node General Ada Libraries
16073 @section General Ada Libraries
16074
16075 @menu
16076 * Building a library::
16077 * Installing a library::
16078 * Using a library::
16079 @end menu
16080
16081 @node Building a library
16082 @subsection Building a library
16083
16084 @noindent
16085 The easiest way to build a library is to use the Project Manager,
16086 which supports a special type of project called a @emph{Library Project}
16087 (@pxref{Library Projects}).
16088
16089 A project is considered a library project, when two project-level attributes
16090 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16091 control different aspects of library configuration, additional optional
16092 project-level attributes can be specified:
16093 @table @code
16094 @item Library_Kind
16095 This attribute controls whether the library is to be static or dynamic
16096
16097 @item Library_Version
16098 This attribute specifies the library version; this value is used
16099 during dynamic linking of shared libraries to determine if the currently
16100 installed versions of the binaries are compatible.
16101
16102 @item Library_Options
16103 @item Library_GCC
16104 These attributes specify additional low-level options to be used during
16105 library generation, and redefine the actual application used to generate
16106 library.
16107 @end table
16108
16109 @noindent
16110 The GNAT Project Manager takes full care of the library maintenance task,
16111 including recompilation of the source files for which objects do not exist
16112 or are not up to date, assembly of the library archive, and installation of
16113 the library (i.e., copying associated source, object and @file{ALI} files
16114 to the specified location).
16115
16116 Here is a simple library project file:
16117 @smallexample @c ada
16118 project My_Lib is
16119    for Source_Dirs use ("src1", "src2");
16120    for Object_Dir use "obj";
16121    for Library_Name use "mylib";
16122    for Library_Dir use "lib";
16123    for Library_Kind use "dynamic";
16124 end My_lib;
16125 @end smallexample
16126
16127 @noindent
16128 and the compilation command to build and install the library:
16129
16130 @smallexample @c ada
16131   $ gnatmake -Pmy_lib
16132 @end smallexample
16133
16134 @noindent
16135 It is not entirely trivial to perform manually all the steps required to
16136 produce a library. We recommend that you use the GNAT Project Manager
16137 for this task. In special cases where this is not desired, the necessary
16138 steps are discussed below.
16139
16140 There are various possibilities for compiling the units that make up the
16141 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16142 with a conventional script. For simple libraries, it is also possible to create
16143 a dummy main program which depends upon all the packages that comprise the
16144 interface of the library. This dummy main program can then be given to
16145 @command{gnatmake}, which will ensure that all necessary objects are built.
16146
16147 After this task is accomplished, you should follow the standard procedure
16148 of the underlying operating system to produce the static or shared library.
16149
16150 Here is an example of such a dummy program:
16151 @smallexample @c ada
16152 @group
16153 with My_Lib.Service1;
16154 with My_Lib.Service2;
16155 with My_Lib.Service3;
16156 procedure My_Lib_Dummy is
16157 begin
16158    null;
16159 end;
16160 @end group
16161 @end smallexample
16162
16163 @noindent
16164 Here are the generic commands that will build an archive or a shared library.
16165
16166 @smallexample
16167 # compiling the library
16168 $ gnatmake -c my_lib_dummy.adb
16169
16170 # we don't need the dummy object itself
16171 $ rm my_lib_dummy.o my_lib_dummy.ali
16172
16173 # create an archive with the remaining objects
16174 $ ar rc libmy_lib.a *.o
16175 # some systems may require "ranlib" to be run as well
16176
16177 # or create a shared library
16178 $ gcc -shared -o libmy_lib.so *.o
16179 # some systems may require the code to have been compiled with -fPIC
16180
16181 # remove the object files that are now in the library
16182 $ rm *.o
16183
16184 # Make the ALI files read-only so that gnatmake will not try to
16185 # regenerate the objects that are in the library
16186 $ chmod -w *.ali
16187 @end smallexample
16188
16189 @noindent
16190 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16191 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16192 be accessed by the directive @option{-l@var{xxx}} at link time.
16193
16194 @node Installing a library
16195 @subsection Installing a library
16196 @cindex @code{ADA_PROJECT_PATH}
16197 @cindex @code{GPR_PROJECT_PATH}
16198
16199 @noindent
16200 If you use project files, library installation is part of the library build
16201 process (@pxref{Installing a library with project files}).
16202
16203 When project files are not an option, it is also possible, but not recommended,
16204 to install the library so that the sources needed to use the library are on the
16205 Ada source path and the ALI files & libraries be on the Ada Object path (see
16206 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16207 administrator can place general-purpose libraries in the default compiler
16208 paths, by specifying the libraries' location in the configuration files
16209 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16210 must be located in the GNAT installation tree at the same place as the gcc spec
16211 file. The location of the gcc spec file can be determined as follows:
16212 @smallexample
16213 $ gcc -v
16214 @end smallexample
16215
16216 @noindent
16217 The configuration files mentioned above have a simple format: each line
16218 must contain one unique directory name.
16219 Those names are added to the corresponding path
16220 in their order of appearance in the file. The names can be either absolute
16221 or relative; in the latter case, they are relative to where theses files
16222 are located.
16223
16224 The files @file{ada_source_path} and @file{ada_object_path} might not be
16225 present in a
16226 GNAT installation, in which case, GNAT will look for its run-time library in
16227 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16228 objects and @file{ALI} files). When the files exist, the compiler does not
16229 look in @file{adainclude} and @file{adalib}, and thus the
16230 @file{ada_source_path} file
16231 must contain the location for the GNAT run-time sources (which can simply
16232 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16233 contain the location for the GNAT run-time objects (which can simply
16234 be @file{adalib}).
16235
16236 You can also specify a new default path to the run-time library at compilation
16237 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16238 the run-time library you want your program to be compiled with. This switch is
16239 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16240 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16241
16242 It is possible to install a library before or after the standard GNAT
16243 library, by reordering the lines in the configuration files. In general, a
16244 library must be installed before the GNAT library if it redefines
16245 any part of it.
16246
16247 @node Using a library
16248 @subsection Using a library
16249
16250 @noindent Once again, the project facility greatly simplifies the use of
16251 libraries. In this context, using a library is just a matter of adding a
16252 @code{with} clause in the user project. For instance, to make use of the
16253 library @code{My_Lib} shown in examples in earlier sections, you can
16254 write:
16255
16256 @smallexample @c projectfile
16257 with "my_lib";
16258 project My_Proj is
16259   @dots{}
16260 end My_Proj;
16261 @end smallexample
16262
16263 Even if you have a third-party, non-Ada library, you can still use GNAT's
16264 Project Manager facility to provide a wrapper for it. For example, the
16265 following project, when @code{with}ed by your main project, will link with the
16266 third-party library @file{liba.a}:
16267
16268 @smallexample @c projectfile
16269 @group
16270 project Liba is
16271    for Externally_Built use "true";
16272    for Source_Files use ();
16273    for Library_Dir use "lib";
16274    for Library_Name use "a";
16275    for Library_Kind use "static";
16276 end Liba;
16277 @end group
16278 @end smallexample
16279 This is an alternative to the use of @code{pragma Linker_Options}. It is
16280 especially interesting in the context of systems with several interdependent
16281 static libraries where finding a proper linker order is not easy and best be
16282 left to the tools having visibility over project dependence information.
16283
16284 @noindent
16285 In order to use an Ada library manually, you need to make sure that this
16286 library is on both your source and object path
16287 (see @ref{Search Paths and the Run-Time Library (RTL)}
16288 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16289 in an archive or a shared library, you need to specify the desired
16290 library at link time.
16291
16292 For example, you can use the library @file{mylib} installed in
16293 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16294
16295 @smallexample
16296 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16297   -largs -lmy_lib
16298 @end smallexample
16299
16300 @noindent
16301 This can be expressed more simply:
16302 @smallexample
16303 $ gnatmake my_appl
16304 @end smallexample
16305 @noindent
16306 when the following conditions are met:
16307 @itemize @bullet
16308 @item
16309 @file{/dir/my_lib_src} has been added by the user to the environment
16310 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16311 @file{ada_source_path}
16312 @item
16313 @file{/dir/my_lib_obj} has been added by the user to the environment
16314 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16315 @file{ada_object_path}
16316 @item
16317 a pragma @code{Linker_Options} has been added to one of the sources.
16318 For example:
16319
16320 @smallexample @c ada
16321 pragma Linker_Options ("-lmy_lib");
16322 @end smallexample
16323 @end itemize
16324
16325 @node Stand-alone Ada Libraries
16326 @section Stand-alone Ada Libraries
16327 @cindex Stand-alone library, building, using
16328
16329 @menu
16330 * Introduction to Stand-alone Libraries::
16331 * Building a Stand-alone Library::
16332 * Creating a Stand-alone Library to be used in a non-Ada context::
16333 * Restrictions in Stand-alone Libraries::
16334 @end menu
16335
16336 @node Introduction to Stand-alone Libraries
16337 @subsection Introduction to Stand-alone Libraries
16338
16339 @noindent
16340 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16341 necessary code to
16342 elaborate the Ada units that are included in the library. In contrast with
16343 an ordinary library, which consists of all sources, objects and @file{ALI}
16344 files of the
16345 library, a SAL may specify a restricted subset of compilation units
16346 to serve as a library interface. In this case, the fully
16347 self-sufficient set of files will normally consist of an objects
16348 archive, the sources of interface units' specs, and the @file{ALI}
16349 files of interface units.
16350 If an interface spec contains a generic unit or an inlined subprogram,
16351 the body's
16352 source must also be provided; if the units that must be provided in the source
16353 form depend on other units, the source and @file{ALI} files of those must
16354 also be provided.
16355
16356 The main purpose of a SAL is to minimize the recompilation overhead of client
16357 applications when a new version of the library is installed. Specifically,
16358 if the interface sources have not changed, client applications do not need to
16359 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16360 version, controlled by @code{Library_Version} attribute, is not changed,
16361 then the clients do not need to be relinked.
16362
16363 SALs also allow the library providers to minimize the amount of library source
16364 text exposed to the clients.  Such ``information hiding'' might be useful or
16365 necessary for various reasons.
16366
16367 Stand-alone libraries are also well suited to be used in an executable whose
16368 main routine is not written in Ada.
16369
16370 @node Building a Stand-alone Library
16371 @subsection Building a Stand-alone Library
16372
16373 @noindent
16374 GNAT's Project facility provides a simple way of building and installing
16375 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16376 To be a Stand-alone Library Project, in addition to the two attributes
16377 that make a project a Library Project (@code{Library_Name} and
16378 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16379 @code{Library_Interface} must be defined.  For example:
16380
16381 @smallexample @c projectfile
16382 @group
16383    for Library_Dir use "lib_dir";
16384    for Library_Name use "dummy";
16385    for Library_Interface use ("int1", "int1.child");
16386 @end group
16387 @end smallexample
16388
16389 @noindent
16390 Attribute @code{Library_Interface} has a non-empty string list value,
16391 each string in the list designating a unit contained in an immediate source
16392 of the project file.
16393
16394 When a Stand-alone Library is built, first the binder is invoked to build
16395 a package whose name depends on the library name
16396 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16397 This binder-generated package includes initialization and
16398 finalization procedures whose
16399 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16400 in the example
16401 above). The object corresponding to this package is included in the library.
16402
16403 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16404 calling of these procedures if a static SAL is built, or if a shared SAL
16405 is built
16406 with the project-level attribute @code{Library_Auto_Init} set to
16407 @code{"false"}.
16408
16409 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16410 (those that are listed in attribute @code{Library_Interface}) are copied to
16411 the Library Directory. As a consequence, only the Interface Units may be
16412 imported from Ada units outside of the library. If other units are imported,
16413 the binding phase will fail.
16414
16415 @noindent
16416 It is also possible to build an encapsulated library where not only
16417 the code to elaborate and finalize the library is embedded but also
16418 ensuring that the library is linked only against static
16419 libraries. So an encapsulated library only depends on system
16420 libraries, all other code, including the GNAT runtime, is embedded. To
16421 build an encapsulated library the attribute
16422 @code{Library_Standalone} must be set to @code{encapsulated}:
16423
16424 @smallexample @c projectfile
16425 @group
16426    for Library_Dir use "lib_dir";
16427    for Library_Name use "dummy";
16428    for Library_Interface use ("int1", "int1.child");
16429    for Library_Standalone use "encapsulated";
16430 @end group
16431 @end smallexample
16432
16433 @noindent
16434 The default value for this attribute is @code{standard} in which case
16435 a stand-alone library is built.
16436
16437 The attribute @code{Library_Src_Dir} may be specified for a
16438 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16439 single string value. Its value must be the path (absolute or relative to the
16440 project directory) of an existing directory. This directory cannot be the
16441 object directory or one of the source directories, but it can be the same as
16442 the library directory. The sources of the Interface
16443 Units of the library that are needed by an Ada client of the library will be
16444 copied to the designated directory, called the Interface Copy directory.
16445 These sources include the specs of the Interface Units, but they may also
16446 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16447 are used, or when there is a generic unit in the spec. Before the sources
16448 are copied to the Interface Copy directory, an attempt is made to delete all
16449 files in the Interface Copy directory.
16450
16451 Building stand-alone libraries by hand is somewhat tedious, but for those
16452 occasions when it is necessary here are the steps that you need to perform:
16453 @itemize @bullet
16454 @item
16455 Compile all library sources.
16456
16457 @item
16458 Invoke the binder with the switch @option{-n} (No Ada main program),
16459 with all the @file{ALI} files of the interfaces, and
16460 with the switch @option{-L} to give specific names to the @code{init}
16461 and @code{final} procedures.  For example:
16462 @smallexample
16463   gnatbind -n int1.ali int2.ali -Lsal1
16464 @end smallexample
16465
16466 @item
16467 Compile the binder generated file:
16468 @smallexample
16469   gcc -c b~int2.adb
16470 @end smallexample
16471
16472 @item
16473 Link the dynamic library with all the necessary object files,
16474 indicating to the linker the names of the @code{init} (and possibly
16475 @code{final}) procedures for automatic initialization (and finalization).
16476 The built library should be placed in a directory different from
16477 the object directory.
16478
16479 @item
16480 Copy the @code{ALI} files of the interface to the library directory,
16481 add in this copy an indication that it is an interface to a SAL
16482 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16483 with letter ``P'') and make the modified copy of the @file{ALI} file
16484 read-only.
16485 @end itemize
16486
16487 @noindent
16488 Using SALs is not different from using other libraries
16489 (see @ref{Using a library}).
16490
16491 @node Creating a Stand-alone Library to be used in a non-Ada context
16492 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16493
16494 @noindent
16495 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16496 a non-Ada context.
16497
16498 The only extra step required is to ensure that library interface subprograms
16499 are compatible with the main program, by means of @code{pragma Export}
16500 or @code{pragma Convention}.
16501
16502 Here is an example of simple library interface for use with C main program:
16503
16504 @smallexample @c ada
16505 package My_Package is
16506
16507    procedure Do_Something;
16508    pragma Export (C, Do_Something, "do_something");
16509
16510    procedure Do_Something_Else;
16511    pragma Export (C, Do_Something_Else, "do_something_else");
16512
16513 end My_Package;
16514 @end smallexample
16515
16516 @noindent
16517 On the foreign language side, you must provide a ``foreign'' view of the
16518 library interface; remember that it should contain elaboration routines in
16519 addition to interface subprograms.
16520
16521 The example below shows the content of @code{mylib_interface.h} (note
16522 that there is no rule for the naming of this file, any name can be used)
16523 @smallexample
16524 /* the library elaboration procedure */
16525 extern void mylibinit (void);
16526
16527 /* the library finalization procedure */
16528 extern void mylibfinal (void);
16529
16530 /* the interface exported by the library */
16531 extern void do_something (void);
16532 extern void do_something_else (void);
16533 @end smallexample
16534
16535 @noindent
16536 Libraries built as explained above can be used from any program, provided
16537 that the elaboration procedures (named @code{mylibinit} in the previous
16538 example) are called before the library services are used. Any number of
16539 libraries can be used simultaneously, as long as the elaboration
16540 procedure of each library is called.
16541
16542 Below is an example of a C program that uses the @code{mylib} library.
16543
16544 @smallexample
16545 #include "mylib_interface.h"
16546
16547 int
16548 main (void)
16549 @{
16550    /* First, elaborate the library before using it */
16551    mylibinit ();
16552
16553    /* Main program, using the library exported entities */
16554    do_something ();
16555    do_something_else ();
16556
16557    /* Library finalization at the end of the program */
16558    mylibfinal ();
16559    return 0;
16560 @}
16561 @end smallexample
16562
16563 @noindent
16564 Note that invoking any library finalization procedure generated by
16565 @code{gnatbind} shuts down the Ada run-time environment.
16566 Consequently, the
16567 finalization of all Ada libraries must be performed at the end of the program.
16568 No call to these libraries or to the Ada run-time library should be made
16569 after the finalization phase.
16570
16571 @node Restrictions in Stand-alone Libraries
16572 @subsection Restrictions in Stand-alone Libraries
16573
16574 @noindent
16575 The pragmas listed below should be used with caution inside libraries,
16576 as they can create incompatibilities with other Ada libraries:
16577 @itemize @bullet
16578 @item pragma @code{Locking_Policy}
16579 @item pragma @code{Queuing_Policy}
16580 @item pragma @code{Task_Dispatching_Policy}
16581 @item pragma @code{Unreserve_All_Interrupts}
16582 @end itemize
16583
16584 @noindent
16585 When using a library that contains such pragmas, the user must make sure
16586 that all libraries use the same pragmas with the same values. Otherwise,
16587 @code{Program_Error} will
16588 be raised during the elaboration of the conflicting
16589 libraries. The usage of these pragmas and its consequences for the user
16590 should therefore be well documented.
16591
16592 Similarly, the traceback in the exception occurrence mechanism should be
16593 enabled or disabled in a consistent manner across all libraries.
16594 Otherwise, Program_Error will be raised during the elaboration of the
16595 conflicting libraries.
16596
16597 If the @code{Version} or @code{Body_Version}
16598 attributes are used inside a library, then you need to
16599 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16600 libraries, so that version identifiers can be properly computed.
16601 In practice these attributes are rarely used, so this is unlikely
16602 to be a consideration.
16603
16604 @node  Rebuilding the GNAT Run-Time Library
16605 @section Rebuilding the GNAT Run-Time Library
16606 @cindex GNAT Run-Time Library, rebuilding
16607 @cindex Building the GNAT Run-Time Library
16608 @cindex Rebuilding the GNAT Run-Time Library
16609 @cindex Run-Time Library, rebuilding
16610
16611 @noindent
16612 It may be useful to recompile the GNAT library in various contexts, the
16613 most important one being the use of partition-wide configuration pragmas
16614 such as @code{Normalize_Scalars}. A special Makefile called
16615 @code{Makefile.adalib} is provided to that effect and can be found in
16616 the directory containing the GNAT library. The location of this
16617 directory depends on the way the GNAT environment has been installed and can
16618 be determined by means of the command:
16619
16620 @smallexample
16621 $ gnatls -v
16622 @end smallexample
16623
16624 @noindent
16625 The last entry in the object search path usually contains the
16626 gnat library. This Makefile contains its own documentation and in
16627 particular the set of instructions needed to rebuild a new library and
16628 to use it.
16629
16630 @node Using the GNU make Utility
16631 @chapter Using the GNU @code{make} Utility
16632 @findex make
16633
16634 @noindent
16635 This chapter offers some examples of makefiles that solve specific
16636 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16637 make, make, GNU @code{make}}), nor does it try to replace the
16638 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16639
16640 All the examples in this section are specific to the GNU version of
16641 make. Although @command{make} is a standard utility, and the basic language
16642 is the same, these examples use some advanced features found only in
16643 @code{GNU make}.
16644
16645 @menu
16646 * Using gnatmake in a Makefile::
16647 * Automatically Creating a List of Directories::
16648 * Generating the Command Line Switches::
16649 * Overcoming Command Line Length Limits::
16650 @end menu
16651
16652 @node Using gnatmake in a Makefile
16653 @section Using gnatmake in a Makefile
16654 @findex makefile
16655 @cindex GNU make
16656
16657 @noindent
16658 Complex project organizations can be handled in a very powerful way by
16659 using GNU make combined with gnatmake. For instance, here is a Makefile
16660 which allows you to build each subsystem of a big project into a separate
16661 shared library. Such a makefile allows you to significantly reduce the link
16662 time of very big applications while maintaining full coherence at
16663 each step of the build process.
16664
16665 The list of dependencies are handled automatically by
16666 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16667 the appropriate directories.
16668
16669 Note that you should also read the example on how to automatically
16670 create the list of directories
16671 (@pxref{Automatically Creating a List of Directories})
16672 which might help you in case your project has a lot of subdirectories.
16673
16674 @smallexample
16675 @iftex
16676 @leftskip=0cm
16677 @font@heightrm=cmr8
16678 @heightrm
16679 @end iftex
16680 ## This Makefile is intended to be used with the following directory
16681 ## configuration:
16682 ##  - The sources are split into a series of csc (computer software components)
16683 ##    Each of these csc is put in its own directory.
16684 ##    Their name are referenced by the directory names.
16685 ##    They will be compiled into shared library (although this would also work
16686 ##    with static libraries
16687 ##  - The main program (and possibly other packages that do not belong to any
16688 ##    csc is put in the top level directory (where the Makefile is).
16689 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16690 ##                    \_ second_csc (sources) __ lib (will contain the library)
16691 ##                    \_ @dots{}
16692 ## Although this Makefile is build for shared library, it is easy to modify
16693 ## to build partial link objects instead (modify the lines with -shared and
16694 ## gnatlink below)
16695 ##
16696 ## With this makefile, you can change any file in the system or add any new
16697 ## file, and everything will be recompiled correctly (only the relevant shared
16698 ## objects will be recompiled, and the main program will be re-linked).
16699
16700 # The list of computer software component for your project. This might be
16701 # generated automatically.
16702 CSC_LIST=aa bb cc
16703
16704 # Name of the main program (no extension)
16705 MAIN=main
16706
16707 # If we need to build objects with -fPIC, uncomment the following line
16708 #NEED_FPIC=-fPIC
16709
16710 # The following variable should give the directory containing libgnat.so
16711 # You can get this directory through 'gnatls -v'. This is usually the last
16712 # directory in the Object_Path.
16713 GLIB=@dots{}
16714
16715 # The directories for the libraries
16716 # (This macro expands the list of CSC to the list of shared libraries, you
16717 # could simply use the expanded form:
16718 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16719 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16720
16721 $@{MAIN@}: objects $@{LIB_DIR@}
16722     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16723     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16724
16725 objects::
16726     # recompile the sources
16727     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16728
16729 # Note: In a future version of GNAT, the following commands will be simplified
16730 # by a new tool, gnatmlib
16731 $@{LIB_DIR@}:
16732     mkdir -p $@{dir $@@ @}
16733     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16734     cd $@{dir $@@ @} && cp -f ../*.ali .
16735
16736 # The dependencies for the modules
16737 # Note that we have to force the expansion of *.o, since in some cases
16738 # make won't be able to do it itself.
16739 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16740 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16741 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16742
16743 # Make sure all of the shared libraries are in the path before starting the
16744 # program
16745 run::
16746     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16747
16748 clean::
16749     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16750     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16751     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16752     $@{RM@} *.o *.ali $@{MAIN@}
16753 @end smallexample
16754
16755 @node Automatically Creating a List of Directories
16756 @section Automatically Creating a List of Directories
16757
16758 @noindent
16759 In most makefiles, you will have to specify a list of directories, and
16760 store it in a variable. For small projects, it is often easier to
16761 specify each of them by hand, since you then have full control over what
16762 is the proper order for these directories, which ones should be
16763 included.
16764
16765 However, in larger projects, which might involve hundreds of
16766 subdirectories, it might be more convenient to generate this list
16767 automatically.
16768
16769 The example below presents two methods. The first one, although less
16770 general, gives you more control over the list. It involves wildcard
16771 characters, that are automatically expanded by @command{make}. Its
16772 shortcoming is that you need to explicitly specify some of the
16773 organization of your project, such as for instance the directory tree
16774 depth, whether some directories are found in a separate tree, @enddots{}
16775
16776 The second method is the most general one. It requires an external
16777 program, called @command{find}, which is standard on all Unix systems. All
16778 the directories found under a given root directory will be added to the
16779 list.
16780
16781 @smallexample
16782 @iftex
16783 @leftskip=0cm
16784 @font@heightrm=cmr8
16785 @heightrm
16786 @end iftex
16787 # The examples below are based on the following directory hierarchy:
16788 # All the directories can contain any number of files
16789 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16790 #                       ->  ab
16791 #                       ->  ac
16792 #                ->  b  ->  ba  ->  baa
16793 #                       ->  bb
16794 #                       ->  bc
16795 # This Makefile creates a variable called DIRS, that can be reused any time
16796 # you need this list (see the other examples in this section)
16797
16798 # The root of your project's directory hierarchy
16799 ROOT_DIRECTORY=.
16800
16801 ####
16802 # First method: specify explicitly the list of directories
16803 # This allows you to specify any subset of all the directories you need.
16804 ####
16805
16806 DIRS := a/aa/ a/ab/ b/ba/
16807
16808 ####
16809 # Second method: use wildcards
16810 # Note that the argument(s) to wildcard below should end with a '/'.
16811 # Since wildcards also return file names, we have to filter them out
16812 # to avoid duplicate directory names.
16813 # We thus use make's @code{dir} and @code{sort} functions.
16814 # It sets DIRs to the following value (note that the directories aaa and baa
16815 # are not given, unless you change the arguments to wildcard).
16816 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16817 ####
16818
16819 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16820                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16821
16822 ####
16823 # Third method: use an external program
16824 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16825 # This is the most complete command: it sets DIRs to the following value:
16826 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16827 ####
16828
16829 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16830
16831 @end smallexample
16832
16833 @node Generating the Command Line Switches
16834 @section Generating the Command Line Switches
16835
16836 @noindent
16837 Once you have created the list of directories as explained in the
16838 previous section (@pxref{Automatically Creating a List of Directories}),
16839 you can easily generate the command line arguments to pass to gnatmake.
16840
16841 For the sake of completeness, this example assumes that the source path
16842 is not the same as the object path, and that you have two separate lists
16843 of directories.
16844
16845 @smallexample
16846 # see "Automatically creating a list of directories" to create
16847 # these variables
16848 SOURCE_DIRS=
16849 OBJECT_DIRS=
16850
16851 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16852 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16853
16854 all:
16855         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16856 @end smallexample
16857
16858 @node Overcoming Command Line Length Limits
16859 @section Overcoming Command Line Length Limits
16860
16861 @noindent
16862 One problem that might be encountered on big projects is that many
16863 operating systems limit the length of the command line. It is thus hard to give
16864 gnatmake the list of source and object directories.
16865
16866 This example shows how you can set up environment variables, which will
16867 make @command{gnatmake} behave exactly as if the directories had been
16868 specified on the command line, but have a much higher length limit (or
16869 even none on most systems).
16870
16871 It assumes that you have created a list of directories in your Makefile,
16872 using one of the methods presented in
16873 @ref{Automatically Creating a List of Directories}.
16874 For the sake of completeness, we assume that the object
16875 path (where the ALI files are found) is different from the sources patch.
16876
16877 Note a small trick in the Makefile below: for efficiency reasons, we
16878 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16879 expanded immediately by @code{make}. This way we overcome the standard
16880 make behavior which is to expand the variables only when they are
16881 actually used.
16882
16883 On Windows, if you are using the standard Windows command shell, you must
16884 replace colons with semicolons in the assignments to these variables.
16885
16886 @smallexample
16887 @iftex
16888 @leftskip=0cm
16889 @font@heightrm=cmr8
16890 @heightrm
16891 @end iftex
16892 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16893 # This is the same thing as putting the -I arguments on the command line.
16894 # (the equivalent of using -aI on the command line would be to define
16895 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16896 # You can of course have different values for these variables.
16897 #
16898 # Note also that we need to keep the previous values of these variables, since
16899 # they might have been set before running 'make' to specify where the GNAT
16900 # library is installed.
16901
16902 # see "Automatically creating a list of directories" to create these
16903 # variables
16904 SOURCE_DIRS=
16905 OBJECT_DIRS=
16906
16907 empty:=
16908 space:=$@{empty@} $@{empty@}
16909 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16910 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16911 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16912 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16913 export ADA_INCLUDE_PATH
16914 export ADA_OBJECTS_PATH
16915
16916 all:
16917         gnatmake main_unit
16918 @end smallexample
16919 @end ifclear
16920
16921 @node Memory Management Issues
16922 @chapter Memory Management Issues
16923
16924 @noindent
16925 This chapter describes some useful memory pools provided in the GNAT library
16926 and in particular the GNAT Debug Pool facility, which can be used to detect
16927 incorrect uses of access values (including ``dangling references'').
16928 @ifclear vms
16929 It also describes the @command{gnatmem} tool, which can be used to track down
16930 ``memory leaks''.
16931 @end ifclear
16932
16933 @menu
16934 * Some Useful Memory Pools::
16935 * The GNAT Debug Pool Facility::
16936 @ifclear vms
16937 * The gnatmem Tool::
16938 @end ifclear
16939 @end menu
16940
16941 @node Some Useful Memory Pools
16942 @section Some Useful Memory Pools
16943 @findex Memory Pool
16944 @cindex storage, pool
16945
16946 @noindent
16947 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16948 storage pool. Allocations use the standard system call @code{malloc} while
16949 deallocations use the standard system call @code{free}. No reclamation is
16950 performed when the pool goes out of scope. For performance reasons, the
16951 standard default Ada allocators/deallocators do not use any explicit storage
16952 pools but if they did, they could use this storage pool without any change in
16953 behavior. That is why this storage pool is used  when the user
16954 manages to make the default implicit allocator explicit as in this example:
16955 @smallexample @c ada
16956    type T1 is access Something;
16957     -- no Storage pool is defined for T2
16958    type T2 is access Something_Else;
16959    for T2'Storage_Pool use T1'Storage_Pool;
16960    -- the above is equivalent to
16961    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16962 @end smallexample
16963
16964 @noindent
16965 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16966 pool. The allocation strategy is similar to @code{Pool_Local}'s
16967 except that the all
16968 storage allocated with this pool is reclaimed when the pool object goes out of
16969 scope. This pool provides a explicit mechanism similar to the implicit one
16970 provided by several Ada 83 compilers for allocations performed through a local
16971 access type and whose purpose was to reclaim memory when exiting the
16972 scope of a given local access. As an example, the following program does not
16973 leak memory even though it does not perform explicit deallocation:
16974
16975 @smallexample @c ada
16976 with System.Pool_Local;
16977 procedure Pooloc1 is
16978    procedure Internal is
16979       type A is access Integer;
16980       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16981       for A'Storage_Pool use X;
16982       v : A;
16983    begin
16984       for I in  1 .. 50 loop
16985          v := new Integer;
16986       end loop;
16987    end Internal;
16988 begin
16989    for I in  1 .. 100 loop
16990       Internal;
16991    end loop;
16992 end Pooloc1;
16993 @end smallexample
16994
16995 @noindent
16996 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16997 @code{Storage_Size} is specified for an access type.
16998 The whole storage for the pool is
16999 allocated at once, usually on the stack at the point where the access type is
17000 elaborated. It is automatically reclaimed when exiting the scope where the
17001 access type is defined. This package is not intended to be used directly by the
17002 user and it is implicitly used for each such declaration:
17003
17004 @smallexample @c ada
17005    type T1 is access Something;
17006    for T1'Storage_Size use 10_000;
17007 @end smallexample
17008
17009 @node The GNAT Debug Pool Facility
17010 @section The GNAT Debug Pool Facility
17011 @findex Debug Pool
17012 @cindex storage, pool, memory corruption
17013
17014 @noindent
17015 The use of unchecked deallocation and unchecked conversion can easily
17016 lead to incorrect memory references. The problems generated by such
17017 references are usually difficult to tackle because the symptoms can be
17018 very remote from the origin of the problem. In such cases, it is
17019 very helpful to detect the problem as early as possible. This is the
17020 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17021
17022 In order to use the GNAT specific debugging pool, the user must
17023 associate a debug pool object with each of the access types that may be
17024 related to suspected memory problems. See Ada Reference Manual 13.11.
17025 @smallexample @c ada
17026 type Ptr is access Some_Type;
17027 Pool : GNAT.Debug_Pools.Debug_Pool;
17028 for Ptr'Storage_Pool use Pool;
17029 @end smallexample
17030
17031 @noindent
17032 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17033 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17034 allow the user to redefine allocation and deallocation strategies. They
17035 also provide a checkpoint for each dereference, through the use of
17036 the primitive operation @code{Dereference} which is implicitly called at
17037 each dereference of an access value.
17038
17039 Once an access type has been associated with a debug pool, operations on
17040 values of the type may raise four distinct exceptions,
17041 which correspond to four potential kinds of memory corruption:
17042 @itemize @bullet
17043 @item
17044 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17045 @item
17046 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17047 @item
17048 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17049 @item
17050 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17051 @end itemize
17052
17053 @noindent
17054 For types associated with a Debug_Pool, dynamic allocation is performed using
17055 the standard GNAT allocation routine. References to all allocated chunks of
17056 memory are kept in an internal dictionary. Several deallocation strategies are
17057 provided, whereupon the user can choose to release the memory to the system,
17058 keep it allocated for further invalid access checks, or fill it with an easily
17059 recognizable pattern for debug sessions. The memory pattern is the old IBM
17060 hexadecimal convention: @code{16#DEADBEEF#}.
17061
17062 See the documentation in the file g-debpoo.ads for more information on the
17063 various strategies.
17064
17065 Upon each dereference, a check is made that the access value denotes a
17066 properly allocated memory location. Here is a complete example of use of
17067 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17068 @smallexample @c ada
17069 @iftex
17070 @leftskip=0cm
17071 @end iftex
17072 with Gnat.Io; use Gnat.Io;
17073 with Unchecked_Deallocation;
17074 with Unchecked_Conversion;
17075 with GNAT.Debug_Pools;
17076 with System.Storage_Elements;
17077 with Ada.Exceptions; use Ada.Exceptions;
17078 procedure Debug_Pool_Test is
17079
17080    type T is access Integer;
17081    type U is access all T;
17082
17083    P : GNAT.Debug_Pools.Debug_Pool;
17084    for T'Storage_Pool use P;
17085
17086    procedure Free is new Unchecked_Deallocation (Integer, T);
17087    function UC is new Unchecked_Conversion (U, T);
17088    A, B : aliased T;
17089
17090    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17091
17092 begin
17093    Info (P);
17094    A := new Integer;
17095    B := new Integer;
17096    B := A;
17097    Info (P);
17098    Free (A);
17099    begin
17100       Put_Line (Integer'Image(B.all));
17101    exception
17102       when E : others => Put_Line ("raised: " & Exception_Name (E));
17103    end;
17104    begin
17105       Free (B);
17106    exception
17107       when E : others => Put_Line ("raised: " & Exception_Name (E));
17108    end;
17109    B := UC(A'Access);
17110    begin
17111       Put_Line (Integer'Image(B.all));
17112    exception
17113       when E : others => Put_Line ("raised: " & Exception_Name (E));
17114    end;
17115    begin
17116       Free (B);
17117    exception
17118       when E : others => Put_Line ("raised: " & Exception_Name (E));
17119    end;
17120    Info (P);
17121 end Debug_Pool_Test;
17122 @end smallexample
17123
17124 @noindent
17125 The debug pool mechanism provides the following precise diagnostics on the
17126 execution of this erroneous program:
17127 @smallexample
17128 Debug Pool info:
17129   Total allocated bytes :  0
17130   Total deallocated bytes :  0
17131   Current Water Mark:  0
17132   High Water Mark:  0
17133
17134 Debug Pool info:
17135   Total allocated bytes :  8
17136   Total deallocated bytes :  0
17137   Current Water Mark:  8
17138   High Water Mark:  8
17139
17140 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17141 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17142 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17143 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17144 Debug Pool info:
17145   Total allocated bytes :  8
17146   Total deallocated bytes :  4
17147   Current Water Mark:  4
17148   High Water Mark:  8
17149 @end smallexample
17150
17151 @ifclear vms
17152 @node The gnatmem Tool
17153 @section The @command{gnatmem} Tool
17154 @findex gnatmem
17155
17156 @noindent
17157 The @code{gnatmem} utility monitors dynamic allocation and
17158 deallocation activity in a program, and displays information about
17159 incorrect deallocations and possible sources of memory leaks.
17160 It is designed to work in association with a static runtime library
17161 only and in this context provides three types of information:
17162 @itemize @bullet
17163 @item
17164 General information concerning memory management, such as the total
17165 number of allocations and deallocations, the amount of allocated
17166 memory and the high water mark, i.e.@: the largest amount of allocated
17167 memory in the course of program execution.
17168
17169 @item
17170 Backtraces for all incorrect deallocations, that is to say deallocations
17171 which do not correspond to a valid allocation.
17172
17173 @item
17174 Information on each allocation that is potentially the origin of a memory
17175 leak.
17176 @end itemize
17177
17178 @menu
17179 * Running gnatmem::
17180 * Switches for gnatmem::
17181 * Example of gnatmem Usage::
17182 @end menu
17183
17184 @node Running gnatmem
17185 @subsection Running @code{gnatmem}
17186
17187 @noindent
17188 @code{gnatmem} makes use of the output created by the special version of
17189 allocation and deallocation routines that record call information. This
17190 allows to obtain accurate dynamic memory usage history at a minimal cost to
17191 the execution speed. Note however, that @code{gnatmem} is not supported on
17192 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17193 Solaris and Windows NT/2000/XP (x86).
17194
17195 @noindent
17196 The @code{gnatmem} command has the form
17197
17198 @smallexample
17199 @c    $ gnatmem @ovar{switches} user_program
17200 @c Expanding @ovar macro inline (explanation in macro def comments)
17201       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17202 @end smallexample
17203
17204 @noindent
17205 The program must have been linked with the instrumented version of the
17206 allocation and deallocation routines. This is done by linking with the
17207 @file{libgmem.a} library. For correct symbolic backtrace information,
17208 the user program should be compiled with debugging options
17209 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17210
17211 @smallexample
17212 $ gnatmake -g my_program -largs -lgmem
17213 @end smallexample
17214
17215 @noindent
17216 As library @file{libgmem.a} contains an alternate body for package
17217 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17218 when an executable is linked with library @file{libgmem.a}. It is then not
17219 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17220
17221 @noindent
17222 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17223 This file contains information about all allocations and deallocations
17224 performed by the program. It is produced by the instrumented allocations and
17225 deallocations routines and will be used by @code{gnatmem}.
17226
17227 In order to produce symbolic backtrace information for allocations and
17228 deallocations performed by the GNAT run-time library, you need to use a
17229 version of that library that has been compiled with the @option{-g} switch
17230 (see @ref{Rebuilding the GNAT Run-Time Library}).
17231
17232 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17233 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17234 @option{-i} switch, gnatmem will assume that this file can be found in the
17235 current directory. For example, after you have executed @file{my_program},
17236 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17237
17238 @smallexample
17239 $ gnatmem my_program
17240 @end smallexample
17241
17242 @noindent
17243 This will produce the output with the following format:
17244
17245 *************** debut cc
17246 @smallexample
17247 $ gnatmem my_program
17248
17249 Global information
17250 ------------------
17251    Total number of allocations        :  45
17252    Total number of deallocations      :   6
17253    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17254    High Water Mark                    :  11.40 Kilobytes
17255
17256 .
17257 .
17258 .
17259 Allocation Root # 2
17260 -------------------
17261  Number of non freed allocations    :  11
17262  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17263  High Water Mark                    :   1.27 Kilobytes
17264  Backtrace                          :
17265    my_program.adb:23 my_program.alloc
17266 .
17267 .
17268 .
17269 @end smallexample
17270
17271 The first block of output gives general information. In this case, the
17272 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17273 Unchecked_Deallocation routine occurred.
17274
17275 @noindent
17276 Subsequent paragraphs display  information on all allocation roots.
17277 An allocation root is a specific point in the execution of the program
17278 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17279 construct. This root is represented by an execution backtrace (or subprogram
17280 call stack). By default the backtrace depth for allocations roots is 1, so
17281 that a root corresponds exactly to a source location. The backtrace can
17282 be made deeper, to make the root more specific.
17283
17284 @node Switches for gnatmem
17285 @subsection Switches for @code{gnatmem}
17286
17287 @noindent
17288 @code{gnatmem} recognizes the following switches:
17289
17290 @table @option
17291
17292 @item -q
17293 @cindex @option{-q} (@code{gnatmem})
17294 Quiet. Gives the minimum output needed to identify the origin of the
17295 memory leaks. Omits statistical information.
17296
17297 @item @var{N}
17298 @cindex @var{N} (@code{gnatmem})
17299 N is an integer literal (usually between 1 and 10) which controls the
17300 depth of the backtraces defining allocation root. The default value for
17301 N is 1. The deeper the backtrace, the more precise the localization of
17302 the root. Note that the total number of roots can depend on this
17303 parameter. This parameter must be specified @emph{before} the name of the
17304 executable to be analyzed, to avoid ambiguity.
17305
17306 @item -b n
17307 @cindex @option{-b} (@code{gnatmem})
17308 This switch has the same effect as just depth parameter.
17309
17310 @item -i @var{file}
17311 @cindex @option{-i} (@code{gnatmem})
17312 Do the @code{gnatmem} processing starting from @file{file}, rather than
17313 @file{gmem.out} in the current directory.
17314
17315 @item -m n
17316 @cindex @option{-m} (@code{gnatmem})
17317 This switch causes @code{gnatmem} to mask the allocation roots that have less
17318 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17319 examine even the roots that didn't result in leaks.
17320
17321 @item -s order
17322 @cindex @option{-s} (@code{gnatmem})
17323 This switch causes @code{gnatmem} to sort the allocation roots according to the
17324 specified order of sort criteria, each identified by a single letter. The
17325 currently supported criteria are @code{n, h, w} standing respectively for
17326 number of unfreed allocations, high watermark, and final watermark
17327 corresponding to a specific root. The default order is @code{nwh}.
17328
17329 @end table
17330
17331 @node Example of gnatmem Usage
17332 @subsection Example of @code{gnatmem} Usage
17333
17334 @noindent
17335 The following example shows the use of @code{gnatmem}
17336 on a simple memory-leaking program.
17337 Suppose that we have the following Ada program:
17338
17339 @smallexample @c ada
17340 @group
17341 @cartouche
17342 with Unchecked_Deallocation;
17343 procedure Test_Gm is
17344
17345    type T is array (1..1000) of Integer;
17346    type Ptr is access T;
17347    procedure Free is new Unchecked_Deallocation (T, Ptr);
17348    A : Ptr;
17349
17350    procedure My_Alloc is
17351    begin
17352       A := new T;
17353    end My_Alloc;
17354
17355    procedure My_DeAlloc is
17356       B : Ptr := A;
17357    begin
17358       Free (B);
17359    end My_DeAlloc;
17360
17361 begin
17362    My_Alloc;
17363    for I in 1 .. 5 loop
17364       for J in I .. 5 loop
17365          My_Alloc;
17366       end loop;
17367       My_Dealloc;
17368    end loop;
17369 end;
17370 @end cartouche
17371 @end group
17372 @end smallexample
17373
17374 @noindent
17375 The program needs to be compiled with debugging option and linked with
17376 @code{gmem} library:
17377
17378 @smallexample
17379 $ gnatmake -g test_gm -largs -lgmem
17380 @end smallexample
17381
17382 @noindent
17383 Then we execute the program as usual:
17384
17385 @smallexample
17386 $ test_gm
17387 @end smallexample
17388
17389 @noindent
17390 Then @code{gnatmem} is invoked simply with
17391 @smallexample
17392 $ gnatmem test_gm
17393 @end smallexample
17394
17395 @noindent
17396 which produces the following output (result may vary on different platforms):
17397
17398 @smallexample
17399 Global information
17400 ------------------
17401    Total number of allocations        :  18
17402    Total number of deallocations      :   5
17403    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17404    High Water Mark                    :  56.90 Kilobytes
17405
17406 Allocation Root # 1
17407 -------------------
17408  Number of non freed allocations    :  11
17409  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17410  High Water Mark                    :  46.88 Kilobytes
17411  Backtrace                          :
17412    test_gm.adb:11 test_gm.my_alloc
17413
17414 Allocation Root # 2
17415 -------------------
17416  Number of non freed allocations    :   1
17417  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17418  High Water Mark                    :  10.02 Kilobytes
17419  Backtrace                          :
17420    s-secsta.adb:81 system.secondary_stack.ss_init
17421
17422 Allocation Root # 3
17423 -------------------
17424  Number of non freed allocations    :   1
17425  Final Water Mark (non freed mem)   :  12 Bytes
17426  High Water Mark                    :  12 Bytes
17427  Backtrace                          :
17428    s-secsta.adb:181 system.secondary_stack.ss_init
17429 @end smallexample
17430
17431 @noindent
17432 Note that the GNAT run time contains itself a certain number of
17433 allocations that have no  corresponding deallocation,
17434 as shown here for root #2 and root
17435 #3. This is a normal behavior when the number of non-freed allocations
17436 is one, it allocates dynamic data structures that the run time needs for
17437 the complete lifetime of the program. Note also that there is only one
17438 allocation root in the user program with a single line back trace:
17439 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17440 program shows that 'My_Alloc' is called at 2 different points in the
17441 source (line 21 and line 24). If those two allocation roots need to be
17442 distinguished, the backtrace depth parameter can be used:
17443
17444 @smallexample
17445 $ gnatmem 3 test_gm
17446 @end smallexample
17447
17448 @noindent
17449 which will give the following output:
17450
17451 @smallexample
17452 Global information
17453 ------------------
17454    Total number of allocations        :  18
17455    Total number of deallocations      :   5
17456    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17457    High Water Mark                    :  56.90 Kilobytes
17458
17459 Allocation Root # 1
17460 -------------------
17461  Number of non freed allocations    :  10
17462  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17463  High Water Mark                    :  42.97 Kilobytes
17464  Backtrace                          :
17465    test_gm.adb:11 test_gm.my_alloc
17466    test_gm.adb:24 test_gm
17467    b_test_gm.c:52 main
17468
17469 Allocation Root # 2
17470 -------------------
17471  Number of non freed allocations    :   1
17472  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17473  High Water Mark                    :  10.02 Kilobytes
17474  Backtrace                          :
17475    s-secsta.adb:81  system.secondary_stack.ss_init
17476    s-secsta.adb:283 <system__secondary_stack___elabb>
17477    b_test_gm.c:33   adainit
17478
17479 Allocation Root # 3
17480 -------------------
17481  Number of non freed allocations    :   1
17482  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17483  High Water Mark                    :   3.91 Kilobytes
17484  Backtrace                          :
17485    test_gm.adb:11 test_gm.my_alloc
17486    test_gm.adb:21 test_gm
17487    b_test_gm.c:52 main
17488
17489 Allocation Root # 4
17490 -------------------
17491  Number of non freed allocations    :   1
17492  Final Water Mark (non freed mem)   :  12 Bytes
17493  High Water Mark                    :  12 Bytes
17494  Backtrace                          :
17495    s-secsta.adb:181 system.secondary_stack.ss_init
17496    s-secsta.adb:283 <system__secondary_stack___elabb>
17497    b_test_gm.c:33   adainit
17498 @end smallexample
17499
17500 @noindent
17501 The allocation root #1 of the first example has been split in 2 roots #1
17502 and #3 thanks to the more precise associated backtrace.
17503
17504 @end ifclear
17505
17506 @node Stack Related Facilities
17507 @chapter Stack Related Facilities
17508
17509 @noindent
17510 This chapter describes some useful tools associated with stack
17511 checking and analysis. In
17512 particular, it deals with dynamic and static stack usage measurements.
17513
17514 @menu
17515 * Stack Overflow Checking::
17516 * Static Stack Usage Analysis::
17517 * Dynamic Stack Usage Analysis::
17518 @end menu
17519
17520 @node Stack Overflow Checking
17521 @section Stack Overflow Checking
17522 @cindex Stack Overflow Checking
17523 @cindex -fstack-check
17524
17525 @noindent
17526 For most operating systems, @command{gcc} does not perform stack overflow
17527 checking by default. This means that if the main environment task or
17528 some other task exceeds the available stack space, then unpredictable
17529 behavior will occur. Most native systems offer some level of protection by
17530 adding a guard page at the end of each task stack. This mechanism is usually
17531 not enough for dealing properly with stack overflow situations because
17532 a large local variable could ``jump'' above the guard page.
17533 Furthermore, when the
17534 guard page is hit, there may not be any space left on the stack for executing
17535 the exception propagation code. Enabling stack checking avoids
17536 such situations.
17537
17538 To activate stack checking, compile all units with the gcc option
17539 @option{-fstack-check}. For example:
17540
17541 @smallexample
17542 gcc -c -fstack-check package1.adb
17543 @end smallexample
17544
17545 @noindent
17546 Units compiled with this option will generate extra instructions to check
17547 that any use of the stack (for procedure calls or for declaring local
17548 variables in declare blocks) does not exceed the available stack space.
17549 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17550
17551 For declared tasks, the stack size is controlled by the size
17552 given in an applicable @code{Storage_Size} pragma or by the value specified
17553 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17554 the default size as defined in the GNAT runtime otherwise.
17555
17556 For the environment task, the stack size depends on
17557 system defaults and is unknown to the compiler. Stack checking
17558 may still work correctly if a fixed
17559 size stack is allocated, but this cannot be guaranteed.
17560 @ifclear vms
17561 To ensure that a clean exception is signalled for stack
17562 overflow, set the environment variable
17563 @env{GNAT_STACK_LIMIT} to indicate the maximum
17564 stack area that can be used, as in:
17565 @cindex GNAT_STACK_LIMIT
17566
17567 @smallexample
17568 SET GNAT_STACK_LIMIT 1600
17569 @end smallexample
17570
17571 @noindent
17572 The limit is given in kilobytes, so the above declaration would
17573 set the stack limit of the environment task to 1.6 megabytes.
17574 Note that the only purpose of this usage is to limit the amount
17575 of stack used by the environment task. If it is necessary to
17576 increase the amount of stack for the environment task, then this
17577 is an operating systems issue, and must be addressed with the
17578 appropriate operating systems commands.
17579 @end ifclear
17580 @ifset vms
17581 To have a fixed size stack in the environment task, the stack must be put
17582 in the P0 address space and its size specified.  Use these switches to
17583 create a p0 image:
17584
17585 @smallexample
17586 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17587 @end smallexample
17588
17589 @noindent
17590 The quotes are required to keep case.  The number after @samp{STACK=} is the
17591 size of the environmental task stack in pagelets (512 bytes).  In this example
17592 the stack size is about 2 megabytes.
17593
17594 @noindent
17595 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17596 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17597 more details about the @option{/p0image} qualifier and the @option{stack}
17598 option.
17599
17600 @noindent
17601 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17602 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17603 stack in kilobytes.  For example:
17604
17605 @smallexample
17606 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17607 @end smallexample
17608 @end ifset
17609
17610 @node Static Stack Usage Analysis
17611 @section Static Stack Usage Analysis
17612 @cindex Static Stack Usage Analysis
17613 @cindex -fstack-usage
17614
17615 @noindent
17616 A unit compiled with @option{-fstack-usage} will generate an extra file
17617 that specifies
17618 the maximum amount of stack used, on a per-function basis.
17619 The file has the same
17620 basename as the target object file with a @file{.su} extension.
17621 Each line of this file is made up of three fields:
17622
17623 @itemize
17624 @item
17625 The name of the function.
17626 @item
17627 A number of bytes.
17628 @item
17629 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17630 @end itemize
17631
17632 The second field corresponds to the size of the known part of the function
17633 frame.
17634
17635 The qualifier @code{static} means that the function frame size
17636 is purely static.
17637 It usually means that all local variables have a static size.
17638 In this case, the second field is a reliable measure of the function stack
17639 utilization.
17640
17641 The qualifier @code{dynamic} means that the function frame size is not static.
17642 It happens mainly when some local variables have a dynamic size. When this
17643 qualifier appears alone, the second field is not a reliable measure
17644 of the function stack analysis. When it is qualified with  @code{bounded}, it
17645 means that the second field is a reliable maximum of the function stack
17646 utilization.
17647
17648 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17649 subprogram whose stack usage might be larger than the specified amount of
17650 bytes.  The wording is in keeping with the qualifier documented above.
17651
17652 @node Dynamic Stack Usage Analysis
17653 @section Dynamic Stack Usage Analysis
17654
17655 @noindent
17656 It is possible to measure the maximum amount of stack used by a task, by
17657 adding a switch to @command{gnatbind}, as:
17658
17659 @smallexample
17660 $ gnatbind -u0 file
17661 @end smallexample
17662
17663 @noindent
17664 With this option, at each task termination, its stack usage is  output on
17665 @file{stderr}.
17666 It is not always convenient to output the stack usage when the program
17667 is still running. Hence, it is possible to delay this output until program
17668 termination. for a given number of tasks specified as the argument of the
17669 @option{-u} option. For instance:
17670
17671 @smallexample
17672 $ gnatbind -u100 file
17673 @end smallexample
17674
17675 @noindent
17676 will buffer the stack usage information of the first 100 tasks to terminate and
17677 output this info at program termination. Results are displayed in four
17678 columns:
17679
17680 @noindent
17681 Index | Task Name | Stack Size | Stack Usage
17682
17683 @noindent
17684 where:
17685
17686 @table @emph
17687 @item Index
17688 is a number associated with each task.
17689
17690 @item Task Name
17691 is the name of the task analyzed.
17692
17693 @item Stack Size
17694 is the maximum size for the stack.
17695
17696 @item Stack Usage
17697 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17698 is not entirely analyzed, and it's not possible to know exactly how
17699 much has actually been used.
17700
17701 @end table
17702
17703 @noindent
17704 The environment task stack, e.g., the stack that contains the main unit, is
17705 only processed when the environment variable GNAT_STACK_LIMIT is set.
17706
17707 @noindent
17708 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17709 stack usage reports at run-time. See its body for the details.
17710
17711 @c *********************************
17712 @c *            GNATCHECK          *
17713 @c *********************************
17714 @node Verifying Properties Using gnatcheck
17715 @chapter Verifying Properties Using @command{gnatcheck}
17716 @findex gnatcheck
17717 @cindex @command{gnatcheck}
17718
17719 @noindent
17720 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17721 of Ada source files according to a given set of semantic rules.
17722 @cindex ASIS
17723
17724 In order to check compliance with a given rule, @command{gnatcheck} has to
17725 semantically analyze the Ada sources.
17726 Therefore, checks can only be performed on
17727 legal Ada units. Moreover, when a unit depends semantically upon units located
17728 outside the current directory, the source search path has to be provided when
17729 calling @command{gnatcheck}, either through a specified project file or
17730 through @command{gnatcheck} switches.
17731
17732 For full details, refer to @cite{GNATcheck Reference Manual} document.
17733
17734
17735 @c *********************************
17736 @node Creating Sample Bodies Using gnatstub
17737 @chapter Creating Sample Bodies Using @command{gnatstub}
17738 @findex gnatstub
17739
17740 @noindent
17741 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17742 for library unit declarations.
17743
17744 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17745 driver (see @ref{The GNAT Driver and Project Files}).
17746
17747 To create a body stub, @command{gnatstub} has to compile the library
17748 unit declaration. Therefore, bodies can be created only for legal
17749 library units. Moreover, if a library unit depends semantically upon
17750 units located outside the current directory, you have to provide
17751 the source search path when calling @command{gnatstub}, see the description
17752 of @command{gnatstub} switches below.
17753
17754 By default, all the program unit body stubs generated by @code{gnatstub}
17755 raise the predefined @code{Program_Error} exception, which will catch
17756 accidental calls of generated stubs. This behavior can be changed with
17757 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17758
17759 @menu
17760 * Running gnatstub::
17761 * Switches for gnatstub::
17762 @end menu
17763
17764 @node Running gnatstub
17765 @section Running @command{gnatstub}
17766
17767 @noindent
17768 @command{gnatstub} has a command-line interface of the form:
17769
17770 @smallexample
17771 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17772 @c Expanding @ovar macro inline (explanation in macro def comments)
17773 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17774 @end smallexample
17775
17776 @noindent
17777 where
17778 @table @var
17779 @item filename
17780 is the name of the source file that contains a library unit declaration
17781 for which a body must be created. The file name may contain the path
17782 information.
17783 The file name does not have to follow the GNAT file name conventions. If the
17784 name
17785 does not follow GNAT file naming conventions, the name of the body file must
17786 be provided
17787 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17788 If the file name follows the GNAT file naming
17789 conventions and the name of the body file is not provided,
17790 @command{gnatstub}
17791 creates the name
17792 of the body file from the argument file name by replacing the @file{.ads}
17793 suffix
17794 with the @file{.adb} suffix.
17795
17796 @item directory
17797 indicates the directory in which the body stub is to be placed (the default
17798 is the
17799 current directory)
17800
17801 @item @samp{@var{gcc_switches}} is a list of switches for
17802 @command{gcc}. They will be passed on to all compiler invocations made by
17803 @command{gnatstub} to generate the ASIS trees. Here you can provide
17804 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17805 use the @option{-gnatec} switch to set the configuration file,
17806 use the @option{-gnat05} switch if sources should be compiled in
17807 Ada 2005 mode etc.
17808
17809 @item switches
17810 is an optional sequence of switches as described in the next section
17811 @end table
17812
17813 @node Switches for gnatstub
17814 @section Switches for @command{gnatstub}
17815
17816 @table @option
17817 @c !sort!
17818
17819 @item ^-f^/FULL^
17820 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17821 If the destination directory already contains a file with the name of the
17822 body file
17823 for the argument spec file, replace it with the generated body stub.
17824
17825 @item ^-hs^/HEADER=SPEC^
17826 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17827 Put the comment header (i.e., all the comments preceding the
17828 compilation unit) from the source of the library unit declaration
17829 into the body stub.
17830
17831 @item ^-hg^/HEADER=GENERAL^
17832 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17833 Put a sample comment header into the body stub.
17834
17835 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17836 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17837 Use the content of the file as the comment header for a generated body stub.
17838
17839 @ifclear vms
17840 @item -IDIR
17841 @cindex @option{-IDIR} (@command{gnatstub})
17842 @itemx -I-
17843 @cindex @option{-I-} (@command{gnatstub})
17844 @end ifclear
17845 @ifset vms
17846 @item /NOCURRENT_DIRECTORY
17847 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17848 @end ifset
17849 ^These switches have ^This switch has^ the same meaning as in calls to
17850 @command{gcc}.
17851 ^They define ^It defines ^ the source search path in the call to
17852 @command{gcc} issued
17853 by @command{gnatstub} to compile an argument source file.
17854
17855 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17856 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17857 This switch has the same meaning as in calls to @command{gcc}.
17858 It defines the additional configuration file to be passed to the call to
17859 @command{gcc} issued
17860 by @command{gnatstub} to compile an argument source file.
17861
17862 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17863 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17864 (@var{n} is a non-negative integer). Set the maximum line length in the
17865 body stub to @var{n}; the default is 79. The maximum value that can be
17866 specified is 32767. Note that in the special case of configuration
17867 pragma files, the maximum is always 32767 regardless of whether or
17868 not this switch appears.
17869
17870 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17871 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17872 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17873 the generated body sample to @var{n}.
17874 The default indentation is 3.
17875
17876 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17877 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17878 Order local bodies alphabetically. (By default local bodies are ordered
17879 in the same way as the corresponding local specs in the argument spec file.)
17880
17881 @item ^-i^/INDENTATION=^@var{n}
17882 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17883 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17884
17885 @item ^-k^/TREE_FILE=SAVE^
17886 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17887 Do not remove the tree file (i.e., the snapshot of the compiler internal
17888 structures used by @command{gnatstub}) after creating the body stub.
17889
17890 @item ^-l^/LINE_LENGTH=^@var{n}
17891 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17892 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17893
17894 @item ^--no-exception^/NO_EXCEPTION^
17895 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17896 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17897 This is not always possible for function stubs.
17898
17899 @item ^--no-local-header^/NO_LOCAL_HEADER^
17900 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17901 Do not place local comment header with unit name before body stub for a
17902 unit.
17903
17904 @item ^-o ^/BODY=^@var{body-name}
17905 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17906 Body file name.  This should be set if the argument file name does not
17907 follow
17908 the GNAT file naming
17909 conventions. If this switch is omitted the default name for the body will be
17910 obtained
17911 from the argument file name according to the GNAT file naming conventions.
17912
17913 @item ^-q^/QUIET^
17914 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17915 Quiet mode: do not generate a confirmation when a body is
17916 successfully created, and do not generate a message when a body is not
17917 required for an
17918 argument unit.
17919
17920 @item ^-r^/TREE_FILE=REUSE^
17921 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17922 Reuse the tree file (if it exists) instead of creating it.  Instead of
17923 creating the tree file for the library unit declaration, @command{gnatstub}
17924 tries to find it in the current directory and use it for creating
17925 a body. If the tree file is not found, no body is created. This option
17926 also implies @option{^-k^/SAVE^}, whether or not
17927 the latter is set explicitly.
17928
17929 @item ^-t^/TREE_FILE=OVERWRITE^
17930 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17931 Overwrite the existing tree file.  If the current directory already
17932 contains the file which, according to the GNAT file naming rules should
17933 be considered as a tree file for the argument source file,
17934 @command{gnatstub}
17935 will refuse to create the tree file needed to create a sample body
17936 unless this option is set.
17937
17938 @item ^-v^/VERBOSE^
17939 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17940 Verbose mode: generate version information.
17941
17942 @end table
17943
17944 @c *********************************
17945 @node Creating Unit Tests Using gnattest
17946 @chapter Creating Unit Tests Using @command{gnattest}
17947 @findex gnattest
17948
17949 @noindent
17950 @command{gnattest} is an ASIS-based utility that creates unit-test stubs
17951 as well as a test driver infrastructure (harness). @command{gnattest} creates
17952 a stub for each visible subprogram in the packages under consideration when
17953 they do not exist already.
17954
17955 In order to process source files from a project, @command{gnattest} has to
17956 semantically analyze the sources. Therefore, test stubs can only be
17957 generated for legal Ada units. If a unit is dependent on other units,
17958 those units should be among the source files of the project or of other projects
17959 imported by this one.
17960
17961 Generated stubs and harnesses are based on the AUnit testing framework. AUnit is
17962 an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit for Java
17963 or CppUnit for C++. While it is advised that gnattest users read the AUnit
17964 manual, deep knowledge of AUnit is not necessary for using gnattest. For correct
17965 operation of @command{gnattest}, AUnit should be installed and aunit.gpr must be
17966 on the project path. This happens automatically when Aunit is installed at its
17967 default location.
17968 @menu
17969 * Running gnattest::
17970 * Switches for gnattest::
17971 * Project Attributes for gnattest::
17972 * Simple Example::
17973 * Setting Up and Tearing Down the Testing Environment::
17974 * Regenerating Tests::
17975 * Default Test Behavior::
17976 * Testing Primitive Operations of Tagged Types::
17977 * Testing Inheritance::
17978 * Tagged Types Substitutability Testing::
17979 * Testing with Contracts::
17980 * Additional Tests::
17981 * Current Limitations::
17982 @end menu
17983
17984 @node Running gnattest
17985 @section Running @command{gnattest}
17986
17987 @noindent
17988 @command{gnattest} has a command-line interface of the form
17989
17990 @smallexample
17991 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17992 @c Expanding @ovar macro inline (explanation in macro def comments)
17993 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17994 @end smallexample
17995
17996 @noindent
17997 where
17998 @table @var
17999
18000 @item -Pprojname
18001 specifies the project defining the location of source files. When no
18002 file names are provided on the command line, all sources in the project
18003 are used as input. This switch is required.
18004
18005 @item --harness-dir=dirname
18006 specifies the directory that will hold the harness packages and project file
18007 for the test driver. The harness directory should be specified either by that
18008 switch or by the corresponding attribute in the project file.
18009
18010 @item filename
18011 is the name of the source file containing the library unit package declaration
18012 for which a test package will be created. The file name may given with a path.
18013
18014 @item @samp{@var{gcc_switches}} is a list of switches for
18015 @command{gcc}. These switches will be passed on to all compiler invocations
18016 made by @command{gnatstub} to generate a set of ASIS trees. Here you can provide
18017 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18018 use the @option{-gnatec} switch to set the configuration file,
18019 use the @option{-gnat05} switch if sources should be compiled in
18020 Ada 2005 mode, etc.
18021
18022 @item switches
18023 is an optional sequence of switches as described in the next section.
18024
18025 @end table
18026
18027 @command{gnattest} results can be found in two different places.
18028
18029 @itemize @bullet
18030 @item automatic harness
18031 the harness code, which is located either in the harness-dir as specified on
18032 the command line or in the project file. All of this code is generated
18033 completely automatically and can be destroyed and regenerated at will. It is not
18034 recommended to modify this code manually, since it could easily be overridden
18035 by mistake. The entry point in the harness code is the project file named
18036 @command{test_driver.gpr}. Tests can be compiled and run using a command
18037 such as:
18038
18039 @smallexample
18040 gnatmake -P<harness-dir>/test_driver
18041 test_runner
18042 @end smallexample
18043
18044 Note that you might need to specify the necessary values of scenario variables
18045 when you are not using the AUnit defaults.
18046
18047 @item actual unit test stubs
18048 a test stub for each visible subprogram is created in a separate file, if it
18049 doesn't exist already. By default, those separate test files are located in a
18050 "tests" directory that is created in the directory containing the source file
18051 itself. If it is not appropriate to create the tests in subdirectories of the
18052 source, option @option{--separate-root} can be used. For example, if a source
18053 file my_unit.ads in directory src contains a visible subprogram Proc, then
18054 the corresponding unit test will be found in file
18055 src/tests/my_unit-tests-proc_<code>.adb. <code> is a signature encoding used to
18056 differentiate test names in cases of overloading.
18057
18058 Note that if the project already has both my_unit.ads and my_unit-tests.ads this
18059 will cause name a conflict with generated test package.
18060 @end itemize
18061
18062 @node Switches for gnattest
18063 @section Switches for @command{gnattest}
18064
18065 @table @option
18066 @c !sort!
18067
18068 @item --harness-only
18069 @cindex @option{--harness-only} (@command{gnattest})
18070 When this option is given, @command{gnattest} creates a harness for all
18071 sources, treating them as test packages.
18072
18073 @item --additional-tests=@var{projname}
18074 @cindex @option{--additional-tests} (@command{gnattest})
18075 Sources described in @var{projname} are considered potential additional
18076 manual tests to be added to the test suite.
18077
18078 @item -r
18079 @cindex @option{-r} (@command{gnattest})
18080 Recursively consider all sources from all projects.
18081
18082 @item -X@var{name=value}
18083 @cindex @option{-X} (@command{gnattest})
18084 Indicate that external variable @var{name} has the value @var{value}.
18085
18086 @item -q
18087 @cindex @option{-q} (@command{gnattest})
18088 Suppresses noncritical output messages.
18089
18090 @item -v
18091 @cindex @option{-v} (@command{gnattest})
18092 Verbose mode: generates version information.
18093
18094 @item --liskov
18095 @cindex @option{--liskov} (@command{gnattest})
18096 Enables Liskov verification: run all tests from all parents in order
18097 to check substitutability.
18098
18099 @item --stub-default=@var{val}
18100 @cindex @option{--stub-default} (@command{gnattest})
18101 Specifies the default behavior of generated stubs. @var{val} can be either
18102 "fail" or "pass", "fail" being the default.
18103
18104 @item --separate-root=@var{dirname}
18105 @cindex @option{--separate-root} (@command{gnattest})
18106 The directory hierarchy of tested sources is recreated in the @var{dirname}
18107 directory, and test packages are placed in corresponding directories.
18108
18109 @item --subdir=@var{dirname}
18110 @cindex @option{--subdir} (@command{gnattest})
18111 Test packages are placed in subdirectories. This is the default output mode
18112 since it does not require any additional input from the user. Subdirectories
18113 named "tests" will be created by default.
18114
18115 @end table
18116
18117 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
18118
18119 @node Project Attributes for gnattest
18120 @section Project Attributes for @command{gnattest}
18121
18122 @noindent
18123
18124 Most of the command-line options can also be passed to the tool by adding
18125 special attributes to the project file. Those attributes should be put in
18126 package gnattest. Here is the list of attributes:
18127
18128 @itemize @bullet
18129
18130 @item Separate_Stub_Root
18131 is used to select the same output mode as with the --separate-root option.
18132 This attribute cannot be used together with Stub_Subdir.
18133
18134 @item Stub_Subdir
18135 is used to select the same output mode as with the --subdir option.
18136 This attribute cannot be used together with Separate_Stub_Root.
18137
18138 @item Harness_Dir
18139 is used to specify the directory in which to place harness packages and project
18140 file for the test driver, otherwise specified by --harness-dir.
18141
18142 @item Additional_Tests
18143 is used to specify the project file, otherwise given by
18144 --additional-tests switch.
18145
18146 @item Stubs_Default
18147 is used to specify the default behaviour of test stubs, otherwise
18148 specified by --stub-default option. The value of this attribute
18149 should be either "pass" or "fail".
18150
18151 @end itemize
18152
18153 Each of those attributes can be overridden from the command line if needed.
18154 Other @command{gnattest} switches can also be passed via the project
18155 file as an attribute list called GNATtest_Switches.
18156
18157 @node Simple Example
18158 @section Simple Example
18159
18160 @noindent
18161
18162 Let's take a very simple example using the first @command{gnattest} example
18163 located in:
18164
18165 @smallexample
18166 <install_prefix>/share/examples/gnattest/simple
18167 @end smallexample
18168
18169 This project contains a simple package containing one subprogram. By running gnattest:
18170
18171 @smallexample
18172 $ gnattest --harness-dir=driver -Psimple.gpr
18173 @end smallexample
18174
18175 a test driver is created in directory "driver". It can be compiled and run:
18176
18177 @smallexample
18178 $ cd driver
18179 $ gprbuild -Ptest_driver
18180 $ test_runner
18181 @end smallexample
18182
18183 One failed test with diagnosis "test not implemented" is reported.
18184 Since no special output option was specified, the test package Simple.Tests
18185 is located in:
18186
18187 @smallexample
18188 <install_prefix>/share/examples/gnattest/simple/src/tests
18189 @end smallexample
18190
18191 For each package containing visible subprograms, a child test package is
18192 generated. It contains one test routine per tested subprogram. Each
18193 declaration of a test subprogram has a comment specifying which tested
18194 subprogram it corresponds to. All of the test routines have separate bodies.
18195 The test routine located at simple-tests-test_inc_5eaee3.adb contains a single
18196 statement: a call to procedure Assert. It has two arguments: the Boolean
18197 expression we want to check and the diagnosis message to display if
18198 the condition is false.
18199
18200 That is where actual testing code should be written after a proper setup.
18201 An actual check can be performed by replacing the Assert call with:
18202
18203 @smallexample @c ada
18204 Assert (Inc (1) = 2, "wrong incrementation");
18205 @end smallexample
18206
18207 After recompiling and running the test driver, one successfully passed test
18208 is reported.
18209
18210 @node Setting Up and Tearing Down the Testing Environment
18211 @section Setting Up and Tearing Down the Testing Environment
18212
18213 @noindent
18214
18215 Besides test routines themselves, each test package has an inner package
18216 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
18217 User_Set_Up is called before each test routine of the package and
18218 User_Tear_Down is called after each test routine. Those two procedures can
18219 be used to perform necessary initialization and finalization,
18220 memory allocation, etc.
18221
18222 @node Regenerating Tests
18223 @section Regenerating Tests
18224
18225 @noindent
18226
18227 Bodies of test routines and env_mgmt packages are never overridden after they
18228 have been created once. As long as the name of the subprogram, full expanded Ada
18229 names, and the order of its parameters is the same, the old test routine will
18230 fit in its place and no test stub will be generated for the subprogram.
18231
18232 This can be demonstrated with the previous example. By uncommenting declaration
18233 and body of function Dec in simple.ads and simple.adb, running
18234 @command{gnattest} on the project, and then running the test driver:
18235
18236 @smallexample
18237 gnattest --harness-dir=driver -Psimple.gpr
18238 cd driver
18239 gprbuild -Ptest_driver
18240 test_runner
18241 @end smallexample
18242
18243 the old test is not replaced with a stub, nor is it lost, but a new test stub is
18244 created for function Dec.
18245
18246 The only way of regenerating tests stubs is to remove the previously created
18247 tests.
18248
18249 @node Default Test Behavior
18250 @section Default Test Behavior
18251
18252 @noindent
18253
18254 The generated test driver can treat unimplemented tests in two ways:
18255 either count them all as failed (this is useful to see which tests are still
18256 left to implement) or as passed (to sort out unimplemented ones from those
18257 actually failing).
18258
18259 The test driver accepts a switch to specify this behavior: --stub-default=val,
18260 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
18261
18262 The default behavior of the test driver is set with the same switch
18263 as passed to gnattest when generating the test driver.
18264
18265 Passing it to the driver generated on the first example:
18266
18267 @smallexample
18268 test_runner --stub-default=pass
18269 @end smallexample
18270
18271 makes both tests pass, even the unimplemented one.
18272
18273 @node Testing Primitive Operations of Tagged Types
18274 @section Testing Primitive Operations of Tagged Types
18275
18276 @noindent
18277
18278 Creation of test stubs for primitive operations of tagged types entails a number
18279 of features. Test routines for all primitives of a given tagged type are
18280 placed in a separate child package named according to the tagged type. For
18281 example, if you have tagged type T in package P, all tests for primitives
18282 of T will be in P.T_Tests.
18283
18284 Consider running gnattest on the second example (note: actual tests for this
18285 example already exist, so there's no need to worry if the tool reports that
18286 no new stubs were generated):
18287
18288 @smallexample
18289 cd <install_prefix>/share/examples/gnattest/tagged_rec
18290 gnattest --harness-dir=driver -Ptagged_rec.gpr
18291 @end smallexample
18292
18293 Taking a closer look at the test type declared in the test package
18294 Speed1.Controller_Tests is necessary. It is declared in:
18295
18296 @smallexample
18297 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18298 @end smallexample
18299
18300 Test types are direct or indirect descendants of
18301 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18302 subprograms, the user doesn't need to be concerned with them. However,
18303 when generating test packages for primitive operations, there are some things
18304 the user needs to know.
18305
18306 Type Test_Controller has components that allow assignment of various
18307 derivations of type Controller. And if you look at the specification of
18308 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18309 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18310 Thus, test types mirror the hierarchy of tested types.
18311
18312 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18313 of primitive operations of type T assigns to Fixture a reference to an
18314 object of that exact type T. Notice, however, that if the tagged type has
18315 discriminants, the User_Set_Up only has a commented template for setting
18316 up the fixture, since filling the discriminant with actual value is up
18317 to the user.
18318
18319 The knowledge of the structure of test types allows additional testing
18320 without additional effort. Those possibilities are described below.
18321
18322 @node Testing Inheritance
18323 @section Testing Inheritance
18324
18325 @noindent
18326
18327 Since the test type hierarchy mimics the hierarchy of tested types, the
18328 inheritance of tests takes place. An example of such inheritance can be
18329 seen by running the test driver generated for the second example. As previously
18330 mentioned, actual tests are already written for this example.
18331
18332 @smallexample
18333 cd driver
18334 gprbuild -Ptest_driver
18335 test_runner
18336 @end smallexample
18337
18338 There are 6 passed tests while there are only 5 testable subprograms. The test
18339 routine for function Speed has been inherited and run against objects of the
18340 derived type.
18341
18342 @node Tagged Types Substitutability Testing
18343 @section Tagged Types Substitutability Testing
18344
18345 @noindent
18346
18347 Tagged Types Substitutability Testing is a way of verifying the Liskov
18348 substitution principle (LSP) by testing. LSP is a principle stating that if
18349 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18350 then objects of type T may be replaced with objects of type S (that is,
18351 objects of type S may be substituted for objects of type T), without
18352 altering any of the desirable properties of the program. When the properties
18353 of the program are expressed in the form of subprogram preconditions and
18354 postconditions (let's call them pre and post), LSP is formulated as relations
18355 between the pre and post of primitive operations and the pre and post of their
18356 derived operations. The pre of a derived operation should not be stronger than
18357 the original pre, and the post of the derived operation should not be weaker
18358 than the original post. Those relations ensure that verifying if a dispatching
18359 call is safe can be done just by using the pre and post of the root operation.
18360
18361 Verifying LSP by testing consists of running all the unit tests associated with
18362 the primitives of a given tagged type with objects of its derived types.
18363
18364 In the example used in the previous section, there was clearly a violation of
18365 LSP. The overriding primitive Adjust_Speed in package Speed2 removes the
18366 functionality of the overridden primitive and thus doesn't respect LSP.
18367 Gnattest has a special option to run overridden parent tests against objects
18368 of the type which have overriding primitives:
18369
18370 @smallexample
18371 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18372 cd driver
18373 gprbuild -Ptest_driver
18374 test_runner
18375 @end smallexample
18376
18377 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18378 against objects of the derived type.
18379
18380 @node Testing with Contracts
18381 @section Testing with Contracts
18382
18383 @noindent
18384
18385 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case.
18386 Test routines are generated, one per each Test_Case associated with a tested
18387 subprogram. Those test routines have special wrappers for tested functions
18388 that have composition of pre- and postcondition of the subprogram with
18389 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18390 either count for Nominal mode or do not count for Robustness mode).
18391
18392 The third example demonstrates how this works:
18393
18394 @smallexample
18395 cd <install_prefix>/share/examples/gnattest/contracts
18396 gnattest --harness-dir=driver -Pcontracts.gpr
18397 @end smallexample
18398
18399 Putting actual checks within the range of the contract does not cause any
18400 error reports. For example, for the test routine which corresponds to
18401 test case 1:
18402
18403 @smallexample @c ada
18404 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18405 @end smallexample
18406
18407 and for the test routine corresponding to test case 2:
18408
18409 @smallexample @c ada
18410 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18411 @end smallexample
18412
18413 are acceptable:
18414
18415 @smallexample
18416 cd driver
18417 gprbuild -Ptest_driver
18418 test_runner
18419 @end smallexample
18420
18421 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18422 a precondition violation for test case one. Also, by using any otherwise
18423 correct but positive pair of numbers in the second test routine, you can also
18424 get a precondition violation. Postconditions are checked and reported
18425 the same way.
18426
18427 @node Additional Tests
18428 @section Additional Tests
18429
18430 @noindent
18431 @command{gnattest} can add user-written tests to the main suite of the test
18432 driver. @command{gnattest} traverses the given packages and searches for test
18433 routines. All procedures with a single in out parameter of a type which is
18434 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18435 specifications are added to the suites and are then executed by the test driver.
18436 (Set_Up and Tear_Down are filtered out.)
18437
18438 An example illustrates two ways of creating test harnesses for user-written
18439 tests. Directory additional_tests contains an AUnit-based test driver written
18440 by hand.
18441
18442 @smallexample
18443 <install_prefix>/share/examples/gnattest/additional_tests/
18444 @end smallexample
18445
18446 To create a test driver for already-written tests, use the --harness-only
18447 option:
18448
18449 @smallexample
18450 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18451   --harness-only
18452 gnatmake -Pharness_only/test_driver.gpr
18453 harness_only/test_runner
18454 @end smallexample
18455
18456 Additional tests can also be executed together with generated tests:
18457
18458 @smallexample
18459 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18460   --harness-dir=mixing
18461 gnatmake -Pmixing/test_driver.gpr
18462 mixing/test_runner
18463 @end smallexample
18464
18465 @node Current Limitations
18466 @section Current Limitations
18467
18468 @noindent
18469
18470 The tool currently does not support following features:
18471
18472 @itemize @bullet
18473 @item generic tests for generic packages and package instantiations
18474 @item tests for protected subprograms and entries
18475 @item aspects Precondition, Postcondition, and Test_Case
18476 @item generating test packages for code that is not conformant with ada 2005
18477
18478 @end itemize
18479
18480 @c *********************************
18481 @node Generating Ada Bindings for C and C++ headers
18482 @chapter Generating Ada Bindings for C and C++ headers
18483 @findex binding
18484
18485 @noindent
18486 GNAT now comes with a binding generator for C and C++ headers which is
18487 intended to do 95% of the tedious work of generating Ada specs from C
18488 or C++ header files.
18489
18490 Note that this capability is not intended to generate 100% correct Ada specs,
18491 and will is some cases require manual adjustments, although it can often
18492 be used out of the box in practice.
18493
18494 Some of the known limitations include:
18495
18496 @itemize @bullet
18497 @item only very simple character constant macros are translated into Ada
18498 constants. Function macros (macros with arguments) are partially translated
18499 as comments, to be completed manually if needed.
18500 @item some extensions (e.g. vector types) are not supported
18501 @item pointers to pointers or complex structures are mapped to System.Address
18502 @item identifiers with identical name (except casing) will generate compilation
18503       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18504 @end itemize
18505
18506 The code generated is using the Ada 2005 syntax, which makes it
18507 easier to interface with other languages than previous versions of Ada.
18508
18509 @menu
18510 * Running the binding generator::
18511 * Generating bindings for C++ headers::
18512 * Switches::
18513 @end menu
18514
18515 @node Running the binding generator
18516 @section Running the binding generator
18517
18518 @noindent
18519 The binding generator is part of the @command{gcc} compiler and can be
18520 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18521 spec files for the header files specified on the command line, and all
18522 header files needed by these files transitively. For example:
18523
18524 @smallexample
18525 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18526 $ gcc -c -gnat05 *.ads
18527 @end smallexample
18528
18529 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18530 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18531 correspond to the files @file{/usr/include/time.h},
18532 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18533 mode these Ada specs.
18534
18535 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18536 and will attempt to generate corresponding Ada comments.
18537
18538 If you want to generate a single Ada file and not the transitive closure, you
18539 can use instead the @option{-fdump-ada-spec-slim} switch.
18540
18541 Note that we recommend when possible to use the @command{g++} driver to
18542 generate bindings, even for most C headers, since this will in general
18543 generate better Ada specs. For generating bindings for C++ headers, it is
18544 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18545 is equivalent in this case. If @command{g++} cannot work on your C headers
18546 because of incompatibilities between C and C++, then you can fallback to
18547 @command{gcc} instead.
18548
18549 For an example of better bindings generated from the C++ front-end,
18550 the name of the parameters (when available) are actually ignored by the C
18551 front-end. Consider the following C header:
18552
18553 @smallexample
18554 extern void foo (int variable);
18555 @end smallexample
18556
18557 with the C front-end, @code{variable} is ignored, and the above is handled as:
18558
18559 @smallexample
18560 extern void foo (int);
18561 @end smallexample
18562
18563 generating a generic:
18564
18565 @smallexample
18566 procedure foo (param1 : int);
18567 @end smallexample
18568
18569 with the C++ front-end, the name is available, and we generate:
18570
18571 @smallexample
18572 procedure foo (variable : int);
18573 @end smallexample
18574
18575 In some cases, the generated bindings will be more complete or more meaningful
18576 when defining some macros, which you can do via the @option{-D} switch. This
18577 is for example the case with @file{Xlib.h} under GNU/Linux:
18578
18579 @smallexample
18580 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18581 @end smallexample
18582
18583 The above will generate more complete bindings than a straight call without
18584 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18585
18586 In other cases, it is not possible to parse a header file in a stand-alone
18587 manner, because other include files need to be included first. In this
18588 case, the solution is to create a small header file including the needed
18589 @code{#include} and possible @code{#define} directives. For example, to
18590 generate Ada bindings for @file{readline/readline.h}, you need to first
18591 include @file{stdio.h}, so you can create a file with the following two
18592 lines in e.g. @file{readline1.h}:
18593
18594 @smallexample
18595 #include <stdio.h>
18596 #include <readline/readline.h>
18597 @end smallexample
18598
18599 and then generate Ada bindings from this file:
18600
18601 @smallexample
18602 $ g++ -c -fdump-ada-spec readline1.h
18603 @end smallexample
18604
18605 @node Generating bindings for C++ headers
18606 @section Generating bindings for C++ headers
18607
18608 @noindent
18609 Generating bindings for C++ headers is done using the same options, always
18610 with the @command{g++} compiler.
18611
18612 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18613 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18614 multiple inheritance of abstract classes will be mapped to Ada interfaces
18615 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18616 information on interfacing to C++).
18617
18618 For example, given the following C++ header file:
18619
18620 @smallexample
18621 @group
18622 @cartouche
18623 class Carnivore @{
18624 public:
18625    virtual int Number_Of_Teeth () = 0;
18626 @};
18627
18628 class Domestic @{
18629 public:
18630    virtual void Set_Owner (char* Name) = 0;
18631 @};
18632
18633 class Animal @{
18634 public:
18635   int Age_Count;
18636   virtual void Set_Age (int New_Age);
18637 @};
18638
18639 class Dog : Animal, Carnivore, Domestic @{
18640  public:
18641   int  Tooth_Count;
18642   char *Owner;
18643
18644   virtual int  Number_Of_Teeth ();
18645   virtual void Set_Owner (char* Name);
18646
18647   Dog();
18648 @};
18649 @end cartouche
18650 @end group
18651 @end smallexample
18652
18653 The corresponding Ada code is generated:
18654
18655 @smallexample @c ada
18656 @group
18657 @cartouche
18658   package Class_Carnivore is
18659     type Carnivore is limited interface;
18660     pragma Import (CPP, Carnivore);
18661
18662     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18663   end;
18664   use Class_Carnivore;
18665
18666   package Class_Domestic is
18667     type Domestic is limited interface;
18668     pragma Import (CPP, Domestic);
18669
18670     procedure Set_Owner
18671       (this : access Domestic;
18672        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18673   end;
18674   use Class_Domestic;
18675
18676   package Class_Animal is
18677     type Animal is tagged limited record
18678       Age_Count : aliased int;
18679     end record;
18680     pragma Import (CPP, Animal);
18681
18682     procedure Set_Age (this : access Animal; New_Age : int);
18683     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18684   end;
18685   use Class_Animal;
18686
18687   package Class_Dog is
18688     type Dog is new Animal and Carnivore and Domestic with record
18689       Tooth_Count : aliased int;
18690       Owner : Interfaces.C.Strings.chars_ptr;
18691     end record;
18692     pragma Import (CPP, Dog);
18693
18694     function Number_Of_Teeth (this : access Dog) return int;
18695     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18696
18697     procedure Set_Owner
18698       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18699     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18700
18701     function New_Dog return Dog;
18702     pragma CPP_Constructor (New_Dog);
18703     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18704   end;
18705   use Class_Dog;
18706 @end cartouche
18707 @end group
18708 @end smallexample
18709
18710 @node Switches
18711 @section Switches
18712
18713 @table @option
18714 @item -fdump-ada-spec
18715 @cindex @option{-fdump-ada-spec} (@command{gcc})
18716 Generate Ada spec files for the given header files transitively (including
18717 all header files that these headers depend upon).
18718
18719 @item -fdump-ada-spec-slim
18720 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18721 Generate Ada spec files for the header files specified on the command line
18722 only.
18723
18724 @item -C
18725 @cindex @option{-C} (@command{gcc})
18726 Extract comments from headers and generate Ada comments in the Ada spec files.
18727 @end table
18728
18729 @node Other Utility Programs
18730 @chapter Other Utility Programs
18731
18732 @noindent
18733 This chapter discusses some other utility programs available in the Ada
18734 environment.
18735
18736 @menu
18737 * Using Other Utility Programs with GNAT::
18738 * The External Symbol Naming Scheme of GNAT::
18739 * Converting Ada Files to html with gnathtml::
18740 * Installing gnathtml::
18741 @ifset vms
18742 * LSE::
18743 * Profiling::
18744 @end ifset
18745 @end menu
18746
18747 @node Using Other Utility Programs with GNAT
18748 @section Using Other Utility Programs with GNAT
18749
18750 @noindent
18751 The object files generated by GNAT are in standard system format and in
18752 particular the debugging information uses this format. This means
18753 programs generated by GNAT can be used with existing utilities that
18754 depend on these formats.
18755
18756 @ifclear vms
18757 In general, any utility program that works with C will also often work with
18758 Ada programs generated by GNAT. This includes software utilities such as
18759 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18760 as Purify.
18761 @end ifclear
18762
18763 @node The External Symbol Naming Scheme of GNAT
18764 @section The External Symbol Naming Scheme of GNAT
18765
18766 @noindent
18767 In order to interpret the output from GNAT, when using tools that are
18768 originally intended for use with other languages, it is useful to
18769 understand the conventions used to generate link names from the Ada
18770 entity names.
18771
18772 All link names are in all lowercase letters. With the exception of library
18773 procedure names, the mechanism used is simply to use the full expanded
18774 Ada name with dots replaced by double underscores. For example, suppose
18775 we have the following package spec:
18776
18777 @smallexample @c ada
18778 @group
18779 @cartouche
18780 package QRS is
18781    MN : Integer;
18782 end QRS;
18783 @end cartouche
18784 @end group
18785 @end smallexample
18786
18787 @noindent
18788 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18789 the corresponding link name is @code{qrs__mn}.
18790 @findex Export
18791 Of course if a @code{pragma Export} is used this may be overridden:
18792
18793 @smallexample @c ada
18794 @group
18795 @cartouche
18796 package Exports is
18797    Var1 : Integer;
18798    pragma Export (Var1, C, External_Name => "var1_name");
18799    Var2 : Integer;
18800    pragma Export (Var2, C, Link_Name => "var2_link_name");
18801 end Exports;
18802 @end cartouche
18803 @end group
18804 @end smallexample
18805
18806 @noindent
18807 In this case, the link name for @var{Var1} is whatever link name the
18808 C compiler would assign for the C function @var{var1_name}. This typically
18809 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18810 system conventions, but other possibilities exist. The link name for
18811 @var{Var2} is @var{var2_link_name}, and this is not operating system
18812 dependent.
18813
18814 @findex _main
18815 One exception occurs for library level procedures. A potential ambiguity
18816 arises between the required name @code{_main} for the C main program,
18817 and the name we would otherwise assign to an Ada library level procedure
18818 called @code{Main} (which might well not be the main program).
18819
18820 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18821 names. So if we have a library level procedure such as
18822
18823 @smallexample @c ada
18824 @group
18825 @cartouche
18826 procedure Hello (S : String);
18827 @end cartouche
18828 @end group
18829 @end smallexample
18830
18831 @noindent
18832 the external name of this procedure will be @var{_ada_hello}.
18833
18834
18835 @node Converting Ada Files to html with gnathtml
18836 @section Converting Ada Files to HTML with @code{gnathtml}
18837
18838 @noindent
18839 This @code{Perl} script allows Ada source files to be browsed using
18840 standard Web browsers. For installation procedure, see the section
18841 @xref{Installing gnathtml}.
18842
18843 Ada reserved keywords are highlighted in a bold font and Ada comments in
18844 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18845 switch to suppress the generation of cross-referencing information, user
18846 defined variables and types will appear in a different color; you will
18847 be able to click on any identifier and go to its declaration.
18848
18849 The command line is as follow:
18850 @smallexample
18851 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18852 @c Expanding @ovar macro inline (explanation in macro def comments)
18853 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18854 @end smallexample
18855
18856 @noindent
18857 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18858 an html file for every ada file, and a global file called @file{index.htm}.
18859 This file is an index of every identifier defined in the files.
18860
18861 The available ^switches^options^ are the following ones:
18862
18863 @table @option
18864 @item -83
18865 @cindex @option{-83} (@code{gnathtml})
18866 Only the Ada 83 subset of keywords will be highlighted.
18867
18868 @item -cc @var{color}
18869 @cindex @option{-cc} (@code{gnathtml})
18870 This option allows you to change the color used for comments. The default
18871 value is green. The color argument can be any name accepted by html.
18872
18873 @item -d
18874 @cindex @option{-d} (@code{gnathtml})
18875 If the Ada files depend on some other files (for instance through
18876 @code{with} clauses, the latter files will also be converted to html.
18877 Only the files in the user project will be converted to html, not the files
18878 in the run-time library itself.
18879
18880 @item -D
18881 @cindex @option{-D} (@code{gnathtml})
18882 This command is the same as @option{-d} above, but @command{gnathtml} will
18883 also look for files in the run-time library, and generate html files for them.
18884
18885 @item -ext @var{extension}
18886 @cindex @option{-ext} (@code{gnathtml})
18887 This option allows you to change the extension of the generated HTML files.
18888 If you do not specify an extension, it will default to @file{htm}.
18889
18890 @item -f
18891 @cindex @option{-f} (@code{gnathtml})
18892 By default, gnathtml will generate html links only for global entities
18893 ('with'ed units, global variables and types,@dots{}).  If you specify
18894 @option{-f} on the command line, then links will be generated for local
18895 entities too.
18896
18897 @item -l @var{number}
18898 @cindex @option{-l} (@code{gnathtml})
18899 If this ^switch^option^ is provided and @var{number} is not 0, then
18900 @code{gnathtml} will number the html files every @var{number} line.
18901
18902 @item -I @var{dir}
18903 @cindex @option{-I} (@code{gnathtml})
18904 Specify a directory to search for library files (@file{.ALI} files) and
18905 source files. You can provide several -I switches on the command line,
18906 and the directories will be parsed in the order of the command line.
18907
18908 @item -o @var{dir}
18909 @cindex @option{-o} (@code{gnathtml})
18910 Specify the output directory for html files. By default, gnathtml will
18911 saved the generated html files in a subdirectory named @file{html/}.
18912
18913 @item -p @var{file}
18914 @cindex @option{-p} (@code{gnathtml})
18915 If you are using Emacs and the most recent Emacs Ada mode, which provides
18916 a full Integrated Development Environment for compiling, checking,
18917 running and debugging applications, you may use @file{.gpr} files
18918 to give the directories where Emacs can find sources and object files.
18919
18920 Using this ^switch^option^, you can tell gnathtml to use these files.
18921 This allows you to get an html version of your application, even if it
18922 is spread over multiple directories.
18923
18924 @item -sc @var{color}
18925 @cindex @option{-sc} (@code{gnathtml})
18926 This ^switch^option^ allows you to change the color used for symbol
18927 definitions.
18928 The default value is red. The color argument can be any name accepted by html.
18929
18930 @item -t @var{file}
18931 @cindex @option{-t} (@code{gnathtml})
18932 This ^switch^option^ provides the name of a file. This file contains a list of
18933 file names to be converted, and the effect is exactly as though they had
18934 appeared explicitly on the command line. This
18935 is the recommended way to work around the command line length limit on some
18936 systems.
18937
18938 @end table
18939
18940 @node Installing gnathtml
18941 @section Installing @code{gnathtml}
18942
18943 @noindent
18944 @code{Perl} needs to be installed on your machine to run this script.
18945 @code{Perl} is freely available for almost every architecture and
18946 Operating System via the Internet.
18947
18948 On Unix systems, you  may want to modify  the  first line of  the script
18949 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18950 is. The syntax of this line is:
18951 @smallexample
18952 #!full_path_name_to_perl
18953 @end smallexample
18954
18955 @noindent
18956 Alternatively, you may run the script using the following command line:
18957
18958 @smallexample
18959 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18960 @c Expanding @ovar macro inline (explanation in macro def comments)
18961 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18962 @end smallexample
18963
18964 @ifset vms
18965 @node LSE
18966 @section LSE
18967 @findex LSE
18968
18969 @noindent
18970 The GNAT distribution provides an Ada 95 template for the HP Language
18971 Sensitive Editor (LSE), a component of DECset. In order to
18972 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18973
18974 @node Profiling
18975 @section Profiling
18976 @findex PCA
18977
18978 @noindent
18979 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18980 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18981 the collection phase with the /DEBUG qualifier.
18982
18983 @smallexample
18984 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18985 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18986 $ RUN/DEBUG <PROGRAM_NAME>
18987 @end smallexample
18988 @noindent
18989 @end ifset
18990
18991 @ifclear vms
18992 @c ******************************
18993 @node Code Coverage and Profiling
18994 @chapter Code Coverage and Profiling
18995 @cindex Code Coverage
18996 @cindex Profiling
18997
18998 @noindent
18999 This chapter describes how to use @code{gcov} - coverage testing tool - and
19000 @code{gprof} - profiler tool - on your Ada programs.
19001
19002 @menu
19003 * Code Coverage of Ada Programs using gcov::
19004 * Profiling an Ada Program using gprof::
19005 @end menu
19006
19007 @node Code Coverage of Ada Programs using gcov
19008 @section Code Coverage of Ada Programs using gcov
19009 @cindex gcov
19010 @cindex -fprofile-arcs
19011 @cindex -ftest-coverage
19012 @cindex -coverage
19013 @cindex Code Coverage
19014
19015 @noindent
19016 @code{gcov} is a test coverage program: it analyzes the execution of a given
19017 program on selected tests, to help you determine the portions of the program
19018 that are still untested.
19019
19020 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19021 User's Guide. You can refer to this documentation for a more complete
19022 description.
19023
19024 This chapter provides a quick startup guide, and
19025 details some Gnat-specific features.
19026
19027 @menu
19028 * Quick startup guide::
19029 * Gnat specifics::
19030 @end menu
19031
19032 @node Quick startup guide
19033 @subsection Quick startup guide
19034
19035 In order to perform coverage analysis of a program using @code{gcov}, 3
19036 steps are needed:
19037
19038 @itemize @bullet
19039 @item
19040 Code instrumentation during the compilation process
19041 @item
19042 Execution of the instrumented program
19043 @item
19044 Execution of the @code{gcov} tool to generate the result.
19045 @end itemize
19046
19047 The code instrumentation needed by gcov is created at the object level:
19048 The source code is not modified in any way, because the instrumentation code is
19049 inserted by gcc during the compilation process. To compile your code with code
19050 coverage activated, you need to recompile your whole project using the
19051 switches
19052 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19053 @code{-fprofile-arcs}.
19054
19055 @smallexample
19056 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19057    -largs -fprofile-arcs
19058 @end smallexample
19059
19060 This compilation process will create @file{.gcno} files together with
19061 the usual object files.
19062
19063 Once the program is compiled with coverage instrumentation, you can
19064 run it as many times as needed - on portions of a test suite for
19065 example. The first execution will produce @file{.gcda} files at the
19066 same location as the @file{.gcno} files.  The following executions
19067 will update those files, so that a cumulative result of the covered
19068 portions of the program is generated.
19069
19070 Finally, you need to call the @code{gcov} tool. The different options of
19071 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19072
19073 This will create annotated source files with a @file{.gcov} extension:
19074 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19075
19076 @node Gnat specifics
19077 @subsection Gnat specifics
19078
19079 Because Ada semantics, portions of the source code may be shared among
19080 several object files. This is the case for example when generics are
19081 involved, when inlining is active  or when declarations generate  initialisation
19082 calls. In order to take
19083 into account this shared code, you need to call @code{gcov} on all
19084 source files of the tested program at once.
19085
19086 The list of source files might exceed the system's maximum command line
19087 length. In order to bypass this limitation, a new mechanism has been
19088 implemented in @code{gcov}: you can now list all your project's files into a
19089 text file, and provide this file to gcov as a parameter,  preceded by a @@
19090 (e.g. @samp{gcov @@mysrclist.txt}).
19091
19092 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19093 not supported as there can be unresolved symbols during the final link.
19094
19095 @node Profiling an Ada Program using gprof
19096 @section Profiling an Ada Program using gprof
19097 @cindex gprof
19098 @cindex -pg
19099 @cindex Profiling
19100
19101 @noindent
19102 This section is not meant to be an exhaustive documentation of @code{gprof}.
19103 Full documentation for it can be found in the GNU Profiler User's Guide
19104 documentation that is part of this GNAT distribution.
19105
19106 Profiling a program helps determine the parts of a program that are executed
19107 most often, and are therefore the most time-consuming.
19108
19109 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19110 better handle Ada programs and multitasking.
19111 It is currently supported on the following platforms
19112 @itemize @bullet
19113 @item
19114 linux x86/x86_64
19115 @item
19116 solaris sparc/sparc64/x86
19117 @item
19118 windows x86
19119 @end itemize
19120
19121 @noindent
19122 In order to profile a program using @code{gprof}, 3 steps are needed:
19123
19124 @itemize @bullet
19125 @item
19126 Code instrumentation, requiring a full recompilation of the project with the
19127 proper switches.
19128 @item
19129 Execution of the program under the analysis conditions, i.e. with the desired
19130 input.
19131 @item
19132 Analysis of the results using the @code{gprof} tool.
19133 @end itemize
19134
19135 @noindent
19136 The following sections detail the different steps, and indicate how
19137 to interpret the results:
19138 @menu
19139 * Compilation for profiling::
19140 * Program execution::
19141 * Running gprof::
19142 * Interpretation of profiling results::
19143 @end menu
19144
19145 @node Compilation for profiling
19146 @subsection Compilation for profiling
19147 @cindex -pg
19148 @cindex Profiling
19149
19150 In order to profile a program the first step is to tell the compiler
19151 to generate the necessary profiling information. The compiler switch to be used
19152 is @code{-pg}, which must be added to other compilation switches. This
19153 switch needs to be specified both during compilation and link stages, and can
19154 be specified once when using gnatmake:
19155
19156 @smallexample
19157 gnatmake -f -pg -P my_project
19158 @end smallexample
19159
19160 @noindent
19161 Note that only the objects that were compiled with the @samp{-pg} switch will
19162 be profiled; if you need to profile your whole project, use the @samp{-f}
19163 gnatmake switch to force full recompilation.
19164
19165 @node Program execution
19166 @subsection Program execution
19167
19168 @noindent
19169 Once the program has been compiled for profiling, you can run it as usual.
19170
19171 The only constraint imposed by profiling is that the program must terminate
19172 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19173 properly analyzed.
19174
19175 Once the program completes execution, a data file called @file{gmon.out} is
19176 generated in the directory where the program was launched from. If this file
19177 already exists, it will be overwritten.
19178
19179 @node Running gprof
19180 @subsection Running gprof
19181
19182 @noindent
19183 The @code{gprof} tool is called as follow:
19184
19185 @smallexample
19186 gprof my_prog gmon.out
19187 @end smallexample
19188
19189 @noindent
19190 or simpler:
19191
19192 @smallexample
19193 gprof my_prog
19194 @end smallexample
19195
19196 @noindent
19197 The complete form of the gprof command line is the following:
19198
19199 @smallexample
19200 gprof [^switches^options^] [executable [data-file]]
19201 @end smallexample
19202
19203 @noindent
19204 @code{gprof} supports numerous ^switch^options^. The order of these
19205 ^switch^options^ does not matter. The full list of options can be found in
19206 the GNU Profiler User's Guide documentation that comes with this documentation.
19207
19208 The following is the subset of those switches that is most relevant:
19209
19210 @table @option
19211
19212 @item --demangle[=@var{style}]
19213 @itemx --no-demangle
19214 @cindex @option{--demangle} (@code{gprof})
19215 These options control whether symbol names should be demangled when
19216 printing output.  The default is to demangle C++ symbols.  The
19217 @code{--no-demangle} option may be used to turn off demangling. Different
19218 compilers have different mangling styles.  The optional demangling style
19219 argument can be used to choose an appropriate demangling style for your
19220 compiler, in particular Ada symbols generated by GNAT can be demangled using
19221 @code{--demangle=gnat}.
19222
19223 @item -e @var{function_name}
19224 @cindex @option{-e} (@code{gprof})
19225 The @samp{-e @var{function}} option tells @code{gprof} not to print
19226 information about the function @var{function_name} (and its
19227 children@dots{}) in the call graph.  The function will still be listed
19228 as a child of any functions that call it, but its index number will be
19229 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19230 given; only one @var{function_name} may be indicated with each @samp{-e}
19231 option.
19232
19233 @item -E @var{function_name}
19234 @cindex @option{-E} (@code{gprof})
19235 The @code{-E @var{function}} option works like the @code{-e} option, but
19236 execution time spent in the function (and children who were not called from
19237 anywhere else), will not be used to compute the percentages-of-time for
19238 the call graph.  More than one @samp{-E} option may be given; only one
19239 @var{function_name} may be indicated with each @samp{-E} option.
19240
19241 @item -f @var{function_name}
19242 @cindex @option{-f} (@code{gprof})
19243 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19244 call graph to the function @var{function_name} and its children (and
19245 their children@dots{}).  More than one @samp{-f} option may be given;
19246 only one @var{function_name} may be indicated with each @samp{-f}
19247 option.
19248
19249 @item -F @var{function_name}
19250 @cindex @option{-F} (@code{gprof})
19251 The @samp{-F @var{function}} option works like the @code{-f} option, but
19252 only time spent in the function and its children (and their
19253 children@dots{}) will be used to determine total-time and
19254 percentages-of-time for the call graph.  More than one @samp{-F} option
19255 may be given; only one @var{function_name} may be indicated with each
19256 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19257
19258 @end table
19259
19260 @node Interpretation of profiling results
19261 @subsection Interpretation of profiling results
19262
19263 @noindent
19264
19265 The results of the profiling analysis are represented by two arrays: the
19266 'flat profile' and the 'call graph'. Full documentation of those outputs
19267 can be found in the GNU Profiler User's Guide.
19268
19269 The flat profile shows the time spent in each function of the program, and how
19270 many time it has been called. This allows you to locate easily the most
19271 time-consuming functions.
19272
19273 The call graph shows, for each subprogram, the subprograms that call it,
19274 and the subprograms that it calls. It also provides an estimate of the time
19275 spent in each of those callers/called subprograms.
19276 @end ifclear
19277
19278 @c ******************************
19279 @node Running and Debugging Ada Programs
19280 @chapter Running and Debugging Ada Programs
19281 @cindex Debugging
19282
19283 @noindent
19284 This chapter discusses how to debug Ada programs.
19285 @ifset vms
19286 It applies to GNAT on the Alpha OpenVMS platform;
19287 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19288 since HP has implemented Ada support in the OpenVMS debugger on I64.
19289 @end ifset
19290
19291 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19292
19293 @enumerate
19294 @item
19295 The illegality may be a violation of the static semantics of Ada. In
19296 that case GNAT diagnoses the constructs in the program that are illegal.
19297 It is then a straightforward matter for the user to modify those parts of
19298 the program.
19299
19300 @item
19301 The illegality may be a violation of the dynamic semantics of Ada. In
19302 that case the program compiles and executes, but may generate incorrect
19303 results, or may terminate abnormally with some exception.
19304
19305 @item
19306 When presented with a program that contains convoluted errors, GNAT
19307 itself may terminate abnormally without providing full diagnostics on
19308 the incorrect user program.
19309 @end enumerate
19310
19311 @menu
19312 * The GNAT Debugger GDB::
19313 * Running GDB::
19314 * Introduction to GDB Commands::
19315 * Using Ada Expressions::
19316 * Calling User-Defined Subprograms::
19317 * Using the Next Command in a Function::
19318 * Ada Exceptions::
19319 * Ada Tasks::
19320 * Debugging Generic Units::
19321 * Remote Debugging using gdbserver::
19322 * GNAT Abnormal Termination or Failure to Terminate::
19323 * Naming Conventions for GNAT Source Files::
19324 * Getting Internal Debugging Information::
19325 * Stack Traceback::
19326 @end menu
19327
19328 @cindex Debugger
19329 @findex gdb
19330
19331 @node The GNAT Debugger GDB
19332 @section The GNAT Debugger GDB
19333
19334 @noindent
19335 @code{GDB} is a general purpose, platform-independent debugger that
19336 can be used to debug mixed-language programs compiled with @command{gcc},
19337 and in particular is capable of debugging Ada programs compiled with
19338 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19339 complex Ada data structures.
19340
19341 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19342 @ifset vms
19343 located in the GNU:[DOCS] directory,
19344 @end ifset
19345 for full details on the usage of @code{GDB}, including a section on
19346 its usage on programs. This manual should be consulted for full
19347 details. The section that follows is a brief introduction to the
19348 philosophy and use of @code{GDB}.
19349
19350 When GNAT programs are compiled, the compiler optionally writes debugging
19351 information into the generated object file, including information on
19352 line numbers, and on declared types and variables. This information is
19353 separate from the generated code. It makes the object files considerably
19354 larger, but it does not add to the size of the actual executable that
19355 will be loaded into memory, and has no impact on run-time performance. The
19356 generation of debug information is triggered by the use of the
19357 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19358 used to carry out the compilations. It is important to emphasize that
19359 the use of these options does not change the generated code.
19360
19361 The debugging information is written in standard system formats that
19362 are used by many tools, including debuggers and profilers. The format
19363 of the information is typically designed to describe C types and
19364 semantics, but GNAT implements a translation scheme which allows full
19365 details about Ada types and variables to be encoded into these
19366 standard C formats. Details of this encoding scheme may be found in
19367 the file exp_dbug.ads in the GNAT source distribution. However, the
19368 details of this encoding are, in general, of no interest to a user,
19369 since @code{GDB} automatically performs the necessary decoding.
19370
19371 When a program is bound and linked, the debugging information is
19372 collected from the object files, and stored in the executable image of
19373 the program. Again, this process significantly increases the size of
19374 the generated executable file, but it does not increase the size of
19375 the executable program itself. Furthermore, if this program is run in
19376 the normal manner, it runs exactly as if the debug information were
19377 not present, and takes no more actual memory.
19378
19379 However, if the program is run under control of @code{GDB}, the
19380 debugger is activated.  The image of the program is loaded, at which
19381 point it is ready to run.  If a run command is given, then the program
19382 will run exactly as it would have if @code{GDB} were not present. This
19383 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19384 entirely non-intrusive until a breakpoint is encountered.  If no
19385 breakpoint is ever hit, the program will run exactly as it would if no
19386 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19387 the debugging information and can respond to user commands to inspect
19388 variables, and more generally to report on the state of execution.
19389
19390 @c **************
19391 @node Running GDB
19392 @section Running GDB
19393
19394 @noindent
19395 This section describes how to initiate the debugger.
19396 @c The above sentence is really just filler, but it was otherwise
19397 @c clumsy to get the first paragraph nonindented given the conditional
19398 @c nature of the description
19399
19400 @ifclear vms
19401 The debugger can be launched from a @code{GPS} menu or
19402 directly from the command line. The description below covers the latter use.
19403 All the commands shown can be used in the @code{GPS} debug console window,
19404 but there are usually more GUI-based ways to achieve the same effect.
19405 @end ifclear
19406
19407 The command to run @code{GDB} is
19408
19409 @smallexample
19410 $ ^gdb program^GDB PROGRAM^
19411 @end smallexample
19412
19413 @noindent
19414 where @code{^program^PROGRAM^} is the name of the executable file. This
19415 activates the debugger and results in a prompt for debugger commands.
19416 The simplest command is simply @code{run}, which causes the program to run
19417 exactly as if the debugger were not present. The following section
19418 describes some of the additional commands that can be given to @code{GDB}.
19419
19420 @c *******************************
19421 @node Introduction to GDB Commands
19422 @section Introduction to GDB Commands
19423
19424 @noindent
19425 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19426 Debugging with GDB, gdb, Debugging with GDB},
19427 @ifset vms
19428 located in the GNU:[DOCS] directory,
19429 @end ifset
19430 for extensive documentation on the use
19431 of these commands, together with examples of their use. Furthermore,
19432 the command @command{help} invoked from within GDB activates a simple help
19433 facility which summarizes the available commands and their options.
19434 In this section we summarize a few of the most commonly
19435 used commands to give an idea of what @code{GDB} is about. You should create
19436 a simple program with debugging information and experiment with the use of
19437 these @code{GDB} commands on the program as you read through the
19438 following section.
19439
19440 @table @code
19441 @item set args @var{arguments}
19442 The @var{arguments} list above is a list of arguments to be passed to
19443 the program on a subsequent run command, just as though the arguments
19444 had been entered on a normal invocation of the program. The @code{set args}
19445 command is not needed if the program does not require arguments.
19446
19447 @item run
19448 The @code{run} command causes execution of the program to start from
19449 the beginning. If the program is already running, that is to say if
19450 you are currently positioned at a breakpoint, then a prompt will ask
19451 for confirmation that you want to abandon the current execution and
19452 restart.
19453
19454 @item breakpoint @var{location}
19455 The breakpoint command sets a breakpoint, that is to say a point at which
19456 execution will halt and @code{GDB} will await further
19457 commands. @var{location} is
19458 either a line number within a file, given in the format @code{file:linenumber},
19459 or it is the name of a subprogram. If you request that a breakpoint be set on
19460 a subprogram that is overloaded, a prompt will ask you to specify on which of
19461 those subprograms you want to breakpoint. You can also
19462 specify that all of them should be breakpointed. If the program is run
19463 and execution encounters the breakpoint, then the program
19464 stops and @code{GDB} signals that the breakpoint was encountered by
19465 printing the line of code before which the program is halted.
19466
19467 @item catch exception @var{name}
19468 This command causes the program execution to stop whenever exception
19469 @var{name} is raised.  If @var{name} is omitted, then the execution is
19470 suspended when any exception is raised.
19471
19472 @item print @var{expression}
19473 This will print the value of the given expression. Most simple
19474 Ada expression formats are properly handled by @code{GDB}, so the expression
19475 can contain function calls, variables, operators, and attribute references.
19476
19477 @item continue
19478 Continues execution following a breakpoint, until the next breakpoint or the
19479 termination of the program.
19480
19481 @item step
19482 Executes a single line after a breakpoint. If the next statement
19483 is a subprogram call, execution continues into (the first statement of)
19484 the called subprogram.
19485
19486 @item next
19487 Executes a single line. If this line is a subprogram call, executes and
19488 returns from the call.
19489
19490 @item list
19491 Lists a few lines around the current source location. In practice, it
19492 is usually more convenient to have a separate edit window open with the
19493 relevant source file displayed. Successive applications of this command
19494 print subsequent lines. The command can be given an argument which is a
19495 line number, in which case it displays a few lines around the specified one.
19496
19497 @item backtrace
19498 Displays a backtrace of the call chain. This command is typically
19499 used after a breakpoint has occurred, to examine the sequence of calls that
19500 leads to the current breakpoint. The display includes one line for each
19501 activation record (frame) corresponding to an active subprogram.
19502
19503 @item up
19504 At a breakpoint, @code{GDB} can display the values of variables local
19505 to the current frame. The command @code{up} can be used to
19506 examine the contents of other active frames, by moving the focus up
19507 the stack, that is to say from callee to caller, one frame at a time.
19508
19509 @item down
19510 Moves the focus of @code{GDB} down from the frame currently being
19511 examined to the frame of its callee (the reverse of the previous command),
19512
19513 @item frame @var{n}
19514 Inspect the frame with the given number. The value 0 denotes the frame
19515 of the current breakpoint, that is to say the top of the call stack.
19516
19517 @end table
19518
19519 @noindent
19520 The above list is a very short introduction to the commands that
19521 @code{GDB} provides. Important additional capabilities, including conditional
19522 breakpoints, the ability to execute command sequences on a breakpoint,
19523 the ability to debug at the machine instruction level and many other
19524 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19525 Debugging with GDB}.  Note that most commands can be abbreviated
19526 (for example, c for continue, bt for backtrace).
19527
19528 @node Using Ada Expressions
19529 @section Using Ada Expressions
19530 @cindex Ada expressions
19531
19532 @noindent
19533 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19534 extensions. The philosophy behind the design of this subset is
19535
19536 @itemize @bullet
19537 @item
19538 That @code{GDB} should provide basic literals and access to operations for
19539 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19540 leaving more sophisticated computations to subprograms written into the
19541 program (which therefore may be called from @code{GDB}).
19542
19543 @item
19544 That type safety and strict adherence to Ada language restrictions
19545 are not particularly important to the @code{GDB} user.
19546
19547 @item
19548 That brevity is important to the @code{GDB} user.
19549 @end itemize
19550
19551 @noindent
19552 Thus, for brevity, the debugger acts as if there were
19553 implicit @code{with} and @code{use} clauses in effect for all user-written
19554 packages, thus making it unnecessary to fully qualify most names with
19555 their packages, regardless of context. Where this causes ambiguity,
19556 @code{GDB} asks the user's intent.
19557
19558 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19559 GDB, gdb, Debugging with GDB}.
19560
19561 @node Calling User-Defined Subprograms
19562 @section Calling User-Defined Subprograms
19563
19564 @noindent
19565 An important capability of @code{GDB} is the ability to call user-defined
19566 subprograms while debugging. This is achieved simply by entering
19567 a subprogram call statement in the form:
19568
19569 @smallexample
19570 call subprogram-name (parameters)
19571 @end smallexample
19572
19573 @noindent
19574 The keyword @code{call} can be omitted in the normal case where the
19575 @code{subprogram-name} does not coincide with any of the predefined
19576 @code{GDB} commands.
19577
19578 The effect is to invoke the given subprogram, passing it the
19579 list of parameters that is supplied. The parameters can be expressions and
19580 can include variables from the program being debugged. The
19581 subprogram must be defined
19582 at the library level within your program, and @code{GDB} will call the
19583 subprogram within the environment of your program execution (which
19584 means that the subprogram is free to access or even modify variables
19585 within your program).
19586
19587 The most important use of this facility is in allowing the inclusion of
19588 debugging routines that are tailored to particular data structures
19589 in your program. Such debugging routines can be written to provide a suitably
19590 high-level description of an abstract type, rather than a low-level dump
19591 of its physical layout. After all, the standard
19592 @code{GDB print} command only knows the physical layout of your
19593 types, not their abstract meaning. Debugging routines can provide information
19594 at the desired semantic level and are thus enormously useful.
19595
19596 For example, when debugging GNAT itself, it is crucial to have access to
19597 the contents of the tree nodes used to represent the program internally.
19598 But tree nodes are represented simply by an integer value (which in turn
19599 is an index into a table of nodes).
19600 Using the @code{print} command on a tree node would simply print this integer
19601 value, which is not very useful. But the PN routine (defined in file
19602 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19603 a useful high level representation of the tree node, which includes the
19604 syntactic category of the node, its position in the source, the integers
19605 that denote descendant nodes and parent node, as well as varied
19606 semantic information. To study this example in more detail, you might want to
19607 look at the body of the PN procedure in the stated file.
19608
19609 @node Using the Next Command in a Function
19610 @section Using the Next Command in a Function
19611
19612 @noindent
19613 When you use the @code{next} command in a function, the current source
19614 location will advance to the next statement as usual. A special case
19615 arises in the case of a @code{return} statement.
19616
19617 Part of the code for a return statement is the ``epilog'' of the function.
19618 This is the code that returns to the caller. There is only one copy of
19619 this epilog code, and it is typically associated with the last return
19620 statement in the function if there is more than one return. In some
19621 implementations, this epilog is associated with the first statement
19622 of the function.
19623
19624 The result is that if you use the @code{next} command from a return
19625 statement that is not the last return statement of the function you
19626 may see a strange apparent jump to the last return statement or to
19627 the start of the function. You should simply ignore this odd jump.
19628 The value returned is always that from the first return statement
19629 that was stepped through.
19630
19631 @node Ada Exceptions
19632 @section Stopping when Ada Exceptions are Raised
19633 @cindex Exceptions
19634
19635 @noindent
19636 You can set catchpoints that stop the program execution when your program
19637 raises selected exceptions.
19638
19639 @table @code
19640 @item catch exception
19641 Set a catchpoint that stops execution whenever (any task in the) program
19642 raises any exception.
19643
19644 @item catch exception @var{name}
19645 Set a catchpoint that stops execution whenever (any task in the) program
19646 raises the exception @var{name}.
19647
19648 @item catch exception unhandled
19649 Set a catchpoint that stops executing whenever (any task in the) program
19650 raises an exception for which there is no handler.
19651
19652 @item info exceptions
19653 @itemx info exceptions @var{regexp}
19654 The @code{info exceptions} command permits the user to examine all defined
19655 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19656 argument, prints out only those exceptions whose name matches @var{regexp}.
19657 @end table
19658
19659 @node Ada Tasks
19660 @section Ada Tasks
19661 @cindex Tasks
19662
19663 @noindent
19664 @code{GDB} allows the following task-related commands:
19665
19666 @table @code
19667 @item info tasks
19668 This command shows a list of current Ada tasks, as in the following example:
19669
19670 @smallexample
19671 @iftex
19672 @leftskip=0cm
19673 @end iftex
19674 (gdb) info tasks
19675   ID       TID P-ID   Thread Pri State                 Name
19676    1   8088000   0   807e000  15 Child Activation Wait main_task
19677    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19678    3   809a800   1   80a4800  15 Child Activation Wait a
19679 *  4   80ae800   3   80b8000  15 Running               c
19680 @end smallexample
19681
19682 @noindent
19683 In this listing, the asterisk before the first task indicates it to be the
19684 currently running task. The first column lists the task ID that is used
19685 to refer to tasks in the following commands.
19686
19687 @item break @var{linespec} task @var{taskid}
19688 @itemx break @var{linespec} task @var{taskid} if @dots{}
19689 @cindex Breakpoints and tasks
19690 These commands are like the @code{break @dots{} thread @dots{}}.
19691 @var{linespec} specifies source lines.
19692
19693 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19694 to specify that you only want @code{GDB} to stop the program when a
19695 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19696 numeric task identifiers assigned by @code{GDB}, shown in the first
19697 column of the @samp{info tasks} display.
19698
19699 If you do not specify @samp{task @var{taskid}} when you set a
19700 breakpoint, the breakpoint applies to @emph{all} tasks of your
19701 program.
19702
19703 You can use the @code{task} qualifier on conditional breakpoints as
19704 well; in this case, place @samp{task @var{taskid}} before the
19705 breakpoint condition (before the @code{if}).
19706
19707 @item task @var{taskno}
19708 @cindex Task switching
19709
19710 This command allows to switch to the task referred by @var{taskno}. In
19711 particular, This allows to browse the backtrace of the specified
19712 task. It is advised to switch back to the original task before
19713 continuing execution otherwise the scheduling of the program may be
19714 perturbed.
19715 @end table
19716
19717 @noindent
19718 For more detailed information on the tasking support,
19719 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19720
19721 @node Debugging Generic Units
19722 @section Debugging Generic Units
19723 @cindex Debugging Generic Units
19724 @cindex Generics
19725
19726 @noindent
19727 GNAT always uses code expansion for generic instantiation. This means that
19728 each time an instantiation occurs, a complete copy of the original code is
19729 made, with appropriate substitutions of formals by actuals.
19730
19731 It is not possible to refer to the original generic entities in
19732 @code{GDB}, but it is always possible to debug a particular instance of
19733 a generic, by using the appropriate expanded names. For example, if we have
19734
19735 @smallexample @c ada
19736 @group
19737 @cartouche
19738 procedure g is
19739
19740    generic package k is
19741       procedure kp (v1 : in out integer);
19742    end k;
19743
19744    package body k is
19745       procedure kp (v1 : in out integer) is
19746       begin
19747          v1 := v1 + 1;
19748       end kp;
19749    end k;
19750
19751    package k1 is new k;
19752    package k2 is new k;
19753
19754    var : integer := 1;
19755
19756 begin
19757    k1.kp (var);
19758    k2.kp (var);
19759    k1.kp (var);
19760    k2.kp (var);
19761 end;
19762 @end cartouche
19763 @end group
19764 @end smallexample
19765
19766 @noindent
19767 Then to break on a call to procedure kp in the k2 instance, simply
19768 use the command:
19769
19770 @smallexample
19771 (gdb) break g.k2.kp
19772 @end smallexample
19773
19774 @noindent
19775 When the breakpoint occurs, you can step through the code of the
19776 instance in the normal manner and examine the values of local variables, as for
19777 other units.
19778
19779 @node Remote Debugging using gdbserver
19780 @section Remote Debugging using gdbserver
19781 @cindex Remote Debugging using gdbserver
19782
19783 @noindent
19784 On platforms where gdbserver is supported, it is possible to use this tool
19785 to debug your application remotely.  This can be useful in situations
19786 where the program needs to be run on a target host that is different
19787 from the host used for development, particularly when the target has
19788 a limited amount of resources (either CPU and/or memory).
19789
19790 To do so, start your program using gdbserver on the target machine.
19791 gdbserver then automatically suspends the execution of your program
19792 at its entry point, waiting for a debugger to connect to it.  The
19793 following commands starts an application and tells gdbserver to
19794 wait for a connection with the debugger on localhost port 4444.
19795
19796 @smallexample
19797 $ gdbserver localhost:4444 program
19798 Process program created; pid = 5685
19799 Listening on port 4444
19800 @end smallexample
19801
19802 Once gdbserver has started listening, we can tell the debugger to establish
19803 a connection with this gdbserver, and then start the same debugging session
19804 as if the program was being debugged on the same host, directly under
19805 the control of GDB.
19806
19807 @smallexample
19808 $ gdb program
19809 (gdb) target remote targethost:4444
19810 Remote debugging using targethost:4444
19811 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19812 (gdb) b foo.adb:3
19813 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19814 (gdb) continue
19815 Continuing.
19816
19817 Breakpoint 1, foo () at foo.adb:4
19818 4       end foo;
19819 @end smallexample
19820
19821 It is also possible to use gdbserver to attach to an already running
19822 program, in which case the execution of that program is simply suspended
19823 until the connection between the debugger and gdbserver is established.
19824
19825 For more information on how to use gdbserver, @ref{Top, Server, Using
19826 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
19827 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19828
19829 @node GNAT Abnormal Termination or Failure to Terminate
19830 @section GNAT Abnormal Termination or Failure to Terminate
19831 @cindex GNAT Abnormal Termination or Failure to Terminate
19832
19833 @noindent
19834 When presented with programs that contain serious errors in syntax
19835 or semantics,
19836 GNAT may on rare occasions  experience problems in operation, such
19837 as aborting with a
19838 segmentation fault or illegal memory access, raising an internal
19839 exception, terminating abnormally, or failing to terminate at all.
19840 In such cases, you can activate
19841 various features of GNAT that can help you pinpoint the construct in your
19842 program that is the likely source of the problem.
19843
19844 The following strategies are presented in increasing order of
19845 difficulty, corresponding to your experience in using GNAT and your
19846 familiarity with compiler internals.
19847
19848 @enumerate
19849 @item
19850 Run @command{gcc} with the @option{-gnatf}. This first
19851 switch causes all errors on a given line to be reported. In its absence,
19852 only the first error on a line is displayed.
19853
19854 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19855 are encountered, rather than after compilation is terminated. If GNAT
19856 terminates prematurely or goes into an infinite loop, the last error
19857 message displayed may help to pinpoint the culprit.
19858
19859 @item
19860 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19861 mode, @command{gcc} produces ongoing information about the progress of the
19862 compilation and provides the name of each procedure as code is
19863 generated. This switch allows you to find which Ada procedure was being
19864 compiled when it encountered a code generation problem.
19865
19866 @item
19867 @cindex @option{-gnatdc} switch
19868 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19869 switch that does for the front-end what @option{^-v^VERBOSE^} does
19870 for the back end. The system prints the name of each unit,
19871 either a compilation unit or nested unit, as it is being analyzed.
19872 @item
19873 Finally, you can start
19874 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19875 front-end of GNAT, and can be run independently (normally it is just
19876 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19877 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19878 @code{where} command is the first line of attack; the variable
19879 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19880 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19881 which the execution stopped, and @code{input_file name} indicates the name of
19882 the source file.
19883 @end enumerate
19884
19885 @node Naming Conventions for GNAT Source Files
19886 @section Naming Conventions for GNAT Source Files
19887
19888 @noindent
19889 In order to examine the workings of the GNAT system, the following
19890 brief description of its organization may be helpful:
19891
19892 @itemize @bullet
19893 @item
19894 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19895
19896 @item
19897 All files prefixed with @file{^par^PAR^} are components of the parser. The
19898 numbers correspond to chapters of the Ada Reference Manual. For example,
19899 parsing of select statements can be found in @file{par-ch9.adb}.
19900
19901 @item
19902 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19903 numbers correspond to chapters of the Ada standard. For example, all
19904 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19905 addition, some features of the language require sufficient special processing
19906 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19907 dynamic dispatching, etc.
19908
19909 @item
19910 All files prefixed with @file{^exp^EXP^} perform normalization and
19911 expansion of the intermediate representation (abstract syntax tree, or AST).
19912 these files use the same numbering scheme as the parser and semantics files.
19913 For example, the construction of record initialization procedures is done in
19914 @file{exp_ch3.adb}.
19915
19916 @item
19917 The files prefixed with @file{^bind^BIND^} implement the binder, which
19918 verifies the consistency of the compilation, determines an order of
19919 elaboration, and generates the bind file.
19920
19921 @item
19922 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19923 data structures used by the front-end.
19924
19925 @item
19926 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19927 the abstract syntax tree as produced by the parser.
19928
19929 @item
19930 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19931 all entities, computed during semantic analysis.
19932
19933 @item
19934 Library management issues are dealt with in files with prefix
19935 @file{^lib^LIB^}.
19936
19937 @item
19938 @findex Ada
19939 @cindex Annex A
19940 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19941 defined in Annex A.
19942
19943 @item
19944 @findex Interfaces
19945 @cindex Annex B
19946 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19947 defined in Annex B.
19948
19949 @item
19950 @findex System
19951 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19952 both language-defined children and GNAT run-time routines.
19953
19954 @item
19955 @findex GNAT
19956 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19957 general-purpose packages, fully documented in their specs. All
19958 the other @file{.c} files are modifications of common @command{gcc} files.
19959 @end itemize
19960
19961 @node Getting Internal Debugging Information
19962 @section Getting Internal Debugging Information
19963
19964 @noindent
19965 Most compilers have internal debugging switches and modes. GNAT
19966 does also, except GNAT internal debugging switches and modes are not
19967 secret. A summary and full description of all the compiler and binder
19968 debug flags are in the file @file{debug.adb}. You must obtain the
19969 sources of the compiler to see the full detailed effects of these flags.
19970
19971 The switches that print the source of the program (reconstructed from
19972 the internal tree) are of general interest for user programs, as are the
19973 options to print
19974 the full internal tree, and the entity table (the symbol table
19975 information). The reconstructed source provides a readable version of the
19976 program after the front-end has completed analysis and  expansion,
19977 and is useful when studying the performance of specific constructs.
19978 For example, constraint checks are indicated, complex aggregates
19979 are replaced with loops and assignments, and tasking primitives
19980 are replaced with run-time calls.
19981
19982 @node Stack Traceback
19983 @section Stack Traceback
19984 @cindex traceback
19985 @cindex stack traceback
19986 @cindex stack unwinding
19987
19988 @noindent
19989 Traceback is a mechanism to display the sequence of subprogram calls that
19990 leads to a specified execution point in a program. Often (but not always)
19991 the execution point is an instruction at which an exception has been raised.
19992 This mechanism is also known as @i{stack unwinding} because it obtains
19993 its information by scanning the run-time stack and recovering the activation
19994 records of all active subprograms. Stack unwinding is one of the most
19995 important tools for program debugging.
19996
19997 The first entry stored in traceback corresponds to the deepest calling level,
19998 that is to say the subprogram currently executing the instruction
19999 from which we want to obtain the traceback.
20000
20001 Note that there is no runtime performance penalty when stack traceback
20002 is enabled, and no exception is raised during program execution.
20003
20004 @menu
20005 * Non-Symbolic Traceback::
20006 * Symbolic Traceback::
20007 @end menu
20008
20009 @node Non-Symbolic Traceback
20010 @subsection Non-Symbolic Traceback
20011 @cindex traceback, non-symbolic
20012
20013 @noindent
20014 Note: this feature is not supported on all platforms. See
20015 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20016 platforms.
20017
20018 @menu
20019 * Tracebacks From an Unhandled Exception::
20020 * Tracebacks From Exception Occurrences (non-symbolic)::
20021 * Tracebacks From Anywhere in a Program (non-symbolic)::
20022 @end menu
20023
20024 @node Tracebacks From an Unhandled Exception
20025 @subsubsection Tracebacks From an Unhandled Exception
20026
20027 @noindent
20028 A runtime non-symbolic traceback is a list of addresses of call instructions.
20029 To enable this feature you must use the @option{-E}
20030 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20031 of exception information. You can retrieve this information using the
20032 @code{addr2line} tool.
20033
20034 Here is a simple example:
20035
20036 @smallexample @c ada
20037 @cartouche
20038 procedure STB is
20039
20040    procedure P1 is
20041    begin
20042       raise Constraint_Error;
20043    end P1;
20044
20045    procedure P2 is
20046    begin
20047       P1;
20048    end P2;
20049
20050 begin
20051    P2;
20052 end STB;
20053 @end cartouche
20054 @end smallexample
20055
20056 @smallexample
20057 $ gnatmake stb -bargs -E
20058 $ stb
20059
20060 Execution terminated by unhandled exception
20061 Exception name: CONSTRAINT_ERROR
20062 Message: stb.adb:5
20063 Call stack traceback locations:
20064 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20065 @end smallexample
20066
20067 @noindent
20068 As we see the traceback lists a sequence of addresses for the unhandled
20069 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20070 guess that this exception come from procedure P1. To translate these
20071 addresses into the source lines where the calls appear, the
20072 @code{addr2line} tool, described below, is invaluable. The use of this tool
20073 requires the program to be compiled with debug information.
20074
20075 @smallexample
20076 $ gnatmake -g stb -bargs -E
20077 $ stb
20078
20079 Execution terminated by unhandled exception
20080 Exception name: CONSTRAINT_ERROR
20081 Message: stb.adb:5
20082 Call stack traceback locations:
20083 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20084
20085 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20086    0x4011f1 0x77e892a4
20087
20088 00401373 at d:/stb/stb.adb:5
20089 0040138B at d:/stb/stb.adb:10
20090 0040139C at d:/stb/stb.adb:14
20091 00401335 at d:/stb/b~stb.adb:104
20092 004011C4 at /build/@dots{}/crt1.c:200
20093 004011F1 at /build/@dots{}/crt1.c:222
20094 77E892A4 in ?? at ??:0
20095 @end smallexample
20096
20097 @noindent
20098 The @code{addr2line} tool has several other useful options:
20099
20100 @table @code
20101 @item --functions
20102 to get the function name corresponding to any location
20103
20104 @item --demangle=gnat
20105 to use the gnat decoding mode for the function names. Note that
20106 for binutils version 2.9.x the option is simply @option{--demangle}.
20107 @end table
20108
20109 @smallexample
20110 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20111    0x40139c 0x401335 0x4011c4 0x4011f1
20112
20113 00401373 in stb.p1 at d:/stb/stb.adb:5
20114 0040138B in stb.p2 at d:/stb/stb.adb:10
20115 0040139C in stb at d:/stb/stb.adb:14
20116 00401335 in main at d:/stb/b~stb.adb:104
20117 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20118 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20119 @end smallexample
20120
20121 @noindent
20122 From this traceback we can see that the exception was raised in
20123 @file{stb.adb} at line 5, which was reached from a procedure call in
20124 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20125 which contains the call to the main program.
20126 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20127 and the output will vary from platform to platform.
20128
20129 It is also possible to use @code{GDB} with these traceback addresses to debug
20130 the program. For example, we can break at a given code location, as reported
20131 in the stack traceback:
20132
20133 @smallexample
20134 $ gdb -nw stb
20135 @ifclear vms
20136 @noindent
20137 Furthermore, this feature is not implemented inside Windows DLL. Only
20138 the non-symbolic traceback is reported in this case.
20139 @end ifclear
20140
20141 (gdb) break *0x401373
20142 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20143 @end smallexample
20144
20145 @noindent
20146 It is important to note that the stack traceback addresses
20147 do not change when debug information is included. This is particularly useful
20148 because it makes it possible to release software without debug information (to
20149 minimize object size), get a field report that includes a stack traceback
20150 whenever an internal bug occurs, and then be able to retrieve the sequence
20151 of calls with the same program compiled with debug information.
20152
20153 @node Tracebacks From Exception Occurrences (non-symbolic)
20154 @subsubsection Tracebacks From Exception Occurrences
20155
20156 @noindent
20157 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20158 The stack traceback is attached to the exception information string, and can
20159 be retrieved in an exception handler within the Ada program, by means of the
20160 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20161
20162 @smallexample @c ada
20163 with Ada.Text_IO;
20164 with Ada.Exceptions;
20165
20166 procedure STB is
20167
20168    use Ada;
20169    use Ada.Exceptions;
20170
20171    procedure P1 is
20172       K : Positive := 1;
20173    begin
20174       K := K - 1;
20175    exception
20176       when E : others =>
20177          Text_IO.Put_Line (Exception_Information (E));
20178    end P1;
20179
20180    procedure P2 is
20181    begin
20182       P1;
20183    end P2;
20184
20185 begin
20186    P2;
20187 end STB;
20188 @end smallexample
20189
20190 @noindent
20191 This program will output:
20192
20193 @smallexample
20194 $ stb
20195
20196 Exception name: CONSTRAINT_ERROR
20197 Message: stb.adb:12
20198 Call stack traceback locations:
20199 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20200 @end smallexample
20201
20202 @node Tracebacks From Anywhere in a Program (non-symbolic)
20203 @subsubsection Tracebacks From Anywhere in a Program
20204
20205 @noindent
20206 It is also possible to retrieve a stack traceback from anywhere in a
20207 program. For this you need to
20208 use the @code{GNAT.Traceback} API. This package includes a procedure called
20209 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20210 display procedures described below. It is not necessary to use the
20211 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20212 is invoked explicitly.
20213
20214 @noindent
20215 In the following example we compute a traceback at a specific location in
20216 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20217 convert addresses to strings:
20218
20219 @smallexample @c ada
20220 with Ada.Text_IO;
20221 with GNAT.Traceback;
20222 with GNAT.Debug_Utilities;
20223
20224 procedure STB is
20225
20226    use Ada;
20227    use GNAT;
20228    use GNAT.Traceback;
20229
20230    procedure P1 is
20231       TB  : Tracebacks_Array (1 .. 10);
20232       --  We are asking for a maximum of 10 stack frames.
20233       Len : Natural;
20234       --  Len will receive the actual number of stack frames returned.
20235    begin
20236       Call_Chain (TB, Len);
20237
20238       Text_IO.Put ("In STB.P1 : ");
20239
20240       for K in 1 .. Len loop
20241          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20242          Text_IO.Put (' ');
20243       end loop;
20244
20245       Text_IO.New_Line;
20246    end P1;
20247
20248    procedure P2 is
20249    begin
20250       P1;
20251    end P2;
20252
20253 begin
20254    P2;
20255 end STB;
20256 @end smallexample
20257
20258 @smallexample
20259 $ gnatmake -g stb
20260 $ stb
20261
20262 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20263 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20264 @end smallexample
20265
20266 @noindent
20267 You can then get further information by invoking the @code{addr2line}
20268 tool as described earlier (note that the hexadecimal addresses
20269 need to be specified in C format, with a leading ``0x'').
20270
20271 @node Symbolic Traceback
20272 @subsection Symbolic Traceback
20273 @cindex traceback, symbolic
20274
20275 @noindent
20276 A symbolic traceback is a stack traceback in which procedure names are
20277 associated with each code location.
20278
20279 @noindent
20280 Note that this feature is not supported on all platforms. See
20281 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20282 list of currently supported platforms.
20283
20284 @noindent
20285 Note that the symbolic traceback requires that the program be compiled
20286 with debug information. If it is not compiled with debug information
20287 only the non-symbolic information will be valid.
20288
20289 @menu
20290 * Tracebacks From Exception Occurrences (symbolic)::
20291 * Tracebacks From Anywhere in a Program (symbolic)::
20292 @end menu
20293
20294 @node Tracebacks From Exception Occurrences (symbolic)
20295 @subsubsection Tracebacks From Exception Occurrences
20296
20297 @smallexample @c ada
20298 with Ada.Text_IO;
20299 with GNAT.Traceback.Symbolic;
20300
20301 procedure STB is
20302
20303    procedure P1 is
20304    begin
20305       raise Constraint_Error;
20306    end P1;
20307
20308    procedure P2 is
20309    begin
20310       P1;
20311    end P2;
20312
20313    procedure P3 is
20314    begin
20315       P2;
20316    end P3;
20317
20318 begin
20319    P3;
20320 exception
20321    when E : others =>
20322       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20323 end STB;
20324 @end smallexample
20325
20326 @smallexample
20327 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20328 $ stb
20329
20330 0040149F in stb.p1 at stb.adb:8
20331 004014B7 in stb.p2 at stb.adb:13
20332 004014CF in stb.p3 at stb.adb:18
20333 004015DD in ada.stb at stb.adb:22
20334 00401461 in main at b~stb.adb:168
20335 004011C4 in __mingw_CRTStartup at crt1.c:200
20336 004011F1 in mainCRTStartup at crt1.c:222
20337 77E892A4 in ?? at ??:0
20338 @end smallexample
20339
20340 @noindent
20341 In the above example the ``.\'' syntax in the @command{gnatmake} command
20342 is currently required by @command{addr2line} for files that are in
20343 the current working directory.
20344 Moreover, the exact sequence of linker options may vary from platform
20345 to platform.
20346 The above @option{-largs} section is for Windows platforms. By contrast,
20347 under Unix there is no need for the @option{-largs} section.
20348 Differences across platforms are due to details of linker implementation.
20349
20350 @node Tracebacks From Anywhere in a Program (symbolic)
20351 @subsubsection Tracebacks From Anywhere in a Program
20352
20353 @noindent
20354 It is possible to get a symbolic stack traceback
20355 from anywhere in a program, just as for non-symbolic tracebacks.
20356 The first step is to obtain a non-symbolic
20357 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20358 information. Here is an example:
20359
20360 @smallexample @c ada
20361 with Ada.Text_IO;
20362 with GNAT.Traceback;
20363 with GNAT.Traceback.Symbolic;
20364
20365 procedure STB is
20366
20367    use Ada;
20368    use GNAT.Traceback;
20369    use GNAT.Traceback.Symbolic;
20370
20371    procedure P1 is
20372       TB  : Tracebacks_Array (1 .. 10);
20373       --  We are asking for a maximum of 10 stack frames.
20374       Len : Natural;
20375       --  Len will receive the actual number of stack frames returned.
20376    begin
20377       Call_Chain (TB, Len);
20378       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20379    end P1;
20380
20381    procedure P2 is
20382    begin
20383       P1;
20384    end P2;
20385
20386 begin
20387    P2;
20388 end STB;
20389 @end smallexample
20390
20391 @c ******************************
20392 @ifset vms
20393 @node Compatibility with HP Ada
20394 @chapter Compatibility with HP Ada
20395 @cindex Compatibility
20396
20397 @noindent
20398 @cindex DEC Ada
20399 @cindex HP Ada
20400 @cindex Compatibility between GNAT and HP Ada
20401 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20402 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20403 GNAT is highly compatible
20404 with HP Ada, and it should generally be straightforward to port code
20405 from the HP Ada environment to GNAT. However, there are a few language
20406 and implementation differences of which the user must be aware. These
20407 differences are discussed in this chapter. In
20408 addition, the operating environment and command structure for the
20409 compiler are different, and these differences are also discussed.
20410
20411 For further details on these and other compatibility issues,
20412 see Appendix E of the HP publication
20413 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20414
20415 Except where otherwise indicated, the description of GNAT for OpenVMS
20416 applies to both the Alpha and I64 platforms.
20417
20418 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20419 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20420
20421 The discussion in this chapter addresses specifically the implementation
20422 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20423 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20424 GNAT always follows the Alpha implementation.
20425
20426 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20427 attributes are recognized, although only a subset of them can sensibly
20428 be implemented.  The description of pragmas in
20429 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20430 indicates whether or not they are applicable to non-VMS systems.
20431
20432 @menu
20433 * Ada Language Compatibility::
20434 * Differences in the Definition of Package System::
20435 * Language-Related Features::
20436 * The Package STANDARD::
20437 * The Package SYSTEM::
20438 * Tasking and Task-Related Features::
20439 * Pragmas and Pragma-Related Features::
20440 * Library of Predefined Units::
20441 * Bindings::
20442 * Main Program Definition::
20443 * Implementation-Defined Attributes::
20444 * Compiler and Run-Time Interfacing::
20445 * Program Compilation and Library Management::
20446 * Input-Output::
20447 * Implementation Limits::
20448 * Tools and Utilities::
20449 @end menu
20450
20451 @node Ada Language Compatibility
20452 @section Ada Language Compatibility
20453
20454 @noindent
20455 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20456 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20457 with Ada 83, and therefore Ada 83 programs will compile
20458 and run under GNAT with
20459 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20460 provides details on specific incompatibilities.
20461
20462 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20463 as well as the pragma @code{ADA_83}, to force the compiler to
20464 operate in Ada 83 mode. This mode does not guarantee complete
20465 conformance to Ada 83, but in practice is sufficient to
20466 eliminate most sources of incompatibilities.
20467 In particular, it eliminates the recognition of the
20468 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20469 in Ada 83 programs is legal, and handles the cases of packages
20470 with optional bodies, and generics that instantiate unconstrained
20471 types without the use of @code{(<>)}.
20472
20473 @node Differences in the Definition of Package System
20474 @section Differences in the Definition of Package @code{System}
20475
20476 @noindent
20477 An Ada compiler is allowed to add
20478 implementation-dependent declarations to package @code{System}.
20479 In normal mode,
20480 GNAT does not take advantage of this permission, and the version of
20481 @code{System} provided by GNAT exactly matches that defined in the Ada
20482 Reference Manual.
20483
20484 However, HP Ada adds an extensive set of declarations to package
20485 @code{System},
20486 as fully documented in the HP Ada manuals. To minimize changes required
20487 for programs that make use of these extensions, GNAT provides the pragma
20488 @code{Extend_System} for extending the definition of package System. By using:
20489 @cindex pragma @code{Extend_System}
20490 @cindex @code{Extend_System} pragma
20491
20492 @smallexample @c ada
20493 @group
20494 @cartouche
20495 pragma Extend_System (Aux_DEC);
20496 @end cartouche
20497 @end group
20498 @end smallexample
20499
20500 @noindent
20501 the set of definitions in @code{System} is extended to include those in
20502 package @code{System.Aux_DEC}.
20503 @cindex @code{System.Aux_DEC} package
20504 @cindex @code{Aux_DEC} package (child of @code{System})
20505 These definitions are incorporated directly into package @code{System},
20506 as though they had been declared there. For a
20507 list of the declarations added, see the spec of this package,
20508 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20509 @cindex @file{s-auxdec.ads} file
20510 The pragma @code{Extend_System} is a configuration pragma, which means that
20511 it can be placed in the file @file{gnat.adc}, so that it will automatically
20512 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20513 for further details.
20514
20515 An alternative approach that avoids the use of the non-standard
20516 @code{Extend_System} pragma is to add a context clause to the unit that
20517 references these facilities:
20518
20519 @smallexample @c ada
20520 @cartouche
20521 with System.Aux_DEC;
20522 use  System.Aux_DEC;
20523 @end cartouche
20524 @end smallexample
20525
20526 @noindent
20527 The effect is not quite semantically identical to incorporating
20528 the declarations directly into package @code{System},
20529 but most programs will not notice a difference
20530 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20531 to reference the entities directly in package @code{System}.
20532 For units containing such references,
20533 the prefixes must either be removed, or the pragma @code{Extend_System}
20534 must be used.
20535
20536 @node Language-Related Features
20537 @section Language-Related Features
20538
20539 @noindent
20540 The following sections highlight differences in types,
20541 representations of types, operations, alignment, and
20542 related topics.
20543
20544 @menu
20545 * Integer Types and Representations::
20546 * Floating-Point Types and Representations::
20547 * Pragmas Float_Representation and Long_Float::
20548 * Fixed-Point Types and Representations::
20549 * Record and Array Component Alignment::
20550 * Address Clauses::
20551 * Other Representation Clauses::
20552 @end menu
20553
20554 @node Integer Types and Representations
20555 @subsection Integer Types and Representations
20556
20557 @noindent
20558 The set of predefined integer types is identical in HP Ada and GNAT.
20559 Furthermore the representation of these integer types is also identical,
20560 including the capability of size clauses forcing biased representation.
20561
20562 In addition,
20563 HP Ada for OpenVMS Alpha systems has defined the
20564 following additional integer types in package @code{System}:
20565
20566 @itemize @bullet
20567
20568 @item
20569 @code{INTEGER_8}
20570
20571 @item
20572 @code{INTEGER_16}
20573
20574 @item
20575 @code{INTEGER_32}
20576
20577 @item
20578 @code{INTEGER_64}
20579
20580 @item
20581 @code{LARGEST_INTEGER}
20582 @end itemize
20583
20584 @noindent
20585 In GNAT, the first four of these types may be obtained from the
20586 standard Ada package @code{Interfaces}.
20587 Alternatively, by use of the pragma @code{Extend_System}, identical
20588 declarations can be referenced directly in package @code{System}.
20589 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20590
20591 @node Floating-Point Types and Representations
20592 @subsection Floating-Point Types and Representations
20593 @cindex Floating-Point types
20594
20595 @noindent
20596 The set of predefined floating-point types is identical in HP Ada and GNAT.
20597 Furthermore the representation of these floating-point
20598 types is also identical. One important difference is that the default
20599 representation for HP Ada is @code{VAX_Float}, but the default representation
20600 for GNAT is IEEE.
20601
20602 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20603 pragma @code{Float_Representation} as described in the HP Ada
20604 documentation.
20605 For example, the declarations:
20606
20607 @smallexample @c ada
20608 @cartouche
20609 type F_Float is digits 6;
20610 pragma Float_Representation (VAX_Float, F_Float);
20611 @end cartouche
20612 @end smallexample
20613
20614 @noindent
20615 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20616 format.
20617 This set of declarations actually appears in @code{System.Aux_DEC},
20618 which contains
20619 the full set of additional floating-point declarations provided in
20620 the HP Ada version of package @code{System}.
20621 This and similar declarations may be accessed in a user program
20622 by using pragma @code{Extend_System}. The use of this
20623 pragma, and the related pragma @code{Long_Float} is described in further
20624 detail in the following section.
20625
20626 @node Pragmas Float_Representation and Long_Float
20627 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20628
20629 @noindent
20630 HP Ada provides the pragma @code{Float_Representation}, which
20631 acts as a program library switch to allow control over
20632 the internal representation chosen for the predefined
20633 floating-point types declared in the package @code{Standard}.
20634 The format of this pragma is as follows:
20635
20636 @smallexample @c ada
20637 @cartouche
20638 pragma Float_Representation(VAX_Float | IEEE_Float);
20639 @end cartouche
20640 @end smallexample
20641
20642 @noindent
20643 This pragma controls the representation of floating-point
20644 types as follows:
20645
20646 @itemize @bullet
20647 @item
20648 @code{VAX_Float} specifies that floating-point
20649 types are represented by default with the VAX system hardware types
20650 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20651 Note that the @code{H-floating}
20652 type was available only on VAX systems, and is not available
20653 in either HP Ada or GNAT.
20654
20655 @item
20656 @code{IEEE_Float} specifies that floating-point
20657 types are represented by default with the IEEE single and
20658 double floating-point types.
20659 @end itemize
20660
20661 @noindent
20662 GNAT provides an identical implementation of the pragma
20663 @code{Float_Representation}, except that it functions as a
20664 configuration pragma. Note that the
20665 notion of configuration pragma corresponds closely to the
20666 HP Ada notion of a program library switch.
20667
20668 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20669 which is different
20670 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20671 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20672 advisable to change the format of numbers passed to standard library
20673 routines, and if necessary explicit type conversions may be needed.
20674
20675 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20676 efficient, and (given that it conforms to an international standard)
20677 potentially more portable.
20678 The situation in which @code{VAX_Float} may be useful is in interfacing
20679 to existing code and data that expect the use of @code{VAX_Float}.
20680 In such a situation use the predefined @code{VAX_Float}
20681 types in package @code{System}, as extended by
20682 @code{Extend_System}. For example, use @code{System.F_Float}
20683 to specify the 32-bit @code{F-Float} format.
20684
20685 @noindent
20686 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20687 to allow control over the internal representation chosen
20688 for the predefined type @code{Long_Float} and for floating-point
20689 type declarations with digits specified in the range 7 .. 15.
20690 The format of this pragma is as follows:
20691
20692 @smallexample @c ada
20693 @cartouche
20694 pragma Long_Float (D_FLOAT | G_FLOAT);
20695 @end cartouche
20696 @end smallexample
20697
20698 @node Fixed-Point Types and Representations
20699 @subsection Fixed-Point Types and Representations
20700
20701 @noindent
20702 On HP Ada for OpenVMS Alpha systems, rounding is
20703 away from zero for both positive and negative numbers.
20704 Therefore, @code{+0.5} rounds to @code{1},
20705 and @code{-0.5} rounds to @code{-1}.
20706
20707 On GNAT the results of operations
20708 on fixed-point types are in accordance with the Ada
20709 rules. In particular, results of operations on decimal
20710 fixed-point types are truncated.
20711
20712 @node Record and Array Component Alignment
20713 @subsection Record and Array Component Alignment
20714
20715 @noindent
20716 On HP Ada for OpenVMS Alpha, all non-composite components
20717 are aligned on natural boundaries. For example, 1-byte
20718 components are aligned on byte boundaries, 2-byte
20719 components on 2-byte boundaries, 4-byte components on 4-byte
20720 byte boundaries, and so on. The OpenVMS Alpha hardware
20721 runs more efficiently with naturally aligned data.
20722
20723 On GNAT, alignment rules are compatible
20724 with HP Ada for OpenVMS Alpha.
20725
20726 @node Address Clauses
20727 @subsection Address Clauses
20728
20729 @noindent
20730 In HP Ada and GNAT, address clauses are supported for
20731 objects and imported subprograms.
20732 The predefined type @code{System.Address} is a private type
20733 in both compilers on Alpha OpenVMS, with the same representation
20734 (it is simply a machine pointer). Addition, subtraction, and comparison
20735 operations are available in the standard Ada package
20736 @code{System.Storage_Elements}, or in package @code{System}
20737 if it is extended to include @code{System.Aux_DEC} using a
20738 pragma @code{Extend_System} as previously described.
20739
20740 Note that code that @code{with}'s both this extended package @code{System}
20741 and the package @code{System.Storage_Elements} should not @code{use}
20742 both packages, or ambiguities will result. In general it is better
20743 not to mix these two sets of facilities. The Ada package was
20744 designed specifically to provide the kind of features that HP Ada
20745 adds directly to package @code{System}.
20746
20747 The type @code{System.Address} is a 64-bit integer type in GNAT for
20748 I64 OpenVMS.  For more information,
20749 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20750
20751 GNAT is compatible with HP Ada in its handling of address
20752 clauses, except for some limitations in
20753 the form of address clauses for composite objects with
20754 initialization. Such address clauses are easily replaced
20755 by the use of an explicitly-defined constant as described
20756 in the Ada Reference Manual (13.1(22)). For example, the sequence
20757 of declarations:
20758
20759 @smallexample @c ada
20760 @cartouche
20761 X, Y : Integer := Init_Func;
20762 Q : String (X .. Y) := "abc";
20763 @dots{}
20764 for Q'Address use Compute_Address;
20765 @end cartouche
20766 @end smallexample
20767
20768 @noindent
20769 will be rejected by GNAT, since the address cannot be computed at the time
20770 that @code{Q} is declared. To achieve the intended effect, write instead:
20771
20772 @smallexample @c ada
20773 @group
20774 @cartouche
20775 X, Y : Integer := Init_Func;
20776 Q_Address : constant Address := Compute_Address;
20777 Q : String (X .. Y) := "abc";
20778 @dots{}
20779 for Q'Address use Q_Address;
20780 @end cartouche
20781 @end group
20782 @end smallexample
20783
20784 @noindent
20785 which will be accepted by GNAT (and other Ada compilers), and is also
20786 compatible with Ada 83. A fuller description of the restrictions
20787 on address specifications is found in @ref{Top, GNAT Reference Manual,
20788 About This Guide, gnat_rm, GNAT Reference Manual}.
20789
20790 @node Other Representation Clauses
20791 @subsection Other Representation Clauses
20792
20793 @noindent
20794 GNAT implements in a compatible manner all the representation
20795 clauses supported by HP Ada. In addition, GNAT
20796 implements the representation clause forms that were introduced in Ada 95,
20797 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20798
20799 @node The Package STANDARD
20800 @section The Package @code{STANDARD}
20801
20802 @noindent
20803 The package @code{STANDARD}, as implemented by HP Ada, is fully
20804 described in the @cite{Ada Reference Manual} and in the
20805 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20806 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20807
20808 In addition, HP Ada supports the Latin-1 character set in
20809 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20810 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20811 the type @code{WIDE_CHARACTER}.
20812
20813 The floating-point types supported by GNAT are those
20814 supported by HP Ada, but the defaults are different, and are controlled by
20815 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20816
20817 @node The Package SYSTEM
20818 @section The Package @code{SYSTEM}
20819
20820 @noindent
20821 HP Ada provides a specific version of the package
20822 @code{SYSTEM} for each platform on which the language is implemented.
20823 For the complete spec of the package @code{SYSTEM}, see
20824 Appendix F of the @cite{HP Ada Language Reference Manual}.
20825
20826 On HP Ada, the package @code{SYSTEM} includes the following conversion
20827 functions:
20828 @itemize @bullet
20829 @item @code{TO_ADDRESS(INTEGER)}
20830
20831 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20832
20833 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20834
20835 @item @code{TO_INTEGER(ADDRESS)}
20836
20837 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20838
20839 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20840 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20841 @end itemize
20842
20843 @noindent
20844 By default, GNAT supplies a version of @code{SYSTEM} that matches
20845 the definition given in the @cite{Ada Reference Manual}.
20846 This
20847 is a subset of the HP system definitions, which is as
20848 close as possible to the original definitions. The only difference
20849 is that the definition of @code{SYSTEM_NAME} is different:
20850
20851 @smallexample @c ada
20852 @cartouche
20853 type Name is (SYSTEM_NAME_GNAT);
20854 System_Name : constant Name := SYSTEM_NAME_GNAT;
20855 @end cartouche
20856 @end smallexample
20857
20858 @noindent
20859 Also, GNAT adds the Ada declarations for
20860 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20861
20862 However, the use of the following pragma causes GNAT
20863 to extend the definition of package @code{SYSTEM} so that it
20864 encompasses the full set of HP-specific extensions,
20865 including the functions listed above:
20866
20867 @smallexample @c ada
20868 @cartouche
20869 pragma Extend_System (Aux_DEC);
20870 @end cartouche
20871 @end smallexample
20872
20873 @noindent
20874 The pragma @code{Extend_System} is a configuration pragma that
20875 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20876 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20877
20878 HP Ada does not allow the recompilation of the package
20879 @code{SYSTEM}. Instead HP Ada provides several pragmas
20880 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20881 to modify values in the package @code{SYSTEM}.
20882 On OpenVMS Alpha systems, the pragma
20883 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20884 its single argument.
20885
20886 GNAT does permit the recompilation of package @code{SYSTEM} using
20887 the special switch @option{-gnatg}, and this switch can be used if
20888 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20889 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20890 or @code{MEMORY_SIZE} by any other means.
20891
20892 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20893 enumeration literal @code{SYSTEM_NAME_GNAT}.
20894
20895 The definitions provided by the use of
20896
20897 @smallexample @c ada
20898 pragma Extend_System (AUX_Dec);
20899 @end smallexample
20900
20901 @noindent
20902 are virtually identical to those provided by the HP Ada 83 package
20903 @code{SYSTEM}. One important difference is that the name of the
20904 @code{TO_ADDRESS}
20905 function for type @code{UNSIGNED_LONGWORD} is changed to
20906 @code{TO_ADDRESS_LONG}.
20907 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20908 discussion of why this change was necessary.
20909
20910 @noindent
20911 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20912 is in fact
20913 an extension to Ada 83 not strictly compatible with the reference manual.
20914 GNAT, in order to be exactly compatible with the standard,
20915 does not provide this capability. In HP Ada 83, the
20916 point of this definition is to deal with a call like:
20917
20918 @smallexample @c ada
20919 TO_ADDRESS (16#12777#);
20920 @end smallexample
20921
20922 @noindent
20923 Normally, according to Ada 83 semantics, one would expect this to be
20924 ambiguous, since it matches both the @code{INTEGER} and
20925 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20926 However, in HP Ada 83, there is no ambiguity, since the
20927 definition using @i{universal_integer} takes precedence.
20928
20929 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20930 it is
20931 not possible to be 100% compatible. Since there are many programs using
20932 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20933 GNAT was
20934 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20935 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20936
20937 @smallexample @c ada
20938 function To_Address (X : Integer) return Address;
20939 pragma Pure_Function (To_Address);
20940
20941 function To_Address_Long (X : Unsigned_Longword) return Address;
20942 pragma Pure_Function (To_Address_Long);
20943 @end smallexample
20944
20945 @noindent
20946 This means that programs using @code{TO_ADDRESS} for
20947 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20948
20949 @node Tasking and Task-Related Features
20950 @section Tasking and Task-Related Features
20951
20952 @noindent
20953 This section compares the treatment of tasking in GNAT
20954 and in HP Ada for OpenVMS Alpha.
20955 The GNAT description applies to both Alpha and I64 OpenVMS.
20956 For detailed information on tasking in
20957 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20958 relevant run-time reference manual.
20959
20960 @menu
20961 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20962 * Assigning Task IDs::
20963 * Task IDs and Delays::
20964 * Task-Related Pragmas::
20965 * Scheduling and Task Priority::
20966 * The Task Stack::
20967 * External Interrupts::
20968 @end menu
20969
20970 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20971 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20972
20973 @noindent
20974 On OpenVMS Alpha systems, each Ada task (except a passive
20975 task) is implemented as a single stream of execution
20976 that is created and managed by the kernel. On these
20977 systems, HP Ada tasking support is based on DECthreads,
20978 an implementation of the POSIX standard for threads.
20979
20980 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20981 code that calls DECthreads routines can be used together.
20982 The interaction between Ada tasks and DECthreads routines
20983 can have some benefits. For example when on OpenVMS Alpha,
20984 HP Ada can call C code that is already threaded.
20985
20986 GNAT uses the facilities of DECthreads,
20987 and Ada tasks are mapped to threads.
20988
20989 @node Assigning Task IDs
20990 @subsection Assigning Task IDs
20991
20992 @noindent
20993 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20994 the environment task that executes the main program. On
20995 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20996 that have been created but are not yet activated.
20997
20998 On OpenVMS Alpha systems, task IDs are assigned at
20999 activation. On GNAT systems, task IDs are also assigned at
21000 task creation but do not have the same form or values as
21001 task ID values in HP Ada. There is no null task, and the
21002 environment task does not have a specific task ID value.
21003
21004 @node Task IDs and Delays
21005 @subsection Task IDs and Delays
21006
21007 @noindent
21008 On OpenVMS Alpha systems, tasking delays are implemented
21009 using Timer System Services. The Task ID is used for the
21010 identification of the timer request (the @code{REQIDT} parameter).
21011 If Timers are used in the application take care not to use
21012 @code{0} for the identification, because cancelling such a timer
21013 will cancel all timers and may lead to unpredictable results.
21014
21015 @node Task-Related Pragmas
21016 @subsection Task-Related Pragmas
21017
21018 @noindent
21019 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21020 specification of the size of the guard area for a task
21021 stack. (The guard area forms an area of memory that has no
21022 read or write access and thus helps in the detection of
21023 stack overflow.) On OpenVMS Alpha systems, if the pragma
21024 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21025 area is created. In the absence of a pragma @code{TASK_STORAGE},
21026 a default guard area is created.
21027
21028 GNAT supplies the following task-related pragmas:
21029
21030 @itemize @bullet
21031 @item  @code{TASK_INFO}
21032
21033 This pragma appears within a task definition and
21034 applies to the task in which it appears. The argument
21035 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21036
21037 @item  @code{TASK_STORAGE}
21038
21039 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21040 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21041 @code{SUPPRESS}, and @code{VOLATILE}.
21042 @end itemize
21043 @node Scheduling and Task Priority
21044 @subsection Scheduling and Task Priority
21045
21046 @noindent
21047 HP Ada implements the Ada language requirement that
21048 when two tasks are eligible for execution and they have
21049 different priorities, the lower priority task does not
21050 execute while the higher priority task is waiting. The HP
21051 Ada Run-Time Library keeps a task running until either the
21052 task is suspended or a higher priority task becomes ready.
21053
21054 On OpenVMS Alpha systems, the default strategy is round-
21055 robin with preemption. Tasks of equal priority take turns
21056 at the processor. A task is run for a certain period of
21057 time and then placed at the tail of the ready queue for
21058 its priority level.
21059
21060 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21061 which can be used to enable or disable round-robin
21062 scheduling of tasks with the same priority.
21063 See the relevant HP Ada run-time reference manual for
21064 information on using the pragmas to control HP Ada task
21065 scheduling.
21066
21067 GNAT follows the scheduling rules of Annex D (Real-Time
21068 Annex) of the @cite{Ada Reference Manual}. In general, this
21069 scheduling strategy is fully compatible with HP Ada
21070 although it provides some additional constraints (as
21071 fully documented in Annex D).
21072 GNAT implements time slicing control in a manner compatible with
21073 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21074 are identical to the HP Ada 83 pragma of the same name.
21075 Note that it is not possible to mix GNAT tasking and
21076 HP Ada 83 tasking in the same program, since the two run-time
21077 libraries are not compatible.
21078
21079 @node The Task Stack
21080 @subsection The Task Stack
21081
21082 @noindent
21083 In HP Ada, a task stack is allocated each time a
21084 non-passive task is activated. As soon as the task is
21085 terminated, the storage for the task stack is deallocated.
21086 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21087 a default stack size is used. Also, regardless of the size
21088 specified, some additional space is allocated for task
21089 management purposes. On OpenVMS Alpha systems, at least
21090 one page is allocated.
21091
21092 GNAT handles task stacks in a similar manner. In accordance with
21093 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21094 an alternative method for controlling the task stack size.
21095 The specification of the attribute @code{T'STORAGE_SIZE} is also
21096 supported in a manner compatible with HP Ada.
21097
21098 @node External Interrupts
21099 @subsection External Interrupts
21100
21101 @noindent
21102 On HP Ada, external interrupts can be associated with task entries.
21103 GNAT is compatible with HP Ada in its handling of external interrupts.
21104
21105 @node Pragmas and Pragma-Related Features
21106 @section Pragmas and Pragma-Related Features
21107
21108 @noindent
21109 Both HP Ada and GNAT supply all language-defined pragmas
21110 as specified by the Ada 83 standard. GNAT also supplies all
21111 language-defined pragmas introduced by Ada 95 and Ada 2005.
21112 In addition, GNAT implements the implementation-defined pragmas
21113 from HP Ada 83.
21114
21115 @itemize @bullet
21116 @item  @code{AST_ENTRY}
21117
21118 @item  @code{COMMON_OBJECT}
21119
21120 @item  @code{COMPONENT_ALIGNMENT}
21121
21122 @item  @code{EXPORT_EXCEPTION}
21123
21124 @item  @code{EXPORT_FUNCTION}
21125
21126 @item  @code{EXPORT_OBJECT}
21127
21128 @item  @code{EXPORT_PROCEDURE}
21129
21130 @item  @code{EXPORT_VALUED_PROCEDURE}
21131
21132 @item  @code{FLOAT_REPRESENTATION}
21133
21134 @item  @code{IDENT}
21135
21136 @item  @code{IMPORT_EXCEPTION}
21137
21138 @item  @code{IMPORT_FUNCTION}
21139
21140 @item  @code{IMPORT_OBJECT}
21141
21142 @item  @code{IMPORT_PROCEDURE}
21143
21144 @item  @code{IMPORT_VALUED_PROCEDURE}
21145
21146 @item  @code{INLINE_GENERIC}
21147
21148 @item  @code{INTERFACE_NAME}
21149
21150 @item  @code{LONG_FLOAT}
21151
21152 @item  @code{MAIN_STORAGE}
21153
21154 @item  @code{PASSIVE}
21155
21156 @item  @code{PSECT_OBJECT}
21157
21158 @item  @code{SHARE_GENERIC}
21159
21160 @item  @code{SUPPRESS_ALL}
21161
21162 @item  @code{TASK_STORAGE}
21163
21164 @item  @code{TIME_SLICE}
21165
21166 @item  @code{TITLE}
21167 @end itemize
21168
21169 @noindent
21170 These pragmas are all fully implemented, with the exception of @code{TITLE},
21171 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21172 recognized, but which have no
21173 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21174 use of Ada protected objects. In GNAT, all generics are inlined.
21175
21176 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21177 a separate subprogram specification which must appear before the
21178 subprogram body.
21179
21180 GNAT also supplies a number of implementation-defined pragmas including the
21181 following:
21182
21183 @itemize @bullet
21184 @item  @code{ABORT_DEFER}
21185
21186 @item  @code{ADA_83}
21187
21188 @item  @code{ADA_95}
21189
21190 @item  @code{ADA_05}
21191
21192 @item  @code{Ada_2005}
21193
21194 @item  @code{Ada_12}
21195
21196 @item  @code{Ada_2012}
21197
21198 @item  @code{ANNOTATE}
21199
21200 @item  @code{ASSERT}
21201
21202 @item  @code{C_PASS_BY_COPY}
21203
21204 @item  @code{CPP_CLASS}
21205
21206 @item  @code{CPP_CONSTRUCTOR}
21207
21208 @item  @code{CPP_DESTRUCTOR}
21209
21210 @item  @code{DEBUG}
21211
21212 @item  @code{EXTEND_SYSTEM}
21213
21214 @item  @code{LINKER_ALIAS}
21215
21216 @item  @code{LINKER_SECTION}
21217
21218 @item  @code{MACHINE_ATTRIBUTE}
21219
21220 @item  @code{NO_RETURN}
21221
21222 @item  @code{PURE_FUNCTION}
21223
21224 @item  @code{SOURCE_FILE_NAME}
21225
21226 @item  @code{SOURCE_REFERENCE}
21227
21228 @item  @code{TASK_INFO}
21229
21230 @item  @code{UNCHECKED_UNION}
21231
21232 @item  @code{UNIMPLEMENTED_UNIT}
21233
21234 @item  @code{UNIVERSAL_DATA}
21235
21236 @item  @code{UNSUPPRESS}
21237
21238 @item  @code{WARNINGS}
21239
21240 @item  @code{WEAK_EXTERNAL}
21241 @end itemize
21242
21243 @noindent
21244 For full details on these and other GNAT implementation-defined pragmas,
21245 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21246 Manual}.
21247
21248 @menu
21249 * Restrictions on the Pragma INLINE::
21250 * Restrictions on the Pragma INTERFACE::
21251 * Restrictions on the Pragma SYSTEM_NAME::
21252 @end menu
21253
21254 @node Restrictions on the Pragma INLINE
21255 @subsection Restrictions on Pragma @code{INLINE}
21256
21257 @noindent
21258 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21259 @itemize @bullet
21260 @item  Parameters cannot have a task type.
21261
21262 @item  Function results cannot be task types, unconstrained
21263 array types, or unconstrained types with discriminants.
21264
21265 @item  Bodies cannot declare the following:
21266 @itemize @bullet
21267 @item  Subprogram body or stub (imported subprogram is allowed)
21268
21269 @item  Tasks
21270
21271 @item  Generic declarations
21272
21273 @item  Instantiations
21274
21275 @item  Exceptions
21276
21277 @item  Access types (types derived from access types allowed)
21278
21279 @item  Array or record types
21280
21281 @item  Dependent tasks
21282
21283 @item  Direct recursive calls of subprogram or containing
21284 subprogram, directly or via a renaming
21285
21286 @end itemize
21287 @end itemize
21288
21289 @noindent
21290 In GNAT, the only restriction on pragma @code{INLINE} is that the
21291 body must occur before the call if both are in the same
21292 unit, and the size must be appropriately small. There are
21293 no other specific restrictions which cause subprograms to
21294 be incapable of being inlined.
21295
21296 @node  Restrictions on the Pragma INTERFACE
21297 @subsection  Restrictions on Pragma @code{INTERFACE}
21298
21299 @noindent
21300 The following restrictions on pragma @code{INTERFACE}
21301 are enforced by both HP Ada and GNAT:
21302 @itemize @bullet
21303 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21304 Default is the default on OpenVMS Alpha systems.
21305
21306 @item  Parameter passing: Language specifies default
21307 mechanisms but can be overridden with an @code{EXPORT} pragma.
21308
21309 @itemize @bullet
21310 @item  Ada: Use internal Ada rules.
21311
21312 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21313 record or task type. Result cannot be a string, an
21314 array, or a record.
21315
21316 @item  Fortran: Parameters cannot have a task type. Result cannot
21317 be a string, an array, or a record.
21318 @end itemize
21319 @end itemize
21320
21321 @noindent
21322 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21323 record parameters for all languages.
21324
21325 @node  Restrictions on the Pragma SYSTEM_NAME
21326 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21327
21328 @noindent
21329 For HP Ada for OpenVMS Alpha, the enumeration literal
21330 for the type @code{NAME} is @code{OPENVMS_AXP}.
21331 In GNAT, the enumeration
21332 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21333
21334 @node  Library of Predefined Units
21335 @section  Library of Predefined Units
21336
21337 @noindent
21338 A library of predefined units is provided as part of the
21339 HP Ada and GNAT implementations. HP Ada does not provide
21340 the package @code{MACHINE_CODE} but instead recommends importing
21341 assembler code.
21342
21343 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21344 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21345 version.
21346 The HP Ada Predefined Library units are modified to remove post-Ada 83
21347 incompatibilities and to make them interoperable with GNAT
21348 (@pxref{Changes to DECLIB}, for details).
21349 The units are located in the @file{DECLIB} directory.
21350
21351 The GNAT RTL is contained in
21352 the @file{ADALIB} directory, and
21353 the default search path is set up to find @code{DECLIB} units in preference
21354 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21355 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21356
21357 @menu
21358 * Changes to DECLIB::
21359 @end menu
21360
21361 @node Changes to DECLIB
21362 @subsection Changes to @code{DECLIB}
21363
21364 @noindent
21365 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21366 compatibility are minor and include the following:
21367
21368 @itemize @bullet
21369 @item  Adjusting the location of pragmas and record representation
21370 clauses to obey Ada 95 (and thus Ada 2005) rules
21371
21372 @item  Adding the proper notation to generic formal parameters
21373 that take unconstrained types in instantiation
21374
21375 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21376 that have package bodies not otherwise allowed
21377
21378 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21379 ``@code{PROTECTD}''.
21380 Currently these are found only in the @code{STARLET} package spec.
21381
21382 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21383 where the address size is constrained to 32 bits.
21384 @end itemize
21385
21386 @noindent
21387 None of the above changes is visible to users.
21388
21389 @node Bindings
21390 @section Bindings
21391
21392 @noindent
21393 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21394 @itemize @bullet
21395
21396 @item  Command Language Interpreter (CLI interface)
21397
21398 @item  DECtalk Run-Time Library (DTK interface)
21399
21400 @item  Librarian utility routines (LBR interface)
21401
21402 @item  General Purpose Run-Time Library (LIB interface)
21403
21404 @item  Math Run-Time Library (MTH interface)
21405
21406 @item  National Character Set Run-Time Library (NCS interface)
21407
21408 @item  Compiled Code Support Run-Time Library (OTS interface)
21409
21410 @item  Parallel Processing Run-Time Library (PPL interface)
21411
21412 @item  Screen Management Run-Time Library (SMG interface)
21413
21414 @item  Sort Run-Time Library (SOR interface)
21415
21416 @item  String Run-Time Library (STR interface)
21417
21418 @item STARLET System Library
21419 @findex Starlet
21420
21421 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21422
21423 @item  X Windows Toolkit (XT interface)
21424
21425 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21426 @end itemize
21427
21428 @noindent
21429 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21430 directory, on both the Alpha and I64 OpenVMS platforms.
21431
21432 The X components of DECLIB compatibility package are located in a separate
21433 library, called XDECGNAT, which is not linked with by default; this library
21434 must be explicitly linked with any application that makes use of any X facilities,
21435 with a command similar to
21436
21437 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21438
21439 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21440 in the
21441 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21442 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21443 @code{Xt}, and @code{X_Lib}
21444 causing the default X/Motif sharable image libraries to be linked in. This
21445 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21446 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21447
21448 It may be necessary to edit these options files to update or correct the
21449 library names if, for example, the newer X/Motif bindings from
21450 @file{ADA$EXAMPLES}
21451 had been (previous to installing GNAT) copied and renamed to supersede the
21452 default @file{ADA$PREDEFINED} versions.
21453
21454 @menu
21455 * Shared Libraries and Options Files::
21456 * Interfaces to C::
21457 @end menu
21458
21459 @node Shared Libraries and Options Files
21460 @subsection Shared Libraries and Options Files
21461
21462 @noindent
21463 When using the HP Ada
21464 predefined X and Motif bindings, the linking with their sharable images is
21465 done automatically by @command{GNAT LINK}.
21466 When using other X and Motif bindings, you need
21467 to add the corresponding sharable images to the command line for
21468 @code{GNAT LINK}. When linking with shared libraries, or with
21469 @file{.OPT} files, you must
21470 also add them to the command line for @command{GNAT LINK}.
21471
21472 A shared library to be used with GNAT is built in the same way as other
21473 libraries under VMS. The VMS Link command can be used in standard fashion.
21474
21475 @node Interfaces to C
21476 @subsection Interfaces to C
21477
21478 @noindent
21479 HP Ada
21480 provides the following Ada types and operations:
21481
21482 @itemize @bullet
21483 @item C types package (@code{C_TYPES})
21484
21485 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21486
21487 @item Other_types (@code{SHORT_INT})
21488 @end itemize
21489
21490 @noindent
21491 Interfacing to C with GNAT, you can use the above approach
21492 described for HP Ada or the facilities of Annex B of
21493 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21494 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21495 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21496
21497 The @option{-gnatF} qualifier forces default and explicit
21498 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21499 to be uppercased for compatibility with the default behavior
21500 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21501
21502 @node Main Program Definition
21503 @section Main Program Definition
21504
21505 @noindent
21506 The following section discusses differences in the
21507 definition of main programs on HP Ada and GNAT.
21508 On HP Ada, main programs are defined to meet the
21509 following conditions:
21510 @itemize @bullet
21511 @item  Procedure with no formal parameters (returns @code{0} upon
21512 normal completion)
21513
21514 @item  Procedure with no formal parameters (returns @code{42} when
21515 an unhandled exception is raised)
21516
21517 @item  Function with no formal parameters whose returned value
21518 is of a discrete type
21519
21520 @item  Procedure with one @code{out} formal of a discrete type for
21521 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21522
21523 @end itemize
21524
21525 @noindent
21526 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21527 a main function or main procedure returns a discrete
21528 value whose size is less than 64 bits (32 on VAX systems),
21529 the value is zero- or sign-extended as appropriate.
21530 On GNAT, main programs are defined as follows:
21531 @itemize @bullet
21532 @item  Must be a non-generic, parameterless subprogram that
21533 is either a procedure or function returning an Ada
21534 @code{STANDARD.INTEGER} (the predefined type)
21535
21536 @item  Cannot be a generic subprogram or an instantiation of a
21537 generic subprogram
21538 @end itemize
21539
21540 @node Implementation-Defined Attributes
21541 @section Implementation-Defined Attributes
21542
21543 @noindent
21544 GNAT provides all HP Ada implementation-defined
21545 attributes.
21546
21547 @node Compiler and Run-Time Interfacing
21548 @section Compiler and Run-Time Interfacing
21549
21550 @noindent
21551 HP Ada provides the following qualifiers to pass options to the linker
21552 (ACS LINK):
21553 @itemize @bullet
21554 @item  @option{/WAIT} and @option{/SUBMIT}
21555
21556 @item  @option{/COMMAND}
21557
21558 @item  @option{/@r{[}NO@r{]}MAP}
21559
21560 @item  @option{/OUTPUT=@var{file-spec}}
21561
21562 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21563 @end itemize
21564
21565 @noindent
21566 To pass options to the linker, GNAT provides the following
21567 switches:
21568
21569 @itemize @bullet
21570 @item   @option{/EXECUTABLE=@var{exec-name}}
21571
21572 @item   @option{/VERBOSE}
21573
21574 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21575 @end itemize
21576
21577 @noindent
21578 For more information on these switches, see
21579 @ref{Switches for gnatlink}.
21580 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21581 to control optimization. HP Ada also supplies the
21582 following pragmas:
21583 @itemize @bullet
21584 @item  @code{OPTIMIZE}
21585
21586 @item  @code{INLINE}
21587
21588 @item  @code{INLINE_GENERIC}
21589
21590 @item  @code{SUPPRESS_ALL}
21591
21592 @item  @code{PASSIVE}
21593 @end itemize
21594
21595 @noindent
21596 In GNAT, optimization is controlled strictly by command
21597 line parameters, as described in the corresponding section of this guide.
21598 The HP pragmas for control of optimization are
21599 recognized but ignored.
21600
21601 Note that in GNAT, the default is optimization off, whereas in HP Ada
21602 the default is that optimization is turned on.
21603
21604 @node Program Compilation and Library Management
21605 @section Program Compilation and Library Management
21606
21607 @noindent
21608 HP Ada and GNAT provide a comparable set of commands to
21609 build programs. HP Ada also provides a program library,
21610 which is a concept that does not exist on GNAT. Instead,
21611 GNAT provides directories of sources that are compiled as
21612 needed.
21613
21614 The following table summarizes
21615 the HP Ada commands and provides
21616 equivalent GNAT commands. In this table, some GNAT
21617 equivalents reflect the fact that GNAT does not use the
21618 concept of a program library. Instead, it uses a model
21619 in which collections of source and object files are used
21620 in a manner consistent with other languages like C and
21621 Fortran. Therefore, standard system file commands are used
21622 to manipulate these elements. Those GNAT commands are marked with
21623 an asterisk.
21624 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21625
21626 @need 1500
21627 @multitable @columnfractions .35 .65
21628
21629 @item @emph{HP Ada Command}
21630 @tab @emph{GNAT Equivalent / Description}
21631
21632 @item @command{ADA}
21633 @tab @command{GNAT COMPILE}@*
21634 Invokes the compiler to compile one or more Ada source files.
21635
21636 @item @command{ACS ATTACH}@*
21637 @tab [No equivalent]@*
21638 Switches control of terminal from current process running the program
21639 library manager.
21640
21641 @item @command{ACS CHECK}
21642 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21643 Forms the execution closure of one
21644 or more compiled units and checks completeness and currency.
21645
21646 @item @command{ACS COMPILE}
21647 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21648 Forms the execution closure of one or
21649 more specified units, checks completeness and currency,
21650 identifies units that have revised source files, compiles same,
21651 and recompiles units that are or will become obsolete.
21652 Also completes incomplete generic instantiations.
21653
21654 @item @command{ACS COPY FOREIGN}
21655 @tab Copy (*)@*
21656 Copies a foreign object file into the program library as a
21657 library unit body.
21658
21659 @item @command{ACS COPY UNIT}
21660 @tab Copy (*)@*
21661 Copies a compiled unit from one program library to another.
21662
21663 @item @command{ACS CREATE LIBRARY}
21664 @tab Create /directory (*)@*
21665 Creates a program library.
21666
21667 @item @command{ACS CREATE SUBLIBRARY}
21668 @tab Create /directory (*)@*
21669 Creates a program sublibrary.
21670
21671 @item @command{ACS DELETE LIBRARY}
21672 @tab @*
21673 Deletes a program library and its contents.
21674
21675 @item @command{ACS DELETE SUBLIBRARY}
21676 @tab @*
21677 Deletes a program sublibrary and its contents.
21678
21679 @item @command{ACS DELETE UNIT}
21680 @tab Delete file (*)@*
21681 On OpenVMS systems, deletes one or more compiled units from
21682 the current program library.
21683
21684 @item @command{ACS DIRECTORY}
21685 @tab Directory (*)@*
21686 On OpenVMS systems, lists units contained in the current
21687 program library.
21688
21689 @item @command{ACS ENTER FOREIGN}
21690 @tab Copy (*)@*
21691 Allows the import of a foreign body as an Ada library
21692 spec and enters a reference to a pointer.
21693
21694 @item @command{ACS ENTER UNIT}
21695 @tab Copy (*)@*
21696 Enters a reference (pointer) from the current program library to
21697 a unit compiled into another program library.
21698
21699 @item @command{ACS EXIT}
21700 @tab [No equivalent]@*
21701 Exits from the program library manager.
21702
21703 @item @command{ACS EXPORT}
21704 @tab Copy (*)@*
21705 Creates an object file that contains system-specific object code
21706 for one or more units. With GNAT, object files can simply be copied
21707 into the desired directory.
21708
21709 @item @command{ACS EXTRACT SOURCE}
21710 @tab Copy (*)@*
21711 Allows access to the copied source file for each Ada compilation unit
21712
21713 @item @command{ACS HELP}
21714 @tab @command{HELP GNAT}@*
21715 Provides online help.
21716
21717 @item @command{ACS LINK}
21718 @tab @command{GNAT LINK}@*
21719 Links an object file containing Ada units into an executable file.
21720
21721 @item @command{ACS LOAD}
21722 @tab Copy (*)@*
21723 Loads (partially compiles) Ada units into the program library.
21724 Allows loading a program from a collection of files into a library
21725 without knowing the relationship among units.
21726
21727 @item @command{ACS MERGE}
21728 @tab Copy (*)@*
21729 Merges into the current program library, one or more units from
21730 another library where they were modified.
21731
21732 @item @command{ACS RECOMPILE}
21733 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21734 Recompiles from   external or copied source files any obsolete
21735 unit in the closure. Also, completes any incomplete generic
21736 instantiations.
21737
21738 @item @command{ACS REENTER}
21739 @tab @command{GNAT MAKE}@*
21740 Reenters current references to units compiled after last entered
21741 with the @command{ACS ENTER UNIT} command.
21742
21743 @item @command{ACS SET LIBRARY}
21744 @tab Set default (*)@*
21745 Defines a program library to be the compilation context as well
21746 as the target library for compiler output and commands in general.
21747
21748 @item @command{ACS SET PRAGMA}
21749 @tab Edit @file{gnat.adc} (*)@*
21750 Redefines specified  values of the library characteristics
21751 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21752 and @code{Float_Representation}.
21753
21754 @item @command{ACS SET SOURCE}
21755 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21756 Defines the source file search list for the @command{ACS COMPILE} command.
21757
21758 @item @command{ACS SHOW LIBRARY}
21759 @tab Directory (*)@*
21760 Lists information about one or more program libraries.
21761
21762 @item @command{ACS SHOW PROGRAM}
21763 @tab [No equivalent]@*
21764 Lists information about the execution closure of one or
21765 more units in the program library.
21766
21767 @item @command{ACS SHOW SOURCE}
21768 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21769 Shows the source file search used when compiling units.
21770
21771 @item @command{ACS SHOW VERSION}
21772 @tab Compile with @option{VERBOSE} option
21773 Displays the version number of the compiler and program library
21774 manager used.
21775
21776 @item @command{ACS SPAWN}
21777 @tab [No equivalent]@*
21778 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21779 command).
21780
21781 @item @command{ACS VERIFY}
21782 @tab [No equivalent]@*
21783 Performs a series of consistency checks on a program library to
21784 determine whether the library structure and library files are in
21785 valid form.
21786 @end multitable
21787
21788 @noindent
21789
21790 @node Input-Output
21791 @section Input-Output
21792
21793 @noindent
21794 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21795 Management Services (RMS) to perform operations on
21796 external files.
21797
21798 @noindent
21799 HP Ada and GNAT predefine an identical set of input-
21800 output packages. To make the use of the
21801 generic @code{TEXT_IO} operations more convenient, HP Ada
21802 provides predefined library packages that instantiate the
21803 integer and floating-point operations for the predefined
21804 integer and floating-point types as shown in the following table.
21805
21806 @multitable @columnfractions .45 .55
21807 @item @emph{Package Name} @tab Instantiation
21808
21809 @item @code{INTEGER_TEXT_IO}
21810 @tab @code{INTEGER_IO(INTEGER)}
21811
21812 @item @code{SHORT_INTEGER_TEXT_IO}
21813 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21814
21815 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21816 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21817
21818 @item @code{FLOAT_TEXT_IO}
21819 @tab @code{FLOAT_IO(FLOAT)}
21820
21821 @item @code{LONG_FLOAT_TEXT_IO}
21822 @tab @code{FLOAT_IO(LONG_FLOAT)}
21823 @end multitable
21824
21825 @noindent
21826 The HP Ada predefined packages and their operations
21827 are implemented using OpenVMS Alpha files and input-output
21828 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21829 Familiarity with the following is recommended:
21830 @itemize @bullet
21831 @item  RMS file organizations and access methods
21832
21833 @item  OpenVMS file specifications and directories
21834
21835 @item  OpenVMS File Definition Language (FDL)
21836 @end itemize
21837
21838 @noindent
21839 GNAT provides I/O facilities that are completely
21840 compatible with HP Ada. The distribution includes the
21841 standard HP Ada versions of all I/O packages, operating
21842 in a manner compatible with HP Ada. In particular, the
21843 following packages are by default the HP Ada (Ada 83)
21844 versions of these packages rather than the renamings
21845 suggested in Annex J of the Ada Reference Manual:
21846 @itemize @bullet
21847 @item  @code{TEXT_IO}
21848
21849 @item  @code{SEQUENTIAL_IO}
21850
21851 @item  @code{DIRECT_IO}
21852 @end itemize
21853
21854 @noindent
21855 The use of the standard child package syntax (for
21856 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21857 packages.
21858 GNAT provides HP-compatible predefined instantiations
21859 of the @code{TEXT_IO} packages, and also
21860 provides the standard predefined instantiations required
21861 by the @cite{Ada Reference Manual}.
21862
21863 For further information on how GNAT interfaces to the file
21864 system or how I/O is implemented in programs written in
21865 mixed languages, see @ref{Implementation of the Standard I/O,,,
21866 gnat_rm, GNAT Reference Manual}.
21867 This chapter covers the following:
21868 @itemize @bullet
21869 @item  Standard I/O packages
21870
21871 @item  @code{FORM} strings
21872
21873 @item  @code{ADA.DIRECT_IO}
21874
21875 @item  @code{ADA.SEQUENTIAL_IO}
21876
21877 @item  @code{ADA.TEXT_IO}
21878
21879 @item  Stream pointer positioning
21880
21881 @item  Reading and writing non-regular files
21882
21883 @item  @code{GET_IMMEDIATE}
21884
21885 @item  Treating @code{TEXT_IO} files as streams
21886
21887 @item  Shared files
21888
21889 @item  Open modes
21890 @end itemize
21891
21892 @node Implementation Limits
21893 @section Implementation Limits
21894
21895 @noindent
21896 The following table lists implementation limits for HP Ada
21897 and GNAT systems.
21898 @multitable @columnfractions .60 .20 .20
21899 @sp 1
21900 @item  @emph{Compilation Parameter}
21901 @tab   @emph{HP Ada}
21902 @tab   @emph{GNAT}
21903 @sp 1
21904
21905 @item  In a subprogram or entry  declaration, maximum number of
21906 formal parameters that are of an unconstrained record type
21907 @tab   32
21908 @tab   No set limit
21909 @sp 1
21910
21911 @item  Maximum identifier length (number of characters)
21912 @tab   255
21913 @tab   32766
21914 @sp 1
21915
21916 @item  Maximum number of characters in a source line
21917 @tab   255
21918 @tab   32766
21919 @sp 1
21920
21921 @item  Maximum collection size   (number of bytes)
21922 @tab   2**31-1
21923 @tab   2**31-1
21924 @sp 1
21925
21926 @item  Maximum number of discriminants for a record type
21927 @tab   245
21928 @tab   No set limit
21929 @sp 1
21930
21931 @item  Maximum number of formal parameters in an entry or
21932 subprogram declaration
21933 @tab   246
21934 @tab    No set limit
21935 @sp 1
21936
21937 @item  Maximum number of dimensions in an array type
21938 @tab   255
21939 @tab   No set limit
21940 @sp 1
21941
21942 @item  Maximum number of library  units and subunits in a compilation.
21943 @tab   4095
21944 @tab   No set limit
21945 @sp 1
21946
21947 @item  Maximum number of library units and subunits in an execution.
21948 @tab   16383
21949 @tab   No set limit
21950 @sp 1
21951
21952 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21953 or @code{PSECT_OBJECT}
21954 @tab   32757
21955 @tab   No set limit
21956 @sp 1
21957
21958 @item  Maximum number of enumeration literals in an enumeration type
21959 definition
21960 @tab   65535
21961 @tab   No set limit
21962 @sp 1
21963
21964 @item  Maximum number of lines in a source file
21965 @tab   65534
21966 @tab   No set limit
21967 @sp 1
21968
21969 @item  Maximum number of bits in any object
21970 @tab   2**31-1
21971 @tab   2**31-1
21972 @sp 1
21973
21974 @item  Maximum size of the static portion of a stack frame (approximate)
21975 @tab   2**31-1
21976 @tab   2**31-1
21977 @end multitable
21978
21979 @node Tools and Utilities
21980 @section Tools and Utilities
21981
21982 @noindent
21983 The following table lists some of the OpenVMS development tools
21984 available for HP Ada, and the corresponding tools for
21985 use with @value{EDITION} on Alpha and I64 platforms.
21986 Aside from the debugger, all the OpenVMS tools identified are part
21987 of the DECset package.
21988
21989 @iftex
21990 @c Specify table in TeX since Texinfo does a poor job
21991 @tex
21992 \smallskip
21993 \smallskip
21994 \settabs\+Language-Sensitive Editor\quad
21995    &Product with HP Ada\quad
21996    &\cr
21997 \+\it Tool
21998    &\it Product with HP Ada
21999    & \it Product with @value{EDITION}\cr
22000 \smallskip
22001 \+Code Management System
22002    &HP CMS
22003    & HP CMS\cr
22004 \smallskip
22005 \+Language-Sensitive Editor
22006    &HP LSE
22007    & emacs or HP LSE (Alpha)\cr
22008 \+
22009    &
22010    & HP LSE (I64)\cr
22011 \smallskip
22012 \+Debugger
22013    &OpenVMS Debug
22014    & gdb (Alpha),\cr
22015 \+
22016    &
22017    & OpenVMS Debug (I64)\cr
22018 \smallskip
22019 \+Source Code Analyzer /
22020    &HP SCA
22021    & GNAT XREF\cr
22022 \+Cross Referencer
22023    &
22024    &\cr
22025 \smallskip
22026 \+Test Manager
22027    &HP Digital Test
22028    & HP DTM\cr
22029 \+
22030    &Manager (DTM)
22031    &\cr
22032 \smallskip
22033 \+Performance and
22034    & HP PCA
22035    & HP PCA\cr
22036 \+Coverage Analyzer
22037    &
22038    &\cr
22039 \smallskip
22040 \+Module Management
22041    & HP MMS
22042    & Not applicable\cr
22043 \+ System
22044    &
22045    &\cr
22046 \smallskip
22047 \smallskip
22048 @end tex
22049 @end iftex
22050
22051 @ifnottex
22052 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22053 @c the TeX version above for the printed version
22054 @flushleft
22055 @c @multitable @columnfractions .3 .4 .4
22056 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22057 @item @i{Tool}
22058 @tab @i{Tool with HP Ada}
22059 @tab @i{Tool with @value{EDITION}}
22060 @item Code Management@*System
22061 @tab HP CMS
22062 @tab HP CMS
22063 @item Language-Sensitive@*Editor
22064 @tab HP LSE
22065 @tab emacs or HP LSE (Alpha)
22066 @item
22067 @tab
22068 @tab HP LSE (I64)
22069 @item Debugger
22070 @tab OpenVMS Debug
22071 @tab gdb (Alpha),
22072 @item
22073 @tab
22074 @tab OpenVMS Debug (I64)
22075 @item Source Code Analyzer /@*Cross Referencer
22076 @tab HP SCA
22077 @tab GNAT XREF
22078 @item Test Manager
22079 @tab HP Digital Test@*Manager (DTM)
22080 @tab HP DTM
22081 @item Performance and@*Coverage Analyzer
22082 @tab HP PCA
22083 @tab HP PCA
22084 @item Module Management@*System
22085 @tab HP MMS
22086 @tab Not applicable
22087 @end multitable
22088 @end flushleft
22089 @end ifnottex
22090
22091 @end ifset
22092
22093 @c **************************************
22094 @node Platform-Specific Information for the Run-Time Libraries
22095 @appendix Platform-Specific Information for the Run-Time Libraries
22096 @cindex Tasking and threads libraries
22097 @cindex Threads libraries and tasking
22098 @cindex Run-time libraries (platform-specific information)
22099
22100 @noindent
22101 The GNAT run-time implementation may vary with respect to both the
22102 underlying threads library and the exception handling scheme.
22103 For threads support, one or more of the following are supplied:
22104 @itemize @bullet
22105 @item @b{native threads library}, a binding to the thread package from
22106 the underlying operating system
22107
22108 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22109 POSIX thread package
22110 @end itemize
22111
22112 @noindent
22113 For exception handling, either or both of two models are supplied:
22114 @itemize @bullet
22115 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22116 Most programs should experience a substantial speed improvement by
22117 being compiled with a ZCX run-time.
22118 This is especially true for
22119 tasking applications or applications with many exception handlers.}
22120 @cindex Zero-Cost Exceptions
22121 @cindex ZCX (Zero-Cost Exceptions)
22122 which uses binder-generated tables that
22123 are interrogated at run time to locate a handler
22124
22125 @item @b{setjmp / longjmp} (``SJLJ''),
22126 @cindex setjmp/longjmp Exception Model
22127 @cindex SJLJ (setjmp/longjmp Exception Model)
22128 which uses dynamically-set data to establish
22129 the set of handlers
22130 @end itemize
22131
22132 @noindent
22133 This appendix summarizes which combinations of threads and exception support
22134 are supplied on various GNAT platforms.
22135 It then shows how to select a particular library either
22136 permanently or temporarily,
22137 explains the properties of (and tradeoffs among) the various threads
22138 libraries, and provides some additional
22139 information about several specific platforms.
22140
22141 @menu
22142 * Summary of Run-Time Configurations::
22143 * Specifying a Run-Time Library::
22144 * Choosing the Scheduling Policy::
22145 * Solaris-Specific Considerations::
22146 * Linux-Specific Considerations::
22147 * AIX-Specific Considerations::
22148 * Irix-Specific Considerations::
22149 * RTX-Specific Considerations::
22150 * HP-UX-Specific Considerations::
22151 @end menu
22152
22153 @node Summary of Run-Time Configurations
22154 @section Summary of Run-Time Configurations
22155
22156 @multitable @columnfractions .30 .70
22157 @item @b{alpha-openvms}
22158 @item @code{@ @ }@i{rts-native (default)}
22159 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22160 @item @code{@ @ @ @ }Exceptions @tab ZCX
22161 @*
22162 @item @b{alpha-tru64}
22163 @item @code{@ @ }@i{rts-native (default)}
22164 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22165 @item @code{@ @ @ @ }Exceptions @tab ZCX
22166 @*
22167 @item @code{@ @ }@i{rts-sjlj}
22168 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22169 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22170 @*
22171 @item @b{ia64-hp_linux}
22172 @item @code{@ @ }@i{rts-native (default)}
22173 @item @code{@ @ @ @ }Tasking    @tab pthread library
22174 @item @code{@ @ @ @ }Exceptions @tab ZCX
22175 @*
22176 @item @b{ia64-hpux}
22177 @item @code{@ @ }@i{rts-native (default)}
22178 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22179 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22180 @*
22181 @item @b{ia64-openvms}
22182 @item @code{@ @ }@i{rts-native (default)}
22183 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22184 @item @code{@ @ @ @ }Exceptions @tab ZCX
22185 @*
22186 @item @b{ia64-sgi_linux}
22187 @item @code{@ @ }@i{rts-native (default)}
22188 @item @code{@ @ @ @ }Tasking    @tab pthread library
22189 @item @code{@ @ @ @ }Exceptions @tab ZCX
22190 @*
22191 @item @b{mips-irix}
22192 @item @code{@ @ }@i{rts-native (default)}
22193 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22194 @item @code{@ @ @ @ }Exceptions @tab ZCX
22195 @*
22196 @item @b{pa-hpux}
22197 @item @code{@ @ }@i{rts-native (default)}
22198 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22199 @item @code{@ @ @ @ }Exceptions @tab ZCX
22200 @*
22201 @item @code{@ @ }@i{rts-sjlj}
22202 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22203 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22204 @*
22205 @item @b{ppc-aix}
22206 @item @code{@ @ }@i{rts-native (default)}
22207 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22208 @item @code{@ @ @ @ }Exceptions @tab ZCX
22209 @*
22210 @item @code{@ @ }@i{rts-sjlj}
22211 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22212 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22213 @*
22214 @item @b{ppc-darwin}
22215 @item @code{@ @ }@i{rts-native (default)}
22216 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22217 @item @code{@ @ @ @ }Exceptions @tab ZCX
22218 @*
22219 @item @b{sparc-solaris}  @tab
22220 @item @code{@ @ }@i{rts-native (default)}
22221 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22222 @item @code{@ @ @ @ }Exceptions @tab ZCX
22223 @*
22224 @item @code{@ @ }@i{rts-pthread}
22225 @item @code{@ @ @ @ }Tasking    @tab pthread library
22226 @item @code{@ @ @ @ }Exceptions @tab ZCX
22227 @*
22228 @item @code{@ @ }@i{rts-sjlj}
22229 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22230 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22231 @*
22232 @item @b{sparc64-solaris}  @tab
22233 @item @code{@ @ }@i{rts-native (default)}
22234 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22235 @item @code{@ @ @ @ }Exceptions @tab ZCX
22236 @*
22237 @item @b{x86-linux}
22238 @item @code{@ @ }@i{rts-native (default)}
22239 @item @code{@ @ @ @ }Tasking    @tab pthread library
22240 @item @code{@ @ @ @ }Exceptions @tab ZCX
22241 @*
22242 @item @code{@ @ }@i{rts-sjlj}
22243 @item @code{@ @ @ @ }Tasking    @tab pthread library
22244 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22245 @*
22246 @item @b{x86-lynx}
22247 @item @code{@ @ }@i{rts-native (default)}
22248 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22249 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22250 @*
22251 @item @b{x86-solaris}
22252 @item @code{@ @ }@i{rts-native (default)}
22253 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22254 @item @code{@ @ @ @ }Exceptions @tab ZCX
22255 @*
22256 @item @code{@ @ }@i{rts-sjlj}
22257 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22258 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22259 @*
22260 @item @b{x86-windows}
22261 @item @code{@ @ }@i{rts-native (default)}
22262 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22263 @item @code{@ @ @ @ }Exceptions @tab ZCX
22264 @*
22265 @item @code{@ @ }@i{rts-sjlj}
22266 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22267 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22268 @*
22269 @item @b{x86-windows-rtx}
22270 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22271 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22272 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22273 @*
22274 @item @code{@ @ }@i{rts-rtx-w32}
22275 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22276 @item @code{@ @ @ @ }Exceptions @tab ZCX
22277 @*
22278 @item @b{x86_64-linux}
22279 @item @code{@ @ }@i{rts-native (default)}
22280 @item @code{@ @ @ @ }Tasking    @tab pthread library
22281 @item @code{@ @ @ @ }Exceptions @tab ZCX
22282 @*
22283 @item @code{@ @ }@i{rts-sjlj}
22284 @item @code{@ @ @ @ }Tasking    @tab pthread library
22285 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22286 @*
22287 @end multitable
22288
22289 @node Specifying a Run-Time Library
22290 @section Specifying a Run-Time Library
22291
22292 @noindent
22293 The @file{adainclude} subdirectory containing the sources of the GNAT
22294 run-time library, and the @file{adalib} subdirectory containing the
22295 @file{ALI} files and the static and/or shared GNAT library, are located
22296 in the gcc target-dependent area:
22297
22298 @smallexample
22299 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22300 @end smallexample
22301
22302 @noindent
22303 As indicated above, on some platforms several run-time libraries are supplied.
22304 These libraries are installed in the target dependent area and
22305 contain a complete source and binary subdirectory. The detailed description
22306 below explains the differences between the different libraries in terms of
22307 their thread support.
22308
22309 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22310 This default run time is selected by the means of soft links.
22311 For example on x86-linux:
22312
22313 @smallexample
22314 @group
22315  $(target-dir)
22316      |
22317      +--- adainclude----------+
22318      |                        |
22319      +--- adalib-----------+  |
22320      |                     |  |
22321      +--- rts-native       |  |
22322      |    |                |  |
22323      |    +--- adainclude <---+
22324      |    |                |
22325      |    +--- adalib <----+
22326      |
22327      +--- rts-sjlj
22328           |
22329           +--- adainclude
22330           |
22331           +--- adalib
22332 @end group
22333 @end smallexample
22334
22335 @noindent
22336 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22337 these soft links can be modified with the following commands:
22338
22339 @smallexample
22340 $ cd $target
22341 $ rm -f adainclude adalib
22342 $ ln -s rts-sjlj/adainclude adainclude
22343 $ ln -s rts-sjlj/adalib adalib
22344 @end smallexample
22345
22346 @noindent
22347 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22348 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22349 @file{$target/ada_object_path}.
22350
22351 Selecting another run-time library temporarily can be
22352 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22353 @cindex @option{--RTS} option
22354
22355 @node Choosing the Scheduling Policy
22356 @section Choosing the Scheduling Policy
22357
22358 @noindent
22359 When using a POSIX threads implementation, you have a choice of several
22360 scheduling policies: @code{SCHED_FIFO},
22361 @cindex @code{SCHED_FIFO} scheduling policy
22362 @code{SCHED_RR}
22363 @cindex @code{SCHED_RR} scheduling policy
22364 and @code{SCHED_OTHER}.
22365 @cindex @code{SCHED_OTHER} scheduling policy
22366 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22367 or @code{SCHED_RR} requires special (e.g., root) privileges.
22368
22369 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22370 @code{SCHED_FIFO},
22371 @cindex @code{SCHED_FIFO} scheduling policy
22372 you can use one of the following:
22373
22374 @itemize @bullet
22375 @item
22376 @code{pragma Time_Slice (0.0)}
22377 @cindex pragma Time_Slice
22378 @item
22379 the corresponding binder option @option{-T0}
22380 @cindex @option{-T0} option
22381 @item
22382 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22383 @cindex pragma Task_Dispatching_Policy
22384 @end itemize
22385
22386 @noindent
22387 To specify @code{SCHED_RR},
22388 @cindex @code{SCHED_RR} scheduling policy
22389 you should use @code{pragma Time_Slice} with a
22390 value greater than @code{0.0}, or else use the corresponding @option{-T}
22391 binder option.
22392
22393 @node Solaris-Specific Considerations
22394 @section Solaris-Specific Considerations
22395 @cindex Solaris Sparc threads libraries
22396
22397 @noindent
22398 This section addresses some topics related to the various threads libraries
22399 on Sparc Solaris.
22400
22401 @menu
22402 * Solaris Threads Issues::
22403 @end menu
22404
22405 @node Solaris Threads Issues
22406 @subsection Solaris Threads Issues
22407
22408 @noindent
22409 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22410 library based on POSIX threads --- @emph{rts-pthread}.
22411 @cindex rts-pthread threads library
22412 This run-time library has the advantage of being mostly shared across all
22413 POSIX-compliant thread implementations, and it also provides under
22414 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22415 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22416 and @code{PTHREAD_PRIO_PROTECT}
22417 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22418 semantics that can be selected using the predefined pragma
22419 @code{Locking_Policy}
22420 @cindex pragma Locking_Policy (under rts-pthread)
22421 with respectively
22422 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22423 @cindex @code{Inheritance_Locking} (under rts-pthread)
22424 @cindex @code{Ceiling_Locking} (under rts-pthread)
22425
22426 As explained above, the native run-time library is based on the Solaris thread
22427 library (@code{libthread}) and is the default library.
22428
22429 When the Solaris threads library is used (this is the default), programs
22430 compiled with GNAT can automatically take advantage of
22431 and can thus execute on multiple processors.
22432 The user can alternatively specify a processor on which the program should run
22433 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22434 is made by
22435 setting the environment variable @env{GNAT_PROCESSOR}
22436 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22437 to one of the following:
22438
22439 @table @code
22440 @item -2
22441 Use the default configuration (run the program on all
22442 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22443 unset
22444
22445 @item -1
22446 Let the run-time implementation choose one processor and run the program on
22447 that processor
22448
22449 @item 0 .. Last_Proc
22450 Run the program on the specified processor.
22451 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22452 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22453 @end table
22454
22455 @node Linux-Specific Considerations
22456 @section Linux-Specific Considerations
22457 @cindex Linux threads libraries
22458
22459 @noindent
22460 On GNU/Linux without NPTL support (usually system with GNU C Library
22461 older than 2.3), the signal model is not POSIX compliant, which means
22462 that to send a signal to the process, you need to send the signal to all
22463 threads, e.g.@: by using @code{killpg()}.
22464
22465 @node AIX-Specific Considerations
22466 @section AIX-Specific Considerations
22467 @cindex AIX resolver library
22468
22469 @noindent
22470 On AIX, the resolver library initializes some internal structure on
22471 the first call to @code{get*by*} functions, which are used to implement
22472 @code{GNAT.Sockets.Get_Host_By_Name} and
22473 @code{GNAT.Sockets.Get_Host_By_Address}.
22474 If such initialization occurs within an Ada task, and the stack size for
22475 the task is the default size, a stack overflow may occur.
22476
22477 To avoid this overflow, the user should either ensure that the first call
22478 to @code{GNAT.Sockets.Get_Host_By_Name} or
22479 @code{GNAT.Sockets.Get_Host_By_Addrss}
22480 occurs in the environment task, or use @code{pragma Storage_Size} to
22481 specify a sufficiently large size for the stack of the task that contains
22482 this call.
22483
22484 @node Irix-Specific Considerations
22485 @section Irix-Specific Considerations
22486 @cindex Irix libraries
22487
22488 @noindent
22489 The GCC support libraries coming with the Irix compiler have moved to
22490 their canonical place with respect to the general Irix ABI related
22491 conventions. Running applications built with the default shared GNAT
22492 run-time now requires the LD_LIBRARY_PATH environment variable to
22493 include this location. A possible way to achieve this is to issue the
22494 following command line on a bash prompt:
22495
22496 @smallexample
22497 @group
22498 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22499 @end group
22500 @end smallexample
22501
22502 @node RTX-Specific Considerations
22503 @section RTX-Specific Considerations
22504 @cindex RTX libraries
22505
22506 @noindent
22507 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22508 API. Applications can be built to work in two different modes:
22509
22510 @itemize @bullet
22511 @item
22512 Windows executables that run in Ring 3 to utilize memory protection
22513 (@emph{rts-rtx-w32}).
22514
22515 @item
22516 Real-time subsystem (RTSS) executables that run in Ring 0, where
22517 performance can be optimized with RTSS applications taking precedent
22518 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22519 the Microsoft linker to handle RTSS libraries.
22520
22521 @end itemize
22522
22523 @node HP-UX-Specific Considerations
22524 @section HP-UX-Specific Considerations
22525 @cindex HP-UX Scheduling
22526
22527 @noindent
22528 On HP-UX, appropriate privileges are required to change the scheduling
22529 parameters of a task. The calling process must have appropriate
22530 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22531 successfully change the scheduling parameters.
22532
22533 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22534 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22535 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22536
22537 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22538 one of the following:
22539
22540 @itemize @bullet
22541 @item
22542 @code{pragma Time_Slice (0.0)}
22543 @cindex pragma Time_Slice
22544 @item
22545 the corresponding binder option @option{-T0}
22546 @cindex @option{-T0} option
22547 @item
22548 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22549 @cindex pragma Task_Dispatching_Policy
22550 @end itemize
22551
22552 @noindent
22553 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22554 you should use @code{pragma Time_Slice} with a
22555 value greater than @code{0.0}, or use the corresponding @option{-T}
22556 binder option, or set the @code{pragma Task_Dispatching_Policy
22557 (Round_Robin_Within_Priorities)}.
22558
22559 @c *******************************
22560 @node Example of Binder Output File
22561 @appendix Example of Binder Output File
22562
22563 @noindent
22564 This Appendix displays the source code for @command{gnatbind}'s output
22565 file generated for a simple ``Hello World'' program.
22566 Comments have been added for clarification purposes.
22567
22568 @smallexample @c adanocomment
22569 @iftex
22570 @leftskip=0cm
22571 @end iftex
22572 --  The package is called Ada_Main unless this name is actually used
22573 --  as a unit name in the partition, in which case some other unique
22574 --  name is used.
22575
22576 with System;
22577 package ada_main is
22578
22579    Elab_Final_Code : Integer;
22580    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22581
22582    --  The main program saves the parameters (argument count,
22583    --  argument values, environment pointer) in global variables
22584    --  for later access by other units including
22585    --  Ada.Command_Line.
22586
22587    gnat_argc : Integer;
22588    gnat_argv : System.Address;
22589    gnat_envp : System.Address;
22590
22591    --  The actual variables are stored in a library routine. This
22592    --  is useful for some shared library situations, where there
22593    --  are problems if variables are not in the library.
22594
22595    pragma Import (C, gnat_argc);
22596    pragma Import (C, gnat_argv);
22597    pragma Import (C, gnat_envp);
22598
22599    --  The exit status is similarly an external location
22600
22601    gnat_exit_status : Integer;
22602    pragma Import (C, gnat_exit_status);
22603
22604    GNAT_Version : constant String :=
22605                     "GNAT Version: 6.0.0w (20061115)";
22606    pragma Export (C, GNAT_Version, "__gnat_version");
22607
22608    --  This is the generated adafinal routine that performs
22609    --  finalization at the end of execution. In the case where
22610    --  Ada is the main program, this main program makes a call
22611    --  to adafinal at program termination.
22612
22613    procedure adafinal;
22614    pragma Export (C, adafinal, "adafinal");
22615
22616    --  This is the generated adainit routine that performs
22617    --  initialization at the start of execution. In the case
22618    --  where Ada is the main program, this main program makes
22619    --  a call to adainit at program startup.
22620
22621    procedure adainit;
22622    pragma Export (C, adainit, "adainit");
22623
22624    --  This routine is called at the start of execution. It is
22625    --  a dummy routine that is used by the debugger to breakpoint
22626    --  at the start of execution.
22627
22628    procedure Break_Start;
22629    pragma Import (C, Break_Start, "__gnat_break_start");
22630
22631    --  This is the actual generated main program (it would be
22632    --  suppressed if the no main program switch were used). As
22633    --  required by standard system conventions, this program has
22634    --  the external name main.
22635
22636    function main
22637      (argc : Integer;
22638       argv : System.Address;
22639       envp : System.Address)
22640       return Integer;
22641    pragma Export (C, main, "main");
22642
22643    --  The following set of constants give the version
22644    --  identification values for every unit in the bound
22645    --  partition. This identification is computed from all
22646    --  dependent semantic units, and corresponds to the
22647    --  string that would be returned by use of the
22648    --  Body_Version or Version attributes.
22649
22650    type Version_32 is mod 2 ** 32;
22651    u00001 : constant Version_32 := 16#7880BEB3#;
22652    u00002 : constant Version_32 := 16#0D24CBD0#;
22653    u00003 : constant Version_32 := 16#3283DBEB#;
22654    u00004 : constant Version_32 := 16#2359F9ED#;
22655    u00005 : constant Version_32 := 16#664FB847#;
22656    u00006 : constant Version_32 := 16#68E803DF#;
22657    u00007 : constant Version_32 := 16#5572E604#;
22658    u00008 : constant Version_32 := 16#46B173D8#;
22659    u00009 : constant Version_32 := 16#156A40CF#;
22660    u00010 : constant Version_32 := 16#033DABE0#;
22661    u00011 : constant Version_32 := 16#6AB38FEA#;
22662    u00012 : constant Version_32 := 16#22B6217D#;
22663    u00013 : constant Version_32 := 16#68A22947#;
22664    u00014 : constant Version_32 := 16#18CC4A56#;
22665    u00015 : constant Version_32 := 16#08258E1B#;
22666    u00016 : constant Version_32 := 16#367D5222#;
22667    u00017 : constant Version_32 := 16#20C9ECA4#;
22668    u00018 : constant Version_32 := 16#50D32CB6#;
22669    u00019 : constant Version_32 := 16#39A8BB77#;
22670    u00020 : constant Version_32 := 16#5CF8FA2B#;
22671    u00021 : constant Version_32 := 16#2F1EB794#;
22672    u00022 : constant Version_32 := 16#31AB6444#;
22673    u00023 : constant Version_32 := 16#1574B6E9#;
22674    u00024 : constant Version_32 := 16#5109C189#;
22675    u00025 : constant Version_32 := 16#56D770CD#;
22676    u00026 : constant Version_32 := 16#02F9DE3D#;
22677    u00027 : constant Version_32 := 16#08AB6B2C#;
22678    u00028 : constant Version_32 := 16#3FA37670#;
22679    u00029 : constant Version_32 := 16#476457A0#;
22680    u00030 : constant Version_32 := 16#731E1B6E#;
22681    u00031 : constant Version_32 := 16#23C2E789#;
22682    u00032 : constant Version_32 := 16#0F1BD6A1#;
22683    u00033 : constant Version_32 := 16#7C25DE96#;
22684    u00034 : constant Version_32 := 16#39ADFFA2#;
22685    u00035 : constant Version_32 := 16#571DE3E7#;
22686    u00036 : constant Version_32 := 16#5EB646AB#;
22687    u00037 : constant Version_32 := 16#4249379B#;
22688    u00038 : constant Version_32 := 16#0357E00A#;
22689    u00039 : constant Version_32 := 16#3784FB72#;
22690    u00040 : constant Version_32 := 16#2E723019#;
22691    u00041 : constant Version_32 := 16#623358EA#;
22692    u00042 : constant Version_32 := 16#107F9465#;
22693    u00043 : constant Version_32 := 16#6843F68A#;
22694    u00044 : constant Version_32 := 16#63305874#;
22695    u00045 : constant Version_32 := 16#31E56CE1#;
22696    u00046 : constant Version_32 := 16#02917970#;
22697    u00047 : constant Version_32 := 16#6CCBA70E#;
22698    u00048 : constant Version_32 := 16#41CD4204#;
22699    u00049 : constant Version_32 := 16#572E3F58#;
22700    u00050 : constant Version_32 := 16#20729FF5#;
22701    u00051 : constant Version_32 := 16#1D4F93E8#;
22702    u00052 : constant Version_32 := 16#30B2EC3D#;
22703    u00053 : constant Version_32 := 16#34054F96#;
22704    u00054 : constant Version_32 := 16#5A199860#;
22705    u00055 : constant Version_32 := 16#0E7F912B#;
22706    u00056 : constant Version_32 := 16#5760634A#;
22707    u00057 : constant Version_32 := 16#5D851835#;
22708
22709    --  The following Export pragmas export the version numbers
22710    --  with symbolic names ending in B (for body) or S
22711    --  (for spec) so that they can be located in a link. The
22712    --  information provided here is sufficient to track down
22713    --  the exact versions of units used in a given build.
22714
22715    pragma Export (C, u00001, "helloB");
22716    pragma Export (C, u00002, "system__standard_libraryB");
22717    pragma Export (C, u00003, "system__standard_libraryS");
22718    pragma Export (C, u00004, "adaS");
22719    pragma Export (C, u00005, "ada__text_ioB");
22720    pragma Export (C, u00006, "ada__text_ioS");
22721    pragma Export (C, u00007, "ada__exceptionsB");
22722    pragma Export (C, u00008, "ada__exceptionsS");
22723    pragma Export (C, u00009, "gnatS");
22724    pragma Export (C, u00010, "gnat__heap_sort_aB");
22725    pragma Export (C, u00011, "gnat__heap_sort_aS");
22726    pragma Export (C, u00012, "systemS");
22727    pragma Export (C, u00013, "system__exception_tableB");
22728    pragma Export (C, u00014, "system__exception_tableS");
22729    pragma Export (C, u00015, "gnat__htableB");
22730    pragma Export (C, u00016, "gnat__htableS");
22731    pragma Export (C, u00017, "system__exceptionsS");
22732    pragma Export (C, u00018, "system__machine_state_operationsB");
22733    pragma Export (C, u00019, "system__machine_state_operationsS");
22734    pragma Export (C, u00020, "system__machine_codeS");
22735    pragma Export (C, u00021, "system__storage_elementsB");
22736    pragma Export (C, u00022, "system__storage_elementsS");
22737    pragma Export (C, u00023, "system__secondary_stackB");
22738    pragma Export (C, u00024, "system__secondary_stackS");
22739    pragma Export (C, u00025, "system__parametersB");
22740    pragma Export (C, u00026, "system__parametersS");
22741    pragma Export (C, u00027, "system__soft_linksB");
22742    pragma Export (C, u00028, "system__soft_linksS");
22743    pragma Export (C, u00029, "system__stack_checkingB");
22744    pragma Export (C, u00030, "system__stack_checkingS");
22745    pragma Export (C, u00031, "system__tracebackB");
22746    pragma Export (C, u00032, "system__tracebackS");
22747    pragma Export (C, u00033, "ada__streamsS");
22748    pragma Export (C, u00034, "ada__tagsB");
22749    pragma Export (C, u00035, "ada__tagsS");
22750    pragma Export (C, u00036, "system__string_opsB");
22751    pragma Export (C, u00037, "system__string_opsS");
22752    pragma Export (C, u00038, "interfacesS");
22753    pragma Export (C, u00039, "interfaces__c_streamsB");
22754    pragma Export (C, u00040, "interfaces__c_streamsS");
22755    pragma Export (C, u00041, "system__file_ioB");
22756    pragma Export (C, u00042, "system__file_ioS");
22757    pragma Export (C, u00043, "ada__finalizationB");
22758    pragma Export (C, u00044, "ada__finalizationS");
22759    pragma Export (C, u00045, "system__finalization_rootB");
22760    pragma Export (C, u00046, "system__finalization_rootS");
22761    pragma Export (C, u00047, "system__finalization_implementationB");
22762    pragma Export (C, u00048, "system__finalization_implementationS");
22763    pragma Export (C, u00049, "system__string_ops_concat_3B");
22764    pragma Export (C, u00050, "system__string_ops_concat_3S");
22765    pragma Export (C, u00051, "system__stream_attributesB");
22766    pragma Export (C, u00052, "system__stream_attributesS");
22767    pragma Export (C, u00053, "ada__io_exceptionsS");
22768    pragma Export (C, u00054, "system__unsigned_typesS");
22769    pragma Export (C, u00055, "system__file_control_blockS");
22770    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22771    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22772
22773    -- BEGIN ELABORATION ORDER
22774    -- ada (spec)
22775    -- gnat (spec)
22776    -- gnat.heap_sort_a (spec)
22777    -- gnat.heap_sort_a (body)
22778    -- gnat.htable (spec)
22779    -- gnat.htable (body)
22780    -- interfaces (spec)
22781    -- system (spec)
22782    -- system.machine_code (spec)
22783    -- system.parameters (spec)
22784    -- system.parameters (body)
22785    -- interfaces.c_streams (spec)
22786    -- interfaces.c_streams (body)
22787    -- system.standard_library (spec)
22788    -- ada.exceptions (spec)
22789    -- system.exception_table (spec)
22790    -- system.exception_table (body)
22791    -- ada.io_exceptions (spec)
22792    -- system.exceptions (spec)
22793    -- system.storage_elements (spec)
22794    -- system.storage_elements (body)
22795    -- system.machine_state_operations (spec)
22796    -- system.machine_state_operations (body)
22797    -- system.secondary_stack (spec)
22798    -- system.stack_checking (spec)
22799    -- system.soft_links (spec)
22800    -- system.soft_links (body)
22801    -- system.stack_checking (body)
22802    -- system.secondary_stack (body)
22803    -- system.standard_library (body)
22804    -- system.string_ops (spec)
22805    -- system.string_ops (body)
22806    -- ada.tags (spec)
22807    -- ada.tags (body)
22808    -- ada.streams (spec)
22809    -- system.finalization_root (spec)
22810    -- system.finalization_root (body)
22811    -- system.string_ops_concat_3 (spec)
22812    -- system.string_ops_concat_3 (body)
22813    -- system.traceback (spec)
22814    -- system.traceback (body)
22815    -- ada.exceptions (body)
22816    -- system.unsigned_types (spec)
22817    -- system.stream_attributes (spec)
22818    -- system.stream_attributes (body)
22819    -- system.finalization_implementation (spec)
22820    -- system.finalization_implementation (body)
22821    -- ada.finalization (spec)
22822    -- ada.finalization (body)
22823    -- ada.finalization.list_controller (spec)
22824    -- ada.finalization.list_controller (body)
22825    -- system.file_control_block (spec)
22826    -- system.file_io (spec)
22827    -- system.file_io (body)
22828    -- ada.text_io (spec)
22829    -- ada.text_io (body)
22830    -- hello (body)
22831    -- END ELABORATION ORDER
22832
22833 end ada_main;
22834
22835 --  The following source file name pragmas allow the generated file
22836 --  names to be unique for different main programs. They are needed
22837 --  since the package name will always be Ada_Main.
22838
22839 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22840 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22841
22842 --  Generated package body for Ada_Main starts here
22843
22844 package body ada_main is
22845
22846    --  The actual finalization is performed by calling the
22847    --  library routine in System.Standard_Library.Adafinal
22848
22849    procedure Do_Finalize;
22850    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22851
22852    -------------
22853    -- adainit --
22854    -------------
22855
22856 @findex adainit
22857    procedure adainit is
22858
22859       --  These booleans are set to True once the associated unit has
22860       --  been elaborated. It is also used to avoid elaborating the
22861       --  same unit twice.
22862
22863       E040 : Boolean;
22864       pragma Import (Ada, E040, "interfaces__c_streams_E");
22865
22866       E008 : Boolean;
22867       pragma Import (Ada, E008, "ada__exceptions_E");
22868
22869       E014 : Boolean;
22870       pragma Import (Ada, E014, "system__exception_table_E");
22871
22872       E053 : Boolean;
22873       pragma Import (Ada, E053, "ada__io_exceptions_E");
22874
22875       E017 : Boolean;
22876       pragma Import (Ada, E017, "system__exceptions_E");
22877
22878       E024 : Boolean;
22879       pragma Import (Ada, E024, "system__secondary_stack_E");
22880
22881       E030 : Boolean;
22882       pragma Import (Ada, E030, "system__stack_checking_E");
22883
22884       E028 : Boolean;
22885       pragma Import (Ada, E028, "system__soft_links_E");
22886
22887       E035 : Boolean;
22888       pragma Import (Ada, E035, "ada__tags_E");
22889
22890       E033 : Boolean;
22891       pragma Import (Ada, E033, "ada__streams_E");
22892
22893       E046 : Boolean;
22894       pragma Import (Ada, E046, "system__finalization_root_E");
22895
22896       E048 : Boolean;
22897       pragma Import (Ada, E048, "system__finalization_implementation_E");
22898
22899       E044 : Boolean;
22900       pragma Import (Ada, E044, "ada__finalization_E");
22901
22902       E057 : Boolean;
22903       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22904
22905       E055 : Boolean;
22906       pragma Import (Ada, E055, "system__file_control_block_E");
22907
22908       E042 : Boolean;
22909       pragma Import (Ada, E042, "system__file_io_E");
22910
22911       E006 : Boolean;
22912       pragma Import (Ada, E006, "ada__text_io_E");
22913
22914       --  Set_Globals is a library routine that stores away the
22915       --  value of the indicated set of global values in global
22916       --  variables within the library.
22917
22918       procedure Set_Globals
22919         (Main_Priority            : Integer;
22920          Time_Slice_Value         : Integer;
22921          WC_Encoding              : Character;
22922          Locking_Policy           : Character;
22923          Queuing_Policy           : Character;
22924          Task_Dispatching_Policy  : Character;
22925          Adafinal                 : System.Address;
22926          Unreserve_All_Interrupts : Integer;
22927          Exception_Tracebacks     : Integer);
22928 @findex __gnat_set_globals
22929       pragma Import (C, Set_Globals, "__gnat_set_globals");
22930
22931       --  SDP_Table_Build is a library routine used to build the
22932       --  exception tables. See unit Ada.Exceptions in files
22933       --  a-except.ads/adb for full details of how zero cost
22934       --  exception handling works. This procedure, the call to
22935       --  it, and the two following tables are all omitted if the
22936       --  build is in longjmp/setjmp exception mode.
22937
22938 @findex SDP_Table_Build
22939 @findex Zero Cost Exceptions
22940       procedure SDP_Table_Build
22941         (SDP_Addresses   : System.Address;
22942          SDP_Count       : Natural;
22943          Elab_Addresses  : System.Address;
22944          Elab_Addr_Count : Natural);
22945       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22946
22947       --  Table of Unit_Exception_Table addresses. Used for zero
22948       --  cost exception handling to build the top level table.
22949
22950       ST : aliased constant array (1 .. 23) of System.Address := (
22951         Hello'UET_Address,
22952         Ada.Text_Io'UET_Address,
22953         Ada.Exceptions'UET_Address,
22954         Gnat.Heap_Sort_A'UET_Address,
22955         System.Exception_Table'UET_Address,
22956         System.Machine_State_Operations'UET_Address,
22957         System.Secondary_Stack'UET_Address,
22958         System.Parameters'UET_Address,
22959         System.Soft_Links'UET_Address,
22960         System.Stack_Checking'UET_Address,
22961         System.Traceback'UET_Address,
22962         Ada.Streams'UET_Address,
22963         Ada.Tags'UET_Address,
22964         System.String_Ops'UET_Address,
22965         Interfaces.C_Streams'UET_Address,
22966         System.File_Io'UET_Address,
22967         Ada.Finalization'UET_Address,
22968         System.Finalization_Root'UET_Address,
22969         System.Finalization_Implementation'UET_Address,
22970         System.String_Ops_Concat_3'UET_Address,
22971         System.Stream_Attributes'UET_Address,
22972         System.File_Control_Block'UET_Address,
22973         Ada.Finalization.List_Controller'UET_Address);
22974
22975       --  Table of addresses of elaboration routines. Used for
22976       --  zero cost exception handling to make sure these
22977       --  addresses are included in the top level procedure
22978       --  address table.
22979
22980       EA : aliased constant array (1 .. 23) of System.Address := (
22981         adainit'Code_Address,
22982         Do_Finalize'Code_Address,
22983         Ada.Exceptions'Elab_Spec'Address,
22984         System.Exceptions'Elab_Spec'Address,
22985         Interfaces.C_Streams'Elab_Spec'Address,
22986         System.Exception_Table'Elab_Body'Address,
22987         Ada.Io_Exceptions'Elab_Spec'Address,
22988         System.Stack_Checking'Elab_Spec'Address,
22989         System.Soft_Links'Elab_Body'Address,
22990         System.Secondary_Stack'Elab_Body'Address,
22991         Ada.Tags'Elab_Spec'Address,
22992         Ada.Tags'Elab_Body'Address,
22993         Ada.Streams'Elab_Spec'Address,
22994         System.Finalization_Root'Elab_Spec'Address,
22995         Ada.Exceptions'Elab_Body'Address,
22996         System.Finalization_Implementation'Elab_Spec'Address,
22997         System.Finalization_Implementation'Elab_Body'Address,
22998         Ada.Finalization'Elab_Spec'Address,
22999         Ada.Finalization.List_Controller'Elab_Spec'Address,
23000         System.File_Control_Block'Elab_Spec'Address,
23001         System.File_Io'Elab_Body'Address,
23002         Ada.Text_Io'Elab_Spec'Address,
23003         Ada.Text_Io'Elab_Body'Address);
23004
23005    --  Start of processing for adainit
23006
23007    begin
23008
23009       --  Call SDP_Table_Build to build the top level procedure
23010       --  table for zero cost exception handling (omitted in
23011       --  longjmp/setjmp mode).
23012
23013       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23014
23015       --  Call Set_Globals to record various information for
23016       --  this partition.  The values are derived by the binder
23017       --  from information stored in the ali files by the compiler.
23018
23019 @findex __gnat_set_globals
23020       Set_Globals
23021         (Main_Priority            => -1,
23022          --  Priority of main program, -1 if no pragma Priority used
23023
23024          Time_Slice_Value         => -1,
23025          --  Time slice from Time_Slice pragma, -1 if none used
23026
23027          WC_Encoding              => 'b',
23028          --  Wide_Character encoding used, default is brackets
23029
23030          Locking_Policy           => ' ',
23031          --  Locking_Policy used, default of space means not
23032          --  specified, otherwise it is the first character of
23033          --  the policy name.
23034
23035          Queuing_Policy           => ' ',
23036          --  Queuing_Policy used, default of space means not
23037          --  specified, otherwise it is the first character of
23038          --  the policy name.
23039
23040          Task_Dispatching_Policy  => ' ',
23041          --  Task_Dispatching_Policy used, default of space means
23042          --  not specified, otherwise first character of the
23043          --  policy name.
23044
23045          Adafinal                 => System.Null_Address,
23046          --  Address of Adafinal routine, not used anymore
23047
23048          Unreserve_All_Interrupts => 0,
23049          --  Set true if pragma Unreserve_All_Interrupts was used
23050
23051          Exception_Tracebacks     => 0);
23052          --  Indicates if exception tracebacks are enabled
23053
23054       Elab_Final_Code := 1;
23055
23056       --  Now we have the elaboration calls for all units in the partition.
23057       --  The Elab_Spec and Elab_Body attributes generate references to the
23058       --  implicit elaboration procedures generated by the compiler for
23059       --  each unit that requires elaboration.
23060
23061       if not E040 then
23062          Interfaces.C_Streams'Elab_Spec;
23063       end if;
23064       E040 := True;
23065       if not E008 then
23066          Ada.Exceptions'Elab_Spec;
23067       end if;
23068       if not E014 then
23069          System.Exception_Table'Elab_Body;
23070          E014 := True;
23071       end if;
23072       if not E053 then
23073          Ada.Io_Exceptions'Elab_Spec;
23074          E053 := True;
23075       end if;
23076       if not E017 then
23077          System.Exceptions'Elab_Spec;
23078          E017 := True;
23079       end if;
23080       if not E030 then
23081          System.Stack_Checking'Elab_Spec;
23082       end if;
23083       if not E028 then
23084          System.Soft_Links'Elab_Body;
23085          E028 := True;
23086       end if;
23087       E030 := True;
23088       if not E024 then
23089          System.Secondary_Stack'Elab_Body;
23090          E024 := True;
23091       end if;
23092       if not E035 then
23093          Ada.Tags'Elab_Spec;
23094       end if;
23095       if not E035 then
23096          Ada.Tags'Elab_Body;
23097          E035 := True;
23098       end if;
23099       if not E033 then
23100          Ada.Streams'Elab_Spec;
23101          E033 := True;
23102       end if;
23103       if not E046 then
23104          System.Finalization_Root'Elab_Spec;
23105       end if;
23106       E046 := True;
23107       if not E008 then
23108          Ada.Exceptions'Elab_Body;
23109          E008 := True;
23110       end if;
23111       if not E048 then
23112          System.Finalization_Implementation'Elab_Spec;
23113       end if;
23114       if not E048 then
23115          System.Finalization_Implementation'Elab_Body;
23116          E048 := True;
23117       end if;
23118       if not E044 then
23119          Ada.Finalization'Elab_Spec;
23120       end if;
23121       E044 := True;
23122       if not E057 then
23123          Ada.Finalization.List_Controller'Elab_Spec;
23124       end if;
23125       E057 := True;
23126       if not E055 then
23127          System.File_Control_Block'Elab_Spec;
23128          E055 := True;
23129       end if;
23130       if not E042 then
23131          System.File_Io'Elab_Body;
23132          E042 := True;
23133       end if;
23134       if not E006 then
23135          Ada.Text_Io'Elab_Spec;
23136       end if;
23137       if not E006 then
23138          Ada.Text_Io'Elab_Body;
23139          E006 := True;
23140       end if;
23141
23142       Elab_Final_Code := 0;
23143    end adainit;
23144
23145    --------------
23146    -- adafinal --
23147    --------------
23148
23149 @findex adafinal
23150    procedure adafinal is
23151    begin
23152       Do_Finalize;
23153    end adafinal;
23154
23155    ----------
23156    -- main --
23157    ----------
23158
23159    --  main is actually a function, as in the ANSI C standard,
23160    --  defined to return the exit status. The three parameters
23161    --  are the argument count, argument values and environment
23162    --  pointer.
23163
23164 @findex Main Program
23165    function main
23166      (argc : Integer;
23167       argv : System.Address;
23168       envp : System.Address)
23169       return Integer
23170    is
23171       --  The initialize routine performs low level system
23172       --  initialization using a standard library routine which
23173       --  sets up signal handling and performs any other
23174       --  required setup. The routine can be found in file
23175       --  a-init.c.
23176
23177 @findex __gnat_initialize
23178       procedure initialize;
23179       pragma Import (C, initialize, "__gnat_initialize");
23180
23181       --  The finalize routine performs low level system
23182       --  finalization using a standard library routine. The
23183       --  routine is found in file a-final.c and in the standard
23184       --  distribution is a dummy routine that does nothing, so
23185       --  really this is a hook for special user finalization.
23186
23187 @findex __gnat_finalize
23188       procedure finalize;
23189       pragma Import (C, finalize, "__gnat_finalize");
23190
23191       --  We get to the main program of the partition by using
23192       --  pragma Import because if we try to with the unit and
23193       --  call it Ada style, then not only do we waste time
23194       --  recompiling it, but also, we don't really know the right
23195       --  switches (e.g.@: identifier character set) to be used
23196       --  to compile it.
23197
23198       procedure Ada_Main_Program;
23199       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23200
23201    --  Start of processing for main
23202
23203    begin
23204       --  Save global variables
23205
23206       gnat_argc := argc;
23207       gnat_argv := argv;
23208       gnat_envp := envp;
23209
23210       --  Call low level system initialization
23211
23212       Initialize;
23213
23214       --  Call our generated Ada initialization routine
23215
23216       adainit;
23217
23218       --  This is the point at which we want the debugger to get
23219       --  control
23220
23221       Break_Start;
23222
23223       --  Now we call the main program of the partition
23224
23225       Ada_Main_Program;
23226
23227       --  Perform Ada finalization
23228
23229       adafinal;
23230
23231       --  Perform low level system finalization
23232
23233       Finalize;
23234
23235       --  Return the proper exit status
23236       return (gnat_exit_status);
23237    end;
23238
23239 --  This section is entirely comments, so it has no effect on the
23240 --  compilation of the Ada_Main package. It provides the list of
23241 --  object files and linker options, as well as some standard
23242 --  libraries needed for the link. The gnatlink utility parses
23243 --  this b~hello.adb file to read these comment lines to generate
23244 --  the appropriate command line arguments for the call to the
23245 --  system linker. The BEGIN/END lines are used for sentinels for
23246 --  this parsing operation.
23247
23248 --  The exact file names will of course depend on the environment,
23249 --  host/target and location of files on the host system.
23250
23251 @findex Object file list
23252 -- BEGIN Object file/option list
23253    --   ./hello.o
23254    --   -L./
23255    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23256    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23257 -- END Object file/option list
23258
23259 end ada_main;
23260 @end smallexample
23261
23262 @noindent
23263 The Ada code in the above example is exactly what is generated by the
23264 binder. We have added comments to more clearly indicate the function
23265 of each part of the generated @code{Ada_Main} package.
23266
23267 The code is standard Ada in all respects, and can be processed by any
23268 tools that handle Ada. In particular, it is possible to use the debugger
23269 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23270 suppose that for reasons that you do not understand, your program is crashing
23271 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23272 you can place a breakpoint on the call:
23273
23274 @smallexample @c ada
23275 Ada.Text_Io'Elab_Body;
23276 @end smallexample
23277
23278 @noindent
23279 and trace the elaboration routine for this package to find out where
23280 the problem might be (more usually of course you would be debugging
23281 elaboration code in your own application).
23282
23283 @node Elaboration Order Handling in GNAT
23284 @appendix Elaboration Order Handling in GNAT
23285 @cindex Order of elaboration
23286 @cindex Elaboration control
23287
23288 @menu
23289 * Elaboration Code::
23290 * Checking the Elaboration Order::
23291 * Controlling the Elaboration Order::
23292 * Controlling Elaboration in GNAT - Internal Calls::
23293 * Controlling Elaboration in GNAT - External Calls::
23294 * Default Behavior in GNAT - Ensuring Safety::
23295 * Treatment of Pragma Elaborate::
23296 * Elaboration Issues for Library Tasks::
23297 * Mixing Elaboration Models::
23298 * What to Do If the Default Elaboration Behavior Fails::
23299 * Elaboration for Access-to-Subprogram Values::
23300 * Summary of Procedures for Elaboration Control::
23301 * Other Elaboration Order Considerations::
23302 @end menu
23303
23304 @noindent
23305 This chapter describes the handling of elaboration code in Ada and
23306 in GNAT, and discusses how the order of elaboration of program units can
23307 be controlled in GNAT, either automatically or with explicit programming
23308 features.
23309
23310 @node Elaboration Code
23311 @section Elaboration Code
23312
23313 @noindent
23314 Ada provides rather general mechanisms for executing code at elaboration
23315 time, that is to say before the main program starts executing. Such code arises
23316 in three contexts:
23317
23318 @table @asis
23319 @item Initializers for variables.
23320 Variables declared at the library level, in package specs or bodies, can
23321 require initialization that is performed at elaboration time, as in:
23322 @smallexample @c ada
23323 @cartouche
23324 Sqrt_Half : Float := Sqrt (0.5);
23325 @end cartouche
23326 @end smallexample
23327
23328 @item Package initialization code
23329 Code in a @code{BEGIN-END} section at the outer level of a package body is
23330 executed as part of the package body elaboration code.
23331
23332 @item Library level task allocators
23333 Tasks that are declared using task allocators at the library level
23334 start executing immediately and hence can execute at elaboration time.
23335 @end table
23336
23337 @noindent
23338 Subprogram calls are possible in any of these contexts, which means that
23339 any arbitrary part of the program may be executed as part of the elaboration
23340 code. It is even possible to write a program which does all its work at
23341 elaboration time, with a null main program, although stylistically this
23342 would usually be considered an inappropriate way to structure
23343 a program.
23344
23345 An important concern arises in the context of elaboration code:
23346 we have to be sure that it is executed in an appropriate order. What we
23347 have is a series of elaboration code sections, potentially one section
23348 for each unit in the program. It is important that these execute
23349 in the correct order. Correctness here means that, taking the above
23350 example of the declaration of @code{Sqrt_Half},
23351 if some other piece of
23352 elaboration code references @code{Sqrt_Half},
23353 then it must run after the
23354 section of elaboration code that contains the declaration of
23355 @code{Sqrt_Half}.
23356
23357 There would never be any order of elaboration problem if we made a rule
23358 that whenever you @code{with} a unit, you must elaborate both the spec and body
23359 of that unit before elaborating the unit doing the @code{with}'ing:
23360
23361 @smallexample @c ada
23362 @group
23363 @cartouche
23364 with Unit_1;
23365 package Unit_2 is @dots{}
23366 @end cartouche
23367 @end group
23368 @end smallexample
23369
23370 @noindent
23371 would require that both the body and spec of @code{Unit_1} be elaborated
23372 before the spec of @code{Unit_2}. However, a rule like that would be far too
23373 restrictive. In particular, it would make it impossible to have routines
23374 in separate packages that were mutually recursive.
23375
23376 You might think that a clever enough compiler could look at the actual
23377 elaboration code and determine an appropriate correct order of elaboration,
23378 but in the general case, this is not possible. Consider the following
23379 example.
23380
23381 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23382 that references
23383 the variable @code{Sqrt_1}, which is declared in the elaboration code
23384 of the body of @code{Unit_1}:
23385
23386 @smallexample @c ada
23387 @cartouche
23388 Sqrt_1 : Float := Sqrt (0.1);
23389 @end cartouche
23390 @end smallexample
23391
23392 @noindent
23393 The elaboration code of the body of @code{Unit_1} also contains:
23394
23395 @smallexample @c ada
23396 @group
23397 @cartouche
23398 if expression_1 = 1 then
23399    Q := Unit_2.Func_2;
23400 end if;
23401 @end cartouche
23402 @end group
23403 @end smallexample
23404
23405 @noindent
23406 @code{Unit_2} is exactly parallel,
23407 it has a procedure @code{Func_2} that references
23408 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23409 the body @code{Unit_2}:
23410
23411 @smallexample @c ada
23412 @cartouche
23413 Sqrt_2 : Float := Sqrt (0.1);
23414 @end cartouche
23415 @end smallexample
23416
23417 @noindent
23418 The elaboration code of the body of @code{Unit_2} also contains:
23419
23420 @smallexample @c ada
23421 @group
23422 @cartouche
23423 if expression_2 = 2 then
23424    Q := Unit_1.Func_1;
23425 end if;
23426 @end cartouche
23427 @end group
23428 @end smallexample
23429
23430 @noindent
23431 Now the question is, which of the following orders of elaboration is
23432 acceptable:
23433
23434 @smallexample
23435 @group
23436 Spec of Unit_1
23437 Spec of Unit_2
23438 Body of Unit_1
23439 Body of Unit_2
23440 @end group
23441 @end smallexample
23442
23443 @noindent
23444 or
23445
23446 @smallexample
23447 @group
23448 Spec of Unit_2
23449 Spec of Unit_1
23450 Body of Unit_2
23451 Body of Unit_1
23452 @end group
23453 @end smallexample
23454
23455 @noindent
23456 If you carefully analyze the flow here, you will see that you cannot tell
23457 at compile time the answer to this question.
23458 If @code{expression_1} is not equal to 1,
23459 and @code{expression_2} is not equal to 2,
23460 then either order is acceptable, because neither of the function calls is
23461 executed. If both tests evaluate to true, then neither order is acceptable
23462 and in fact there is no correct order.
23463
23464 If one of the two expressions is true, and the other is false, then one
23465 of the above orders is correct, and the other is incorrect. For example,
23466 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23467 then the call to @code{Func_1}
23468 will occur, but not the call to @code{Func_2.}
23469 This means that it is essential
23470 to elaborate the body of @code{Unit_1} before
23471 the body of @code{Unit_2}, so the first
23472 order of elaboration is correct and the second is wrong.
23473
23474 By making @code{expression_1} and @code{expression_2}
23475 depend on input data, or perhaps
23476 the time of day, we can make it impossible for the compiler or binder
23477 to figure out which of these expressions will be true, and hence it
23478 is impossible to guarantee a safe order of elaboration at run time.
23479
23480 @node Checking the Elaboration Order
23481 @section Checking the Elaboration Order
23482
23483 @noindent
23484 In some languages that involve the same kind of elaboration problems,
23485 e.g.@: Java and C++, the programmer is expected to worry about these
23486 ordering problems himself, and it is common to
23487 write a program in which an incorrect elaboration order  gives
23488 surprising results, because it references variables before they
23489 are initialized.
23490 Ada is designed to be a safe language, and a programmer-beware approach is
23491 clearly not sufficient. Consequently, the language provides three lines
23492 of defense:
23493
23494 @table @asis
23495 @item Standard rules
23496 Some standard rules restrict the possible choice of elaboration
23497 order. In particular, if you @code{with} a unit, then its spec is always
23498 elaborated before the unit doing the @code{with}. Similarly, a parent
23499 spec is always elaborated before the child spec, and finally
23500 a spec is always elaborated before its corresponding body.
23501
23502 @item Dynamic elaboration checks
23503 @cindex Elaboration checks
23504 @cindex Checks, elaboration
23505 Dynamic checks are made at run time, so that if some entity is accessed
23506 before it is elaborated (typically  by means of a subprogram call)
23507 then the exception (@code{Program_Error}) is raised.
23508
23509 @item Elaboration control
23510 Facilities are provided for the programmer to specify the desired order
23511 of elaboration.
23512 @end table
23513
23514 Let's look at these facilities in more detail. First, the rules for
23515 dynamic checking. One possible rule would be simply to say that the
23516 exception is raised if you access a variable which has not yet been
23517 elaborated. The trouble with this approach is that it could require
23518 expensive checks on every variable reference. Instead Ada has two
23519 rules which are a little more restrictive, but easier to check, and
23520 easier to state:
23521
23522 @table @asis
23523 @item Restrictions on calls
23524 A subprogram can only be called at elaboration time if its body
23525 has been elaborated. The rules for elaboration given above guarantee
23526 that the spec of the subprogram has been elaborated before the
23527 call, but not the body. If this rule is violated, then the
23528 exception @code{Program_Error} is raised.
23529
23530 @item Restrictions on instantiations
23531 A generic unit can only be instantiated if the body of the generic
23532 unit has been elaborated. Again, the rules for elaboration given above
23533 guarantee that the spec of the generic unit has been elaborated
23534 before the instantiation, but not the body. If this rule is
23535 violated, then the exception @code{Program_Error} is raised.
23536 @end table
23537
23538 @noindent
23539 The idea is that if the body has been elaborated, then any variables
23540 it references must have been elaborated; by checking for the body being
23541 elaborated we guarantee that none of its references causes any
23542 trouble. As we noted above, this is a little too restrictive, because a
23543 subprogram that has no non-local references in its body may in fact be safe
23544 to call. However, it really would be unsafe to rely on this, because
23545 it would mean that the caller was aware of details of the implementation
23546 in the body. This goes against the basic tenets of Ada.
23547
23548 A plausible implementation can be described as follows.
23549 A Boolean variable is associated with each subprogram
23550 and each generic unit. This variable is initialized to False, and is set to
23551 True at the point body is elaborated. Every call or instantiation checks the
23552 variable, and raises @code{Program_Error} if the variable is False.
23553
23554 Note that one might think that it would be good enough to have one Boolean
23555 variable for each package, but that would not deal with cases of trying
23556 to call a body in the same package as the call
23557 that has not been elaborated yet.
23558 Of course a compiler may be able to do enough analysis to optimize away
23559 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23560 does such optimizations, but still the easiest conceptual model is to
23561 think of there being one variable per subprogram.
23562
23563 @node Controlling the Elaboration Order
23564 @section Controlling the Elaboration Order
23565
23566 @noindent
23567 In the previous section we discussed the rules in Ada which ensure
23568 that @code{Program_Error} is raised if an incorrect elaboration order is
23569 chosen. This prevents erroneous executions, but we need mechanisms to
23570 specify a correct execution and avoid the exception altogether.
23571 To achieve this, Ada provides a number of features for controlling
23572 the order of elaboration. We discuss these features in this section.
23573
23574 First, there are several ways of indicating to the compiler that a given
23575 unit has no elaboration problems:
23576
23577 @table @asis
23578 @item packages that do not require a body
23579 A library package that does not require a body does not permit
23580 a body (this rule was introduced in Ada 95).
23581 Thus if we have a such a package, as in:
23582
23583 @smallexample @c ada
23584 @group
23585 @cartouche
23586 package Definitions is
23587    generic
23588       type m is new integer;
23589    package Subp is
23590       type a is array (1 .. 10) of m;
23591       type b is array (1 .. 20) of m;
23592    end Subp;
23593 end Definitions;
23594 @end cartouche
23595 @end group
23596 @end smallexample
23597
23598 @noindent
23599 A package that @code{with}'s @code{Definitions} may safely instantiate
23600 @code{Definitions.Subp} because the compiler can determine that there
23601 definitely is no package body to worry about in this case
23602
23603 @item pragma Pure
23604 @cindex pragma Pure
23605 @findex Pure
23606 Places sufficient restrictions on a unit to guarantee that
23607 no call to any subprogram in the unit can result in an
23608 elaboration problem. This means that the compiler does not need
23609 to worry about the point of elaboration of such units, and in
23610 particular, does not need to check any calls to any subprograms
23611 in this unit.
23612
23613 @item pragma Preelaborate
23614 @findex Preelaborate
23615 @cindex pragma Preelaborate
23616 This pragma places slightly less stringent restrictions on a unit than
23617 does pragma Pure,
23618 but these restrictions are still sufficient to ensure that there
23619 are no elaboration problems with any calls to the unit.
23620
23621 @item pragma Elaborate_Body
23622 @findex Elaborate_Body
23623 @cindex pragma Elaborate_Body
23624 This pragma requires that the body of a unit be elaborated immediately
23625 after its spec. Suppose a unit @code{A} has such a pragma,
23626 and unit @code{B} does
23627 a @code{with} of unit @code{A}. Recall that the standard rules require
23628 the spec of unit @code{A}
23629 to be elaborated before the @code{with}'ing unit; given the pragma in
23630 @code{A}, we also know that the body of @code{A}
23631 will be elaborated before @code{B}, so
23632 that calls to @code{A} are safe and do not need a check.
23633 @end table
23634
23635 @noindent
23636 Note that,
23637 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23638 the use of
23639 @code{Elaborate_Body} does not guarantee that the program is
23640 free of elaboration problems, because it may not be possible
23641 to satisfy the requested elaboration order.
23642 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23643 If a programmer
23644 marks @code{Unit_1} as @code{Elaborate_Body},
23645 and not @code{Unit_2,} then the order of
23646 elaboration will be:
23647
23648 @smallexample
23649 @group
23650 Spec of Unit_2
23651 Spec of Unit_1
23652 Body of Unit_1
23653 Body of Unit_2
23654 @end group
23655 @end smallexample
23656
23657 @noindent
23658 Now that means that the call to @code{Func_1} in @code{Unit_2}
23659 need not be checked,
23660 it must be safe. But the call to @code{Func_2} in
23661 @code{Unit_1} may still fail if
23662 @code{Expression_1} is equal to 1,
23663 and the programmer must still take
23664 responsibility for this not being the case.
23665
23666 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23667 eliminated, except for calls entirely within a body, which are
23668 in any case fully under programmer control. However, using the pragma
23669 everywhere is not always possible.
23670 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23671 we marked both of them as having pragma @code{Elaborate_Body}, then
23672 clearly there would be no possible elaboration order.
23673
23674 The above pragmas allow a server to guarantee safe use by clients, and
23675 clearly this is the preferable approach. Consequently a good rule
23676 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23677 and if this is not possible,
23678 mark them as @code{Elaborate_Body} if possible.
23679 As we have seen, there are situations where neither of these
23680 three pragmas can be used.
23681 So we also provide methods for clients to control the
23682 order of elaboration of the servers on which they depend:
23683
23684 @table @asis
23685 @item pragma Elaborate (unit)
23686 @findex Elaborate
23687 @cindex pragma Elaborate
23688 This pragma is placed in the context clause, after a @code{with} clause,
23689 and it requires that the body of the named unit be elaborated before
23690 the unit in which the pragma occurs. The idea is to use this pragma
23691 if the current unit calls at elaboration time, directly or indirectly,
23692 some subprogram in the named unit.
23693
23694 @item pragma Elaborate_All (unit)
23695 @findex Elaborate_All
23696 @cindex pragma Elaborate_All
23697 This is a stronger version of the Elaborate pragma. Consider the
23698 following example:
23699
23700 @smallexample
23701 Unit A @code{with}'s unit B and calls B.Func in elab code
23702 Unit B @code{with}'s unit C, and B.Func calls C.Func
23703 @end smallexample
23704
23705 @noindent
23706 Now if we put a pragma @code{Elaborate (B)}
23707 in unit @code{A}, this ensures that the
23708 body of @code{B} is elaborated before the call, but not the
23709 body of @code{C}, so
23710 the call to @code{C.Func} could still cause @code{Program_Error} to
23711 be raised.
23712
23713 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23714 not only that the body of the named unit be elaborated before the
23715 unit doing the @code{with}, but also the bodies of all units that the
23716 named unit uses, following @code{with} links transitively. For example,
23717 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23718 then it requires
23719 not only that the body of @code{B} be elaborated before @code{A},
23720 but also the
23721 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23722 @end table
23723
23724 @noindent
23725 We are now in a position to give a usage rule in Ada for avoiding
23726 elaboration problems, at least if dynamic dispatching and access to
23727 subprogram values are not used. We will handle these cases separately
23728 later.
23729
23730 The rule is simple. If a unit has elaboration code that can directly or
23731 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23732 a generic package in a @code{with}'ed unit,
23733 then if the @code{with}'ed unit does not have
23734 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23735 a pragma @code{Elaborate_All}
23736 for the @code{with}'ed unit. By following this rule a client is
23737 assured that calls can be made without risk of an exception.
23738
23739 For generic subprogram instantiations, the rule can be relaxed to
23740 require only a pragma @code{Elaborate} since elaborating the body
23741 of a subprogram cannot cause any transitive elaboration (we are
23742 not calling the subprogram in this case, just elaborating its
23743 declaration).
23744
23745 If this rule is not followed, then a program may be in one of four
23746 states:
23747
23748 @table @asis
23749 @item No order exists
23750 No order of elaboration exists which follows the rules, taking into
23751 account any @code{Elaborate}, @code{Elaborate_All},
23752 or @code{Elaborate_Body} pragmas. In
23753 this case, an Ada compiler must diagnose the situation at bind
23754 time, and refuse to build an executable program.
23755
23756 @item One or more orders exist, all incorrect
23757 One or more acceptable elaboration orders exist, and all of them
23758 generate an elaboration order problem. In this case, the binder
23759 can build an executable program, but @code{Program_Error} will be raised
23760 when the program is run.
23761
23762 @item Several orders exist, some right, some incorrect
23763 One or more acceptable elaboration orders exists, and some of them
23764 work, and some do not. The programmer has not controlled
23765 the order of elaboration, so the binder may or may not pick one of
23766 the correct orders, and the program may or may not raise an
23767 exception when it is run. This is the worst case, because it means
23768 that the program may fail when moved to another compiler, or even
23769 another version of the same compiler.
23770
23771 @item One or more orders exists, all correct
23772 One ore more acceptable elaboration orders exist, and all of them
23773 work. In this case the program runs successfully. This state of
23774 affairs can be guaranteed by following the rule we gave above, but
23775 may be true even if the rule is not followed.
23776 @end table
23777
23778 @noindent
23779 Note that one additional advantage of following our rules on the use
23780 of @code{Elaborate} and @code{Elaborate_All}
23781 is that the program continues to stay in the ideal (all orders OK) state
23782 even if maintenance
23783 changes some bodies of some units. Conversely, if a program that does
23784 not follow this rule happens to be safe at some point, this state of affairs
23785 may deteriorate silently as a result of maintenance changes.
23786
23787 You may have noticed that the above discussion did not mention
23788 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23789 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23790 code in the body makes calls to some other unit, so it is still necessary
23791 to use @code{Elaborate_All} on such units.
23792
23793 @node Controlling Elaboration in GNAT - Internal Calls
23794 @section Controlling Elaboration in GNAT - Internal Calls
23795
23796 @noindent
23797 In the case of internal calls, i.e., calls within a single package, the
23798 programmer has full control over the order of elaboration, and it is up
23799 to the programmer to elaborate declarations in an appropriate order. For
23800 example writing:
23801
23802 @smallexample @c ada
23803 @group
23804 @cartouche
23805 function One return Float;
23806
23807 Q : Float := One;
23808
23809 function One return Float is
23810 begin
23811      return 1.0;
23812 end One;
23813 @end cartouche
23814 @end group
23815 @end smallexample
23816
23817 @noindent
23818 will obviously raise @code{Program_Error} at run time, because function
23819 One will be called before its body is elaborated. In this case GNAT will
23820 generate a warning that the call will raise @code{Program_Error}:
23821
23822 @smallexample
23823 @group
23824 @cartouche
23825  1. procedure y is
23826  2.    function One return Float;
23827  3.
23828  4.    Q : Float := One;
23829                     |
23830     >>> warning: cannot call "One" before body is elaborated
23831     >>> warning: Program_Error will be raised at run time
23832
23833  5.
23834  6.    function One return Float is
23835  7.    begin
23836  8.         return 1.0;
23837  9.    end One;
23838 10.
23839 11. begin
23840 12.    null;
23841 13. end;
23842 @end cartouche
23843 @end group
23844 @end smallexample
23845
23846 @noindent
23847 Note that in this particular case, it is likely that the call is safe, because
23848 the function @code{One} does not access any global variables.
23849 Nevertheless in Ada, we do not want the validity of the check to depend on
23850 the contents of the body (think about the separate compilation case), so this
23851 is still wrong, as we discussed in the previous sections.
23852
23853 The error is easily corrected by rearranging the declarations so that the
23854 body of @code{One} appears before the declaration containing the call
23855 (note that in Ada 95 and Ada 2005,
23856 declarations can appear in any order, so there is no restriction that
23857 would prevent this reordering, and if we write:
23858
23859 @smallexample @c ada
23860 @group
23861 @cartouche
23862 function One return Float;
23863
23864 function One return Float is
23865 begin
23866      return 1.0;
23867 end One;
23868
23869 Q : Float := One;
23870 @end cartouche
23871 @end group
23872 @end smallexample
23873
23874 @noindent
23875 then all is well, no warning is generated, and no
23876 @code{Program_Error} exception
23877 will be raised.
23878 Things are more complicated when a chain of subprograms is executed:
23879
23880 @smallexample @c ada
23881 @group
23882 @cartouche
23883 function A return Integer;
23884 function B return Integer;
23885 function C return Integer;
23886
23887 function B return Integer is begin return A; end;
23888 function C return Integer is begin return B; end;
23889
23890 X : Integer := C;
23891
23892 function A return Integer is begin return 1; end;
23893 @end cartouche
23894 @end group
23895 @end smallexample
23896
23897 @noindent
23898 Now the call to @code{C}
23899 at elaboration time in the declaration of @code{X} is correct, because
23900 the body of @code{C} is already elaborated,
23901 and the call to @code{B} within the body of
23902 @code{C} is correct, but the call
23903 to @code{A} within the body of @code{B} is incorrect, because the body
23904 of @code{A} has not been elaborated, so @code{Program_Error}
23905 will be raised on the call to @code{A}.
23906 In this case GNAT will generate a
23907 warning that @code{Program_Error} may be
23908 raised at the point of the call. Let's look at the warning:
23909
23910 @smallexample
23911 @group
23912 @cartouche
23913  1. procedure x is
23914  2.    function A return Integer;
23915  3.    function B return Integer;
23916  4.    function C return Integer;
23917  5.
23918  6.    function B return Integer is begin return A; end;
23919                                                     |
23920     >>> warning: call to "A" before body is elaborated may
23921                  raise Program_Error
23922     >>> warning: "B" called at line 7
23923     >>> warning: "C" called at line 9
23924
23925  7.    function C return Integer is begin return B; end;
23926  8.
23927  9.    X : Integer := C;
23928 10.
23929 11.    function A return Integer is begin return 1; end;
23930 12.
23931 13. begin
23932 14.    null;
23933 15. end;
23934 @end cartouche
23935 @end group
23936 @end smallexample
23937
23938 @noindent
23939 Note that the message here says ``may raise'', instead of the direct case,
23940 where the message says ``will be raised''. That's because whether
23941 @code{A} is
23942 actually called depends in general on run-time flow of control.
23943 For example, if the body of @code{B} said
23944
23945 @smallexample @c ada
23946 @group
23947 @cartouche
23948 function B return Integer is
23949 begin
23950    if some-condition-depending-on-input-data then
23951       return A;
23952    else
23953       return 1;
23954    end if;
23955 end B;
23956 @end cartouche
23957 @end group
23958 @end smallexample
23959
23960 @noindent
23961 then we could not know until run time whether the incorrect call to A would
23962 actually occur, so @code{Program_Error} might
23963 or might not be raised. It is possible for a compiler to
23964 do a better job of analyzing bodies, to
23965 determine whether or not @code{Program_Error}
23966 might be raised, but it certainly
23967 couldn't do a perfect job (that would require solving the halting problem
23968 and is provably impossible), and because this is a warning anyway, it does
23969 not seem worth the effort to do the analysis. Cases in which it
23970 would be relevant are rare.
23971
23972 In practice, warnings of either of the forms given
23973 above will usually correspond to
23974 real errors, and should be examined carefully and eliminated.
23975 In the rare case where a warning is bogus, it can be suppressed by any of
23976 the following methods:
23977
23978 @itemize @bullet
23979 @item
23980 Compile with the @option{-gnatws} switch set
23981
23982 @item
23983 Suppress @code{Elaboration_Check} for the called subprogram
23984
23985 @item
23986 Use pragma @code{Warnings_Off} to turn warnings off for the call
23987 @end itemize
23988
23989 @noindent
23990 For the internal elaboration check case,
23991 GNAT by default generates the
23992 necessary run-time checks to ensure
23993 that @code{Program_Error} is raised if any
23994 call fails an elaboration check. Of course this can only happen if a
23995 warning has been issued as described above. The use of pragma
23996 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23997 some of these checks, meaning that it may be possible (but is not
23998 guaranteed) for a program to be able to call a subprogram whose body
23999 is not yet elaborated, without raising a @code{Program_Error} exception.
24000
24001 @node Controlling Elaboration in GNAT - External Calls
24002 @section Controlling Elaboration in GNAT - External Calls
24003
24004 @noindent
24005 The previous section discussed the case in which the execution of a
24006 particular thread of elaboration code occurred entirely within a
24007 single unit. This is the easy case to handle, because a programmer
24008 has direct and total control over the order of elaboration, and
24009 furthermore, checks need only be generated in cases which are rare
24010 and which the compiler can easily detect.
24011 The situation is more complex when separate compilation is taken into account.
24012 Consider the following:
24013
24014 @smallexample @c ada
24015 @cartouche
24016 @group
24017 package Math is
24018    function Sqrt (Arg : Float) return Float;
24019 end Math;
24020
24021 package body Math is
24022    function Sqrt (Arg : Float) return Float is
24023    begin
24024          @dots{}
24025    end Sqrt;
24026 end Math;
24027 @end group
24028 @group
24029 with Math;
24030 package Stuff is
24031    X : Float := Math.Sqrt (0.5);
24032 end Stuff;
24033
24034 with Stuff;
24035 procedure Main is
24036 begin
24037    @dots{}
24038 end Main;
24039 @end group
24040 @end cartouche
24041 @end smallexample
24042
24043 @noindent
24044 where @code{Main} is the main program. When this program is executed, the
24045 elaboration code must first be executed, and one of the jobs of the
24046 binder is to determine the order in which the units of a program are
24047 to be elaborated. In this case we have four units: the spec and body
24048 of @code{Math},
24049 the spec of @code{Stuff} and the body of @code{Main}).
24050 In what order should the four separate sections of elaboration code
24051 be executed?
24052
24053 There are some restrictions in the order of elaboration that the binder
24054 can choose. In particular, if unit U has a @code{with}
24055 for a package @code{X}, then you
24056 are assured that the spec of @code{X}
24057 is elaborated before U , but you are
24058 not assured that the body of @code{X}
24059 is elaborated before U.
24060 This means that in the above case, the binder is allowed to choose the
24061 order:
24062
24063 @smallexample
24064 spec of Math
24065 spec of Stuff
24066 body of Math
24067 body of Main
24068 @end smallexample
24069
24070 @noindent
24071 but that's not good, because now the call to @code{Math.Sqrt}
24072 that happens during
24073 the elaboration of the @code{Stuff}
24074 spec happens before the body of @code{Math.Sqrt} is
24075 elaborated, and hence causes @code{Program_Error} exception to be raised.
24076 At first glance, one might say that the binder is misbehaving, because
24077 obviously you want to elaborate the body of something you @code{with}
24078 first, but
24079 that is not a general rule that can be followed in all cases. Consider
24080
24081 @smallexample @c ada
24082 @group
24083 @cartouche
24084 package X is @dots{}
24085
24086 package Y is @dots{}
24087
24088 with X;
24089 package body Y is @dots{}
24090
24091 with Y;
24092 package body X is @dots{}
24093 @end cartouche
24094 @end group
24095 @end smallexample
24096
24097 @noindent
24098 This is a common arrangement, and, apart from the order of elaboration
24099 problems that might arise in connection with elaboration code, this works fine.
24100 A rule that says that you must first elaborate the body of anything you
24101 @code{with} cannot work in this case:
24102 the body of @code{X} @code{with}'s @code{Y},
24103 which means you would have to
24104 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24105 which means
24106 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24107 loop that cannot be broken.
24108
24109 It is true that the binder can in many cases guess an order of elaboration
24110 that is unlikely to cause a @code{Program_Error}
24111 exception to be raised, and it tries to do so (in the
24112 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24113 by default
24114 elaborate the body of @code{Math} right after its spec, so all will be well).
24115
24116 However, a program that blindly relies on the binder to be helpful can
24117 get into trouble, as we discussed in the previous sections, so
24118 GNAT
24119 provides a number of facilities for assisting the programmer in
24120 developing programs that are robust with respect to elaboration order.
24121
24122 @node Default Behavior in GNAT - Ensuring Safety
24123 @section Default Behavior in GNAT - Ensuring Safety
24124
24125 @noindent
24126 The default behavior in GNAT ensures elaboration safety. In its
24127 default mode GNAT implements the
24128 rule we previously described as the right approach. Let's restate it:
24129
24130 @itemize
24131 @item
24132 @emph{If a unit has elaboration code that can directly or indirectly make a
24133 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24134 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24135 does not have pragma @code{Pure} or
24136 @code{Preelaborate}, then the client should have an
24137 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24138
24139 @emph{In the case of instantiating a generic subprogram, it is always
24140 sufficient to have only an @code{Elaborate} pragma for the
24141 @code{with}'ed unit.}
24142 @end itemize
24143
24144 @noindent
24145 By following this rule a client is assured that calls and instantiations
24146 can be made without risk of an exception.
24147
24148 In this mode GNAT traces all calls that are potentially made from
24149 elaboration code, and puts in any missing implicit @code{Elaborate}
24150 and @code{Elaborate_All} pragmas.
24151 The advantage of this approach is that no elaboration problems
24152 are possible if the binder can find an elaboration order that is
24153 consistent with these implicit @code{Elaborate} and
24154 @code{Elaborate_All} pragmas. The
24155 disadvantage of this approach is that no such order may exist.
24156
24157 If the binder does not generate any diagnostics, then it means that it has
24158 found an elaboration order that is guaranteed to be safe. However, the binder
24159 may still be relying on implicitly generated @code{Elaborate} and
24160 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24161 guaranteed.
24162
24163 If it is important to guarantee portability, then the compilations should
24164 use the
24165 @option{-gnatwl}
24166 (warn on elaboration problems) switch. This will cause warning messages
24167 to be generated indicating the missing @code{Elaborate} and
24168 @code{Elaborate_All} pragmas.
24169 Consider the following source program:
24170
24171 @smallexample @c ada
24172 @group
24173 @cartouche
24174 with k;
24175 package j is
24176   m : integer := k.r;
24177 end;
24178 @end cartouche
24179 @end group
24180 @end smallexample
24181
24182 @noindent
24183 where it is clear that there
24184 should be a pragma @code{Elaborate_All}
24185 for unit @code{k}. An implicit pragma will be generated, and it is
24186 likely that the binder will be able to honor it. However, if you want
24187 to port this program to some other Ada compiler than GNAT.
24188 it is safer to include the pragma explicitly in the source. If this
24189 unit is compiled with the
24190 @option{-gnatwl}
24191 switch, then the compiler outputs a warning:
24192
24193 @smallexample
24194 @group
24195 @cartouche
24196 1. with k;
24197 2. package j is
24198 3.   m : integer := k.r;
24199                      |
24200    >>> warning: call to "r" may raise Program_Error
24201    >>> warning: missing pragma Elaborate_All for "k"
24202
24203 4. end;
24204 @end cartouche
24205 @end group
24206 @end smallexample
24207
24208 @noindent
24209 and these warnings can be used as a guide for supplying manually
24210 the missing pragmas. It is usually a bad idea to use this warning
24211 option during development. That's because it will warn you when
24212 you need to put in a pragma, but cannot warn you when it is time
24213 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24214 unnecessary dependencies and even false circularities.
24215
24216 This default mode is more restrictive than the Ada Reference
24217 Manual, and it is possible to construct programs which will compile
24218 using the dynamic model described there, but will run into a
24219 circularity using the safer static model we have described.
24220
24221 Of course any Ada compiler must be able to operate in a mode
24222 consistent with the requirements of the Ada Reference Manual,
24223 and in particular must have the capability of implementing the
24224 standard dynamic model of elaboration with run-time checks.
24225
24226 In GNAT, this standard mode can be achieved either by the use of
24227 the @option{-gnatE} switch on the compiler (@command{gcc} or
24228 @command{gnatmake}) command, or by the use of the configuration pragma:
24229
24230 @smallexample @c ada
24231 pragma Elaboration_Checks (DYNAMIC);
24232 @end smallexample
24233
24234 @noindent
24235 Either approach will cause the unit affected to be compiled using the
24236 standard dynamic run-time elaboration checks described in the Ada
24237 Reference Manual. The static model is generally preferable, since it
24238 is clearly safer to rely on compile and link time checks rather than
24239 run-time checks. However, in the case of legacy code, it may be
24240 difficult to meet the requirements of the static model. This
24241 issue is further discussed in
24242 @ref{What to Do If the Default Elaboration Behavior Fails}.
24243
24244 Note that the static model provides a strict subset of the allowed
24245 behavior and programs of the Ada Reference Manual, so if you do
24246 adhere to the static model and no circularities exist,
24247 then you are assured that your program will
24248 work using the dynamic model, providing that you remove any
24249 pragma Elaborate statements from the source.
24250
24251 @node Treatment of Pragma Elaborate
24252 @section Treatment of Pragma Elaborate
24253 @cindex Pragma Elaborate
24254
24255 @noindent
24256 The use of @code{pragma Elaborate}
24257 should generally be avoided in Ada 95 and Ada 2005 programs,
24258 since there is no guarantee that transitive calls
24259 will be properly handled. Indeed at one point, this pragma was placed
24260 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24261
24262 Now that's a bit restrictive. In practice, the case in which
24263 @code{pragma Elaborate} is useful is when the caller knows that there
24264 are no transitive calls, or that the called unit contains all necessary
24265 transitive @code{pragma Elaborate} statements, and legacy code often
24266 contains such uses.
24267
24268 Strictly speaking the static mode in GNAT should ignore such pragmas,
24269 since there is no assurance at compile time that the necessary safety
24270 conditions are met. In practice, this would cause GNAT to be incompatible
24271 with correctly written Ada 83 code that had all necessary
24272 @code{pragma Elaborate} statements in place. Consequently, we made the
24273 decision that GNAT in its default mode will believe that if it encounters
24274 a @code{pragma Elaborate} then the programmer knows what they are doing,
24275 and it will trust that no elaboration errors can occur.
24276
24277 The result of this decision is two-fold. First to be safe using the
24278 static mode, you should remove all @code{pragma Elaborate} statements.
24279 Second, when fixing circularities in existing code, you can selectively
24280 use @code{pragma Elaborate} statements to convince the static mode of
24281 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24282 statement.
24283
24284 When using the static mode with @option{-gnatwl}, any use of
24285 @code{pragma Elaborate} will generate a warning about possible
24286 problems.
24287
24288 @node Elaboration Issues for Library Tasks
24289 @section Elaboration Issues for Library Tasks
24290 @cindex Library tasks, elaboration issues
24291 @cindex Elaboration of library tasks
24292
24293 @noindent
24294 In this section we examine special elaboration issues that arise for
24295 programs that declare library level tasks.
24296
24297 Generally the model of execution of an Ada program is that all units are
24298 elaborated, and then execution of the program starts. However, the
24299 declaration of library tasks definitely does not fit this model. The
24300 reason for this is that library tasks start as soon as they are declared
24301 (more precisely, as soon as the statement part of the enclosing package
24302 body is reached), that is to say before elaboration
24303 of the program is complete. This means that if such a task calls a
24304 subprogram, or an entry in another task, the callee may or may not be
24305 elaborated yet, and in the standard
24306 Reference Manual model of dynamic elaboration checks, you can even
24307 get timing dependent Program_Error exceptions, since there can be
24308 a race between the elaboration code and the task code.
24309
24310 The static model of elaboration in GNAT seeks to avoid all such
24311 dynamic behavior, by being conservative, and the conservative
24312 approach in this particular case is to assume that all the code
24313 in a task body is potentially executed at elaboration time if
24314 a task is declared at the library level.
24315
24316 This can definitely result in unexpected circularities. Consider
24317 the following example
24318
24319 @smallexample @c ada
24320 package Decls is
24321   task Lib_Task is
24322      entry Start;
24323   end Lib_Task;
24324
24325   type My_Int is new Integer;
24326
24327   function Ident (M : My_Int) return My_Int;
24328 end Decls;
24329
24330 with Utils;
24331 package body Decls is
24332   task body Lib_Task is
24333   begin
24334      accept Start;
24335      Utils.Put_Val (2);
24336   end Lib_Task;
24337
24338   function Ident (M : My_Int) return My_Int is
24339   begin
24340      return M;
24341   end Ident;
24342 end Decls;
24343
24344 with Decls;
24345 package Utils is
24346   procedure Put_Val (Arg : Decls.My_Int);
24347 end Utils;
24348
24349 with Text_IO;
24350 package body Utils is
24351   procedure Put_Val (Arg : Decls.My_Int) is
24352   begin
24353      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24354   end Put_Val;
24355 end Utils;
24356
24357 with Decls;
24358 procedure Main is
24359 begin
24360    Decls.Lib_Task.Start;
24361 end;
24362 @end smallexample
24363
24364 @noindent
24365 If the above example is compiled in the default static elaboration
24366 mode, then a circularity occurs. The circularity comes from the call
24367 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24368 this call occurs in elaboration code, we need an implicit pragma
24369 @code{Elaborate_All} for @code{Utils}. This means that not only must
24370 the spec and body of @code{Utils} be elaborated before the body
24371 of @code{Decls}, but also the spec and body of any unit that is
24372 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24373 the body of @code{Decls}. This is the transitive implication of
24374 pragma @code{Elaborate_All} and it makes sense, because in general
24375 the body of @code{Put_Val} might have a call to something in a
24376 @code{with'ed} unit.
24377
24378 In this case, the body of Utils (actually its spec) @code{with's}
24379 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24380 must be elaborated before itself, in case there is a call from the
24381 body of @code{Utils}.
24382
24383 Here is the exact chain of events we are worrying about:
24384
24385 @enumerate
24386 @item
24387 In the body of @code{Decls} a call is made from within the body of a library
24388 task to a subprogram in the package @code{Utils}. Since this call may
24389 occur at elaboration time (given that the task is activated at elaboration
24390 time), we have to assume the worst, i.e., that the
24391 call does happen at elaboration time.
24392
24393 @item
24394 This means that the body and spec of @code{Util} must be elaborated before
24395 the body of @code{Decls} so that this call does not cause an access before
24396 elaboration.
24397
24398 @item
24399 Within the body of @code{Util}, specifically within the body of
24400 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24401 by this package.
24402
24403 @item
24404 One such @code{with}'ed package is package @code{Decls}, so there
24405 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24406 In fact there is such a call in this example, but we would have to
24407 assume that there was such a call even if it were not there, since
24408 we are not supposed to write the body of @code{Decls} knowing what
24409 is in the body of @code{Utils}; certainly in the case of the
24410 static elaboration model, the compiler does not know what is in
24411 other bodies and must assume the worst.
24412
24413 @item
24414 This means that the spec and body of @code{Decls} must also be
24415 elaborated before we elaborate the unit containing the call, but
24416 that unit is @code{Decls}! This means that the body of @code{Decls}
24417 must be elaborated before itself, and that's a circularity.
24418 @end enumerate
24419
24420 @noindent
24421 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24422 the body of @code{Decls} you will get a true Ada Reference Manual
24423 circularity that makes the program illegal.
24424
24425 In practice, we have found that problems with the static model of
24426 elaboration in existing code often arise from library tasks, so
24427 we must address this particular situation.
24428
24429 Note that if we compile and run the program above, using the dynamic model of
24430 elaboration (that is to say use the @option{-gnatE} switch),
24431 then it compiles, binds,
24432 links, and runs, printing the expected result of 2. Therefore in some sense
24433 the circularity here is only apparent, and we need to capture
24434 the properties of this program that  distinguish it from other library-level
24435 tasks that have real elaboration problems.
24436
24437 We have four possible answers to this question:
24438
24439 @itemize @bullet
24440
24441 @item
24442 Use the dynamic model of elaboration.
24443
24444 If we use the @option{-gnatE} switch, then as noted above, the program works.
24445 Why is this? If we examine the task body, it is apparent that the task cannot
24446 proceed past the
24447 @code{accept} statement until after elaboration has been completed, because
24448 the corresponding entry call comes from the main program, not earlier.
24449 This is why the dynamic model works here. But that's really giving
24450 up on a precise analysis, and we prefer to take this approach only if we cannot
24451 solve the
24452 problem in any other manner. So let us examine two ways to reorganize
24453 the program to avoid the potential elaboration problem.
24454
24455 @item
24456 Split library tasks into separate packages.
24457
24458 Write separate packages, so that library tasks are isolated from
24459 other declarations as much as possible. Let us look at a variation on
24460 the above program.
24461
24462 @smallexample @c ada
24463 package Decls1 is
24464   task Lib_Task is
24465      entry Start;
24466   end Lib_Task;
24467 end Decls1;
24468
24469 with Utils;
24470 package body Decls1 is
24471   task body Lib_Task is
24472   begin
24473      accept Start;
24474      Utils.Put_Val (2);
24475   end Lib_Task;
24476 end Decls1;
24477
24478 package Decls2 is
24479   type My_Int is new Integer;
24480   function Ident (M : My_Int) return My_Int;
24481 end Decls2;
24482
24483 with Utils;
24484 package body Decls2 is
24485   function Ident (M : My_Int) return My_Int is
24486   begin
24487      return M;
24488   end Ident;
24489 end Decls2;
24490
24491 with Decls2;
24492 package Utils is
24493   procedure Put_Val (Arg : Decls2.My_Int);
24494 end Utils;
24495
24496 with Text_IO;
24497 package body Utils is
24498   procedure Put_Val (Arg : Decls2.My_Int) is
24499   begin
24500      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24501   end Put_Val;
24502 end Utils;
24503
24504 with Decls1;
24505 procedure Main is
24506 begin
24507    Decls1.Lib_Task.Start;
24508 end;
24509 @end smallexample
24510
24511 @noindent
24512 All we have done is to split @code{Decls} into two packages, one
24513 containing the library task, and one containing everything else. Now
24514 there is no cycle, and the program compiles, binds, links and executes
24515 using the default static model of elaboration.
24516
24517 @item
24518 Declare separate task types.
24519
24520 A significant part of the problem arises because of the use of the
24521 single task declaration form. This means that the elaboration of
24522 the task type, and the elaboration of the task itself (i.e.@: the
24523 creation of the task) happen at the same time. A good rule
24524 of style in Ada is to always create explicit task types. By
24525 following the additional step of placing task objects in separate
24526 packages from the task type declaration, many elaboration problems
24527 are avoided. Here is another modified example of the example program:
24528
24529 @smallexample @c ada
24530 package Decls is
24531   task type Lib_Task_Type is
24532      entry Start;
24533   end Lib_Task_Type;
24534
24535   type My_Int is new Integer;
24536
24537   function Ident (M : My_Int) return My_Int;
24538 end Decls;
24539
24540 with Utils;
24541 package body Decls is
24542   task body Lib_Task_Type is
24543   begin
24544      accept Start;
24545      Utils.Put_Val (2);
24546   end Lib_Task_Type;
24547
24548   function Ident (M : My_Int) return My_Int is
24549   begin
24550      return M;
24551   end Ident;
24552 end Decls;
24553
24554 with Decls;
24555 package Utils is
24556   procedure Put_Val (Arg : Decls.My_Int);
24557 end Utils;
24558
24559 with Text_IO;
24560 package body Utils is
24561   procedure Put_Val (Arg : Decls.My_Int) is
24562   begin
24563      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24564   end Put_Val;
24565 end Utils;
24566
24567 with Decls;
24568 package Declst is
24569    Lib_Task : Decls.Lib_Task_Type;
24570 end Declst;
24571
24572 with Declst;
24573 procedure Main is
24574 begin
24575    Declst.Lib_Task.Start;
24576 end;
24577 @end smallexample
24578
24579 @noindent
24580 What we have done here is to replace the @code{task} declaration in
24581 package @code{Decls} with a @code{task type} declaration. Then we
24582 introduce a separate package @code{Declst} to contain the actual
24583 task object. This separates the elaboration issues for
24584 the @code{task type}
24585 declaration, which causes no trouble, from the elaboration issues
24586 of the task object, which is also unproblematic, since it is now independent
24587 of the elaboration of  @code{Utils}.
24588 This separation of concerns also corresponds to
24589 a generally sound engineering principle of separating declarations
24590 from instances. This version of the program also compiles, binds, links,
24591 and executes, generating the expected output.
24592
24593 @item
24594 Use No_Entry_Calls_In_Elaboration_Code restriction.
24595 @cindex No_Entry_Calls_In_Elaboration_Code
24596
24597 The previous two approaches described how a program can be restructured
24598 to avoid the special problems caused by library task bodies. in practice,
24599 however, such restructuring may be difficult to apply to existing legacy code,
24600 so we must consider solutions that do not require massive rewriting.
24601
24602 Let us consider more carefully why our original sample program works
24603 under the dynamic model of elaboration. The reason is that the code
24604 in the task body blocks immediately on the @code{accept}
24605 statement. Now of course there is nothing to prohibit elaboration
24606 code from making entry calls (for example from another library level task),
24607 so we cannot tell in isolation that
24608 the task will not execute the accept statement  during elaboration.
24609
24610 However, in practice it is very unusual to see elaboration code
24611 make any entry calls, and the pattern of tasks starting
24612 at elaboration time and then immediately blocking on @code{accept} or
24613 @code{select} statements is very common. What this means is that
24614 the compiler is being too pessimistic when it analyzes the
24615 whole package body as though it might be executed at elaboration
24616 time.
24617
24618 If we know that the elaboration code contains no entry calls, (a very safe
24619 assumption most of the time, that could almost be made the default
24620 behavior), then we can compile all units of the program under control
24621 of the following configuration pragma:
24622
24623 @smallexample
24624 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24625 @end smallexample
24626
24627 @noindent
24628 This pragma can be placed in the @file{gnat.adc} file in the usual
24629 manner. If we take our original unmodified program and compile it
24630 in the presence of a @file{gnat.adc} containing the above pragma,
24631 then once again, we can compile, bind, link, and execute, obtaining
24632 the expected result. In the presence of this pragma, the compiler does
24633 not trace calls in a task body, that appear after the first @code{accept}
24634 or @code{select} statement, and therefore does not report a potential
24635 circularity in the original program.
24636
24637 The compiler will check to the extent it can that the above
24638 restriction is not violated, but it is not always possible to do a
24639 complete check at compile time, so it is important to use this
24640 pragma only if the stated restriction is in fact met, that is to say
24641 no task receives an entry call before elaboration of all units is completed.
24642
24643 @end itemize
24644
24645 @node Mixing Elaboration Models
24646 @section Mixing Elaboration Models
24647 @noindent
24648 So far, we have assumed that the entire program is either compiled
24649 using the dynamic model or static model, ensuring consistency. It
24650 is possible to mix the two models, but rules have to be followed
24651 if this mixing is done to ensure that elaboration checks are not
24652 omitted.
24653
24654 The basic rule is that @emph{a unit compiled with the static model cannot
24655 be @code{with'ed} by a unit compiled with the dynamic model}. The
24656 reason for this is that in the static model, a unit assumes that
24657 its clients guarantee to use (the equivalent of) pragma
24658 @code{Elaborate_All} so that no elaboration checks are required
24659 in inner subprograms, and this assumption is violated if the
24660 client is compiled with dynamic checks.
24661
24662 The precise rule is as follows. A unit that is compiled with dynamic
24663 checks can only @code{with} a unit that meets at least one of the
24664 following criteria:
24665
24666 @itemize @bullet
24667
24668 @item
24669 The @code{with'ed} unit is itself compiled with dynamic elaboration
24670 checks (that is with the @option{-gnatE} switch.
24671
24672 @item
24673 The @code{with'ed} unit is an internal GNAT implementation unit from
24674 the System, Interfaces, Ada, or GNAT hierarchies.
24675
24676 @item
24677 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24678
24679 @item
24680 The @code{with'ing} unit (that is the client) has an explicit pragma
24681 @code{Elaborate_All} for the @code{with'ed} unit.
24682
24683 @end itemize
24684
24685 @noindent
24686 If this rule is violated, that is if a unit with dynamic elaboration
24687 checks @code{with's} a unit that does not meet one of the above four
24688 criteria, then the binder (@code{gnatbind}) will issue a warning
24689 similar to that in the following example:
24690
24691 @smallexample
24692 warning: "x.ads" has dynamic elaboration checks and with's
24693 warning:   "y.ads" which has static elaboration checks
24694 @end smallexample
24695
24696 @noindent
24697 These warnings indicate that the rule has been violated, and that as a result
24698 elaboration checks may be missed in the resulting executable file.
24699 This warning may be suppressed using the @option{-ws} binder switch
24700 in the usual manner.
24701
24702 One useful application of this mixing rule is in the case of a subsystem
24703 which does not itself @code{with} units from the remainder of the
24704 application. In this case, the entire subsystem can be compiled with
24705 dynamic checks to resolve a circularity in the subsystem, while
24706 allowing the main application that uses this subsystem to be compiled
24707 using the more reliable default static model.
24708
24709 @node What to Do If the Default Elaboration Behavior Fails
24710 @section What to Do If the Default Elaboration Behavior Fails
24711
24712 @noindent
24713 If the binder cannot find an acceptable order, it outputs detailed
24714 diagnostics. For example:
24715 @smallexample
24716 @group
24717 @iftex
24718 @leftskip=0cm
24719 @end iftex
24720 error: elaboration circularity detected
24721 info:   "proc (body)" must be elaborated before "pack (body)"
24722 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24723 info:     recompile "pack (body)" with -gnatwl
24724 info:                             for full details
24725 info:       "proc (body)"
24726 info:         is needed by its spec:
24727 info:       "proc (spec)"
24728 info:         which is withed by:
24729 info:       "pack (body)"
24730 info:  "pack (body)" must be elaborated before "proc (body)"
24731 info:     reason: pragma Elaborate in unit "proc (body)"
24732 @end group
24733
24734 @end smallexample
24735
24736 @noindent
24737 In this case we have a cycle that the binder cannot break. On the one
24738 hand, there is an explicit pragma Elaborate in @code{proc} for
24739 @code{pack}. This means that the body of @code{pack} must be elaborated
24740 before the body of @code{proc}. On the other hand, there is elaboration
24741 code in @code{pack} that calls a subprogram in @code{proc}. This means
24742 that for maximum safety, there should really be a pragma
24743 Elaborate_All in @code{pack} for @code{proc} which would require that
24744 the body of @code{proc} be elaborated before the body of
24745 @code{pack}. Clearly both requirements cannot be satisfied.
24746 Faced with a circularity of this kind, you have three different options.
24747
24748 @table @asis
24749 @item Fix the program
24750 The most desirable option from the point of view of long-term maintenance
24751 is to rearrange the program so that the elaboration problems are avoided.
24752 One useful technique is to place the elaboration code into separate
24753 child packages. Another is to move some of the initialization code to
24754 explicitly called subprograms, where the program controls the order
24755 of initialization explicitly. Although this is the most desirable option,
24756 it may be impractical and involve too much modification, especially in
24757 the case of complex legacy code.
24758
24759 @item Perform dynamic checks
24760 If the compilations are done using the
24761 @option{-gnatE}
24762 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24763 manner. Dynamic checks are generated for all calls that could possibly result
24764 in raising an exception. With this switch, the compiler does not generate
24765 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24766 exactly as specified in the @cite{Ada Reference Manual}.
24767 The binder will generate
24768 an executable program that may or may not raise @code{Program_Error}, and then
24769 it is the programmer's job to ensure that it does not raise an exception. Note
24770 that it is important to compile all units with the switch, it cannot be used
24771 selectively.
24772
24773 @item Suppress checks
24774 The drawback of dynamic checks is that they generate a
24775 significant overhead at run time, both in space and time. If you
24776 are absolutely sure that your program cannot raise any elaboration
24777 exceptions, and you still want to use the dynamic elaboration model,
24778 then you can use the configuration pragma
24779 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24780 example this pragma could be placed in the @file{gnat.adc} file.
24781
24782 @item Suppress checks selectively
24783 When you know that certain calls or instantiations in elaboration code cannot
24784 possibly lead to an elaboration error, and the binder nevertheless complains
24785 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24786 elaboration circularities, it is possible to remove those warnings locally and
24787 obtain a program that will bind. Clearly this can be unsafe, and it is the
24788 responsibility of the programmer to make sure that the resulting program has no
24789 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24790 used with different granularity to suppress warnings and break elaboration
24791 circularities:
24792
24793 @itemize @bullet
24794 @item
24795 Place the pragma that names the called subprogram in the declarative part
24796 that contains the call.
24797
24798 @item
24799 Place the pragma in the declarative part, without naming an entity. This
24800 disables warnings on all calls in the corresponding  declarative region.
24801
24802 @item
24803 Place the pragma in the package spec that declares the called subprogram,
24804 and name the subprogram. This disables warnings on all elaboration calls to
24805 that subprogram.
24806
24807 @item
24808 Place the pragma in the package spec that declares the called subprogram,
24809 without naming any entity. This disables warnings on all elaboration calls to
24810 all subprograms declared in this spec.
24811
24812 @item Use Pragma Elaborate
24813 As previously described in section @xref{Treatment of Pragma Elaborate},
24814 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24815 that no elaboration checks are required on calls to the designated unit.
24816 There may be cases in which the caller knows that no transitive calls
24817 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24818 case where @code{pragma Elaborate_All} would cause a circularity.
24819 @end itemize
24820
24821 @noindent
24822 These five cases are listed in order of decreasing safety, and therefore
24823 require increasing programmer care in their application. Consider the
24824 following program:
24825
24826 @smallexample @c adanocomment
24827 package Pack1 is
24828   function F1 return Integer;
24829   X1 : Integer;
24830 end Pack1;
24831
24832 package Pack2 is
24833   function F2 return Integer;
24834   function Pure (x : integer) return integer;
24835   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24836   --  pragma Suppress (Elaboration_Check);              -- (4)
24837 end Pack2;
24838
24839 with Pack2;
24840 package body Pack1 is
24841   function F1 return Integer is
24842   begin
24843     return 100;
24844   end F1;
24845   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24846 begin
24847   declare
24848     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24849     --  pragma Suppress(Elaboration_Check);             -- (2)
24850   begin
24851     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24852   end;
24853 end Pack1;
24854
24855 with Pack1;
24856 package body Pack2 is
24857   function F2 return Integer is
24858   begin
24859      return Pack1.F1;
24860   end F2;
24861   function Pure (x : integer) return integer is
24862   begin
24863      return x ** 3 - 3 * x;
24864   end;
24865 end Pack2;
24866
24867 with Pack1, Ada.Text_IO;
24868 procedure Proc3 is
24869 begin
24870   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24871 end Proc3;
24872 @end smallexample
24873 In the absence of any pragmas, an attempt to bind this program produces
24874 the following diagnostics:
24875 @smallexample
24876 @group
24877 @iftex
24878 @leftskip=.5cm
24879 @end iftex
24880 error: elaboration circularity detected
24881 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24882 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24883 info:       recompile "pack1 (body)" with -gnatwl for full details
24884 info:          "pack1 (body)"
24885 info:             must be elaborated along with its spec:
24886 info:          "pack1 (spec)"
24887 info:             which is withed by:
24888 info:          "pack2 (body)"
24889 info:             which must be elaborated along with its spec:
24890 info:          "pack2 (spec)"
24891 info:             which is withed by:
24892 info:          "pack1 (body)"
24893 @end group
24894 @end smallexample
24895 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24896 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24897 F2 is safe, even though F2 calls F1, because the call appears after the
24898 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24899 remove the warning on the call. It is also possible to use pragma (2)
24900 because there are no other potentially unsafe calls in the block.
24901
24902 @noindent
24903 The call to @code{Pure} is safe because this function does not depend on the
24904 state of @code{Pack2}. Therefore any call to this function is safe, and it
24905 is correct to place pragma (3) in the corresponding package spec.
24906
24907 @noindent
24908 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24909 warnings on all calls to functions declared therein. Note that this is not
24910 necessarily safe, and requires more detailed examination of the subprogram
24911 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24912 be already elaborated.
24913 @end table
24914
24915 @noindent
24916 It is hard to generalize on which of these four approaches should be
24917 taken. Obviously if it is possible to fix the program so that the default
24918 treatment works, this is preferable, but this may not always be practical.
24919 It is certainly simple enough to use
24920 @option{-gnatE}
24921 but the danger in this case is that, even if the GNAT binder
24922 finds a correct elaboration order, it may not always do so,
24923 and certainly a binder from another Ada compiler might not. A
24924 combination of testing and analysis (for which the warnings generated
24925 with the
24926 @option{-gnatwl}
24927 switch can be useful) must be used to ensure that the program is free
24928 of errors. One switch that is useful in this testing is the
24929 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24930 switch for
24931 @code{gnatbind}.
24932 Normally the binder tries to find an order that has the best chance
24933 of avoiding elaboration problems. However, if this switch is used, the binder
24934 plays a devil's advocate role, and tries to choose the order that
24935 has the best chance of failing. If your program works even with this
24936 switch, then it has a better chance of being error free, but this is still
24937 not a guarantee.
24938
24939 For an example of this approach in action, consider the C-tests (executable
24940 tests) from the ACVC suite. If these are compiled and run with the default
24941 treatment, then all but one of them succeed without generating any error
24942 diagnostics from the binder. However, there is one test that fails, and
24943 this is not surprising, because the whole point of this test is to ensure
24944 that the compiler can handle cases where it is impossible to determine
24945 a correct order statically, and it checks that an exception is indeed
24946 raised at run time.
24947
24948 This one test must be compiled and run using the
24949 @option{-gnatE}
24950 switch, and then it passes. Alternatively, the entire suite can
24951 be run using this switch. It is never wrong to run with the dynamic
24952 elaboration switch if your code is correct, and we assume that the
24953 C-tests are indeed correct (it is less efficient, but efficiency is
24954 not a factor in running the ACVC tests.)
24955
24956 @node Elaboration for Access-to-Subprogram Values
24957 @section Elaboration for Access-to-Subprogram Values
24958 @cindex Access-to-subprogram
24959
24960 @noindent
24961 Access-to-subprogram types (introduced in Ada 95) complicate
24962 the handling of elaboration. The trouble is that it becomes
24963 impossible to tell at compile time which procedure
24964 is being called. This means that it is not possible for the binder
24965 to analyze the elaboration requirements in this case.
24966
24967 If at the point at which the access value is created
24968 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24969 the body of the subprogram is
24970 known to have been elaborated, then the access value is safe, and its use
24971 does not require a check. This may be achieved by appropriate arrangement
24972 of the order of declarations if the subprogram is in the current unit,
24973 or, if the subprogram is in another unit, by using pragma
24974 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24975 on the referenced unit.
24976
24977 If the referenced body is not known to have been elaborated at the point
24978 the access value is created, then any use of the access value must do a
24979 dynamic check, and this dynamic check will fail and raise a
24980 @code{Program_Error} exception if the body has not been elaborated yet.
24981 GNAT will generate the necessary checks, and in addition, if the
24982 @option{-gnatwl}
24983 switch is set, will generate warnings that such checks are required.
24984
24985 The use of dynamic dispatching for tagged types similarly generates
24986 a requirement for dynamic checks, and premature calls to any primitive
24987 operation of a tagged type before the body of the operation has been
24988 elaborated, will result in the raising of @code{Program_Error}.
24989
24990 @node Summary of Procedures for Elaboration Control
24991 @section Summary of Procedures for Elaboration Control
24992 @cindex Elaboration control
24993
24994 @noindent
24995 First, compile your program with the default options, using none of
24996 the special elaboration control switches. If the binder successfully
24997 binds your program, then you can be confident that, apart from issues
24998 raised by the use of access-to-subprogram types and dynamic dispatching,
24999 the program is free of elaboration errors. If it is important that the
25000 program be portable, then use the
25001 @option{-gnatwl}
25002 switch to generate warnings about missing @code{Elaborate} or
25003 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25004
25005 If the program fails to bind using the default static elaboration
25006 handling, then you can fix the program to eliminate the binder
25007 message, or recompile the entire program with the
25008 @option{-gnatE} switch to generate dynamic elaboration checks,
25009 and, if you are sure there really are no elaboration problems,
25010 use a global pragma @code{Suppress (Elaboration_Check)}.
25011
25012 @node Other Elaboration Order Considerations
25013 @section Other Elaboration Order Considerations
25014 @noindent
25015 This section has been entirely concerned with the issue of finding a valid
25016 elaboration order, as defined by the Ada Reference Manual. In a case
25017 where several elaboration orders are valid, the task is to find one
25018 of the possible valid elaboration orders (and the static model in GNAT
25019 will ensure that this is achieved).
25020
25021 The purpose of the elaboration rules in the Ada Reference Manual is to
25022 make sure that no entity is accessed before it has been elaborated. For
25023 a subprogram, this means that the spec and body must have been elaborated
25024 before the subprogram is called. For an object, this means that the object
25025 must have been elaborated before its value is read or written. A violation
25026 of either of these two requirements is an access before elaboration order,
25027 and this section has been all about avoiding such errors.
25028
25029 In the case where more than one order of elaboration is possible, in the
25030 sense that access before elaboration errors are avoided, then any one of
25031 the orders is ``correct'' in the sense that it meets the requirements of
25032 the Ada Reference Manual, and no such error occurs.
25033
25034 However, it may be the case for a given program, that there are
25035 constraints on the order of elaboration that come not from consideration
25036 of avoiding elaboration errors, but rather from extra-lingual logic
25037 requirements. Consider this example:
25038
25039 @smallexample @c ada
25040 with Init_Constants;
25041 package Constants is
25042    X : Integer := 0;
25043    Y : Integer := 0;
25044 end Constants;
25045
25046 package Init_Constants is
25047    procedure P; -- require a body
25048 end Init_Constants;
25049
25050 with Constants;
25051 package body Init_Constants is
25052    procedure P is begin null; end;
25053 begin
25054    Constants.X := 3;
25055    Constants.Y := 4;
25056 end Init_Constants;
25057
25058 with Constants;
25059 package Calc is
25060    Z : Integer := Constants.X + Constants.Y;
25061 end Calc;
25062
25063 with Calc;
25064 with Text_IO; use Text_IO;
25065 procedure Main is
25066 begin
25067    Put_Line (Calc.Z'Img);
25068 end Main;
25069 @end smallexample
25070
25071 @noindent
25072 In this example, there is more than one valid order of elaboration. For
25073 example both the following are correct orders:
25074
25075 @smallexample
25076 Init_Constants spec
25077 Constants spec
25078 Calc spec
25079 Init_Constants body
25080 Main body
25081
25082   and
25083
25084 Init_Constants spec
25085 Init_Constants body
25086 Constants spec
25087 Calc spec
25088 Main body
25089 @end smallexample
25090
25091 @noindent
25092 There is no language rule to prefer one or the other, both are correct
25093 from an order of elaboration point of view. But the programmatic effects
25094 of the two orders are very different. In the first, the elaboration routine
25095 of @code{Calc} initializes @code{Z} to zero, and then the main program
25096 runs with this value of zero. But in the second order, the elaboration
25097 routine of @code{Calc} runs after the body of Init_Constants has set
25098 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25099 runs.
25100
25101 One could perhaps by applying pretty clever non-artificial intelligence
25102 to the situation guess that it is more likely that the second order of
25103 elaboration is the one desired, but there is no formal linguistic reason
25104 to prefer one over the other. In fact in this particular case, GNAT will
25105 prefer the second order, because of the rule that bodies are elaborated
25106 as soon as possible, but it's just luck that this is what was wanted
25107 (if indeed the second order was preferred).
25108
25109 If the program cares about the order of elaboration routines in a case like
25110 this, it is important to specify the order required. In this particular
25111 case, that could have been achieved by adding to the spec of Calc:
25112
25113 @smallexample @c ada
25114 pragma Elaborate_All (Constants);
25115 @end smallexample
25116
25117 @noindent
25118 which requires that the body (if any) and spec of @code{Constants},
25119 as well as the body and spec of any unit @code{with}'ed by
25120 @code{Constants} be elaborated before @code{Calc} is elaborated.
25121
25122 Clearly no automatic method can always guess which alternative you require,
25123 and if you are working with legacy code that had constraints of this kind
25124 which were not properly specified by adding @code{Elaborate} or
25125 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25126 compilers can choose different orders.
25127
25128 However, GNAT does attempt to diagnose the common situation where there
25129 are uninitialized variables in the visible part of a package spec, and the
25130 corresponding package body has an elaboration block that directly or
25131 indirectly initialized one or more of these variables. This is the situation
25132 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25133 a warning that suggests this addition if it detects this situation.
25134
25135 The @code{gnatbind}
25136 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25137 out problems. This switch causes bodies to be elaborated as late as possible
25138 instead of as early as possible. In the example above, it would have forced
25139 the choice of the first elaboration order. If you get different results
25140 when using this switch, and particularly if one set of results is right,
25141 and one is wrong as far as you are concerned, it shows that you have some
25142 missing @code{Elaborate} pragmas. For the example above, we have the
25143 following output:
25144
25145 @smallexample
25146 gnatmake -f -q main
25147 main
25148  7
25149 gnatmake -f -q main -bargs -p
25150 main
25151  0
25152 @end smallexample
25153
25154 @noindent
25155 It is of course quite unlikely that both these results are correct, so
25156 it is up to you in a case like this to investigate the source of the
25157 difference, by looking at the two elaboration orders that are chosen,
25158 and figuring out which is correct, and then adding the necessary
25159 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25160
25161
25162
25163 @c *******************************
25164 @node Conditional Compilation
25165 @appendix Conditional Compilation
25166 @c *******************************
25167 @cindex Conditional compilation
25168
25169 @noindent
25170 It is often necessary to arrange for a single source program
25171 to serve multiple purposes, where it is compiled in different
25172 ways to achieve these different goals. Some examples of the
25173 need for this feature are
25174
25175 @itemize @bullet
25176 @item  Adapting a program to a different hardware environment
25177 @item  Adapting a program to a different target architecture
25178 @item  Turning debugging features on and off
25179 @item  Arranging for a program to compile with different compilers
25180 @end itemize
25181
25182 @noindent
25183 In C, or C++, the typical approach would be to use the preprocessor
25184 that is defined as part of the language. The Ada language does not
25185 contain such a feature. This is not an oversight, but rather a very
25186 deliberate design decision, based on the experience that overuse of
25187 the preprocessing features in C and C++ can result in programs that
25188 are extremely difficult to maintain. For example, if we have ten
25189 switches that can be on or off, this means that there are a thousand
25190 separate programs, any one of which might not even be syntactically
25191 correct, and even if syntactically correct, the resulting program
25192 might not work correctly. Testing all combinations can quickly become
25193 impossible.
25194
25195 Nevertheless, the need to tailor programs certainly exists, and in
25196 this Appendix we will discuss how this can
25197 be achieved using Ada in general, and GNAT in particular.
25198
25199 @menu
25200 * Use of Boolean Constants::
25201 * Debugging - A Special Case::
25202 * Conditionalizing Declarations::
25203 * Use of Alternative Implementations::
25204 * Preprocessing::
25205 @end menu
25206
25207 @node Use of Boolean Constants
25208 @section Use of Boolean Constants
25209
25210 @noindent
25211 In the case where the difference is simply which code
25212 sequence is executed, the cleanest solution is to use Boolean
25213 constants to control which code is executed.
25214
25215 @smallexample @c ada
25216 @group
25217 FP_Initialize_Required : constant Boolean := True;
25218 @dots{}
25219 if FP_Initialize_Required then
25220 @dots{}
25221 end if;
25222 @end group
25223 @end smallexample
25224
25225 @noindent
25226 Not only will the code inside the @code{if} statement not be executed if
25227 the constant Boolean is @code{False}, but it will also be completely
25228 deleted from the program.
25229 However, the code is only deleted after the @code{if} statement
25230 has been checked for syntactic and semantic correctness.
25231 (In contrast, with preprocessors the code is deleted before the
25232 compiler ever gets to see it, so it is not checked until the switch
25233 is turned on.)
25234 @cindex Preprocessors (contrasted with conditional compilation)
25235
25236 Typically the Boolean constants will be in a separate package,
25237 something like:
25238
25239 @smallexample @c ada
25240 @group
25241 package Config is
25242    FP_Initialize_Required : constant Boolean := True;
25243    Reset_Available        : constant Boolean := False;
25244    @dots{}
25245 end Config;
25246 @end group
25247 @end smallexample
25248
25249 @noindent
25250 The @code{Config} package exists in multiple forms for the various targets,
25251 with an appropriate script selecting the version of @code{Config} needed.
25252 Then any other unit requiring conditional compilation can do a @code{with}
25253 of @code{Config} to make the constants visible.
25254
25255
25256 @node Debugging - A Special Case
25257 @section Debugging - A Special Case
25258
25259 @noindent
25260 A common use of conditional code is to execute statements (for example
25261 dynamic checks, or output of intermediate results) under control of a
25262 debug switch, so that the debugging behavior can be turned on and off.
25263 This can be done using a Boolean constant to control whether the code
25264 is active:
25265
25266 @smallexample @c ada
25267 @group
25268 if Debugging then
25269    Put_Line ("got to the first stage!");
25270 end if;
25271 @end group
25272 @end smallexample
25273
25274 @noindent
25275 or
25276
25277 @smallexample @c ada
25278 @group
25279 if Debugging and then Temperature > 999.0 then
25280    raise Temperature_Crazy;
25281 end if;
25282 @end group
25283 @end smallexample
25284
25285 @noindent
25286 Since this is a common case, there are special features to deal with
25287 this in a convenient manner. For the case of tests, Ada 2005 has added
25288 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25289 @cindex pragma @code{Assert}
25290 on the @code{Assert} pragma that has always been available in GNAT, so this
25291 feature may be used with GNAT even if you are not using Ada 2005 features.
25292 The use of pragma @code{Assert} is described in
25293 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25294 example, the last test could be written:
25295
25296 @smallexample @c ada
25297 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25298 @end smallexample
25299
25300 @noindent
25301 or simply
25302
25303 @smallexample @c ada
25304 pragma Assert (Temperature <= 999.0);
25305 @end smallexample
25306
25307 @noindent
25308 In both cases, if assertions are active and the temperature is excessive,
25309 the exception @code{Assert_Failure} will be raised, with the given string in
25310 the first case or a string indicating the location of the pragma in the second
25311 case used as the exception message.
25312
25313 You can turn assertions on and off by using the @code{Assertion_Policy}
25314 pragma.
25315 @cindex pragma @code{Assertion_Policy}
25316 This is an Ada 2005 pragma which is implemented in all modes by
25317 GNAT, but only in the latest versions of GNAT which include Ada 2005
25318 capability. Alternatively, you can use the @option{-gnata} switch
25319 @cindex @option{-gnata} switch
25320 to enable assertions from the command line (this is recognized by all versions
25321 of GNAT).
25322
25323 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25324 @code{Debug} can be used:
25325 @cindex pragma @code{Debug}
25326
25327 @smallexample @c ada
25328 pragma Debug (Put_Line ("got to the first stage!"));
25329 @end smallexample
25330
25331 @noindent
25332 If debug pragmas are enabled, the argument, which must be of the form of
25333 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25334 Only one call can be present, but of course a special debugging procedure
25335 containing any code you like can be included in the program and then
25336 called in a pragma @code{Debug} argument as needed.
25337
25338 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25339 construct is that pragma @code{Debug} can appear in declarative contexts,
25340 such as at the very beginning of a procedure, before local declarations have
25341 been elaborated.
25342
25343 Debug pragmas are enabled using either the @option{-gnata} switch that also
25344 controls assertions, or with a separate Debug_Policy pragma.
25345 @cindex pragma @code{Debug_Policy}
25346 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25347 in Ada 95 and Ada 83 programs as well), and is analogous to
25348 pragma @code{Assertion_Policy} to control assertions.
25349
25350 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25351 and thus they can appear in @file{gnat.adc} if you are not using a
25352 project file, or in the file designated to contain configuration pragmas
25353 in a project file.
25354 They then apply to all subsequent compilations. In practice the use of
25355 the @option{-gnata} switch is often the most convenient method of controlling
25356 the status of these pragmas.
25357
25358 Note that a pragma is not a statement, so in contexts where a statement
25359 sequence is required, you can't just write a pragma on its own. You have
25360 to add a @code{null} statement.
25361
25362 @smallexample @c ada
25363 @group
25364 if @dots{} then
25365    @dots{} -- some statements
25366 else
25367    pragma Assert (Num_Cases < 10);
25368    null;
25369 end if;
25370 @end group
25371 @end smallexample
25372
25373
25374 @node Conditionalizing Declarations
25375 @section Conditionalizing Declarations
25376
25377 @noindent
25378 In some cases, it may be necessary to conditionalize declarations to meet
25379 different requirements. For example we might want a bit string whose length
25380 is set to meet some hardware message requirement.
25381
25382 In some cases, it may be possible to do this using declare blocks controlled
25383 by conditional constants:
25384
25385 @smallexample @c ada
25386 @group
25387 if Small_Machine then
25388    declare
25389       X : Bit_String (1 .. 10);
25390    begin
25391       @dots{}
25392    end;
25393 else
25394    declare
25395       X : Large_Bit_String (1 .. 1000);
25396    begin
25397       @dots{}
25398    end;
25399 end if;
25400 @end group
25401 @end smallexample
25402
25403 @noindent
25404 Note that in this approach, both declarations are analyzed by the
25405 compiler so this can only be used where both declarations are legal,
25406 even though one of them will not be used.
25407
25408 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25409 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25410 that are parameterized by these constants. For example
25411
25412 @smallexample @c ada
25413 @group
25414 for Rec use
25415   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25416 end record;
25417 @end group
25418 @end smallexample
25419
25420 @noindent
25421 If @code{Bits_Per_Word} is set to 32, this generates either
25422
25423 @smallexample @c ada
25424 @group
25425 for Rec use
25426   Field1 at 0 range 0 .. 32;
25427 end record;
25428 @end group
25429 @end smallexample
25430
25431 @noindent
25432 for the big endian case, or
25433
25434 @smallexample @c ada
25435 @group
25436 for Rec use record
25437   Field1 at 0 range 10 .. 32;
25438 end record;
25439 @end group
25440 @end smallexample
25441
25442 @noindent
25443 for the little endian case. Since a powerful subset of Ada expression
25444 notation is usable for creating static constants, clever use of this
25445 feature can often solve quite difficult problems in conditionalizing
25446 compilation (note incidentally that in Ada 95, the little endian
25447 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25448 need to define this one yourself).
25449
25450
25451 @node Use of Alternative Implementations
25452 @section Use of Alternative Implementations
25453
25454 @noindent
25455 In some cases, none of the approaches described above are adequate. This
25456 can occur for example if the set of declarations required is radically
25457 different for two different configurations.
25458
25459 In this situation, the official Ada way of dealing with conditionalizing
25460 such code is to write separate units for the different cases. As long as
25461 this does not result in excessive duplication of code, this can be done
25462 without creating maintenance problems. The approach is to share common
25463 code as far as possible, and then isolate the code and declarations
25464 that are different. Subunits are often a convenient method for breaking
25465 out a piece of a unit that is to be conditionalized, with separate files
25466 for different versions of the subunit for different targets, where the
25467 build script selects the right one to give to the compiler.
25468 @cindex Subunits (and conditional compilation)
25469
25470 As an example, consider a situation where a new feature in Ada 2005
25471 allows something to be done in a really nice way. But your code must be able
25472 to compile with an Ada 95 compiler. Conceptually you want to say:
25473
25474 @smallexample @c ada
25475 @group
25476 if Ada_2005 then
25477    @dots{} neat Ada 2005 code
25478 else
25479    @dots{} not quite as neat Ada 95 code
25480 end if;
25481 @end group
25482 @end smallexample
25483
25484 @noindent
25485 where @code{Ada_2005} is a Boolean constant.
25486
25487 But this won't work when @code{Ada_2005} is set to @code{False},
25488 since the @code{then} clause will be illegal for an Ada 95 compiler.
25489 (Recall that although such unreachable code would eventually be deleted
25490 by the compiler, it still needs to be legal.  If it uses features
25491 introduced in Ada 2005, it will be illegal in Ada 95.)
25492
25493 So instead we write
25494
25495 @smallexample @c ada
25496 procedure Insert is separate;
25497 @end smallexample
25498
25499 @noindent
25500 Then we have two files for the subunit @code{Insert}, with the two sets of
25501 code.
25502 If the package containing this is called @code{File_Queries}, then we might
25503 have two files
25504
25505 @itemize @bullet
25506 @item    @file{file_queries-insert-2005.adb}
25507 @item    @file{file_queries-insert-95.adb}
25508 @end itemize
25509
25510 @noindent
25511 and the build script renames the appropriate file to
25512
25513 @smallexample
25514 file_queries-insert.adb
25515 @end smallexample
25516
25517 @noindent
25518 and then carries out the compilation.
25519
25520 This can also be done with project files' naming schemes. For example:
25521
25522 @smallexample @c project
25523 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25524 @end smallexample
25525
25526 @noindent
25527 Note also that with project files it is desirable to use a different extension
25528 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25529 conflict may arise through another commonly used feature: to declare as part
25530 of the project a set of directories containing all the sources obeying the
25531 default naming scheme.
25532
25533 The use of alternative units is certainly feasible in all situations,
25534 and for example the Ada part of the GNAT run-time is conditionalized
25535 based on the target architecture using this approach. As a specific example,
25536 consider the implementation of the AST feature in VMS. There is one
25537 spec:
25538
25539 @smallexample
25540 s-asthan.ads
25541 @end smallexample
25542
25543 @noindent
25544 which is the same for all architectures, and three bodies:
25545
25546 @table @file
25547 @item    s-asthan.adb
25548 used for all non-VMS operating systems
25549 @item    s-asthan-vms-alpha.adb
25550 used for VMS on the Alpha
25551 @item    s-asthan-vms-ia64.adb
25552 used for VMS on the ia64
25553 @end table
25554
25555 @noindent
25556 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25557 this operating system feature is not available, and the two remaining
25558 versions interface with the corresponding versions of VMS to provide
25559 VMS-compatible AST handling. The GNAT build script knows the architecture
25560 and operating system, and automatically selects the right version,
25561 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25562
25563 Another style for arranging alternative implementations is through Ada's
25564 access-to-subprogram facility.
25565 In case some functionality is to be conditionally included,
25566 you can declare an access-to-procedure variable @code{Ref} that is initialized
25567 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25568 when appropriate.
25569 In some library package, set @code{Ref} to @code{Proc'Access} for some
25570 procedure @code{Proc} that performs the relevant processing.
25571 The initialization only occurs if the library package is included in the
25572 program.
25573 The same idea can also be implemented using tagged types and dispatching
25574 calls.
25575
25576
25577 @node Preprocessing
25578 @section Preprocessing
25579 @cindex Preprocessing
25580
25581 @noindent
25582 Although it is quite possible to conditionalize code without the use of
25583 C-style preprocessing, as described earlier in this section, it is
25584 nevertheless convenient in some cases to use the C approach. Moreover,
25585 older Ada compilers have often provided some preprocessing capability,
25586 so legacy code may depend on this approach, even though it is not
25587 standard.
25588
25589 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25590 extent on the various preprocessors that have been used
25591 with legacy code on other compilers, to enable easier transition).
25592
25593 The preprocessor may be used in two separate modes. It can be used quite
25594 separately from the compiler, to generate a separate output source file
25595 that is then fed to the compiler as a separate step. This is the
25596 @code{gnatprep} utility, whose use is fully described in
25597 @ref{Preprocessing Using gnatprep}.
25598 @cindex @code{gnatprep}
25599
25600 The preprocessing language allows such constructs as
25601
25602 @smallexample
25603 @group
25604 #if DEBUG or PRIORITY > 4 then
25605    bunch of declarations
25606 #else
25607    completely different bunch of declarations
25608 #end if;
25609 @end group
25610 @end smallexample
25611
25612 @noindent
25613 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25614 defined either on the command line or in a separate file.
25615
25616 The other way of running the preprocessor is even closer to the C style and
25617 often more convenient. In this approach the preprocessing is integrated into
25618 the compilation process. The compiler is fed the preprocessor input which
25619 includes @code{#if} lines etc, and then the compiler carries out the
25620 preprocessing internally and processes the resulting output.
25621 For more details on this approach, see @ref{Integrated Preprocessing}.
25622
25623
25624 @c *******************************
25625 @node Inline Assembler
25626 @appendix Inline Assembler
25627 @c *******************************
25628
25629 @noindent
25630 If you need to write low-level software that interacts directly
25631 with the hardware, Ada provides two ways to incorporate assembly
25632 language code into your program.  First, you can import and invoke
25633 external routines written in assembly language, an Ada feature fully
25634 supported by GNAT@.  However, for small sections of code it may be simpler
25635 or more efficient to include assembly language statements directly
25636 in your Ada source program, using the facilities of the implementation-defined
25637 package @code{System.Machine_Code}, which incorporates the gcc
25638 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25639 including the following:
25640
25641 @itemize @bullet
25642 @item No need to use non-Ada tools
25643 @item Consistent interface over different targets
25644 @item Automatic usage of the proper calling conventions
25645 @item Access to Ada constants and variables
25646 @item Definition of intrinsic routines
25647 @item Possibility of inlining a subprogram comprising assembler code
25648 @item Code optimizer can take Inline Assembler code into account
25649 @end itemize
25650
25651 This chapter presents a series of examples to show you how to use
25652 the Inline Assembler.  Although it focuses on the Intel x86,
25653 the general approach applies also to other processors.
25654 It is assumed that you are familiar with Ada
25655 and with assembly language programming.
25656
25657 @menu
25658 * Basic Assembler Syntax::
25659 * A Simple Example of Inline Assembler::
25660 * Output Variables in Inline Assembler::
25661 * Input Variables in Inline Assembler::
25662 * Inlining Inline Assembler Code::
25663 * Other Asm Functionality::
25664 @end menu
25665
25666 @c ---------------------------------------------------------------------------
25667 @node Basic Assembler Syntax
25668 @section Basic Assembler Syntax
25669
25670 @noindent
25671 The assembler used by GNAT and gcc is based not on the Intel assembly
25672 language, but rather on a language that descends from the AT&T Unix
25673 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25674 The following table summarizes the main features of @emph{as} syntax
25675 and points out the differences from the Intel conventions.
25676 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25677 pre-processor) documentation for further information.
25678
25679 @table @asis
25680 @item Register names
25681 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25682 @*
25683 Intel: No extra punctuation; for example @code{eax}
25684
25685 @item Immediate operand
25686 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25687 @*
25688 Intel: No extra punctuation; for example @code{4}
25689
25690 @item Address
25691 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25692 @*
25693 Intel: No extra punctuation; for example @code{loc}
25694
25695 @item Memory contents
25696 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25697 @*
25698 Intel: Square brackets; for example @code{[loc]}
25699
25700 @item Register contents
25701 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25702 @*
25703 Intel: Square brackets; for example @code{[eax]}
25704
25705 @item Hexadecimal numbers
25706 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25707 @*
25708 Intel: Trailing ``h''; for example @code{A0h}
25709
25710 @item Operand size
25711 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25712 a 16-bit word
25713 @*
25714 Intel: Implicit, deduced by assembler; for example @code{mov}
25715
25716 @item Instruction repetition
25717 gcc / @emph{as}: Split into two lines; for example
25718 @*
25719 @code{rep}
25720 @*
25721 @code{stosl}
25722 @*
25723 Intel: Keep on one line; for example @code{rep stosl}
25724
25725 @item Order of operands
25726 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25727 @*
25728 Intel: Destination first; for example @code{mov eax, 4}
25729 @end table
25730
25731 @c ---------------------------------------------------------------------------
25732 @node A Simple Example of Inline Assembler
25733 @section A Simple Example of Inline Assembler
25734
25735 @noindent
25736 The following example will generate a single assembly language statement,
25737 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25738 the example will be useful in illustrating the basics of
25739 the Inline Assembler facility.
25740
25741 @smallexample @c ada
25742 @group
25743 with System.Machine_Code; use System.Machine_Code;
25744 procedure Nothing is
25745 begin
25746    Asm ("nop");
25747 end Nothing;
25748 @end group
25749 @end smallexample
25750
25751 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25752 here it takes one parameter, a @emph{template string} that must be a static
25753 expression and that will form the generated instruction.
25754 @code{Asm} may be regarded as a compile-time procedure that parses
25755 the template string and additional parameters (none here),
25756 from which it generates a sequence of assembly language instructions.
25757
25758 The examples in this chapter will illustrate several of the forms
25759 for invoking @code{Asm}; a complete specification of the syntax
25760 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25761 Manual}.
25762
25763 Under the standard GNAT conventions, the @code{Nothing} procedure
25764 should be in a file named @file{nothing.adb}.
25765 You can build the executable in the usual way:
25766 @smallexample
25767 gnatmake nothing
25768 @end smallexample
25769 However, the interesting aspect of this example is not its run-time behavior
25770 but rather the generated assembly code.
25771 To see this output, invoke the compiler as follows:
25772 @smallexample
25773    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25774 @end smallexample
25775 where the options are:
25776
25777 @table @code
25778 @item -c
25779 compile only (no bind or link)
25780 @item -S
25781 generate assembler listing
25782 @item -fomit-frame-pointer
25783 do not set up separate stack frames
25784 @item -gnatp
25785 do not add runtime checks
25786 @end table
25787
25788 This gives a human-readable assembler version of the code. The resulting
25789 file will have the same name as the Ada source file, but with a @code{.s}
25790 extension. In our example, the file @file{nothing.s} has the following
25791 contents:
25792
25793 @smallexample
25794 @group
25795 .file "nothing.adb"
25796 gcc2_compiled.:
25797 ___gnu_compiled_ada:
25798 .text
25799    .align 4
25800 .globl __ada_nothing
25801 __ada_nothing:
25802 #APP
25803    nop
25804 #NO_APP
25805    jmp L1
25806    .align 2,0x90
25807 L1:
25808    ret
25809 @end group
25810 @end smallexample
25811
25812 The assembly code you included is clearly indicated by
25813 the compiler, between the @code{#APP} and @code{#NO_APP}
25814 delimiters. The character before the 'APP' and 'NOAPP'
25815 can differ on different targets. For example, GNU/Linux uses '#APP' while
25816 on NT you will see '/APP'.
25817
25818 If you make a mistake in your assembler code (such as using the
25819 wrong size modifier, or using a wrong operand for the instruction) GNAT
25820 will report this error in a temporary file, which will be deleted when
25821 the compilation is finished.  Generating an assembler file will help
25822 in such cases, since you can assemble this file separately using the
25823 @emph{as} assembler that comes with gcc.
25824
25825 Assembling the file using the command
25826
25827 @smallexample
25828 as @file{nothing.s}
25829 @end smallexample
25830 @noindent
25831 will give you error messages whose lines correspond to the assembler
25832 input file, so you can easily find and correct any mistakes you made.
25833 If there are no errors, @emph{as} will generate an object file
25834 @file{nothing.out}.
25835
25836 @c ---------------------------------------------------------------------------
25837 @node Output Variables in Inline Assembler
25838 @section Output Variables in Inline Assembler
25839
25840 @noindent
25841 The examples in this section, showing how to access the processor flags,
25842 illustrate how to specify the destination operands for assembly language
25843 statements.
25844
25845 @smallexample @c ada
25846 @group
25847 with Interfaces; use Interfaces;
25848 with Ada.Text_IO; use Ada.Text_IO;
25849 with System.Machine_Code; use System.Machine_Code;
25850 procedure Get_Flags is
25851    Flags : Unsigned_32;
25852    use ASCII;
25853 begin
25854    Asm ("pushfl"          & LF & HT & -- push flags on stack
25855         "popl %%eax"      & LF & HT & -- load eax with flags
25856         "movl %%eax, %0",             -- store flags in variable
25857         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25858    Put_Line ("Flags register:" & Flags'Img);
25859 end Get_Flags;
25860 @end group
25861 @end smallexample
25862
25863 In order to have a nicely aligned assembly listing, we have separated
25864 multiple assembler statements in the Asm template string with linefeed
25865 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25866 The resulting section of the assembly output file is:
25867
25868 @smallexample
25869 @group
25870 #APP
25871    pushfl
25872    popl %eax
25873    movl %eax, -40(%ebp)
25874 #NO_APP
25875 @end group
25876 @end smallexample
25877
25878 It would have been legal to write the Asm invocation as:
25879
25880 @smallexample
25881 Asm ("pushfl popl %%eax movl %%eax, %0")
25882 @end smallexample
25883
25884 but in the generated assembler file, this would come out as:
25885
25886 @smallexample
25887 #APP
25888    pushfl popl %eax movl %eax, -40(%ebp)
25889 #NO_APP
25890 @end smallexample
25891
25892 which is not so convenient for the human reader.
25893
25894 We use Ada comments
25895 at the end of each line to explain what the assembler instructions
25896 actually do.  This is a useful convention.
25897
25898 When writing Inline Assembler instructions, you need to precede each register
25899 and variable name with a percent sign.  Since the assembler already requires
25900 a percent sign at the beginning of a register name, you need two consecutive
25901 percent signs for such names in the Asm template string, thus @code{%%eax}.
25902 In the generated assembly code, one of the percent signs will be stripped off.
25903
25904 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25905 variables: operands you later define using @code{Input} or @code{Output}
25906 parameters to @code{Asm}.
25907 An output variable is illustrated in
25908 the third statement in the Asm template string:
25909 @smallexample
25910 movl %%eax, %0
25911 @end smallexample
25912 The intent is to store the contents of the eax register in a variable that can
25913 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25914 necessarily work, since the compiler might optimize by using a register
25915 to hold Flags, and the expansion of the @code{movl} instruction would not be
25916 aware of this optimization.  The solution is not to store the result directly
25917 but rather to advise the compiler to choose the correct operand form;
25918 that is the purpose of the @code{%0} output variable.
25919
25920 Information about the output variable is supplied in the @code{Outputs}
25921 parameter to @code{Asm}:
25922 @smallexample
25923 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25924 @end smallexample
25925
25926 The output is defined by the @code{Asm_Output} attribute of the target type;
25927 the general format is
25928 @smallexample
25929 Type'Asm_Output (constraint_string, variable_name)
25930 @end smallexample
25931
25932 The constraint string directs the compiler how
25933 to store/access the associated variable.  In the example
25934 @smallexample
25935 Unsigned_32'Asm_Output ("=m", Flags);
25936 @end smallexample
25937 the @code{"m"} (memory) constraint tells the compiler that the variable
25938 @code{Flags} should be stored in a memory variable, thus preventing
25939 the optimizer from keeping it in a register.  In contrast,
25940 @smallexample
25941 Unsigned_32'Asm_Output ("=r", Flags);
25942 @end smallexample
25943 uses the @code{"r"} (register) constraint, telling the compiler to
25944 store the variable in a register.
25945
25946 If the constraint is preceded by the equal character (@strong{=}), it tells
25947 the compiler that the variable will be used to store data into it.
25948
25949 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25950 allowing the optimizer to choose whatever it deems best.
25951
25952 There are a fairly large number of constraints, but the ones that are
25953 most useful (for the Intel x86 processor) are the following:
25954
25955 @table @code
25956 @item =
25957 output constraint
25958 @item g
25959 global (i.e.@: can be stored anywhere)
25960 @item m
25961 in memory
25962 @item I
25963 a constant
25964 @item a
25965 use eax
25966 @item b
25967 use ebx
25968 @item c
25969 use ecx
25970 @item d
25971 use edx
25972 @item S
25973 use esi
25974 @item D
25975 use edi
25976 @item r
25977 use one of eax, ebx, ecx or edx
25978 @item q
25979 use one of eax, ebx, ecx, edx, esi or edi
25980 @end table
25981
25982 The full set of constraints is described in the gcc and @emph{as}
25983 documentation; note that it is possible to combine certain constraints
25984 in one constraint string.
25985
25986 You specify the association of an output variable with an assembler operand
25987 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25988 integer.  Thus in
25989 @smallexample @c ada
25990 @group
25991 Asm ("pushfl"          & LF & HT & -- push flags on stack
25992      "popl %%eax"      & LF & HT & -- load eax with flags
25993      "movl %%eax, %0",             -- store flags in variable
25994      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25995 @end group
25996 @end smallexample
25997 @noindent
25998 @code{%0} will be replaced in the expanded code by the appropriate operand,
25999 whatever
26000 the compiler decided for the @code{Flags} variable.
26001
26002 In general, you may have any number of output variables:
26003 @itemize @bullet
26004 @item
26005 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26006 @item
26007 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26008 of @code{Asm_Output} attributes
26009 @end itemize
26010
26011 For example:
26012 @smallexample @c ada
26013 @group
26014 Asm ("movl %%eax, %0" & LF & HT &
26015      "movl %%ebx, %1" & LF & HT &
26016      "movl %%ecx, %2",
26017      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26018                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26019                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26020 @end group
26021 @end smallexample
26022 @noindent
26023 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26024 in the Ada program.
26025
26026 As a variation on the @code{Get_Flags} example, we can use the constraints
26027 string to direct the compiler to store the eax register into the @code{Flags}
26028 variable, instead of including the store instruction explicitly in the
26029 @code{Asm} template string:
26030
26031 @smallexample @c ada
26032 @group
26033 with Interfaces; use Interfaces;
26034 with Ada.Text_IO; use Ada.Text_IO;
26035 with System.Machine_Code; use System.Machine_Code;
26036 procedure Get_Flags_2 is
26037    Flags : Unsigned_32;
26038    use ASCII;
26039 begin
26040    Asm ("pushfl"      & LF & HT & -- push flags on stack
26041         "popl %%eax",             -- save flags in eax
26042         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26043    Put_Line ("Flags register:" & Flags'Img);
26044 end Get_Flags_2;
26045 @end group
26046 @end smallexample
26047
26048 @noindent
26049 The @code{"a"} constraint tells the compiler that the @code{Flags}
26050 variable will come from the eax register. Here is the resulting code:
26051
26052 @smallexample
26053 @group
26054 #APP
26055    pushfl
26056    popl %eax
26057 #NO_APP
26058    movl %eax,-40(%ebp)
26059 @end group
26060 @end smallexample
26061
26062 @noindent
26063 The compiler generated the store of eax into Flags after
26064 expanding the assembler code.
26065
26066 Actually, there was no need to pop the flags into the eax register;
26067 more simply, we could just pop the flags directly into the program variable:
26068
26069 @smallexample @c ada
26070 @group
26071 with Interfaces; use Interfaces;
26072 with Ada.Text_IO; use Ada.Text_IO;
26073 with System.Machine_Code; use System.Machine_Code;
26074 procedure Get_Flags_3 is
26075    Flags : Unsigned_32;
26076    use ASCII;
26077 begin
26078    Asm ("pushfl"  & LF & HT & -- push flags on stack
26079         "pop %0",             -- save flags in Flags
26080         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26081    Put_Line ("Flags register:" & Flags'Img);
26082 end Get_Flags_3;
26083 @end group
26084 @end smallexample
26085
26086 @c ---------------------------------------------------------------------------
26087 @node Input Variables in Inline Assembler
26088 @section Input Variables in Inline Assembler
26089
26090 @noindent
26091 The example in this section illustrates how to specify the source operands
26092 for assembly language statements.
26093 The program simply increments its input value by 1:
26094
26095 @smallexample @c ada
26096 @group
26097 with Interfaces; use Interfaces;
26098 with Ada.Text_IO; use Ada.Text_IO;
26099 with System.Machine_Code; use System.Machine_Code;
26100 procedure Increment is
26101
26102    function Incr (Value : Unsigned_32) return Unsigned_32 is
26103       Result : Unsigned_32;
26104    begin
26105       Asm ("incl %0",
26106            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26107            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26108       return Result;
26109    end Incr;
26110
26111    Value : Unsigned_32;
26112
26113 begin
26114    Value := 5;
26115    Put_Line ("Value before is" & Value'Img);
26116    Value := Incr (Value);
26117    Put_Line ("Value after is" & Value'Img);
26118 end Increment;
26119 @end group
26120 @end smallexample
26121
26122 The @code{Outputs} parameter to @code{Asm} specifies
26123 that the result will be in the eax register and that it is to be stored
26124 in the @code{Result} variable.
26125
26126 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26127 but with an @code{Asm_Input} attribute.
26128 The @code{"="} constraint, indicating an output value, is not present.
26129
26130 You can have multiple input variables, in the same way that you can have more
26131 than one output variable.
26132
26133 The parameter count (%0, %1) etc, now starts at the first input
26134 statement, and continues with the output statements.
26135 When both parameters use the same variable, the
26136 compiler will treat them as the same %n operand, which is the case here.
26137
26138 Just as the @code{Outputs} parameter causes the register to be stored into the
26139 target variable after execution of the assembler statements, so does the
26140 @code{Inputs} parameter cause its variable to be loaded into the register
26141 before execution of the assembler statements.
26142
26143 Thus the effect of the @code{Asm} invocation is:
26144 @enumerate
26145 @item load the 32-bit value of @code{Value} into eax
26146 @item execute the @code{incl %eax} instruction
26147 @item store the contents of eax into the @code{Result} variable
26148 @end enumerate
26149
26150 The resulting assembler file (with @option{-O2} optimization) contains:
26151 @smallexample
26152 @group
26153 _increment__incr.1:
26154    subl $4,%esp
26155    movl 8(%esp),%eax
26156 #APP
26157    incl %eax
26158 #NO_APP
26159    movl %eax,%edx
26160    movl %ecx,(%esp)
26161    addl $4,%esp
26162    ret
26163 @end group
26164 @end smallexample
26165
26166 @c ---------------------------------------------------------------------------
26167 @node Inlining Inline Assembler Code
26168 @section Inlining Inline Assembler Code
26169
26170 @noindent
26171 For a short subprogram such as the @code{Incr} function in the previous
26172 section, the overhead of the call and return (creating / deleting the stack
26173 frame) can be significant, compared to the amount of code in the subprogram
26174 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26175 which directs the compiler to expand invocations of the subprogram at the
26176 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26177 Here is the resulting program:
26178
26179 @smallexample @c ada
26180 @group
26181 with Interfaces; use Interfaces;
26182 with Ada.Text_IO; use Ada.Text_IO;
26183 with System.Machine_Code; use System.Machine_Code;
26184 procedure Increment_2 is
26185
26186    function Incr (Value : Unsigned_32) return Unsigned_32 is
26187       Result : Unsigned_32;
26188    begin
26189       Asm ("incl %0",
26190            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26191            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26192       return Result;
26193    end Incr;
26194    pragma Inline (Increment);
26195
26196    Value : Unsigned_32;
26197
26198 begin
26199    Value := 5;
26200    Put_Line ("Value before is" & Value'Img);
26201    Value := Increment (Value);
26202    Put_Line ("Value after is" & Value'Img);
26203 end Increment_2;
26204 @end group
26205 @end smallexample
26206
26207 Compile the program with both optimization (@option{-O2}) and inlining
26208 (@option{-gnatn}) enabled.
26209
26210 The @code{Incr} function is still compiled as usual, but at the
26211 point in @code{Increment} where our function used to be called:
26212
26213 @smallexample
26214 @group
26215 pushl %edi
26216 call _increment__incr.1
26217 @end group
26218 @end smallexample
26219
26220 @noindent
26221 the code for the function body directly appears:
26222
26223 @smallexample
26224 @group
26225 movl %esi,%eax
26226 #APP
26227    incl %eax
26228 #NO_APP
26229    movl %eax,%edx
26230 @end group
26231 @end smallexample
26232
26233 @noindent
26234 thus saving the overhead of stack frame setup and an out-of-line call.
26235
26236 @c ---------------------------------------------------------------------------
26237 @node Other Asm Functionality
26238 @section Other @code{Asm} Functionality
26239
26240 @noindent
26241 This section describes two important parameters to the @code{Asm}
26242 procedure: @code{Clobber}, which identifies register usage;
26243 and @code{Volatile}, which inhibits unwanted optimizations.
26244
26245 @menu
26246 * The Clobber Parameter::
26247 * The Volatile Parameter::
26248 @end menu
26249
26250 @c ---------------------------------------------------------------------------
26251 @node The Clobber Parameter
26252 @subsection The @code{Clobber} Parameter
26253
26254 @noindent
26255 One of the dangers of intermixing assembly language and a compiled language
26256 such as Ada is that the compiler needs to be aware of which registers are
26257 being used by the assembly code.  In some cases, such as the earlier examples,
26258 the constraint string is sufficient to indicate register usage (e.g.,
26259 @code{"a"} for
26260 the eax register).  But more generally, the compiler needs an explicit
26261 identification of the registers that are used by the Inline Assembly
26262 statements.
26263
26264 Using a register that the compiler doesn't know about
26265 could be a side effect of an instruction (like @code{mull}
26266 storing its result in both eax and edx).
26267 It can also arise from explicit register usage in your
26268 assembly code; for example:
26269 @smallexample
26270 @group
26271 Asm ("movl %0, %%ebx" & LF & HT &
26272      "movl %%ebx, %1",
26273      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26274      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26275 @end group
26276 @end smallexample
26277 @noindent
26278 where the compiler (since it does not analyze the @code{Asm} template string)
26279 does not know you are using the ebx register.
26280
26281 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26282 to identify the registers that will be used by your assembly code:
26283
26284 @smallexample
26285 @group
26286 Asm ("movl %0, %%ebx" & LF & HT &
26287      "movl %%ebx, %1",
26288      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26289      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26290      Clobber => "ebx");
26291 @end group
26292 @end smallexample
26293
26294 The Clobber parameter is a static string expression specifying the
26295 register(s) you are using.  Note that register names are @emph{not} prefixed
26296 by a percent sign. Also, if more than one register is used then their names
26297 are separated by commas; e.g., @code{"eax, ebx"}
26298
26299 The @code{Clobber} parameter has several additional uses:
26300 @enumerate
26301 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26302 @item Use ``register'' name @code{memory} if you changed a memory location
26303 @end enumerate
26304
26305 @c ---------------------------------------------------------------------------
26306 @node The Volatile Parameter
26307 @subsection The @code{Volatile} Parameter
26308 @cindex Volatile parameter
26309
26310 @noindent
26311 Compiler optimizations in the presence of Inline Assembler may sometimes have
26312 unwanted effects.  For example, when an @code{Asm} invocation with an input
26313 variable is inside a loop, the compiler might move the loading of the input
26314 variable outside the loop, regarding it as a one-time initialization.
26315
26316 If this effect is not desired, you can disable such optimizations by setting
26317 the @code{Volatile} parameter to @code{True}; for example:
26318
26319 @smallexample @c ada
26320 @group
26321 Asm ("movl %0, %%ebx" & LF & HT &
26322      "movl %%ebx, %1",
26323      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26324      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26325      Clobber  => "ebx",
26326      Volatile => True);
26327 @end group
26328 @end smallexample
26329
26330 By default, @code{Volatile} is set to @code{False} unless there is no
26331 @code{Outputs} parameter.
26332
26333 Although setting @code{Volatile} to @code{True} prevents unwanted
26334 optimizations, it will also disable other optimizations that might be
26335 important for efficiency. In general, you should set @code{Volatile}
26336 to @code{True} only if the compiler's optimizations have created
26337 problems.
26338 @c END OF INLINE ASSEMBLER CHAPTER
26339 @c ===============================
26340
26341 @c ***********************************
26342 @c * Compatibility and Porting Guide *
26343 @c ***********************************
26344 @node Compatibility and Porting Guide
26345 @appendix Compatibility and Porting Guide
26346
26347 @noindent
26348 This chapter describes the compatibility issues that may arise between
26349 GNAT and other Ada compilation systems (including those for Ada 83),
26350 and shows how GNAT can expedite porting
26351 applications developed in other Ada environments.
26352
26353 @menu
26354 * Compatibility with Ada 83::
26355 * Compatibility between Ada 95 and Ada 2005::
26356 * Implementation-dependent characteristics::
26357 * Compatibility with Other Ada Systems::
26358 * Representation Clauses::
26359 @ifclear vms
26360 @c Brief section is only in non-VMS version
26361 @c Full chapter is in VMS version
26362 * Compatibility with HP Ada 83::
26363 @end ifclear
26364 @ifset vms
26365 * Transitioning to 64-Bit GNAT for OpenVMS::
26366 @end ifset
26367 @end menu
26368
26369 @node Compatibility with Ada 83
26370 @section Compatibility with Ada 83
26371 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26372
26373 @noindent
26374 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26375 particular, the design intention was that the difficulties associated
26376 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26377 that occur when moving from one Ada 83 system to another.
26378
26379 However, there are a number of points at which there are minor
26380 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26381 full details of these issues,
26382 and should be consulted for a complete treatment.
26383 In practice the
26384 following subsections treat the most likely issues to be encountered.
26385
26386 @menu
26387 * Legal Ada 83 programs that are illegal in Ada 95::
26388 * More deterministic semantics::
26389 * Changed semantics::
26390 * Other language compatibility issues::
26391 @end menu
26392
26393 @node Legal Ada 83 programs that are illegal in Ada 95
26394 @subsection Legal Ada 83 programs that are illegal in Ada 95
26395
26396 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26397 Ada 95 and thus also in Ada 2005:
26398
26399 @table @emph
26400 @item Character literals
26401 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26402 @code{Wide_Character} as a new predefined character type, some uses of
26403 character literals that were legal in Ada 83 are illegal in Ada 95.
26404 For example:
26405 @smallexample @c ada
26406    for Char in 'A' .. 'Z' loop @dots{} end loop;
26407 @end smallexample
26408
26409 @noindent
26410 The problem is that @code{'A'} and @code{'Z'} could be from either
26411 @code{Character} or @code{Wide_Character}.  The simplest correction
26412 is to make the type explicit; e.g.:
26413 @smallexample @c ada
26414    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26415 @end smallexample
26416
26417 @item New reserved words
26418 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26419 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26420 Existing Ada 83 code using any of these identifiers must be edited to
26421 use some alternative name.
26422
26423 @item Freezing rules
26424 The rules in Ada 95 are slightly different with regard to the point at
26425 which entities are frozen, and representation pragmas and clauses are
26426 not permitted past the freeze point.  This shows up most typically in
26427 the form of an error message complaining that a representation item
26428 appears too late, and the appropriate corrective action is to move
26429 the item nearer to the declaration of the entity to which it refers.
26430
26431 A particular case is that representation pragmas
26432 @ifset vms
26433 (including the
26434 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26435 @end ifset
26436 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26437 declaration must be introduced to which the pragma can be applied.
26438
26439 @item Optional bodies for library packages
26440 In Ada 83, a package that did not require a package body was nevertheless
26441 allowed to have one.  This lead to certain surprises in compiling large
26442 systems (situations in which the body could be unexpectedly ignored by the
26443 binder).  In Ada 95, if a package does not require a body then it is not
26444 permitted to have a body.  To fix this problem, simply remove a redundant
26445 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26446 into the spec that makes the body required.  One approach is to add a private
26447 part to the package declaration (if necessary), and define a parameterless
26448 procedure called @code{Requires_Body}, which must then be given a dummy
26449 procedure body in the package body, which then becomes required.
26450 Another approach (assuming that this does not introduce elaboration
26451 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26452 since one effect of this pragma is to require the presence of a package body.
26453
26454 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26455 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26456 @code{Constraint_Error}.
26457 This means that it is illegal to have separate exception handlers for
26458 the two exceptions.  The fix is simply to remove the handler for the
26459 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26460 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26461
26462 @item Indefinite subtypes in generics
26463 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26464 as the actual for a generic formal private type, but then the instantiation
26465 would be illegal if there were any instances of declarations of variables
26466 of this type in the generic body.  In Ada 95, to avoid this clear violation
26467 of the methodological principle known as the ``contract model'',
26468 the generic declaration explicitly indicates whether
26469 or not such instantiations are permitted.  If a generic formal parameter
26470 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26471 subtype name, then it can be instantiated with indefinite types, but no
26472 stand-alone variables can be declared of this type.  Any attempt to declare
26473 such a variable will result in an illegality at the time the generic is
26474 declared.  If the @code{(<>)} notation is not used, then it is illegal
26475 to instantiate the generic with an indefinite type.
26476 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26477 It will show up as a compile time error, and
26478 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26479 @end table
26480
26481 @node More deterministic semantics
26482 @subsection More deterministic semantics
26483
26484 @table @emph
26485 @item Conversions
26486 Conversions from real types to integer types round away from 0.  In Ada 83
26487 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26488 implementation freedom was intended to support unbiased rounding in
26489 statistical applications, but in practice it interfered with portability.
26490 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26491 is required.  Numeric code may be affected by this change in semantics.
26492 Note, though, that this issue is no worse than already existed in Ada 83
26493 when porting code from one vendor to another.
26494
26495 @item Tasking
26496 The Real-Time Annex introduces a set of policies that define the behavior of
26497 features that were implementation dependent in Ada 83, such as the order in
26498 which open select branches are executed.
26499 @end table
26500
26501 @node Changed semantics
26502 @subsection Changed semantics
26503
26504 @noindent
26505 The worst kind of incompatibility is one where a program that is legal in
26506 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26507 possible in Ada 83.  Fortunately this is extremely rare, but the one
26508 situation that you should be alert to is the change in the predefined type
26509 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26510
26511 @table @emph
26512 @item Range of type @code{Character}
26513 The range of @code{Standard.Character} is now the full 256 characters
26514 of Latin-1, whereas in most Ada 83 implementations it was restricted
26515 to 128 characters. Although some of the effects of
26516 this change will be manifest in compile-time rejection of legal
26517 Ada 83 programs it is possible for a working Ada 83 program to have
26518 a different effect in Ada 95, one that was not permitted in Ada 83.
26519 As an example, the expression
26520 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26521 delivers @code{255} as its value.
26522 In general, you should look at the logic of any
26523 character-processing Ada 83 program and see whether it needs to be adapted
26524 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26525 character handling package that may be relevant if code needs to be adapted
26526 to account for the additional Latin-1 elements.
26527 The desirable fix is to
26528 modify the program to accommodate the full character set, but in some cases
26529 it may be convenient to define a subtype or derived type of Character that
26530 covers only the restricted range.
26531 @cindex Latin-1
26532 @end table
26533
26534 @node Other language compatibility issues
26535 @subsection Other language compatibility issues
26536
26537 @table @emph
26538 @item @option{-gnat83} switch
26539 All implementations of GNAT provide a switch that causes GNAT to operate
26540 in Ada 83 mode.  In this mode, some but not all compatibility problems
26541 of the type described above are handled automatically.  For example, the
26542 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26543 as identifiers as in Ada 83.
26544 However,
26545 in practice, it is usually advisable to make the necessary modifications
26546 to the program to remove the need for using this switch.
26547 See @ref{Compiling Different Versions of Ada}.
26548
26549 @item Support for removed Ada 83 pragmas and attributes
26550 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26551 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26552 compilers are allowed, but not required, to implement these missing
26553 elements.  In contrast with some other compilers, GNAT implements all
26554 such pragmas and attributes, eliminating this compatibility concern.  These
26555 include @code{pragma Interface} and the floating point type attributes
26556 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26557 @end table
26558
26559
26560 @node Compatibility between Ada 95 and Ada 2005
26561 @section Compatibility between Ada 95 and Ada 2005
26562 @cindex Compatibility between Ada 95 and Ada 2005
26563
26564 @noindent
26565 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26566 a number of incompatibilities. Several are enumerated below;
26567 for a complete description please see the
26568 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26569 @cite{Rationale for Ada 2005}.
26570
26571 @table @emph
26572 @item New reserved words.
26573 The words @code{interface}, @code{overriding} and @code{synchronized} are
26574 reserved in Ada 2005.
26575 A pre-Ada 2005 program that uses any of these as an identifier will be
26576 illegal.
26577
26578 @item New declarations in predefined packages.
26579 A number of packages in the predefined environment contain new declarations:
26580 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26581 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26582 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26583 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26584 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26585 If an Ada 95 program does a @code{with} and @code{use} of any of these
26586 packages, the new declarations may cause name clashes.
26587
26588 @item Access parameters.
26589 A nondispatching subprogram with an access parameter cannot be renamed
26590 as a dispatching operation.  This was permitted in Ada 95.
26591
26592 @item Access types, discriminants, and constraints.
26593 Rule changes in this area have led to some incompatibilities; for example,
26594 constrained subtypes of some access types are not permitted in Ada 2005.
26595
26596 @item Aggregates for limited types.
26597 The allowance of aggregates for limited types in Ada 2005 raises the
26598 possibility of ambiguities in legal Ada 95 programs, since additional types
26599 now need to be considered in expression resolution.
26600
26601 @item Fixed-point multiplication and division.
26602 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26603 were legal in Ada 95 and invoked the predefined versions of these operations,
26604 are now ambiguous.
26605 The ambiguity may be resolved either by applying a type conversion to the
26606 expression, or by explicitly invoking the operation from package
26607 @code{Standard}.
26608
26609 @item Return-by-reference types.
26610 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26611 can declare a function returning a value from an anonymous access type.
26612 @end table
26613
26614
26615 @node Implementation-dependent characteristics
26616 @section Implementation-dependent characteristics
26617 @noindent
26618 Although the Ada language defines the semantics of each construct as
26619 precisely as practical, in some situations (for example for reasons of
26620 efficiency, or where the effect is heavily dependent on the host or target
26621 platform) the implementation is allowed some freedom.  In porting Ada 83
26622 code to GNAT, you need to be aware of whether / how the existing code
26623 exercised such implementation dependencies.  Such characteristics fall into
26624 several categories, and GNAT offers specific support in assisting the
26625 transition from certain Ada 83 compilers.
26626
26627 @menu
26628 * Implementation-defined pragmas::
26629 * Implementation-defined attributes::
26630 * Libraries::
26631 * Elaboration order::
26632 * Target-specific aspects::
26633 @end menu
26634
26635 @node Implementation-defined pragmas
26636 @subsection Implementation-defined pragmas
26637
26638 @noindent
26639 Ada compilers are allowed to supplement the language-defined pragmas, and
26640 these are a potential source of non-portability.  All GNAT-defined pragmas
26641 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26642 Reference Manual}, and these include several that are specifically
26643 intended to correspond to other vendors' Ada 83 pragmas.
26644 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26645 For compatibility with HP Ada 83, GNAT supplies the pragmas
26646 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26647 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26648 and @code{Volatile}.
26649 Other relevant pragmas include @code{External} and @code{Link_With}.
26650 Some vendor-specific
26651 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26652 recognized, thus
26653 avoiding compiler rejection of units that contain such pragmas; they are not
26654 relevant in a GNAT context and hence are not otherwise implemented.
26655
26656 @node Implementation-defined attributes
26657 @subsection Implementation-defined attributes
26658
26659 Analogous to pragmas, the set of attributes may be extended by an
26660 implementation.  All GNAT-defined attributes are described in
26661 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26662 Manual}, and these include several that are specifically intended
26663 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26664 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26665 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26666 @code{Type_Class}.
26667
26668 @node Libraries
26669 @subsection Libraries
26670 @noindent
26671 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26672 code uses vendor-specific libraries then there are several ways to manage
26673 this in Ada 95 or Ada 2005:
26674 @enumerate
26675 @item
26676 If the source code for the libraries (specs and bodies) are
26677 available, then the libraries can be migrated in the same way as the
26678 application.
26679 @item
26680 If the source code for the specs but not the bodies are
26681 available, then you can reimplement the bodies.
26682 @item
26683 Some features introduced by Ada 95 obviate the need for library support.  For
26684 example most Ada 83 vendors supplied a package for unsigned integers.  The
26685 Ada 95 modular type feature is the preferred way to handle this need, so
26686 instead of migrating or reimplementing the unsigned integer package it may
26687 be preferable to retrofit the application using modular types.
26688 @end enumerate
26689
26690 @node Elaboration order
26691 @subsection Elaboration order
26692 @noindent
26693 The implementation can choose any elaboration order consistent with the unit
26694 dependency relationship.  This freedom means that some orders can result in
26695 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26696 to invoke a subprogram its body has been elaborated, or to instantiate a
26697 generic before the generic body has been elaborated.  By default GNAT
26698 attempts to choose a safe order (one that will not encounter access before
26699 elaboration problems) by implicitly inserting @code{Elaborate} or
26700 @code{Elaborate_All} pragmas where
26701 needed.  However, this can lead to the creation of elaboration circularities
26702 and a resulting rejection of the program by gnatbind.  This issue is
26703 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26704 In brief, there are several
26705 ways to deal with this situation:
26706
26707 @itemize @bullet
26708 @item
26709 Modify the program to eliminate the circularities, e.g.@: by moving
26710 elaboration-time code into explicitly-invoked procedures
26711 @item
26712 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26713 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26714 @code{Elaborate_All}
26715 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26716 (by selectively suppressing elaboration checks via pragma
26717 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26718 @end itemize
26719
26720 @node Target-specific aspects
26721 @subsection Target-specific aspects
26722 @noindent
26723 Low-level applications need to deal with machine addresses, data
26724 representations, interfacing with assembler code, and similar issues.  If
26725 such an Ada 83 application is being ported to different target hardware (for
26726 example where the byte endianness has changed) then you will need to
26727 carefully examine the program logic; the porting effort will heavily depend
26728 on the robustness of the original design.  Moreover, Ada 95 (and thus
26729 Ada 2005) are sometimes
26730 incompatible with typical Ada 83 compiler practices regarding implicit
26731 packing, the meaning of the Size attribute, and the size of access values.
26732 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26733
26734 @node Compatibility with Other Ada Systems
26735 @section Compatibility with Other Ada Systems
26736
26737 @noindent
26738 If programs avoid the use of implementation dependent and
26739 implementation defined features, as documented in the @cite{Ada
26740 Reference Manual}, there should be a high degree of portability between
26741 GNAT and other Ada systems.  The following are specific items which
26742 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26743 compilers, but do not affect porting code to GNAT@.
26744 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26745 the following issues may or may not arise for Ada 2005 programs
26746 when other compilers appear.)
26747
26748 @table @emph
26749 @item Ada 83 Pragmas and Attributes
26750 Ada 95 compilers are allowed, but not required, to implement the missing
26751 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26752 GNAT implements all such pragmas and attributes, eliminating this as
26753 a compatibility concern, but some other Ada 95 compilers reject these
26754 pragmas and attributes.
26755
26756 @item Specialized Needs Annexes
26757 GNAT implements the full set of special needs annexes.  At the
26758 current time, it is the only Ada 95 compiler to do so.  This means that
26759 programs making use of these features may not be portable to other Ada
26760 95 compilation systems.
26761
26762 @item Representation Clauses
26763 Some other Ada 95 compilers implement only the minimal set of
26764 representation clauses required by the Ada 95 reference manual.  GNAT goes
26765 far beyond this minimal set, as described in the next section.
26766 @end table
26767
26768 @node Representation Clauses
26769 @section Representation Clauses
26770
26771 @noindent
26772 The Ada 83 reference manual was quite vague in describing both the minimal
26773 required implementation of representation clauses, and also their precise
26774 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26775 minimal set of capabilities required is still quite limited.
26776
26777 GNAT implements the full required set of capabilities in
26778 Ada 95 and Ada 2005, but also goes much further, and in particular
26779 an effort has been made to be compatible with existing Ada 83 usage to the
26780 greatest extent possible.
26781
26782 A few cases exist in which Ada 83 compiler behavior is incompatible with
26783 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26784 intentional or accidental dependence on specific implementation dependent
26785 characteristics of these Ada 83 compilers.  The following is a list of
26786 the cases most likely to arise in existing Ada 83 code.
26787
26788 @table @emph
26789 @item Implicit Packing
26790 Some Ada 83 compilers allowed a Size specification to cause implicit
26791 packing of an array or record.  This could cause expensive implicit
26792 conversions for change of representation in the presence of derived
26793 types, and the Ada design intends to avoid this possibility.
26794 Subsequent AI's were issued to make it clear that such implicit
26795 change of representation in response to a Size clause is inadvisable,
26796 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26797 Reference Manuals as implementation advice that is followed by GNAT@.
26798 The problem will show up as an error
26799 message rejecting the size clause.  The fix is simply to provide
26800 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26801 a Component_Size clause.
26802
26803 @item Meaning of Size Attribute
26804 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26805 the minimal number of bits required to hold values of the type.  For example,
26806 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26807 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26808 some 32 in this situation.  This problem will usually show up as a compile
26809 time error, but not always.  It is a good idea to check all uses of the
26810 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26811 Object_Size can provide a useful way of duplicating the behavior of
26812 some Ada 83 compiler systems.
26813
26814 @item Size of Access Types
26815 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26816 and that therefore it will be the same size as a System.Address value.  This
26817 assumption is true for GNAT in most cases with one exception.  For the case of
26818 a pointer to an unconstrained array type (where the bounds may vary from one
26819 value of the access type to another), the default is to use a ``fat pointer'',
26820 which is represented as two separate pointers, one to the bounds, and one to
26821 the array.  This representation has a number of advantages, including improved
26822 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26823 code which makes the assumption that, for example, pointers fit in 32 bits on
26824 a machine with 32-bit addressing.
26825
26826 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26827 access types in this case (where the designated type is an unconstrained array
26828 type).  These thin pointers are indeed the same size as a System.Address value.
26829 To specify a thin pointer, use a size clause for the type, for example:
26830
26831 @smallexample @c ada
26832 type X is access all String;
26833 for X'Size use Standard'Address_Size;
26834 @end smallexample
26835
26836 @noindent
26837 which will cause the type X to be represented using a single pointer.
26838 When using this representation, the bounds are right behind the array.
26839 This representation is slightly less efficient, and does not allow quite
26840 such flexibility in the use of foreign pointers or in using the
26841 Unrestricted_Access attribute to create pointers to non-aliased objects.
26842 But for any standard portable use of the access type it will work in
26843 a functionally correct manner and allow porting of existing code.
26844 Note that another way of forcing a thin pointer representation
26845 is to use a component size clause for the element size in an array,
26846 or a record representation clause for an access field in a record.
26847 @end table
26848
26849 @ifclear vms
26850 @c This brief section is only in the non-VMS version
26851 @c The complete chapter on HP Ada is in the VMS version
26852 @node Compatibility with HP Ada 83
26853 @section Compatibility with HP Ada 83
26854
26855 @noindent
26856 The VMS version of GNAT fully implements all the pragmas and attributes
26857 provided by HP Ada 83, as well as providing the standard HP Ada 83
26858 libraries, including Starlet.  In addition, data layouts and parameter
26859 passing conventions are highly compatible.  This means that porting
26860 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26861 most other porting efforts.  The following are some of the most
26862 significant differences between GNAT and HP Ada 83.
26863
26864 @table @emph
26865 @item Default floating-point representation
26866 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26867 it is VMS format.  GNAT does implement the necessary pragmas
26868 (Long_Float, Float_Representation) for changing this default.
26869
26870 @item System
26871 The package System in GNAT exactly corresponds to the definition in the
26872 Ada 95 reference manual, which means that it excludes many of the
26873 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26874 that contains the additional definitions, and a special pragma,
26875 Extend_System allows this package to be treated transparently as an
26876 extension of package System.
26877
26878 @item To_Address
26879 The definitions provided by Aux_DEC are exactly compatible with those
26880 in the HP Ada 83 version of System, with one exception.
26881 HP Ada provides the following declarations:
26882
26883 @smallexample @c ada
26884 TO_ADDRESS (INTEGER)
26885 TO_ADDRESS (UNSIGNED_LONGWORD)
26886 TO_ADDRESS (@i{universal_integer})
26887 @end smallexample
26888
26889 @noindent
26890 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26891 an extension to Ada 83 not strictly compatible with the reference manual.
26892 In GNAT, we are constrained to be exactly compatible with the standard,
26893 and this means we cannot provide this capability.  In HP Ada 83, the
26894 point of this definition is to deal with a call like:
26895
26896 @smallexample @c ada
26897 TO_ADDRESS (16#12777#);
26898 @end smallexample
26899
26900 @noindent
26901 Normally, according to the Ada 83 standard, one would expect this to be
26902 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26903 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26904 definition using @i{universal_integer} takes precedence.
26905
26906 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26907 is not possible to be 100% compatible.  Since there are many programs using
26908 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26909 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26910 declarations provided in the GNAT version of AUX_Dec are:
26911
26912 @smallexample @c ada
26913 function To_Address (X : Integer) return Address;
26914 pragma Pure_Function (To_Address);
26915
26916 function To_Address_Long (X : Unsigned_Longword)
26917  return Address;
26918 pragma Pure_Function (To_Address_Long);
26919 @end smallexample
26920
26921 @noindent
26922 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26923 change the name to TO_ADDRESS_LONG@.
26924
26925 @item Task_Id values
26926 The Task_Id values assigned will be different in the two systems, and GNAT
26927 does not provide a specified value for the Task_Id of the environment task,
26928 which in GNAT is treated like any other declared task.
26929 @end table
26930
26931 @noindent
26932 For full details on these and other less significant compatibility issues,
26933 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26934 Overview and Comparison on HP Platforms}.
26935
26936 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26937 attributes are recognized, although only a subset of them can sensibly
26938 be implemented.  The description of pragmas in @ref{Implementation
26939 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26940 indicates whether or not they are applicable to non-VMS systems.
26941 @end ifclear
26942
26943 @ifset vms
26944 @node Transitioning to 64-Bit GNAT for OpenVMS
26945 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26946
26947 @noindent
26948 This section is meant to assist users of pre-2006 @value{EDITION}
26949 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26950 the version of the GNAT technology supplied in 2006 and later for
26951 OpenVMS on both Alpha and I64.
26952
26953 @menu
26954 * Introduction to transitioning::
26955 * Migration of 32 bit code::
26956 * Taking advantage of 64 bit addressing::
26957 * Technical details::
26958 @end menu
26959
26960 @node Introduction to transitioning
26961 @subsection Introduction
26962
26963 @noindent
26964 64-bit @value{EDITION} for Open VMS has been designed to meet
26965 three main goals:
26966
26967 @enumerate
26968 @item
26969 Providing a full conforming implementation of Ada 95 and Ada 2005
26970
26971 @item
26972 Allowing maximum backward compatibility, thus easing migration of existing
26973 Ada source code
26974
26975 @item
26976 Supplying a path for exploiting the full 64-bit address range
26977 @end enumerate
26978
26979 @noindent
26980 Ada's strong typing semantics has made it
26981 impractical to have different 32-bit and 64-bit modes. As soon as
26982 one object could possibly be outside the 32-bit address space, this
26983 would make it necessary for the @code{System.Address} type to be 64 bits.
26984 In particular, this would cause inconsistencies if 32-bit code is
26985 called from 64-bit code that raises an exception.
26986
26987 This issue has been resolved by always using 64-bit addressing
26988 at the system level, but allowing for automatic conversions between
26989 32-bit and 64-bit addresses where required. Thus users who
26990 do not currently require 64-bit addressing capabilities, can
26991 recompile their code with only minimal changes (and indeed
26992 if the code is written in portable Ada, with no assumptions about
26993 the size of the @code{Address} type, then no changes at all are necessary).
26994 At the same time,
26995 this approach provides a simple, gradual upgrade path to future
26996 use of larger memories than available for 32-bit systems.
26997 Also, newly written applications or libraries will by default
26998 be fully compatible with future systems exploiting 64-bit
26999 addressing capabilities.
27000
27001 @ref{Migration of 32 bit code}, will focus on porting applications
27002 that do not require more than 2 GB of
27003 addressable memory. This code will be referred to as
27004 @emph{32-bit code}.
27005 For applications intending to exploit the full 64-bit address space,
27006 @ref{Taking advantage of 64 bit addressing},
27007 will consider further changes that may be required.
27008 Such code will be referred to below as @emph{64-bit code}.
27009
27010 @node Migration of 32 bit code
27011 @subsection Migration of 32-bit code
27012
27013 @menu
27014 * Address types::
27015 * Access types and 32/64-bit allocation::
27016 * Unchecked conversions::
27017 * Predefined constants::
27018 * Interfacing with C::
27019 * 32/64-bit descriptors::
27020 * Experience with source compatibility::
27021 @end menu
27022
27023 @node Address types
27024 @subsubsection Address types
27025
27026 @noindent
27027 To solve the problem of mixing 64-bit and 32-bit addressing,
27028 while maintaining maximum backward compatibility, the following
27029 approach has been taken:
27030
27031 @itemize @bullet
27032 @item
27033 @code{System.Address} always has a size of 64 bits
27034 @cindex @code{System.Address} size
27035 @cindex @code{Address} size
27036
27037 @item
27038 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27039 @cindex @code{System.Short_Address} size
27040 @cindex @code{Short_Address} size
27041 @end itemize
27042
27043 @noindent
27044 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27045 a @code{Short_Address}
27046 may be used where an @code{Address} is required, and vice versa, without
27047 needing explicit type conversions.
27048 By virtue of the Open VMS parameter passing conventions,
27049 even imported
27050 and exported subprograms that have 32-bit address parameters are
27051 compatible with those that have 64-bit address parameters.
27052 (See @ref{Making code 64 bit clean} for details.)
27053
27054 The areas that may need attention are those where record types have
27055 been defined that contain components of the type @code{System.Address}, and
27056 where objects of this type are passed to code expecting a record layout with
27057 32-bit addresses.
27058
27059 Different compilers on different platforms cannot be
27060 expected to represent the same type in the same way,
27061 since alignment constraints
27062 and other system-dependent properties affect the compiler's decision.
27063 For that reason, Ada code
27064 generally uses representation clauses to specify the expected
27065 layout where required.
27066
27067 If such a representation clause uses 32 bits for a component having
27068 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27069 will detect that error and produce a specific diagnostic message.
27070 The developer should then determine whether the representation
27071 should be 64 bits or not and make either of two changes:
27072 change the size to 64 bits and leave the type as @code{System.Address}, or
27073 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27074 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27075 required in any code setting or accessing the field; the compiler will
27076 automatically perform any needed conversions between address
27077 formats.
27078
27079 @node Access types and 32/64-bit allocation
27080 @subsubsection Access types and 32/64-bit allocation
27081 @cindex 32-bit allocation
27082 @cindex 64-bit allocation
27083
27084 @noindent
27085 By default, objects designated by access values are always allocated in
27086 the 64-bit address space, and access values themselves are represented
27087 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
27088 is required (for example if the address of an allocated object is assigned
27089 to a @code{Short_Address} variable), then several alternatives are available:
27090
27091 @itemize @bullet
27092 @item
27093 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27094 definition is @code{access T} versus @code{access all T} or
27095 @code{access constant T}), may be declared with a @code{'Size} representation
27096 clause that establishes the size as 32 bits.
27097 In such circumstances allocations for that type will
27098 be from the 32-bit heap.  Such a clause is not permitted
27099 for a general access type (declared with @code{access all} or
27100 @code{access constant}) as values of such types must be able to refer
27101 to any object of the designated type, including objects residing outside
27102 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
27103 type definitions, however, since general access types were introduced
27104 in @w{Ada 95}.
27105
27106 @item
27107 Switches for @command{GNAT BIND} control whether the internal GNAT
27108 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27109 @cindex @code{__gnat_malloc}
27110 The switches are respectively @option{-H64} (the default) and
27111 @option{-H32}.
27112 @cindex @option{-H32} (@command{gnatbind})
27113 @cindex @option{-H64} (@command{gnatbind})
27114
27115 @item
27116 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
27117 @cindex @code{GNAT$NO_MALLOC_64} environment variable
27118 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
27119 If this variable is left
27120 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
27121 then the default (64-bit) allocation is used.
27122 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
27123 then 32-bit allocation is used.  The gnatbind qualifiers described above
27124 override this logical name.
27125
27126 @item
27127 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
27128 @cindex @option{-mno-malloc64} (^gcc^gcc^)
27129 at a low level to convert explicit calls to @code{malloc} and related
27130 functions from the C run-time library so that they perform allocations
27131 in the 32-bit heap.
27132 Since all internal allocations from GNAT use @code{__gnat_malloc},
27133 this switch is not required unless the program makes explicit calls on
27134 @code{malloc} (or related functions) from interfaced C code.
27135 @end itemize
27136
27137
27138 @node Unchecked conversions
27139 @subsubsection Unchecked conversions
27140
27141 @noindent
27142 In the case of an @code{Unchecked_Conversion} where the source type is a
27143 64-bit access type or the type @code{System.Address}, and the target
27144 type is a 32-bit type, the compiler will generate a warning.
27145 Even though the generated code will still perform the required
27146 conversions, it is highly recommended in these cases to use
27147 respectively a 32-bit access type or @code{System.Short_Address}
27148 as the source type.
27149
27150 @node Predefined constants
27151 @subsubsection Predefined constants
27152
27153 @noindent
27154 The following table shows the correspondence between pre-2006 versions of
27155 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27156 (``New''):
27157
27158 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27159 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
27160 @item   @code{System.Word_Size}          @tab 32      @tab 64
27161 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
27162 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
27163 @item   @code{System.Address_Size}       @tab 32      @tab 64
27164 @end multitable
27165
27166 @noindent
27167 If you need to refer to the specific
27168 memory size of a 32-bit implementation, instead of the
27169 actual memory size, use @code{System.Short_Memory_Size}
27170 rather than @code{System.Memory_Size}.
27171 Similarly, references to @code{System.Address_Size} may need
27172 to be replaced by @code{System.Short_Address'Size}.
27173 The program @command{gnatfind} may be useful for locating
27174 references to the above constants, so that you can verify that they
27175 are still correct.
27176
27177 @node Interfacing with C
27178 @subsubsection Interfacing with C
27179
27180 @noindent
27181 In order to minimize the impact of the transition to 64-bit addresses on
27182 legacy programs, some fundamental types in the @code{Interfaces.C}
27183 package hierarchy continue to be represented in 32 bits.
27184 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27185 This eases integration with the default HP C layout choices, for example
27186 as found in the system routines in @code{DECC$SHR.EXE}.
27187 Because of this implementation choice, the type fully compatible with
27188 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27189 Depending on the context the compiler will issue a
27190 warning or an error when type @code{Address} is used, alerting the user to a
27191 potential problem. Otherwise 32-bit programs that use
27192 @code{Interfaces.C} should normally not require code modifications
27193
27194 The other issue arising with C interfacing concerns pragma @code{Convention}.
27195 For VMS 64-bit systems, there is an issue of the appropriate default size
27196 of C convention pointers in the absence of an explicit size clause. The HP
27197 C compiler can choose either 32 or 64 bits depending on compiler options.
27198 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27199 clause is given. This proves a better choice for porting 32-bit legacy
27200 applications. In order to have a 64-bit representation, it is necessary to
27201 specify a size representation clause. For example:
27202
27203 @smallexample @c ada
27204 type int_star is access Interfaces.C.int;
27205 pragma Convention(C, int_star);
27206 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
27207 @end smallexample
27208
27209 @node 32/64-bit descriptors
27210 @subsubsection 32/64-bit descriptors
27211
27212 @noindent
27213 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
27214 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27215 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27216 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27217 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27218
27219 If the configuration pragma @code{Short_Descriptors} is supplied, then
27220 all descriptors will be 32 bits.
27221 @cindex pragma @code{Short_Descriptors}
27222
27223 @node Experience with source compatibility
27224 @subsubsection Experience with source compatibility
27225
27226 @noindent
27227 The Security Server and STARLET on I64 provide an interesting ``test case''
27228 for source compatibility issues, since it is in such system code
27229 where assumptions about @code{Address} size might be expected to occur.
27230 Indeed, there were a small number of occasions in the Security Server
27231 file @file{jibdef.ads}
27232 where a representation clause for a record type specified
27233 32 bits for a component of type @code{Address}.
27234 All of these errors were detected by the compiler.
27235 The repair was obvious and immediate; to simply replace @code{Address} by
27236 @code{Short_Address}.
27237
27238 In the case of STARLET, there were several record types that should
27239 have had representation clauses but did not.  In these record types
27240 there was an implicit assumption that an @code{Address} value occupied
27241 32 bits.
27242 These compiled without error, but their usage resulted in run-time error
27243 returns from STARLET system calls.
27244 Future GNAT technology enhancements may include a tool that detects and flags
27245 these sorts of potential source code porting problems.
27246
27247 @c ****************************************
27248 @node Taking advantage of 64 bit addressing
27249 @subsection Taking advantage of 64-bit addressing
27250
27251 @menu
27252 * Making code 64 bit clean::
27253 * Allocating memory from the 64 bit storage pool::
27254 * Restrictions on use of 64 bit objects::
27255 * STARLET and other predefined libraries::
27256 @end menu
27257
27258 @node Making code 64 bit clean
27259 @subsubsection Making code 64-bit clean
27260
27261 @noindent
27262 In order to prevent problems that may occur when (parts of) a
27263 system start using memory outside the 32-bit address range,
27264 we recommend some additional guidelines:
27265
27266 @itemize @bullet
27267 @item
27268 For imported subprograms that take parameters of the
27269 type @code{System.Address}, ensure that these subprograms can
27270 indeed handle 64-bit addresses. If not, or when in doubt,
27271 change the subprogram declaration to specify
27272 @code{System.Short_Address} instead.
27273
27274 @item
27275 Resolve all warnings related to size mismatches in
27276 unchecked conversions. Failing to do so causes
27277 erroneous execution if the source object is outside
27278 the 32-bit address space.
27279
27280 @item
27281 (optional) Explicitly use the 32-bit storage pool
27282 for access types used in a 32-bit context, or use
27283 generic access types where possible
27284 (@pxref{Restrictions on use of 64 bit objects}).
27285 @end itemize
27286
27287 @noindent
27288 If these rules are followed, the compiler will automatically insert
27289 any necessary checks to ensure that no addresses or access values
27290 passed to 32-bit code ever refer to objects outside the 32-bit
27291 address range.
27292 Any attempt to do this will raise @code{Constraint_Error}.
27293
27294 @node Allocating memory from the 64 bit storage pool
27295 @subsubsection Allocating memory from the 64-bit storage pool
27296
27297 @noindent
27298 By default, all allocations -- for both pool-specific and general
27299 access types -- use the 64-bit storage pool.  To override
27300 this default, for an individual access type or globally, see
27301 @ref{Access types and 32/64-bit allocation}.
27302
27303 @node Restrictions on use of 64 bit objects
27304 @subsubsection Restrictions on use of 64-bit objects
27305
27306 @noindent
27307 Taking the address of an object allocated from a 64-bit storage pool,
27308 and then passing this address to a subprogram expecting
27309 @code{System.Short_Address},
27310 or assigning it to a variable of type @code{Short_Address}, will cause
27311 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27312 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27313 no exception is raised and execution
27314 will become erroneous.
27315
27316 @node STARLET and other predefined libraries
27317 @subsubsection STARLET and other predefined libraries
27318
27319 @noindent
27320 All code that comes as part of GNAT is 64-bit clean, but the
27321 restrictions given in @ref{Restrictions on use of 64 bit objects},
27322 still apply. Look at the package
27323 specs to see in which contexts objects allocated
27324 in 64-bit address space are acceptable.
27325
27326 @node Technical details
27327 @subsection Technical details
27328
27329 @noindent
27330 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27331 Ada standard with respect to the type of @code{System.Address}. Previous
27332 versions of @value{EDITION} have defined this type as private and implemented it as a
27333 modular type.
27334
27335 In order to allow defining @code{System.Short_Address} as a proper subtype,
27336 and to match the implicit sign extension in parameter passing,
27337 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27338 visible (i.e., non-private) integer type.
27339 Standard operations on the type, such as the binary operators ``+'', ``-'',
27340 etc., that take @code{Address} operands and return an @code{Address} result,
27341 have been hidden by declaring these
27342 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27343 ambiguities that would otherwise result from overloading.
27344 (Note that, although @code{Address} is a visible integer type,
27345 good programming practice dictates against exploiting the type's
27346 integer properties such as literals, since this will compromise
27347 code portability.)
27348
27349 Defining @code{Address} as a visible integer type helps achieve
27350 maximum compatibility for existing Ada code,
27351 without sacrificing the capabilities of the 64-bit architecture.
27352 @end ifset
27353
27354 @c ************************************************
27355 @ifset unw
27356 @node Microsoft Windows Topics
27357 @appendix Microsoft Windows Topics
27358 @cindex Windows NT
27359 @cindex Windows 95
27360 @cindex Windows 98
27361
27362 @noindent
27363 This chapter describes topics that are specific to the Microsoft Windows
27364 platforms (NT, 2000, and XP Professional).
27365
27366 @menu
27367 * Using GNAT on Windows::
27368 * Using a network installation of GNAT::
27369 * CONSOLE and WINDOWS subsystems::
27370 * Temporary Files::
27371 * Mixed-Language Programming on Windows::
27372 * Windows Calling Conventions::
27373 * Introduction to Dynamic Link Libraries (DLLs)::
27374 * Using DLLs with GNAT::
27375 * Building DLLs with GNAT Project files::
27376 * Building DLLs with GNAT::
27377 * Building DLLs with gnatdll::
27378 * GNAT and Windows Resources::
27379 * Debugging a DLL::
27380 * Setting Stack Size from gnatlink::
27381 * Setting Heap Size from gnatlink::
27382 @end menu
27383
27384 @node Using GNAT on Windows
27385 @section Using GNAT on Windows
27386
27387 @noindent
27388 One of the strengths of the GNAT technology is that its tool set
27389 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27390 @code{gdb} debugger, etc.) is used in the same way regardless of the
27391 platform.
27392
27393 On Windows this tool set is complemented by a number of Microsoft-specific
27394 tools that have been provided to facilitate interoperability with Windows
27395 when this is required. With these tools:
27396
27397 @itemize @bullet
27398
27399 @item
27400 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27401 subsystems.
27402
27403 @item
27404 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27405 relocatable and non-relocatable DLLs are supported).
27406
27407 @item
27408 You can build Ada DLLs for use in other applications. These applications
27409 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27410 relocatable and non-relocatable Ada DLLs are supported.
27411
27412 @item
27413 You can include Windows resources in your Ada application.
27414
27415 @item
27416 You can use or create COM/DCOM objects.
27417 @end itemize
27418
27419 @noindent
27420 Immediately below are listed all known general GNAT-for-Windows restrictions.
27421 Other restrictions about specific features like Windows Resources and DLLs
27422 are listed in separate sections below.
27423
27424 @itemize @bullet
27425
27426 @item
27427 It is not possible to use @code{GetLastError} and @code{SetLastError}
27428 when tasking, protected records, or exceptions are used. In these
27429 cases, in order to implement Ada semantics, the GNAT run-time system
27430 calls certain Win32 routines that set the last error variable to 0 upon
27431 success. It should be possible to use @code{GetLastError} and
27432 @code{SetLastError} when tasking, protected record, and exception
27433 features are not used, but it is not guaranteed to work.
27434
27435 @item
27436 It is not possible to link against Microsoft libraries except for
27437 import libraries. Interfacing must be done by the mean of DLLs.
27438
27439 @item
27440 When the compilation environment is located on FAT32 drives, users may
27441 experience recompilations of the source files that have not changed if
27442 Daylight Saving Time (DST) state has changed since the last time files
27443 were compiled. NTFS drives do not have this problem.
27444
27445 @item
27446 No components of the GNAT toolset use any entries in the Windows
27447 registry. The only entries that can be created are file associations and
27448 PATH settings, provided the user has chosen to create them at installation
27449 time, as well as some minimal book-keeping information needed to correctly
27450 uninstall or integrate different GNAT products.
27451 @end itemize
27452
27453 @node Using a network installation of GNAT
27454 @section Using a network installation of GNAT
27455
27456 @noindent
27457 Make sure the system on which GNAT is installed is accessible from the
27458 current machine, i.e., the install location is shared over the network.
27459 Shared resources are accessed on Windows by means of UNC paths, which
27460 have the format @code{\\server\sharename\path}
27461
27462 In order to use such a network installation, simply add the UNC path of the
27463 @file{bin} directory of your GNAT installation in front of your PATH. For
27464 example, if GNAT is installed in @file{\GNAT} directory of a share location
27465 called @file{c-drive} on a machine @file{LOKI}, the following command will
27466 make it available:
27467
27468 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27469
27470 Be aware that every compilation using the network installation results in the
27471 transfer of large amounts of data across the network and will likely cause
27472 serious performance penalty.
27473
27474 @node CONSOLE and WINDOWS subsystems
27475 @section CONSOLE and WINDOWS subsystems
27476 @cindex CONSOLE Subsystem
27477 @cindex WINDOWS Subsystem
27478 @cindex -mwindows
27479
27480 @noindent
27481 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27482 (which is the default subsystem) will always create a console when
27483 launching the application. This is not something desirable when the
27484 application has a Windows GUI. To get rid of this console the
27485 application must be using the @code{WINDOWS} subsystem. To do so
27486 the @option{-mwindows} linker option must be specified.
27487
27488 @smallexample
27489 $ gnatmake winprog -largs -mwindows
27490 @end smallexample
27491
27492 @node Temporary Files
27493 @section Temporary Files
27494 @cindex Temporary files
27495
27496 @noindent
27497 It is possible to control where temporary files gets created by setting
27498 the @env{TMP} environment variable. The file will be created:
27499
27500 @itemize
27501 @item Under the directory pointed to by the @env{TMP} environment variable if
27502 this directory exists.
27503
27504 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27505 set (or not pointing to a directory) and if this directory exists.
27506
27507 @item Under the current working directory otherwise.
27508 @end itemize
27509
27510 @noindent
27511 This allows you to determine exactly where the temporary
27512 file will be created. This is particularly useful in networked
27513 environments where you may not have write access to some
27514 directories.
27515
27516 @node Mixed-Language Programming on Windows
27517 @section Mixed-Language Programming on Windows
27518
27519 @noindent
27520 Developing pure Ada applications on Windows is no different than on
27521 other GNAT-supported platforms. However, when developing or porting an
27522 application that contains a mix of Ada and C/C++, the choice of your
27523 Windows C/C++ development environment conditions your overall
27524 interoperability strategy.
27525
27526 If you use @command{gcc} to compile the non-Ada part of your application,
27527 there are no Windows-specific restrictions that affect the overall
27528 interoperability with your Ada code. If you do want to use the
27529 Microsoft tools for your non-Ada code, you have two choices:
27530
27531 @enumerate
27532 @item
27533 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27534 application. In this case, use the Microsoft or whatever environment to
27535 build the DLL and use GNAT to build your executable
27536 (@pxref{Using DLLs with GNAT}).
27537
27538 @item
27539 Or you can encapsulate your Ada code in a DLL to be linked with the
27540 other part of your application. In this case, use GNAT to build the DLL
27541 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27542 or whatever environment to build your executable.
27543 @end enumerate
27544
27545 @node Windows Calling Conventions
27546 @section Windows Calling Conventions
27547 @findex Stdcall
27548 @findex APIENTRY
27549
27550 This section pertain only to Win32. On Win64 there is a single native
27551 calling convention. All convention specifiers are ignored on this
27552 platform.
27553
27554 @menu
27555 * C Calling Convention::
27556 * Stdcall Calling Convention::
27557 * Win32 Calling Convention::
27558 * DLL Calling Convention::
27559 @end menu
27560
27561 @noindent
27562 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27563 (callee), there are several ways to push @code{G}'s parameters on the
27564 stack and there are several possible scenarios to clean up the stack
27565 upon @code{G}'s return. A calling convention is an agreed upon software
27566 protocol whereby the responsibilities between the caller (@code{F}) and
27567 the callee (@code{G}) are clearly defined. Several calling conventions
27568 are available for Windows:
27569
27570 @itemize @bullet
27571 @item
27572 @code{C} (Microsoft defined)
27573
27574 @item
27575 @code{Stdcall} (Microsoft defined)
27576
27577 @item
27578 @code{Win32} (GNAT specific)
27579
27580 @item
27581 @code{DLL} (GNAT specific)
27582 @end itemize
27583
27584 @node C Calling Convention
27585 @subsection @code{C} Calling Convention
27586
27587 @noindent
27588 This is the default calling convention used when interfacing to C/C++
27589 routines compiled with either @command{gcc} or Microsoft Visual C++.
27590
27591 In the @code{C} calling convention subprogram parameters are pushed on the
27592 stack by the caller from right to left. The caller itself is in charge of
27593 cleaning up the stack after the call. In addition, the name of a routine
27594 with @code{C} calling convention is mangled by adding a leading underscore.
27595
27596 The name to use on the Ada side when importing (or exporting) a routine
27597 with @code{C} calling convention is the name of the routine. For
27598 instance the C function:
27599
27600 @smallexample
27601 int get_val (long);
27602 @end smallexample
27603
27604 @noindent
27605 should be imported from Ada as follows:
27606
27607 @smallexample @c ada
27608 @group
27609 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27610 pragma Import (C, Get_Val, External_Name => "get_val");
27611 @end group
27612 @end smallexample
27613
27614 @noindent
27615 Note that in this particular case the @code{External_Name} parameter could
27616 have been omitted since, when missing, this parameter is taken to be the
27617 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27618 is missing, as in the above example, this parameter is set to be the
27619 @code{External_Name} with a leading underscore.
27620
27621 When importing a variable defined in C, you should always use the @code{C}
27622 calling convention unless the object containing the variable is part of a
27623 DLL (in which case you should use the @code{Stdcall} calling
27624 convention, @pxref{Stdcall Calling Convention}).
27625
27626 @node Stdcall Calling Convention
27627 @subsection @code{Stdcall} Calling Convention
27628
27629 @noindent
27630 This convention, which was the calling convention used for Pascal
27631 programs, is used by Microsoft for all the routines in the Win32 API for
27632 efficiency reasons. It must be used to import any routine for which this
27633 convention was specified.
27634
27635 In the @code{Stdcall} calling convention subprogram parameters are pushed
27636 on the stack by the caller from right to left. The callee (and not the
27637 caller) is in charge of cleaning the stack on routine exit. In addition,
27638 the name of a routine with @code{Stdcall} calling convention is mangled by
27639 adding a leading underscore (as for the @code{C} calling convention) and a
27640 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27641 bytes) of the parameters passed to the routine.
27642
27643 The name to use on the Ada side when importing a C routine with a
27644 @code{Stdcall} calling convention is the name of the C routine. The leading
27645 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27646 the compiler. For instance the Win32 function:
27647
27648 @smallexample
27649 @b{APIENTRY} int get_val (long);
27650 @end smallexample
27651
27652 @noindent
27653 should be imported from Ada as follows:
27654
27655 @smallexample @c ada
27656 @group
27657 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27658 pragma Import (Stdcall, Get_Val);
27659 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27660 @end group
27661 @end smallexample
27662
27663 @noindent
27664 As for the @code{C} calling convention, when the @code{External_Name}
27665 parameter is missing, it is taken to be the name of the Ada entity in lower
27666 case. If instead of writing the above import pragma you write:
27667
27668 @smallexample @c ada
27669 @group
27670 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27671 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27672 @end group
27673 @end smallexample
27674
27675 @noindent
27676 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27677 of specifying the @code{External_Name} parameter you specify the
27678 @code{Link_Name} as in the following example:
27679
27680 @smallexample @c ada
27681 @group
27682 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27683 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27684 @end group
27685 @end smallexample
27686
27687 @noindent
27688 then the imported routine is @code{retrieve_val}, that is, there is no
27689 decoration at all. No leading underscore and no Stdcall suffix
27690 @code{@@}@code{@var{nn}}.
27691
27692 @noindent
27693 This is especially important as in some special cases a DLL's entry
27694 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27695 name generated for a call has it.
27696
27697 @noindent
27698 It is also possible to import variables defined in a DLL by using an
27699 import pragma for a variable. As an example, if a DLL contains a
27700 variable defined as:
27701
27702 @smallexample
27703 int my_var;
27704 @end smallexample
27705
27706 @noindent
27707 then, to access this variable from Ada you should write:
27708
27709 @smallexample @c ada
27710 @group
27711 My_Var : Interfaces.C.int;
27712 pragma Import (Stdcall, My_Var);
27713 @end group
27714 @end smallexample
27715
27716 @noindent
27717 Note that to ease building cross-platform bindings this convention
27718 will be handled as a @code{C} calling convention on non-Windows platforms.
27719
27720 @node Win32 Calling Convention
27721 @subsection @code{Win32} Calling Convention
27722
27723 @noindent
27724 This convention, which is GNAT-specific is fully equivalent to the
27725 @code{Stdcall} calling convention described above.
27726
27727 @node DLL Calling Convention
27728 @subsection @code{DLL} Calling Convention
27729
27730 @noindent
27731 This convention, which is GNAT-specific is fully equivalent to the
27732 @code{Stdcall} calling convention described above.
27733
27734 @node Introduction to Dynamic Link Libraries (DLLs)
27735 @section Introduction to Dynamic Link Libraries (DLLs)
27736 @findex DLL
27737
27738 @noindent
27739 A Dynamically Linked Library (DLL) is a library that can be shared by
27740 several applications running under Windows. A DLL can contain any number of
27741 routines and variables.
27742
27743 One advantage of DLLs is that you can change and enhance them without
27744 forcing all the applications that depend on them to be relinked or
27745 recompiled. However, you should be aware than all calls to DLL routines are
27746 slower since, as you will understand below, such calls are indirect.
27747
27748 To illustrate the remainder of this section, suppose that an application
27749 wants to use the services of a DLL @file{API.dll}. To use the services
27750 provided by @file{API.dll} you must statically link against the DLL or
27751 an import library which contains a jump table with an entry for each
27752 routine and variable exported by the DLL. In the Microsoft world this
27753 import library is called @file{API.lib}. When using GNAT this import
27754 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27755 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27756
27757 After you have linked your application with the DLL or the import library
27758 and you run your application, here is what happens:
27759
27760 @enumerate
27761 @item
27762 Your application is loaded into memory.
27763
27764 @item
27765 The DLL @file{API.dll} is mapped into the address space of your
27766 application. This means that:
27767
27768 @itemize @bullet
27769 @item
27770 The DLL will use the stack of the calling thread.
27771
27772 @item
27773 The DLL will use the virtual address space of the calling process.
27774
27775 @item
27776 The DLL will allocate memory from the virtual address space of the calling
27777 process.
27778
27779 @item
27780 Handles (pointers) can be safely exchanged between routines in the DLL
27781 routines and routines in the application using the DLL.
27782 @end itemize
27783
27784 @item
27785 The entries in the jump table (from the import library @file{libAPI.dll.a}
27786 or @file{API.lib} or automatically created when linking against a DLL)
27787 which is part of your application are initialized with the addresses
27788 of the routines and variables in @file{API.dll}.
27789
27790 @item
27791 If present in @file{API.dll}, routines @code{DllMain} or
27792 @code{DllMainCRTStartup} are invoked. These routines typically contain
27793 the initialization code needed for the well-being of the routines and
27794 variables exported by the DLL.
27795 @end enumerate
27796
27797 @noindent
27798 There is an additional point which is worth mentioning. In the Windows
27799 world there are two kind of DLLs: relocatable and non-relocatable
27800 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27801 in the target application address space. If the addresses of two
27802 non-relocatable DLLs overlap and these happen to be used by the same
27803 application, a conflict will occur and the application will run
27804 incorrectly. Hence, when possible, it is always preferable to use and
27805 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27806 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27807 User's Guide) removes the debugging symbols from the DLL but the DLL can
27808 still be relocated.
27809
27810 As a side note, an interesting difference between Microsoft DLLs and
27811 Unix shared libraries, is the fact that on most Unix systems all public
27812 routines are exported by default in a Unix shared library, while under
27813 Windows it is possible (but not required) to list exported routines in
27814 a definition file (@pxref{The Definition File}).
27815
27816 @node Using DLLs with GNAT
27817 @section Using DLLs with GNAT
27818
27819 @menu
27820 * Creating an Ada Spec for the DLL Services::
27821 * Creating an Import Library::
27822 @end menu
27823
27824 @noindent
27825 To use the services of a DLL, say @file{API.dll}, in your Ada application
27826 you must have:
27827
27828 @enumerate
27829 @item
27830 The Ada spec for the routines and/or variables you want to access in
27831 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27832 header files provided with the DLL.
27833
27834 @item
27835 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27836 mentioned an import library is a statically linked library containing the
27837 import table which will be filled at load time to point to the actual
27838 @file{API.dll} routines. Sometimes you don't have an import library for the
27839 DLL you want to use. The following sections will explain how to build
27840 one. Note that this is optional.
27841
27842 @item
27843 The actual DLL, @file{API.dll}.
27844 @end enumerate
27845
27846 @noindent
27847 Once you have all the above, to compile an Ada application that uses the
27848 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27849 you simply issue the command
27850
27851 @smallexample
27852 $ gnatmake my_ada_app -largs -lAPI
27853 @end smallexample
27854
27855 @noindent
27856 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27857 tells the GNAT linker to look for an import library. The linker will
27858 look for a library name in this specific order:
27859
27860 @enumerate
27861 @item @file{libAPI.dll.a}
27862 @item @file{API.dll.a}
27863 @item @file{libAPI.a}
27864 @item @file{API.lib}
27865 @item @file{libAPI.dll}
27866 @item @file{API.dll}
27867 @end enumerate
27868
27869 The first three are the GNU style import libraries. The third is the
27870 Microsoft style import libraries. The last two are the actual DLL names.
27871
27872 Note that if the Ada package spec for @file{API.dll} contains the
27873 following pragma
27874
27875 @smallexample @c ada
27876 pragma Linker_Options ("-lAPI");
27877 @end smallexample
27878
27879 @noindent
27880 you do not have to add @option{-largs -lAPI} at the end of the
27881 @command{gnatmake} command.
27882
27883 If any one of the items above is missing you will have to create it
27884 yourself. The following sections explain how to do so using as an
27885 example a fictitious DLL called @file{API.dll}.
27886
27887 @node Creating an Ada Spec for the DLL Services
27888 @subsection Creating an Ada Spec for the DLL Services
27889
27890 @noindent
27891 A DLL typically comes with a C/C++ header file which provides the
27892 definitions of the routines and variables exported by the DLL. The Ada
27893 equivalent of this header file is a package spec that contains definitions
27894 for the imported entities. If the DLL you intend to use does not come with
27895 an Ada spec you have to generate one such spec yourself. For example if
27896 the header file of @file{API.dll} is a file @file{api.h} containing the
27897 following two definitions:
27898
27899 @smallexample
27900 @group
27901 @cartouche
27902 int some_var;
27903 int get (char *);
27904 @end cartouche
27905 @end group
27906 @end smallexample
27907
27908 @noindent
27909 then the equivalent Ada spec could be:
27910
27911 @smallexample @c ada
27912 @group
27913 @cartouche
27914 with Interfaces.C.Strings;
27915 package API is
27916    use Interfaces;
27917
27918    Some_Var : C.int;
27919    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27920
27921 private
27922    pragma Import (C, Get);
27923    pragma Import (DLL, Some_Var);
27924 end API;
27925 @end cartouche
27926 @end group
27927 @end smallexample
27928
27929 @noindent
27930 Note that a variable is
27931 @strong{always imported with a DLL convention}. A function
27932 can have @code{C} or @code{Stdcall} convention.
27933 (@pxref{Windows Calling Conventions}).
27934
27935 @node Creating an Import Library
27936 @subsection Creating an Import Library
27937 @cindex Import library
27938
27939 @menu
27940 * The Definition File::
27941 * GNAT-Style Import Library::
27942 * Microsoft-Style Import Library::
27943 @end menu
27944
27945 @noindent
27946 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27947 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27948 with @file{API.dll} you can skip this section. You can also skip this
27949 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27950 as in this case it is possible to link directly against the
27951 DLL. Otherwise read on.
27952
27953 @node The Definition File
27954 @subsubsection The Definition File
27955 @cindex Definition file
27956 @findex .def
27957
27958 @noindent
27959 As previously mentioned, and unlike Unix systems, the list of symbols
27960 that are exported from a DLL must be provided explicitly in Windows.
27961 The main goal of a definition file is precisely that: list the symbols
27962 exported by a DLL. A definition file (usually a file with a @code{.def}
27963 suffix) has the following structure:
27964
27965 @smallexample
27966 @group
27967 @cartouche
27968 @r{[}LIBRARY @var{name}@r{]}
27969 @r{[}DESCRIPTION @var{string}@r{]}
27970 EXPORTS
27971    @var{symbol1}
27972    @var{symbol2}
27973    @dots{}
27974 @end cartouche
27975 @end group
27976 @end smallexample
27977
27978 @table @code
27979 @item LIBRARY @var{name}
27980 This section, which is optional, gives the name of the DLL.
27981
27982 @item DESCRIPTION @var{string}
27983 This section, which is optional, gives a description string that will be
27984 embedded in the import library.
27985
27986 @item EXPORTS
27987 This section gives the list of exported symbols (procedures, functions or
27988 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27989 section of @file{API.def} looks like:
27990
27991 @smallexample
27992 @group
27993 @cartouche
27994 EXPORTS
27995    some_var
27996    get
27997 @end cartouche
27998 @end group
27999 @end smallexample
28000 @end table
28001
28002 @noindent
28003 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28004 (@pxref{Windows Calling Conventions}) for a Stdcall
28005 calling convention function in the exported symbols list.
28006
28007 @noindent
28008 There can actually be other sections in a definition file, but these
28009 sections are not relevant to the discussion at hand.
28010
28011 @node GNAT-Style Import Library
28012 @subsubsection GNAT-Style Import Library
28013
28014 @noindent
28015 To create a static import library from @file{API.dll} with the GNAT tools
28016 you should proceed as follows:
28017
28018 @enumerate
28019 @item
28020 Create the definition file @file{API.def} (@pxref{The Definition File}).
28021 For that use the @code{dll2def} tool as follows:
28022
28023 @smallexample
28024 $ dll2def API.dll > API.def
28025 @end smallexample
28026
28027 @noindent
28028 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28029 to standard output the list of entry points in the DLL. Note that if
28030 some routines in the DLL have the @code{Stdcall} convention
28031 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28032 suffix then you'll have to edit @file{api.def} to add it, and specify
28033 @option{-k} to @command{gnatdll} when creating the import library.
28034
28035 @noindent
28036 Here are some hints to find the right @code{@@}@var{nn} suffix.
28037
28038 @enumerate
28039 @item
28040 If you have the Microsoft import library (.lib), it is possible to get
28041 the right symbols by using Microsoft @code{dumpbin} tool (see the
28042 corresponding Microsoft documentation for further details).
28043
28044 @smallexample
28045 $ dumpbin /exports api.lib
28046 @end smallexample
28047
28048 @item
28049 If you have a message about a missing symbol at link time the compiler
28050 tells you what symbol is expected. You just have to go back to the
28051 definition file and add the right suffix.
28052 @end enumerate
28053
28054 @item
28055 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28056 (@pxref{Using gnatdll}) as follows:
28057
28058 @smallexample
28059 $ gnatdll -e API.def -d API.dll
28060 @end smallexample
28061
28062 @noindent
28063 @code{gnatdll} takes as input a definition file @file{API.def} and the
28064 name of the DLL containing the services listed in the definition file
28065 @file{API.dll}. The name of the static import library generated is
28066 computed from the name of the definition file as follows: if the
28067 definition file name is @var{xyz}@code{.def}, the import library name will
28068 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28069 @option{-e} could have been removed because the name of the definition
28070 file (before the ``@code{.def}'' suffix) is the same as the name of the
28071 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28072 @end enumerate
28073
28074 @node Microsoft-Style Import Library
28075 @subsubsection Microsoft-Style Import Library
28076
28077 @noindent
28078 With GNAT you can either use a GNAT-style or Microsoft-style import
28079 library. A Microsoft import library is needed only if you plan to make an
28080 Ada DLL available to applications developed with Microsoft
28081 tools (@pxref{Mixed-Language Programming on Windows}).
28082
28083 To create a Microsoft-style import library for @file{API.dll} you
28084 should proceed as follows:
28085
28086 @enumerate
28087 @item
28088 Create the definition file @file{API.def} from the DLL. For this use either
28089 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28090 tool (see the corresponding Microsoft documentation for further details).
28091
28092 @item
28093 Build the actual import library using Microsoft's @code{lib} utility:
28094
28095 @smallexample
28096 $ lib -machine:IX86 -def:API.def -out:API.lib
28097 @end smallexample
28098
28099 @noindent
28100 If you use the above command the definition file @file{API.def} must
28101 contain a line giving the name of the DLL:
28102
28103 @smallexample
28104 LIBRARY      "API"
28105 @end smallexample
28106
28107 @noindent
28108 See the Microsoft documentation for further details about the usage of
28109 @code{lib}.
28110 @end enumerate
28111
28112 @node Building DLLs with GNAT Project files
28113 @section Building DLLs with GNAT Project files
28114 @cindex DLLs, building
28115
28116 @noindent
28117 There is nothing specific to Windows in the build process.
28118 @pxref{Library Projects}.
28119
28120 @noindent
28121 Due to a system limitation, it is not possible under Windows to create threads
28122 when inside the @code{DllMain} routine which is used for auto-initialization
28123 of shared libraries, so it is not possible to have library level tasks in SALs.
28124
28125 @node Building DLLs with GNAT
28126 @section Building DLLs with GNAT
28127 @cindex DLLs, building
28128
28129 @noindent
28130 This section explain how to build DLLs using the GNAT built-in DLL
28131 support. With the following procedure it is straight forward to build
28132 and use DLLs with GNAT.
28133
28134 @enumerate
28135
28136 @item building object files
28137
28138 The first step is to build all objects files that are to be included
28139 into the DLL. This is done by using the standard @command{gnatmake} tool.
28140
28141 @item building the DLL
28142
28143 To build the DLL you must use @command{gcc}'s @option{-shared} and
28144 @option{-shared-libgcc} options. It is quite simple to use this method:
28145
28146 @smallexample
28147 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28148 @end smallexample
28149
28150 It is important to note that in this case all symbols found in the
28151 object files are automatically exported. It is possible to restrict
28152 the set of symbols to export by passing to @command{gcc} a definition
28153 file, @pxref{The Definition File}. For example:
28154
28155 @smallexample
28156 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28157 @end smallexample
28158
28159 If you use a definition file you must export the elaboration procedures
28160 for every package that required one. Elaboration procedures are named
28161 using the package name followed by "_E".
28162
28163 @item preparing DLL to be used
28164
28165 For the DLL to be used by client programs the bodies must be hidden
28166 from it and the .ali set with read-only attribute. This is very important
28167 otherwise GNAT will recompile all packages and will not actually use
28168 the code in the DLL. For example:
28169
28170 @smallexample
28171 $ mkdir apilib
28172 $ copy *.ads *.ali api.dll apilib
28173 $ attrib +R apilib\*.ali
28174 @end smallexample
28175
28176 @end enumerate
28177
28178 At this point it is possible to use the DLL by directly linking
28179 against it. Note that you must use the GNAT shared runtime when using
28180 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28181 option.
28182
28183 @smallexample
28184 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28185 @end smallexample
28186
28187 @node Building DLLs with gnatdll
28188 @section Building DLLs with gnatdll
28189 @cindex DLLs, building
28190
28191 @menu
28192 * Limitations When Using Ada DLLs from Ada::
28193 * Exporting Ada Entities::
28194 * Ada DLLs and Elaboration::
28195 * Ada DLLs and Finalization::
28196 * Creating a Spec for Ada DLLs::
28197 * Creating the Definition File::
28198 * Using gnatdll::
28199 @end menu
28200
28201 @noindent
28202 Note that it is preferred to use GNAT Project files
28203 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28204 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28205
28206 This section explains how to build DLLs containing Ada code using
28207 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28208 remainder of this section.
28209
28210 The steps required to build an Ada DLL that is to be used by Ada as well as
28211 non-Ada applications are as follows:
28212
28213 @enumerate
28214 @item
28215 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28216 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28217 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28218 skip this step if you plan to use the Ada DLL only from Ada applications.
28219
28220 @item
28221 Your Ada code must export an initialization routine which calls the routine
28222 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28223 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28224 routine exported by the Ada DLL must be invoked by the clients of the DLL
28225 to initialize the DLL.
28226
28227 @item
28228 When useful, the DLL should also export a finalization routine which calls
28229 routine @code{adafinal} generated by @command{gnatbind} to perform the
28230 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28231 The finalization routine exported by the Ada DLL must be invoked by the
28232 clients of the DLL when the DLL services are no further needed.
28233
28234 @item
28235 You must provide a spec for the services exported by the Ada DLL in each
28236 of the programming languages to which you plan to make the DLL available.
28237
28238 @item
28239 You must provide a definition file listing the exported entities
28240 (@pxref{The Definition File}).
28241
28242 @item
28243 Finally you must use @code{gnatdll} to produce the DLL and the import
28244 library (@pxref{Using gnatdll}).
28245 @end enumerate
28246
28247 @noindent
28248 Note that a relocatable DLL stripped using the @code{strip}
28249 binutils tool will not be relocatable anymore. To build a DLL without
28250 debug information pass @code{-largs -s} to @code{gnatdll}. This
28251 restriction does not apply to a DLL built using a Library Project.
28252 @pxref{Library Projects}.
28253
28254 @node Limitations When Using Ada DLLs from Ada
28255 @subsection Limitations When Using Ada DLLs from Ada
28256
28257 @noindent
28258 When using Ada DLLs from Ada applications there is a limitation users
28259 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28260 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28261 each Ada DLL includes the services of the GNAT run time that are necessary
28262 to the Ada code inside the DLL. As a result, when an Ada program uses an
28263 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28264 one in the main program.
28265
28266 It is therefore not possible to exchange GNAT run-time objects between the
28267 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28268 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28269 types, etc.
28270
28271 It is completely safe to exchange plain elementary, array or record types,
28272 Windows object handles, etc.
28273
28274 @node Exporting Ada Entities
28275 @subsection Exporting Ada Entities
28276 @cindex Export table
28277
28278 @noindent
28279 Building a DLL is a way to encapsulate a set of services usable from any
28280 application. As a result, the Ada entities exported by a DLL should be
28281 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28282 any Ada name mangling. As an example here is an Ada package
28283 @code{API}, spec and body, exporting two procedures, a function, and a
28284 variable:
28285
28286 @smallexample @c ada
28287 @group
28288 @cartouche
28289 with Interfaces.C; use Interfaces;
28290 package API is
28291    Count : C.int := 0;
28292    function Factorial (Val : C.int) return C.int;
28293
28294    procedure Initialize_API;
28295    procedure Finalize_API;
28296    --  Initialization & Finalization routines. More in the next section.
28297 private
28298    pragma Export (C, Initialize_API);
28299    pragma Export (C, Finalize_API);
28300    pragma Export (C, Count);
28301    pragma Export (C, Factorial);
28302 end API;
28303 @end cartouche
28304 @end group
28305 @end smallexample
28306
28307 @smallexample @c ada
28308 @group
28309 @cartouche
28310 package body API is
28311    function Factorial (Val : C.int) return C.int is
28312       Fact : C.int := 1;
28313    begin
28314       Count := Count + 1;
28315       for K in 1 .. Val loop
28316          Fact := Fact * K;
28317       end loop;
28318       return Fact;
28319    end Factorial;
28320
28321    procedure Initialize_API is
28322       procedure Adainit;
28323       pragma Import (C, Adainit);
28324    begin
28325       Adainit;
28326    end Initialize_API;
28327
28328    procedure Finalize_API is
28329       procedure Adafinal;
28330       pragma Import (C, Adafinal);
28331    begin
28332       Adafinal;
28333    end Finalize_API;
28334 end API;
28335 @end cartouche
28336 @end group
28337 @end smallexample
28338
28339 @noindent
28340 If the Ada DLL you are building will only be used by Ada applications
28341 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28342 convention. As an example, the previous package could be written as
28343 follows:
28344
28345 @smallexample @c ada
28346 @group
28347 @cartouche
28348 package API is
28349    Count : Integer := 0;
28350    function Factorial (Val : Integer) return Integer;
28351
28352    procedure Initialize_API;
28353    procedure Finalize_API;
28354    --  Initialization and Finalization routines.
28355 end API;
28356 @end cartouche
28357 @end group
28358 @end smallexample
28359
28360 @smallexample @c ada
28361 @group
28362 @cartouche
28363 package body API is
28364    function Factorial (Val : Integer) return Integer is
28365       Fact : Integer := 1;
28366    begin
28367       Count := Count + 1;
28368       for K in 1 .. Val loop
28369          Fact := Fact * K;
28370       end loop;
28371       return Fact;
28372    end Factorial;
28373
28374    @dots{}
28375    --  The remainder of this package body is unchanged.
28376 end API;
28377 @end cartouche
28378 @end group
28379 @end smallexample
28380
28381 @noindent
28382 Note that if you do not export the Ada entities with a @code{C} or
28383 @code{Stdcall} convention you will have to provide the mangled Ada names
28384 in the definition file of the Ada DLL
28385 (@pxref{Creating the Definition File}).
28386
28387 @node Ada DLLs and Elaboration
28388 @subsection Ada DLLs and Elaboration
28389 @cindex DLLs and elaboration
28390
28391 @noindent
28392 The DLL that you are building contains your Ada code as well as all the
28393 routines in the Ada library that are needed by it. The first thing a
28394 user of your DLL must do is elaborate the Ada code
28395 (@pxref{Elaboration Order Handling in GNAT}).
28396
28397 To achieve this you must export an initialization routine
28398 (@code{Initialize_API} in the previous example), which must be invoked
28399 before using any of the DLL services. This elaboration routine must call
28400 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28401 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28402 @code{Initialize_Api} for an example. Note that the GNAT binder is
28403 automatically invoked during the DLL build process by the @code{gnatdll}
28404 tool (@pxref{Using gnatdll}).
28405
28406 When a DLL is loaded, Windows systematically invokes a routine called
28407 @code{DllMain}. It would therefore be possible to call @code{adainit}
28408 directly from @code{DllMain} without having to provide an explicit
28409 initialization routine. Unfortunately, it is not possible to call
28410 @code{adainit} from the @code{DllMain} if your program has library level
28411 tasks because access to the @code{DllMain} entry point is serialized by
28412 the system (that is, only a single thread can execute ``through'' it at a
28413 time), which means that the GNAT run time will deadlock waiting for the
28414 newly created task to complete its initialization.
28415
28416 @node Ada DLLs and Finalization
28417 @subsection Ada DLLs and Finalization
28418 @cindex DLLs and finalization
28419
28420 @noindent
28421 When the services of an Ada DLL are no longer needed, the client code should
28422 invoke the DLL finalization routine, if available. The DLL finalization
28423 routine is in charge of releasing all resources acquired by the DLL. In the
28424 case of the Ada code contained in the DLL, this is achieved by calling
28425 routine @code{adafinal} generated by the GNAT binder
28426 (@pxref{Binding with Non-Ada Main Programs}).
28427 See the body of @code{Finalize_Api} for an
28428 example. As already pointed out the GNAT binder is automatically invoked
28429 during the DLL build process by the @code{gnatdll} tool
28430 (@pxref{Using gnatdll}).
28431
28432 @node Creating a Spec for Ada DLLs
28433 @subsection Creating a Spec for Ada DLLs
28434
28435 @noindent
28436 To use the services exported by the Ada DLL from another programming
28437 language (e.g.@: C), you have to translate the specs of the exported Ada
28438 entities in that language. For instance in the case of @code{API.dll},
28439 the corresponding C header file could look like:
28440
28441 @smallexample
28442 @group
28443 @cartouche
28444 extern int *_imp__count;
28445 #define count (*_imp__count)
28446 int factorial (int);
28447 @end cartouche
28448 @end group
28449 @end smallexample
28450
28451 @noindent
28452 It is important to understand that when building an Ada DLL to be used by
28453 other Ada applications, you need two different specs for the packages
28454 contained in the DLL: one for building the DLL and the other for using
28455 the DLL. This is because the @code{DLL} calling convention is needed to
28456 use a variable defined in a DLL, but when building the DLL, the variable
28457 must have either the @code{Ada} or @code{C} calling convention. As an
28458 example consider a DLL comprising the following package @code{API}:
28459
28460 @smallexample @c ada
28461 @group
28462 @cartouche
28463 package API is
28464    Count : Integer := 0;
28465    @dots{}
28466    --  Remainder of the package omitted.
28467 end API;
28468 @end cartouche
28469 @end group
28470 @end smallexample
28471
28472 @noindent
28473 After producing a DLL containing package @code{API}, the spec that
28474 must be used to import @code{API.Count} from Ada code outside of the
28475 DLL is:
28476
28477 @smallexample @c ada
28478 @group
28479 @cartouche
28480 package API is
28481    Count : Integer;
28482    pragma Import (DLL, Count);
28483 end API;
28484 @end cartouche
28485 @end group
28486 @end smallexample
28487
28488 @node Creating the Definition File
28489 @subsection Creating the Definition File
28490
28491 @noindent
28492 The definition file is the last file needed to build the DLL. It lists
28493 the exported symbols. As an example, the definition file for a DLL
28494 containing only package @code{API} (where all the entities are exported
28495 with a @code{C} calling convention) is:
28496
28497 @smallexample
28498 @group
28499 @cartouche
28500 EXPORTS
28501     count
28502     factorial
28503     finalize_api
28504     initialize_api
28505 @end cartouche
28506 @end group
28507 @end smallexample
28508
28509 @noindent
28510 If the @code{C} calling convention is missing from package @code{API},
28511 then the definition file contains the mangled Ada names of the above
28512 entities, which in this case are:
28513
28514 @smallexample
28515 @group
28516 @cartouche
28517 EXPORTS
28518     api__count
28519     api__factorial
28520     api__finalize_api
28521     api__initialize_api
28522 @end cartouche
28523 @end group
28524 @end smallexample
28525
28526 @node Using gnatdll
28527 @subsection Using @code{gnatdll}
28528 @findex gnatdll
28529
28530 @menu
28531 * gnatdll Example::
28532 * gnatdll behind the Scenes::
28533 * Using dlltool::
28534 @end menu
28535
28536 @noindent
28537 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28538 and non-Ada sources that make up your DLL have been compiled.
28539 @code{gnatdll} is actually in charge of two distinct tasks: build the
28540 static import library for the DLL and the actual DLL. The form of the
28541 @code{gnatdll} command is
28542
28543 @smallexample
28544 @cartouche
28545 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28546 @c Expanding @ovar macro inline (explanation in macro def comments)
28547 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28548 @end cartouche
28549 @end smallexample
28550
28551 @noindent
28552 where @var{list-of-files} is a list of ALI and object files. The object
28553 file list must be the exact list of objects corresponding to the non-Ada
28554 sources whose services are to be included in the DLL. The ALI file list
28555 must be the exact list of ALI files for the corresponding Ada sources
28556 whose services are to be included in the DLL. If @var{list-of-files} is
28557 missing, only the static import library is generated.
28558
28559 @noindent
28560 You may specify any of the following switches to @code{gnatdll}:
28561
28562 @table @code
28563 @c @item -a@ovar{address}
28564 @c Expanding @ovar macro inline (explanation in macro def comments)
28565 @item -a@r{[}@var{address}@r{]}
28566 @cindex @option{-a} (@code{gnatdll})
28567 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28568 specified the default address @var{0x11000000} will be used. By default,
28569 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28570 advise the reader to build relocatable DLL.
28571
28572 @item -b @var{address}
28573 @cindex @option{-b} (@code{gnatdll})
28574 Set the relocatable DLL base address. By default the address is
28575 @code{0x11000000}.
28576
28577 @item -bargs @var{opts}
28578 @cindex @option{-bargs} (@code{gnatdll})
28579 Binder options. Pass @var{opts} to the binder.
28580
28581 @item -d @var{dllfile}
28582 @cindex @option{-d} (@code{gnatdll})
28583 @var{dllfile} is the name of the DLL. This switch must be present for
28584 @code{gnatdll} to do anything. The name of the generated import library is
28585 obtained algorithmically from @var{dllfile} as shown in the following
28586 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28587 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28588 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28589 as shown in the following example:
28590 if @var{dllfile} is @code{xyz.dll}, the definition
28591 file used is @code{xyz.def}.
28592
28593 @item -e @var{deffile}
28594 @cindex @option{-e} (@code{gnatdll})
28595 @var{deffile} is the name of the definition file.
28596
28597 @item -g
28598 @cindex @option{-g} (@code{gnatdll})
28599 Generate debugging information. This information is stored in the object
28600 file and copied from there to the final DLL file by the linker,
28601 where it can be read by the debugger. You must use the
28602 @option{-g} switch if you plan on using the debugger or the symbolic
28603 stack traceback.
28604
28605 @item -h
28606 @cindex @option{-h} (@code{gnatdll})
28607 Help mode. Displays @code{gnatdll} switch usage information.
28608
28609 @item -Idir
28610 @cindex @option{-I} (@code{gnatdll})
28611 Direct @code{gnatdll} to search the @var{dir} directory for source and
28612 object files needed to build the DLL.
28613 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28614
28615 @item -k
28616 @cindex @option{-k} (@code{gnatdll})
28617 Removes the @code{@@}@var{nn} suffix from the import library's exported
28618 names, but keeps them for the link names. You must specify this
28619 option if you want to use a @code{Stdcall} function in a DLL for which
28620 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28621 of the Windows NT DLL for example. This option has no effect when
28622 @option{-n} option is specified.
28623
28624 @item -l @var{file}
28625 @cindex @option{-l} (@code{gnatdll})
28626 The list of ALI and object files used to build the DLL are listed in
28627 @var{file}, instead of being given in the command line. Each line in
28628 @var{file} contains the name of an ALI or object file.
28629
28630 @item -n
28631 @cindex @option{-n} (@code{gnatdll})
28632 No Import. Do not create the import library.
28633
28634 @item -q
28635 @cindex @option{-q} (@code{gnatdll})
28636 Quiet mode. Do not display unnecessary messages.
28637
28638 @item -v
28639 @cindex @option{-v} (@code{gnatdll})
28640 Verbose mode. Display extra information.
28641
28642 @item -largs @var{opts}
28643 @cindex @option{-largs} (@code{gnatdll})
28644 Linker options. Pass @var{opts} to the linker.
28645 @end table
28646
28647 @node gnatdll Example
28648 @subsubsection @code{gnatdll} Example
28649
28650 @noindent
28651 As an example the command to build a relocatable DLL from @file{api.adb}
28652 once @file{api.adb} has been compiled and @file{api.def} created is
28653
28654 @smallexample
28655 $ gnatdll -d api.dll api.ali
28656 @end smallexample
28657
28658 @noindent
28659 The above command creates two files: @file{libapi.dll.a} (the import
28660 library) and @file{api.dll} (the actual DLL). If you want to create
28661 only the DLL, just type:
28662
28663 @smallexample
28664 $ gnatdll -d api.dll -n api.ali
28665 @end smallexample
28666
28667 @noindent
28668 Alternatively if you want to create just the import library, type:
28669
28670 @smallexample
28671 $ gnatdll -d api.dll
28672 @end smallexample
28673
28674 @node gnatdll behind the Scenes
28675 @subsubsection @code{gnatdll} behind the Scenes
28676
28677 @noindent
28678 This section details the steps involved in creating a DLL. @code{gnatdll}
28679 does these steps for you. Unless you are interested in understanding what
28680 goes on behind the scenes, you should skip this section.
28681
28682 We use the previous example of a DLL containing the Ada package @code{API},
28683 to illustrate the steps necessary to build a DLL. The starting point is a
28684 set of objects that will make up the DLL and the corresponding ALI
28685 files. In the case of this example this means that @file{api.o} and
28686 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28687 the following:
28688
28689 @enumerate
28690 @item
28691 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28692 the information necessary to generate relocation information for the
28693 DLL.
28694
28695 @smallexample
28696 @group
28697 $ gnatbind -n api
28698 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28699 @end group
28700 @end smallexample
28701
28702 @noindent
28703 In addition to the base file, the @command{gnatlink} command generates an
28704 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28705 asks @command{gnatlink} to generate the routines @code{DllMain} and
28706 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28707 is loaded into memory.
28708
28709 @item
28710 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28711 export table (@file{api.exp}). The export table contains the relocation
28712 information in a form which can be used during the final link to ensure
28713 that the Windows loader is able to place the DLL anywhere in memory.
28714
28715 @smallexample
28716 @group
28717 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28718           --output-exp api.exp
28719 @end group
28720 @end smallexample
28721
28722 @item
28723 @code{gnatdll} builds the base file using the new export table. Note that
28724 @command{gnatbind} must be called once again since the binder generated file
28725 has been deleted during the previous call to @command{gnatlink}.
28726
28727 @smallexample
28728 @group
28729 $ gnatbind -n api
28730 $ gnatlink api -o api.jnk api.exp -mdll
28731       -Wl,--base-file,api.base
28732 @end group
28733 @end smallexample
28734
28735 @item
28736 @code{gnatdll} builds the new export table using the new base file and
28737 generates the DLL import library @file{libAPI.dll.a}.
28738
28739 @smallexample
28740 @group
28741 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28742           --output-exp api.exp --output-lib libAPI.a
28743 @end group
28744 @end smallexample
28745
28746 @item
28747 Finally @code{gnatdll} builds the relocatable DLL using the final export
28748 table.
28749
28750 @smallexample
28751 @group
28752 $ gnatbind -n api
28753 $ gnatlink api api.exp -o api.dll -mdll
28754 @end group
28755 @end smallexample
28756 @end enumerate
28757
28758 @node Using dlltool
28759 @subsubsection Using @code{dlltool}
28760
28761 @noindent
28762 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28763 DLLs and static import libraries. This section summarizes the most
28764 common @code{dlltool} switches. The form of the @code{dlltool} command
28765 is
28766
28767 @smallexample
28768 @c $ dlltool @ovar{switches}
28769 @c Expanding @ovar macro inline (explanation in macro def comments)
28770 $ dlltool @r{[}@var{switches}@r{]}
28771 @end smallexample
28772
28773 @noindent
28774 @code{dlltool} switches include:
28775
28776 @table @option
28777 @item --base-file @var{basefile}
28778 @cindex @option{--base-file} (@command{dlltool})
28779 Read the base file @var{basefile} generated by the linker. This switch
28780 is used to create a relocatable DLL.
28781
28782 @item --def @var{deffile}
28783 @cindex @option{--def} (@command{dlltool})
28784 Read the definition file.
28785
28786 @item --dllname @var{name}
28787 @cindex @option{--dllname} (@command{dlltool})
28788 Gives the name of the DLL. This switch is used to embed the name of the
28789 DLL in the static import library generated by @code{dlltool} with switch
28790 @option{--output-lib}.
28791
28792 @item -k
28793 @cindex @option{-k} (@command{dlltool})
28794 Kill @code{@@}@var{nn} from exported names
28795 (@pxref{Windows Calling Conventions}
28796 for a discussion about @code{Stdcall}-style symbols.
28797
28798 @item --help
28799 @cindex @option{--help} (@command{dlltool})
28800 Prints the @code{dlltool} switches with a concise description.
28801
28802 @item --output-exp @var{exportfile}
28803 @cindex @option{--output-exp} (@command{dlltool})
28804 Generate an export file @var{exportfile}. The export file contains the
28805 export table (list of symbols in the DLL) and is used to create the DLL.
28806
28807 @item --output-lib @var{libfile}
28808 @cindex @option{--output-lib} (@command{dlltool})
28809 Generate a static import library @var{libfile}.
28810
28811 @item -v
28812 @cindex @option{-v} (@command{dlltool})
28813 Verbose mode.
28814
28815 @item --as @var{assembler-name}
28816 @cindex @option{--as} (@command{dlltool})
28817 Use @var{assembler-name} as the assembler. The default is @code{as}.
28818 @end table
28819
28820 @node GNAT and Windows Resources
28821 @section GNAT and Windows Resources
28822 @cindex Resources, windows
28823
28824 @menu
28825 * Building Resources::
28826 * Compiling Resources::
28827 * Using Resources::
28828 @end menu
28829
28830 @noindent
28831 Resources are an easy way to add Windows specific objects to your
28832 application. The objects that can be added as resources include:
28833
28834 @itemize @bullet
28835 @item menus
28836
28837 @item accelerators
28838
28839 @item dialog boxes
28840
28841 @item string tables
28842
28843 @item bitmaps
28844
28845 @item cursors
28846
28847 @item icons
28848
28849 @item fonts
28850
28851 @item version information
28852 @end itemize
28853
28854 For example, a version information resource can be defined as follow and
28855 embedded into an executable or DLL:
28856
28857 A version information resource can be used to embed information into an
28858 executable or a DLL. These information can be viewed using the file properties
28859 from the Windows Explorer. Here is an example of a version information
28860 resource:
28861
28862 @smallexample
28863 @group
28864 1 VERSIONINFO
28865 FILEVERSION     1,0,0,0
28866 PRODUCTVERSION  1,0,0,0
28867 BEGIN
28868   BLOCK "StringFileInfo"
28869   BEGIN
28870     BLOCK "080904E4"
28871     BEGIN
28872       VALUE "CompanyName", "My Company Name"
28873       VALUE "FileDescription", "My application"
28874       VALUE "FileVersion", "1.0"
28875       VALUE "InternalName", "my_app"
28876       VALUE "LegalCopyright", "My Name"
28877       VALUE "OriginalFilename", "my_app.exe"
28878       VALUE "ProductName", "My App"
28879       VALUE "ProductVersion", "1.0"
28880     END
28881   END
28882
28883   BLOCK "VarFileInfo"
28884   BEGIN
28885     VALUE "Translation", 0x809, 1252
28886   END
28887 END
28888 @end group
28889 @end smallexample
28890
28891 The value @code{0809} (langID) is for the U.K English language and
28892 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28893 multilingual.
28894
28895 @noindent
28896 This section explains how to build, compile and use resources. Note that this
28897 section does not cover all resource objects, for a complete description see
28898 the corresponding Microsoft documentation.
28899
28900 @node Building Resources
28901 @subsection Building Resources
28902 @cindex Resources, building
28903
28904 @noindent
28905 A resource file is an ASCII file. By convention resource files have an
28906 @file{.rc} extension.
28907 The easiest way to build a resource file is to use Microsoft tools
28908 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28909 @code{dlgedit.exe} to build dialogs.
28910 It is always possible to build an @file{.rc} file yourself by writing a
28911 resource script.
28912
28913 It is not our objective to explain how to write a resource file. A
28914 complete description of the resource script language can be found in the
28915 Microsoft documentation.
28916
28917 @node Compiling Resources
28918 @subsection Compiling Resources
28919 @findex rc
28920 @findex windres
28921 @cindex Resources, compiling
28922
28923 @noindent
28924 This section describes how to build a GNAT-compatible (COFF) object file
28925 containing the resources. This is done using the Resource Compiler
28926 @code{windres} as follows:
28927
28928 @smallexample
28929 $ windres -i myres.rc -o myres.o
28930 @end smallexample
28931
28932 @noindent
28933 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28934 file. You can specify an alternate preprocessor (usually named
28935 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28936 parameter. A list of all possible options may be obtained by entering
28937 the command @code{windres} @option{--help}.
28938
28939 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28940 to produce a @file{.res} file (binary resource file). See the
28941 corresponding Microsoft documentation for further details. In this case
28942 you need to use @code{windres} to translate the @file{.res} file to a
28943 GNAT-compatible object file as follows:
28944
28945 @smallexample
28946 $ windres -i myres.res -o myres.o
28947 @end smallexample
28948
28949 @node Using Resources
28950 @subsection Using Resources
28951 @cindex Resources, using
28952
28953 @noindent
28954 To include the resource file in your program just add the
28955 GNAT-compatible object file for the resource(s) to the linker
28956 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28957 option:
28958
28959 @smallexample
28960 $ gnatmake myprog -largs myres.o
28961 @end smallexample
28962
28963 @node Debugging a DLL
28964 @section Debugging a DLL
28965 @cindex DLL debugging
28966
28967 @menu
28968 * Program and DLL Both Built with GCC/GNAT::
28969 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28970 @end menu
28971
28972 @noindent
28973 Debugging a DLL is similar to debugging a standard program. But
28974 we have to deal with two different executable parts: the DLL and the
28975 program that uses it. We have the following four possibilities:
28976
28977 @enumerate 1
28978 @item
28979 The program and the DLL are built with @code{GCC/GNAT}.
28980 @item
28981 The program is built with foreign tools and the DLL is built with
28982 @code{GCC/GNAT}.
28983 @item
28984 The program is built with @code{GCC/GNAT} and the DLL is built with
28985 foreign tools.
28986 @end enumerate
28987
28988 @noindent
28989 In this section we address only cases one and two above.
28990 There is no point in trying to debug
28991 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28992 information in it. To do so you must use a debugger compatible with the
28993 tools suite used to build the DLL.
28994
28995 @node Program and DLL Both Built with GCC/GNAT
28996 @subsection Program and DLL Both Built with GCC/GNAT
28997
28998 @noindent
28999 This is the simplest case. Both the DLL and the program have @code{GDB}
29000 compatible debugging information. It is then possible to break anywhere in
29001 the process. Let's suppose here that the main procedure is named
29002 @code{ada_main} and that in the DLL there is an entry point named
29003 @code{ada_dll}.
29004
29005 @noindent
29006 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29007 program must have been built with the debugging information (see GNAT -g
29008 switch). Here are the step-by-step instructions for debugging it:
29009
29010 @enumerate 1
29011 @item Launch @code{GDB} on the main program.
29012
29013 @smallexample
29014 $ gdb -nw ada_main
29015 @end smallexample
29016
29017 @item Start the program and stop at the beginning of the main procedure
29018
29019 @smallexample
29020 (gdb) start
29021 @end smallexample
29022
29023 @noindent
29024 This step is required to be able to set a breakpoint inside the DLL. As long
29025 as the program is not run, the DLL is not loaded. This has the
29026 consequence that the DLL debugging information is also not loaded, so it is not
29027 possible to set a breakpoint in the DLL.
29028
29029 @item Set a breakpoint inside the DLL
29030
29031 @smallexample
29032 (gdb) break ada_dll
29033 (gdb) cont
29034 @end smallexample
29035
29036 @end enumerate
29037
29038 @noindent
29039 At this stage a breakpoint is set inside the DLL. From there on
29040 you can use the standard approach to debug the whole program
29041 (@pxref{Running and Debugging Ada Programs}).
29042
29043 @ignore
29044 @c This used to work, probably because the DLLs were non-relocatable
29045 @c keep this section around until the problem is sorted out.
29046
29047 To break on the @code{DllMain} routine it is not possible to follow
29048 the procedure above. At the time the program stop on @code{ada_main}
29049 the @code{DllMain} routine as already been called. Either you can use
29050 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29051
29052 @enumerate 1
29053 @item Launch @code{GDB} on the main program.
29054
29055 @smallexample
29056 $ gdb ada_main
29057 @end smallexample
29058
29059 @item Load DLL symbols
29060
29061 @smallexample
29062 (gdb) add-sym api.dll
29063 @end smallexample
29064
29065 @item Set a breakpoint inside the DLL
29066
29067 @smallexample
29068 (gdb) break ada_dll.adb:45
29069 @end smallexample
29070
29071 Note that at this point it is not possible to break using the routine symbol
29072 directly as the program is not yet running. The solution is to break
29073 on the proper line (break in @file{ada_dll.adb} line 45).
29074
29075 @item Start the program
29076
29077 @smallexample
29078 (gdb) run
29079 @end smallexample
29080
29081 @end enumerate
29082 @end ignore
29083
29084 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29085 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29086
29087 @menu
29088 * Debugging the DLL Directly::
29089 * Attaching to a Running Process::
29090 @end menu
29091
29092 @noindent
29093 In this case things are slightly more complex because it is not possible to
29094 start the main program and then break at the beginning to load the DLL and the
29095 associated DLL debugging information. It is not possible to break at the
29096 beginning of the program because there is no @code{GDB} debugging information,
29097 and therefore there is no direct way of getting initial control. This
29098 section addresses this issue by describing some methods that can be used
29099 to break somewhere in the DLL to debug it.
29100
29101 @noindent
29102 First suppose that the main procedure is named @code{main} (this is for
29103 example some C code built with Microsoft Visual C) and that there is a
29104 DLL named @code{test.dll} containing an Ada entry point named
29105 @code{ada_dll}.
29106
29107 @noindent
29108 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29109 been built with debugging information (see GNAT -g option).
29110
29111 @node Debugging the DLL Directly
29112 @subsubsection Debugging the DLL Directly
29113
29114 @enumerate 1
29115 @item
29116 Find out the executable starting address
29117
29118 @smallexample
29119 $ objdump --file-header main.exe
29120 @end smallexample
29121
29122 The starting address is reported on the last line. For example:
29123
29124 @smallexample
29125 main.exe:     file format pei-i386
29126 architecture: i386, flags 0x0000010a:
29127 EXEC_P, HAS_DEBUG, D_PAGED
29128 start address 0x00401010
29129 @end smallexample
29130
29131 @item
29132 Launch the debugger on the executable.
29133
29134 @smallexample
29135 $ gdb main.exe
29136 @end smallexample
29137
29138 @item
29139 Set a breakpoint at the starting address, and launch the program.
29140
29141 @smallexample
29142 $ (gdb) break *0x00401010
29143 $ (gdb) run
29144 @end smallexample
29145
29146 The program will stop at the given address.
29147
29148 @item
29149 Set a breakpoint on a DLL subroutine.
29150
29151 @smallexample
29152 (gdb) break ada_dll.adb:45
29153 @end smallexample
29154
29155 Or if you want to break using a symbol on the DLL, you need first to
29156 select the Ada language (language used by the DLL).
29157
29158 @smallexample
29159 (gdb) set language ada
29160 (gdb) break ada_dll
29161 @end smallexample
29162
29163 @item
29164 Continue the program.
29165
29166 @smallexample
29167 (gdb) cont
29168 @end smallexample
29169
29170 @noindent
29171 This will run the program until it reaches the breakpoint that has been
29172 set. From that point you can use the standard way to debug a program
29173 as described in (@pxref{Running and Debugging Ada Programs}).
29174
29175 @end enumerate
29176
29177 @noindent
29178 It is also possible to debug the DLL by attaching to a running process.
29179
29180 @node Attaching to a Running Process
29181 @subsubsection Attaching to a Running Process
29182 @cindex DLL debugging, attach to process
29183
29184 @noindent
29185 With @code{GDB} it is always possible to debug a running process by
29186 attaching to it. It is possible to debug a DLL this way. The limitation
29187 of this approach is that the DLL must run long enough to perform the
29188 attach operation. It may be useful for instance to insert a time wasting
29189 loop in the code of the DLL to meet this criterion.
29190
29191 @enumerate 1
29192
29193 @item Launch the main program @file{main.exe}.
29194
29195 @smallexample
29196 $ main
29197 @end smallexample
29198
29199 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29200 that the process PID for @file{main.exe} is 208.
29201
29202 @item Launch gdb.
29203
29204 @smallexample
29205 $ gdb
29206 @end smallexample
29207
29208 @item Attach to the running process to be debugged.
29209
29210 @smallexample
29211 (gdb) attach 208
29212 @end smallexample
29213
29214 @item Load the process debugging information.
29215
29216 @smallexample
29217 (gdb) symbol-file main.exe
29218 @end smallexample
29219
29220 @item Break somewhere in the DLL.
29221
29222 @smallexample
29223 (gdb) break ada_dll
29224 @end smallexample
29225
29226 @item Continue process execution.
29227
29228 @smallexample
29229 (gdb) cont
29230 @end smallexample
29231
29232 @end enumerate
29233
29234 @noindent
29235 This last step will resume the process execution, and stop at
29236 the breakpoint we have set. From there you can use the standard
29237 approach to debug a program as described in
29238 (@pxref{Running and Debugging Ada Programs}).
29239
29240 @node Setting Stack Size from gnatlink
29241 @section Setting Stack Size from @command{gnatlink}
29242
29243 @noindent
29244 It is possible to specify the program stack size at link time. On modern
29245 versions of Windows, starting with XP, this is mostly useful to set the size of
29246 the main stack (environment task). The other task stacks are set with pragma
29247 Storage_Size or with the @command{gnatbind -d} command.
29248
29249 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29250 reserve size of individual tasks, the link-time stack size applies to all
29251 tasks, and pragma Storage_Size has no effect.
29252 In particular, Stack Overflow checks are made against this
29253 link-time specified size.
29254
29255 This setting can be done with
29256 @command{gnatlink} using either:
29257
29258 @itemize @bullet
29259
29260 @item using @option{-Xlinker} linker option
29261
29262 @smallexample
29263 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29264 @end smallexample
29265
29266 This sets the stack reserve size to 0x10000 bytes and the stack commit
29267 size to 0x1000 bytes.
29268
29269 @item using @option{-Wl} linker option
29270
29271 @smallexample
29272 $ gnatlink hello -Wl,--stack=0x1000000
29273 @end smallexample
29274
29275 This sets the stack reserve size to 0x1000000 bytes. Note that with
29276 @option{-Wl} option it is not possible to set the stack commit size
29277 because the coma is a separator for this option.
29278
29279 @end itemize
29280
29281 @node Setting Heap Size from gnatlink
29282 @section Setting Heap Size from @command{gnatlink}
29283
29284 @noindent
29285 Under Windows systems, it is possible to specify the program heap size from
29286 @command{gnatlink} using either:
29287
29288 @itemize @bullet
29289
29290 @item using @option{-Xlinker} linker option
29291
29292 @smallexample
29293 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29294 @end smallexample
29295
29296 This sets the heap reserve size to 0x10000 bytes and the heap commit
29297 size to 0x1000 bytes.
29298
29299 @item using @option{-Wl} linker option
29300
29301 @smallexample
29302 $ gnatlink hello -Wl,--heap=0x1000000
29303 @end smallexample
29304
29305 This sets the heap reserve size to 0x1000000 bytes. Note that with
29306 @option{-Wl} option it is not possible to set the heap commit size
29307 because the coma is a separator for this option.
29308
29309 @end itemize
29310
29311 @end ifset
29312
29313 @c **********************************
29314 @c * GNU Free Documentation License *
29315 @c **********************************
29316 @include fdl.texi
29317 @c GNU Free Documentation License
29318
29319 @node Index,,GNU Free Documentation License, Top
29320 @unnumbered Index
29321
29322 @printindex cp
29323
29324 @contents
29325 @c Put table of contents at end, otherwise it precedes the "title page" in
29326 @c the .txt version
29327 @c Edit the pdf file to move the contents to the beginning, after the title
29328 @c page
29329
29330 @bye