OSDN Git Service

* gcc-interface/trans.c (Subprogram_Body_to_gnu): Pop the stack of
[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. In addition expressions of the form 2*x for small x
5476 generate a warning (the almost certainly accurate guess being that
5477 2**x was intended). The default is that these warnings are given.
5478
5479 @item -gnatw.M
5480 @emph{Disable warnings on suspicious modulus values.}
5481 @cindex @option{-gnatw.M} (@command{gcc})
5482 This switch disables warnings for suspicious modulus values.
5483
5484 @item -gnatwn
5485 @emph{Set normal warnings mode.}
5486 @cindex @option{-gnatwn} (@command{gcc})
5487 This switch sets normal warning mode, in which enabled warnings are
5488 issued and treated as warnings rather than errors. This is the default
5489 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5490 an explicit @option{-gnatws} or
5491 @option{-gnatwe}. It also cancels the effect of the
5492 implicit @option{-gnatwe} that is activated by the
5493 use of @option{-gnatg}.
5494
5495 @item -gnatwo
5496 @emph{Activate warnings on address clause overlays.}
5497 @cindex @option{-gnatwo} (@command{gcc})
5498 @cindex Address Clauses, warnings
5499 This switch activates warnings for possibly unintended initialization
5500 effects of defining address clauses that cause one variable to overlap
5501 another. The default is that such warnings are generated.
5502 This warning can also be turned on using @option{-gnatwa}.
5503
5504 @item -gnatwO
5505 @emph{Suppress warnings on address clause overlays.}
5506 @cindex @option{-gnatwO} (@command{gcc})
5507 This switch suppresses warnings on possibly unintended initialization
5508 effects of defining address clauses that cause one variable to overlap
5509 another.
5510
5511 @item -gnatw.o
5512 @emph{Activate warnings on modified but unreferenced out parameters.}
5513 @cindex @option{-gnatw.o} (@command{gcc})
5514 This switch activates warnings for variables that are modified by using
5515 them as actuals for a call to a procedure with an out mode formal, where
5516 the resulting assigned value is never read. It is applicable in the case
5517 where there is more than one out mode formal. If there is only one out
5518 mode formal, the warning is issued by default (controlled by -gnatwu).
5519 The warning is suppressed for volatile
5520 variables and also for variables that are renamings of other variables
5521 or for which an address clause is given.
5522 The default is that these warnings are not given. Note that this warning
5523 is not included in -gnatwa, it must be activated explicitly.
5524
5525 @item -gnatw.O
5526 @emph{Disable warnings on modified but unreferenced out parameters.}
5527 @cindex @option{-gnatw.O} (@command{gcc})
5528 This switch suppresses warnings for variables that are modified by using
5529 them as actuals for a call to a procedure with an out mode formal, where
5530 the resulting assigned value is never read.
5531
5532 @item -gnatwp
5533 @emph{Activate warnings on ineffective pragma Inlines.}
5534 @cindex @option{-gnatwp} (@command{gcc})
5535 @cindex Inlining, warnings
5536 This switch activates warnings for failure of front end inlining
5537 (activated by @option{-gnatN}) to inline a particular call. There are
5538 many reasons for not being able to inline a call, including most
5539 commonly that the call is too complex to inline. The default is
5540 that such warnings are not given.
5541 This warning can also be turned on using @option{-gnatwa}.
5542 Warnings on ineffective inlining by the gcc back-end can be activated
5543 separately, using the gcc switch -Winline.
5544
5545 @item -gnatwP
5546 @emph{Suppress warnings on ineffective pragma Inlines.}
5547 @cindex @option{-gnatwP} (@command{gcc})
5548 This switch suppresses warnings on ineffective pragma Inlines. If the
5549 inlining mechanism cannot inline a call, it will simply ignore the
5550 request silently.
5551
5552 @item -gnatw.p
5553 @emph{Activate warnings on parameter ordering.}
5554 @cindex @option{-gnatw.p} (@command{gcc})
5555 @cindex Parameter order, warnings
5556 This switch activates warnings for cases of suspicious parameter
5557 ordering when the list of arguments are all simple identifiers that
5558 match the names of the formals, but are in a different order. The
5559 warning is suppressed if any use of named parameter notation is used,
5560 so this is the appropriate way to suppress a false positive (and
5561 serves to emphasize that the "misordering" is deliberate). The
5562 default is
5563 that such warnings are not given.
5564 This warning can also be turned on using @option{-gnatwa}.
5565
5566 @item -gnatw.P
5567 @emph{Suppress warnings on parameter ordering.}
5568 @cindex @option{-gnatw.P} (@command{gcc})
5569 This switch suppresses warnings on cases of suspicious parameter
5570 ordering.
5571
5572 @item -gnatwq
5573 @emph{Activate warnings on questionable missing parentheses.}
5574 @cindex @option{-gnatwq} (@command{gcc})
5575 @cindex Parentheses, warnings
5576 This switch activates warnings for cases where parentheses are not used and
5577 the result is potential ambiguity from a readers point of view. For example
5578 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5579 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5580 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5581 follow the rule of always parenthesizing to make the association clear, and
5582 this warning switch warns if such parentheses are not present. The default
5583 is that these warnings are given.
5584 This warning can also be turned on using @option{-gnatwa}.
5585
5586 @item -gnatwQ
5587 @emph{Suppress warnings on questionable missing parentheses.}
5588 @cindex @option{-gnatwQ} (@command{gcc})
5589 This switch suppresses warnings for cases where the association is not
5590 clear and the use of parentheses is preferred.
5591
5592 @item -gnatwr
5593 @emph{Activate warnings on redundant constructs.}
5594 @cindex @option{-gnatwr} (@command{gcc})
5595 This switch activates warnings for redundant constructs. The following
5596 is the current list of constructs regarded as redundant:
5597
5598 @itemize @bullet
5599 @item
5600 Assignment of an item to itself.
5601 @item
5602 Type conversion that converts an expression to its own type.
5603 @item
5604 Use of the attribute @code{Base} where @code{typ'Base} is the same
5605 as @code{typ}.
5606 @item
5607 Use of pragma @code{Pack} when all components are placed by a record
5608 representation clause.
5609 @item
5610 Exception handler containing only a reraise statement (raise with no
5611 operand) which has no effect.
5612 @item
5613 Use of the operator abs on an operand that is known at compile time
5614 to be non-negative
5615 @item
5616 Comparison of boolean expressions to an explicit True value.
5617 @end itemize
5618
5619 This warning can also be turned on using @option{-gnatwa}.
5620 The default is that warnings for redundant constructs are not given.
5621
5622 @item -gnatwR
5623 @emph{Suppress warnings on redundant constructs.}
5624 @cindex @option{-gnatwR} (@command{gcc})
5625 This switch suppresses warnings for redundant constructs.
5626
5627 @item -gnatw.r
5628 @emph{Activate warnings for object renaming function.}
5629 @cindex @option{-gnatw.r} (@command{gcc})
5630 This switch activates warnings for an object renaming that renames a
5631 function call, which is equivalent to a constant declaration (as
5632 opposed to renaming the function itself).  The default is that these
5633 warnings are given.  This warning can also be turned on using
5634 @option{-gnatwa}.
5635
5636 @item -gnatw.R
5637 @emph{Suppress warnings for object renaming function.}
5638 @cindex @option{-gnatwT} (@command{gcc})
5639 This switch suppresses warnings for object renaming function.
5640
5641 @item -gnatws
5642 @emph{Suppress all warnings.}
5643 @cindex @option{-gnatws} (@command{gcc})
5644 This switch completely suppresses the
5645 output of all warning messages from the GNAT front end, including
5646 both warnings that can be controlled by switches described in this
5647 section, and those that are normally given unconditionally. The
5648 effect of this suppress action can only be cancelled by a subsequent
5649 use of the switch @option{-gnatwn}.
5650
5651 Note that switch @option{-gnatws} does not suppress
5652 warnings from the @command{gcc} back end.
5653 To suppress these back end warnings as well, use the switch @option{-w}
5654 in addition to @option{-gnatws}. Also this switch has no effect on the
5655 handling of style check messages.
5656
5657 @item -gnatw.s
5658 @emph{Activate warnings on overridden size clauses.}
5659 @cindex @option{-gnatw.s} (@command{gcc})
5660 @cindex Record Representation (component sizes)
5661 This switch activates warnings on component clauses in record
5662 representation clauses where the length given overrides that
5663 specified by an explicit size clause for the component type. A
5664 warning is similarly given in the array case if a specified
5665 component size overrides an explicit size clause for the array
5666 component type.
5667 Note that @option{-gnatwa} does not affect the setting of this warning option.
5668
5669 @item -gnatw.S
5670 @emph{Suppress warnings on overridden size clauses.}
5671 @cindex @option{-gnatw.S} (@command{gcc})
5672 This switch suppresses warnings on component clauses in record
5673 representation clauses that override size clauses, and similar
5674 warnings when an array component size overrides a size clause.
5675
5676 @item -gnatwt
5677 @emph{Activate warnings for tracking of deleted conditional code.}
5678 @cindex @option{-gnatwt} (@command{gcc})
5679 @cindex Deactivated code, warnings
5680 @cindex Deleted code, warnings
5681 This switch activates warnings for tracking of code in conditionals (IF and
5682 CASE statements) that is detected to be dead code which cannot be executed, and
5683 which is removed by the front end. This warning is off by default, and is not
5684 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5685 useful for detecting deactivated code in certified applications.
5686
5687 @item -gnatwT
5688 @emph{Suppress warnings for tracking of deleted conditional code.}
5689 @cindex @option{-gnatwT} (@command{gcc})
5690 This switch suppresses warnings for tracking of deleted conditional code.
5691
5692 @item -gnatw.t
5693 @emph{Activate warnings on suspicious contracts.}
5694 @cindex @option{-gnatw.t} (@command{gcc})
5695 This switch activates warnings on suspicious postconditions (whether a
5696 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012). A
5697 function postcondition is suspicious when it does not mention the result
5698 of the function. A procedure postcondition is suspicious when it only
5699 refers to the pre-state of the procedure, because in that case it should
5700 rather be expressed as a precondition. The default is that such warnings
5701 are not generated. This warning can also be turned on using @option{-gnatwa}.
5702
5703 @item -gnatw.T
5704 @emph{Suppress warnings on suspicious contracts.}
5705 @cindex @option{-gnatw.T} (@command{gcc})
5706 This switch suppresses warnings on suspicious postconditions.
5707
5708 @item -gnatwu
5709 @emph{Activate warnings on unused entities.}
5710 @cindex @option{-gnatwu} (@command{gcc})
5711 This switch activates warnings to be generated for entities that
5712 are declared but not referenced, and for units that are @code{with}'ed
5713 and not
5714 referenced. In the case of packages, a warning is also generated if
5715 no entities in the package are referenced. This means that if a with'ed
5716 package is referenced but the only references are in @code{use}
5717 clauses or @code{renames}
5718 declarations, a warning is still generated. A warning is also generated
5719 for a generic package that is @code{with}'ed but never instantiated.
5720 In the case where a package or subprogram body is compiled, and there
5721 is a @code{with} on the corresponding spec
5722 that is only referenced in the body,
5723 a warning is also generated, noting that the
5724 @code{with} can be moved to the body. The default is that
5725 such warnings are not generated.
5726 This switch also activates warnings on unreferenced formals
5727 (it includes the effect of @option{-gnatwf}).
5728 This warning can also be turned on using @option{-gnatwa}.
5729
5730 @item -gnatwU
5731 @emph{Suppress warnings on unused entities.}
5732 @cindex @option{-gnatwU} (@command{gcc})
5733 This switch suppresses warnings for unused entities and packages.
5734 It also turns off warnings on unreferenced formals (and thus includes
5735 the effect of @option{-gnatwF}).
5736
5737 @item -gnatw.u
5738 @emph{Activate warnings on unordered enumeration types.}
5739 @cindex @option{-gnatw.u} (@command{gcc})
5740 This switch causes enumeration types to be considered as conceptually
5741 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5742 The effect is to generate warnings in clients that use explicit comparisons
5743 or subranges, since these constructs both treat objects of the type as
5744 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5745 which the type is declared, or its body or subunits.) Please refer to
5746 the description of pragma @code{Ordered} in the
5747 @cite{@value{EDITION} Reference Manual} for further details.
5748 The default is that such warnings are not generated.
5749 This warning is not automatically turned on by the use of @option{-gnatwa}.
5750
5751 @item -gnatw.U
5752 @emph{Deactivate warnings on unordered enumeration types.}
5753 @cindex @option{-gnatw.U} (@command{gcc})
5754 This switch causes all enumeration types to be considered as ordered, so
5755 that no warnings are given for comparisons or subranges for any type.
5756
5757 @item -gnatwv
5758 @emph{Activate warnings on unassigned variables.}
5759 @cindex @option{-gnatwv} (@command{gcc})
5760 @cindex Unassigned variable warnings
5761 This switch activates warnings for access to variables which
5762 may not be properly initialized. The default is that
5763 such warnings are generated.
5764 This warning can also be turned on using @option{-gnatwa}.
5765
5766 @item -gnatwV
5767 @emph{Suppress warnings on unassigned variables.}
5768 @cindex @option{-gnatwV} (@command{gcc})
5769 This switch suppresses warnings for access to variables which
5770 may not be properly initialized.
5771 For variables of a composite type, the warning can also be suppressed in
5772 Ada 2005 by using a default initialization with a box. For example, if
5773 Table is an array of records whose components are only partially uninitialized,
5774 then the following code:
5775
5776 @smallexample @c ada
5777    Tab : Table := (others => <>);
5778 @end smallexample
5779
5780 will suppress warnings on subsequent statements that access components
5781 of variable Tab.
5782
5783 @item -gnatww
5784 @emph{Activate warnings on wrong low bound assumption.}
5785 @cindex @option{-gnatww} (@command{gcc})
5786 @cindex String indexing warnings
5787 This switch activates warnings for indexing an unconstrained string parameter
5788 with a literal or S'Length. This is a case where the code is assuming that the
5789 low bound is one, which is in general not true (for example when a slice is
5790 passed). The default is that such warnings are generated.
5791 This warning can also be turned on using @option{-gnatwa}.
5792
5793 @item -gnatwW
5794 @emph{Suppress warnings on wrong low bound assumption.}
5795 @cindex @option{-gnatwW} (@command{gcc})
5796 This switch suppresses warnings for indexing an unconstrained string parameter
5797 with a literal or S'Length. Note that this warning can also be suppressed
5798 in a particular case by adding an
5799 assertion that the lower bound is 1,
5800 as shown in the following example.
5801
5802 @smallexample @c ada
5803    procedure K (S : String) is
5804       pragma Assert (S'First = 1);
5805       @dots{}
5806 @end smallexample
5807
5808 @item -gnatw.w
5809 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5810 @cindex @option{-gnatw.w} (@command{gcc})
5811 @cindex Warnings Off control
5812 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5813 where either the pragma is entirely useless (because it suppresses no
5814 warnings), or it could be replaced by @code{pragma Unreferenced} or
5815 @code{pragma Unmodified}. The default is that these warnings are not given.
5816 Note that this warning is not included in -gnatwa, it must be
5817 activated explicitly.
5818
5819 @item -gnatw.W
5820 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5821 @cindex @option{-gnatw.W} (@command{gcc})
5822 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5823
5824 @item -gnatwx
5825 @emph{Activate warnings on Export/Import pragmas.}
5826 @cindex @option{-gnatwx} (@command{gcc})
5827 @cindex Export/Import pragma warnings
5828 This switch activates warnings on Export/Import pragmas when
5829 the compiler detects a possible conflict between the Ada and
5830 foreign language calling sequences. For example, the use of
5831 default parameters in a convention C procedure is dubious
5832 because the C compiler cannot supply the proper default, so
5833 a warning is issued. The default is that such warnings are
5834 generated.
5835 This warning can also be turned on using @option{-gnatwa}.
5836
5837 @item -gnatwX
5838 @emph{Suppress warnings on Export/Import pragmas.}
5839 @cindex @option{-gnatwX} (@command{gcc})
5840 This switch suppresses warnings on Export/Import pragmas.
5841 The sense of this is that you are telling the compiler that
5842 you know what you are doing in writing the pragma, and it
5843 should not complain at you.
5844
5845 @item -gnatw.x
5846 @emph{Activate warnings for No_Exception_Propagation mode.}
5847 @cindex @option{-gnatwm} (@command{gcc})
5848 This switch activates warnings for exception usage when pragma Restrictions
5849 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5850 explicit exception raises which are not covered by a local handler, and for
5851 exception handlers which do not cover a local raise. The default is that these
5852 warnings are not given.
5853
5854 @item -gnatw.X
5855 @emph{Disable warnings for No_Exception_Propagation mode.}
5856 This switch disables warnings for exception usage when pragma Restrictions
5857 (No_Exception_Propagation) is in effect.
5858
5859 @item -gnatwy
5860 @emph{Activate warnings for Ada compatibility issues.}
5861 @cindex @option{-gnatwy} (@command{gcc})
5862 @cindex Ada compatibility issues warnings
5863 For the most part, newer versions of Ada are upwards compatible
5864 with older versions. For example, Ada 2005 programs will almost
5865 always work when compiled as Ada 2012.
5866 However there are some exceptions (for example the fact that
5867 @code{some} is now a reserved word in Ada 2012). This
5868 switch activates several warnings to help in identifying
5869 and correcting such incompatibilities. The default is that
5870 these warnings are generated. Note that at one point Ada 2005
5871 was called Ada 0Y, hence the choice of character.
5872 This warning can also be turned on using @option{-gnatwa}.
5873
5874 @item -gnatwY
5875 @emph{Disable warnings for Ada compatibility issues.}
5876 @cindex @option{-gnatwY} (@command{gcc})
5877 @cindex Ada compatibility issues warnings
5878 This switch suppresses the warnings intended to help in identifying
5879 incompatibilities between Ada language versions.
5880
5881 @item -gnatwz
5882 @emph{Activate warnings on unchecked conversions.}
5883 @cindex @option{-gnatwz} (@command{gcc})
5884 @cindex Unchecked_Conversion warnings
5885 This switch activates warnings for unchecked conversions
5886 where the types are known at compile time to have different
5887 sizes. The default
5888 is that such warnings are generated. Warnings are also
5889 generated for subprogram pointers with different conventions,
5890 and, on VMS only, for data pointers with different conventions.
5891 This warning can also be turned on using @option{-gnatwa}.
5892
5893 @item -gnatwZ
5894 @emph{Suppress warnings on unchecked conversions.}
5895 @cindex @option{-gnatwZ} (@command{gcc})
5896 This switch suppresses warnings for unchecked conversions
5897 where the types are known at compile time to have different
5898 sizes or conventions.
5899
5900 @item ^-Wunused^WARNINGS=UNUSED^
5901 @cindex @option{-Wunused}
5902 The warnings controlled by the @option{-gnatw} switch are generated by
5903 the front end of the compiler. The @option{GCC} back end can provide
5904 additional warnings and they are controlled by the @option{-W} switch.
5905 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5906 warnings for entities that are declared but not referenced.
5907
5908 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5909 @cindex @option{-Wuninitialized}
5910 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5911 the back end warning for uninitialized variables. This switch must be
5912 used in conjunction with an optimization level greater than zero.
5913
5914 @item -Wstack-usage=@var{len}
5915 @cindex @option{-Wstack-usage}
5916 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5917 See @ref{Static Stack Usage Analysis} for details.
5918
5919 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5920 @cindex @option{-Wall}
5921 This switch enables most warnings from the @option{GCC} back end.
5922 The code generator detects a number of warning situations that are missed
5923 by the @option{GNAT} front end, and this switch can be used to activate them.
5924 The use of this switch also sets the default front end warning mode to
5925 @option{-gnatwa}, that is, most front end warnings activated as well.
5926
5927 @item ^-w^/NO_BACK_END_WARNINGS^
5928 @cindex @option{-w}
5929 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5930 The use of this switch also sets the default front end warning mode to
5931 @option{-gnatws}, that is, front end warnings suppressed as well.
5932
5933 @end table
5934
5935 @noindent
5936 @ifclear vms
5937 A string of warning parameters can be used in the same parameter. For example:
5938
5939 @smallexample
5940 -gnatwaGe
5941 @end smallexample
5942
5943 @noindent
5944 will turn on all optional warnings except for unrecognized pragma warnings,
5945 and also specify that warnings should be treated as errors.
5946 @end ifclear
5947
5948 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5949
5950 @table @option
5951 @c !sort!
5952 @item -gnatwB
5953 @item -gnatw.b
5954 @item -gnatwC
5955 @item -gnatw.C
5956 @item -gnatwD
5957 @item -gnatwF
5958 @item -gnatwg
5959 @item -gnatwH
5960 @item -gnatwi
5961 @item -gnatw.I
5962 @item -gnatwJ
5963 @item -gnatwK
5964 @item -gnatwL
5965 @item -gnatw.L
5966 @item -gnatwM
5967 @item -gnatw.m
5968 @item -gnatwn
5969 @item -gnatwo
5970 @item -gnatw.O
5971 @item -gnatwP
5972 @item -gnatw.P
5973 @item -gnatwq
5974 @item -gnatwR
5975 @item -gnatw.R
5976 @item -gnatw.S
5977 @item -gnatwT
5978 @item -gnatw.T
5979 @item -gnatwU
5980 @item -gnatwv
5981 @item -gnatww
5982 @item -gnatw.W
5983 @item -gnatwx
5984 @item -gnatw.X
5985 @item -gnatwy
5986 @item -gnatwz
5987
5988 @end table
5989
5990 @node Debugging and Assertion Control
5991 @subsection Debugging and Assertion Control
5992
5993 @table @option
5994 @item -gnata
5995 @cindex @option{-gnata} (@command{gcc})
5996 @findex Assert
5997 @findex Debug
5998 @cindex Assertions
5999
6000 @noindent
6001 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6002 are ignored. This switch, where @samp{a} stands for assert, causes
6003 @code{Assert} and @code{Debug} pragmas to be activated.
6004
6005 The pragmas have the form:
6006
6007 @smallexample
6008 @cartouche
6009    @b{pragma} Assert (@var{Boolean-expression} @r{[},
6010                       @var{static-string-expression}@r{]})
6011    @b{pragma} Debug (@var{procedure call})
6012 @end cartouche
6013 @end smallexample
6014
6015 @noindent
6016 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6017 If the result is @code{True}, the pragma has no effect (other than
6018 possible side effects from evaluating the expression). If the result is
6019 @code{False}, the exception @code{Assert_Failure} declared in the package
6020 @code{System.Assertions} is
6021 raised (passing @var{static-string-expression}, if present, as the
6022 message associated with the exception). If no string expression is
6023 given the default is a string giving the file name and line number
6024 of the pragma.
6025
6026 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6027 @code{pragma Debug} may appear within a declaration sequence, allowing
6028 debugging procedures to be called between declarations.
6029
6030 @ifset vms
6031 @item /DEBUG@r{[}=debug-level@r{]}
6032 @itemx  /NODEBUG
6033 Specifies how much debugging information is to be included in
6034 the resulting object file where 'debug-level' is one of the following:
6035 @table @code
6036 @item   TRACEBACK
6037 Include both debugger symbol records and traceback
6038 the object file.
6039 This is the default setting.
6040 @item   ALL
6041 Include both debugger symbol records and traceback in
6042 object file.
6043 @item   NONE
6044 Excludes both debugger symbol records and traceback
6045 the object file. Same as /NODEBUG.
6046 @item   SYMBOLS
6047 Includes only debugger symbol records in the object
6048 file. Note that this doesn't include traceback information.
6049 @end table
6050 @end ifset
6051 @end table
6052
6053 @node Validity Checking
6054 @subsection Validity Checking
6055 @findex Validity Checking
6056
6057 @noindent
6058 The Ada Reference Manual defines the concept of invalid values (see
6059 RM 13.9.1). The primary source of invalid values is uninitialized
6060 variables. A scalar variable that is left uninitialized may contain
6061 an invalid value; the concept of invalid does not apply to access or
6062 composite types.
6063
6064 It is an error to read an invalid value, but the RM does not require
6065 run-time checks to detect such errors, except for some minimal
6066 checking to prevent erroneous execution (i.e. unpredictable
6067 behavior). This corresponds to the @option{-gnatVd} switch below,
6068 which is the default. For example, by default, if the expression of a
6069 case statement is invalid, it will raise Constraint_Error rather than
6070 causing a wild jump, and if an array index on the left-hand side of an
6071 assignment is invalid, it will raise Constraint_Error rather than
6072 overwriting an arbitrary memory location.
6073
6074 The @option{-gnatVa} may be used to enable additional validity checks,
6075 which are not required by the RM. These checks are often very
6076 expensive (which is why the RM does not require them). These checks
6077 are useful in tracking down uninitialized variables, but they are
6078 not usually recommended for production builds.
6079
6080 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6081 control; you can enable whichever validity checks you desire. However,
6082 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6083 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6084 sufficient for non-debugging use.
6085
6086 The @option{-gnatB} switch tells the compiler to assume that all
6087 values are valid (that is, within their declared subtype range)
6088 except in the context of a use of the Valid attribute. This means
6089 the compiler can generate more efficient code, since the range
6090 of values is better known at compile time. However, an uninitialized
6091 variable can cause wild jumps and memory corruption in this mode.
6092
6093 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6094 checking mode as described below.
6095 @ifclear vms
6096 The @code{x} argument is a string of letters that
6097 indicate validity checks that are performed or not performed in addition
6098 to the default checks required by Ada as described above.
6099 @end ifclear
6100 @ifset vms
6101 The options allowed for this qualifier
6102 indicate validity checks that are performed or not performed in addition
6103 to the default checks required by Ada as described above.
6104 @end ifset
6105
6106 @table @option
6107 @c !sort!
6108 @item -gnatVa
6109 @emph{All validity checks.}
6110 @cindex @option{-gnatVa} (@command{gcc})
6111 All validity checks are turned on.
6112 @ifclear vms
6113 That is, @option{-gnatVa} is
6114 equivalent to @option{gnatVcdfimorst}.
6115 @end ifclear
6116
6117 @item -gnatVc
6118 @emph{Validity checks for copies.}
6119 @cindex @option{-gnatVc} (@command{gcc})
6120 The right hand side of assignments, and the initializing values of
6121 object declarations are validity checked.
6122
6123 @item -gnatVd
6124 @emph{Default (RM) validity checks.}
6125 @cindex @option{-gnatVd} (@command{gcc})
6126 Some validity checks are done by default following normal Ada semantics
6127 (RM 13.9.1 (9-11)).
6128 A check is done in case statements that the expression is within the range
6129 of the subtype. If it is not, Constraint_Error is raised.
6130 For assignments to array components, a check is done that the expression used
6131 as index is within the range. If it is not, Constraint_Error is raised.
6132 Both these validity checks may be turned off using switch @option{-gnatVD}.
6133 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6134 switch @option{-gnatVd} will leave the checks turned on.
6135 Switch @option{-gnatVD} should be used only if you are sure that all such
6136 expressions have valid values. If you use this switch and invalid values
6137 are present, then the program is erroneous, and wild jumps or memory
6138 overwriting may occur.
6139
6140 @item -gnatVe
6141 @emph{Validity checks for elementary components.}
6142 @cindex @option{-gnatVe} (@command{gcc})
6143 In the absence of this switch, assignments to record or array components are
6144 not validity checked, even if validity checks for assignments generally
6145 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6146 require valid data, but assignment of individual components does. So for
6147 example, there is a difference between copying the elements of an array with a
6148 slice assignment, compared to assigning element by element in a loop. This
6149 switch allows you to turn off validity checking for components, even when they
6150 are assigned component by component.
6151
6152 @item -gnatVf
6153 @emph{Validity checks for floating-point values.}
6154 @cindex @option{-gnatVf} (@command{gcc})
6155 In the absence of this switch, validity checking occurs only for discrete
6156 values. If @option{-gnatVf} is specified, then validity checking also applies
6157 for floating-point values, and NaNs and infinities are considered invalid,
6158 as well as out of range values for constrained types. Note that this means
6159 that standard IEEE infinity mode is not allowed. The exact contexts
6160 in which floating-point values are checked depends on the setting of other
6161 options. For example,
6162 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6163 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6164 (the order does not matter) specifies that floating-point parameters of mode
6165 @code{in} should be validity checked.
6166
6167 @item -gnatVi
6168 @emph{Validity checks for @code{in} mode parameters}
6169 @cindex @option{-gnatVi} (@command{gcc})
6170 Arguments for parameters of mode @code{in} are validity checked in function
6171 and procedure calls at the point of call.
6172
6173 @item -gnatVm
6174 @emph{Validity checks for @code{in out} mode parameters.}
6175 @cindex @option{-gnatVm} (@command{gcc})
6176 Arguments for parameters of mode @code{in out} are validity checked in
6177 procedure calls at the point of call. The @code{'m'} here stands for
6178 modify, since this concerns parameters that can be modified by the call.
6179 Note that there is no specific option to test @code{out} parameters,
6180 but any reference within the subprogram will be tested in the usual
6181 manner, and if an invalid value is copied back, any reference to it
6182 will be subject to validity checking.
6183
6184 @item -gnatVn
6185 @emph{No validity checks.}
6186 @cindex @option{-gnatVn} (@command{gcc})
6187 This switch turns off all validity checking, including the default checking
6188 for case statements and left hand side subscripts. Note that the use of
6189 the switch @option{-gnatp} suppresses all run-time checks, including
6190 validity checks, and thus implies @option{-gnatVn}. When this switch
6191 is used, it cancels any other @option{-gnatV} previously issued.
6192
6193 @item -gnatVo
6194 @emph{Validity checks for operator and attribute operands.}
6195 @cindex @option{-gnatVo} (@command{gcc})
6196 Arguments for predefined operators and attributes are validity checked.
6197 This includes all operators in package @code{Standard},
6198 the shift operators defined as intrinsic in package @code{Interfaces}
6199 and operands for attributes such as @code{Pos}. Checks are also made
6200 on individual component values for composite comparisons, and on the
6201 expressions in type conversions and qualified expressions. Checks are
6202 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6203
6204 @item -gnatVp
6205 @emph{Validity checks for parameters.}
6206 @cindex @option{-gnatVp} (@command{gcc})
6207 This controls the treatment of parameters within a subprogram (as opposed
6208 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6209 of parameters on a call. If either of these call options is used, then
6210 normally an assumption is made within a subprogram that the input arguments
6211 have been validity checking at the point of call, and do not need checking
6212 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6213 is not made, and parameters are not assumed to be valid, so their validity
6214 will be checked (or rechecked) within the subprogram.
6215
6216 @item -gnatVr
6217 @emph{Validity checks for function returns.}
6218 @cindex @option{-gnatVr} (@command{gcc})
6219 The expression in @code{return} statements in functions is validity
6220 checked.
6221
6222 @item -gnatVs
6223 @emph{Validity checks for subscripts.}
6224 @cindex @option{-gnatVs} (@command{gcc})
6225 All subscripts expressions are checked for validity, whether they appear
6226 on the right side or left side (in default mode only left side subscripts
6227 are validity checked).
6228
6229 @item -gnatVt
6230 @emph{Validity checks for tests.}
6231 @cindex @option{-gnatVt} (@command{gcc})
6232 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6233 statements are checked, as well as guard expressions in entry calls.
6234
6235 @end table
6236
6237 @noindent
6238 The @option{-gnatV} switch may be followed by
6239 ^a string of letters^a list of options^
6240 to turn on a series of validity checking options.
6241 For example,
6242 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6243 specifies that in addition to the default validity checking, copies and
6244 function return expressions are to be validity checked.
6245 In order to make it easier
6246 to specify the desired combination of effects,
6247 @ifclear vms
6248 the upper case letters @code{CDFIMORST} may
6249 be used to turn off the corresponding lower case option.
6250 @end ifclear
6251 @ifset vms
6252 the prefix @code{NO} on an option turns off the corresponding validity
6253 checking:
6254 @itemize @bullet
6255 @item @code{NOCOPIES}
6256 @item @code{NODEFAULT}
6257 @item @code{NOFLOATS}
6258 @item @code{NOIN_PARAMS}
6259 @item @code{NOMOD_PARAMS}
6260 @item @code{NOOPERANDS}
6261 @item @code{NORETURNS}
6262 @item @code{NOSUBSCRIPTS}
6263 @item @code{NOTESTS}
6264 @end itemize
6265 @end ifset
6266 Thus
6267 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6268 turns on all validity checking options except for
6269 checking of @code{@b{in out}} procedure arguments.
6270
6271 The specification of additional validity checking generates extra code (and
6272 in the case of @option{-gnatVa} the code expansion can be substantial).
6273 However, these additional checks can be very useful in detecting
6274 uninitialized variables, incorrect use of unchecked conversion, and other
6275 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6276 is useful in conjunction with the extra validity checking, since this
6277 ensures that wherever possible uninitialized variables have invalid values.
6278
6279 See also the pragma @code{Validity_Checks} which allows modification of
6280 the validity checking mode at the program source level, and also allows for
6281 temporary disabling of validity checks.
6282
6283 @node Style Checking
6284 @subsection Style Checking
6285 @findex Style checking
6286
6287 @noindent
6288 The @option{-gnaty^x^(option,option,@dots{})^} switch
6289 @cindex @option{-gnaty} (@command{gcc})
6290 causes the compiler to
6291 enforce specified style rules. A limited set of style rules has been used
6292 in writing the GNAT sources themselves. This switch allows user programs
6293 to activate all or some of these checks. If the source program fails a
6294 specified style check, an appropriate message is given, preceded by
6295 the character sequence ``(style)''. This message does not prevent
6296 successful compilation (unless the @option{-gnatwe} switch is used).
6297
6298 Note that this is by no means intended to be a general facility for
6299 checking arbitrary coding standards. It is simply an embedding of the
6300 style rules we have chosen for the GNAT sources. If you are starting
6301 a project which does not have established style standards, you may
6302 find it useful to adopt the entire set of GNAT coding standards, or
6303 some subset of them. If you already have an established set of coding
6304 standards, then it may be that selected style checking options do
6305 indeed correspond to choices you have made, but for general checking
6306 of an existing set of coding rules, you should look to the gnatcheck
6307 tool, which is designed for that purpose.
6308
6309 @ifset vms
6310 @code{(option,option,@dots{})} is a sequence of keywords
6311 @end ifset
6312 @ifclear vms
6313 The string @var{x} is a sequence of letters or digits
6314 @end ifclear
6315 indicating the particular style
6316 checks to be performed. The following checks are defined:
6317
6318 @table @option
6319 @c !sort!
6320 @item 0-9
6321 @emph{Specify indentation level.}
6322 If a digit from 1-9 appears
6323 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6324 then proper indentation is checked, with the digit indicating the
6325 indentation level required. A value of zero turns off this style check.
6326 The general style of required indentation is as specified by
6327 the examples in the Ada Reference Manual. Full line comments must be
6328 aligned with the @code{--} starting on a column that is a multiple of
6329 the alignment level, or they may be aligned the same way as the following
6330 non-blank line (this is useful when full line comments appear in the middle
6331 of a statement.
6332
6333 @item ^a^ATTRIBUTE^
6334 @emph{Check attribute casing.}
6335 Attribute names, including the case of keywords such as @code{digits}
6336 used as attributes names, must be written in mixed case, that is, the
6337 initial letter and any letter following an underscore must be uppercase.
6338 All other letters must be lowercase.
6339
6340 @item ^A^ARRAY_INDEXES^
6341 @emph{Use of array index numbers in array attributes.}
6342 When using the array attributes First, Last, Range,
6343 or Length, the index number must be omitted for one-dimensional arrays
6344 and is required for multi-dimensional arrays.
6345
6346 @item ^b^BLANKS^
6347 @emph{Blanks not allowed at statement end.}
6348 Trailing blanks are not allowed at the end of statements. The purpose of this
6349 rule, together with h (no horizontal tabs), is to enforce a canonical format
6350 for the use of blanks to separate source tokens.
6351
6352 @item ^B^BOOLEAN_OPERATORS^
6353 @emph{Check Boolean operators.}
6354 The use of AND/OR operators is not permitted except in the cases of modular
6355 operands, array operands, and simple stand-alone boolean variables or
6356 boolean constants. In all other cases @code{and then}/@code{or else} are
6357 required.
6358
6359 @item ^c^COMMENTS^
6360 @emph{Check comments, double space.}
6361 Comments must meet the following set of rules:
6362
6363 @itemize @bullet
6364
6365 @item
6366 The ``@code{--}'' that starts the column must either start in column one,
6367 or else at least one blank must precede this sequence.
6368
6369 @item
6370 Comments that follow other tokens on a line must have at least one blank
6371 following the ``@code{--}'' at the start of the comment.
6372
6373 @item
6374 Full line comments must have at least two blanks following the
6375 ``@code{--}'' that starts the comment, with the following exceptions.
6376
6377 @item
6378 A line consisting only of the ``@code{--}'' characters, possibly preceded
6379 by blanks is permitted.
6380
6381 @item
6382 A comment starting with ``@code{--x}'' where @code{x} is a special character
6383 is permitted.
6384 This allows proper processing of the output generated by specialized tools
6385 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6386 annotation
6387 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6388 special character is defined as being in one of the ASCII ranges
6389 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6390 Note that this usage is not permitted
6391 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6392
6393 @item
6394 A line consisting entirely of minus signs, possibly preceded by blanks, is
6395 permitted. This allows the construction of box comments where lines of minus
6396 signs are used to form the top and bottom of the box.
6397
6398 @item
6399 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6400 least one blank follows the initial ``@code{--}''. Together with the preceding
6401 rule, this allows the construction of box comments, as shown in the following
6402 example:
6403 @smallexample
6404 ---------------------------
6405 -- This is a box comment --
6406 -- with two text lines.  --
6407 ---------------------------
6408 @end smallexample
6409 @end itemize
6410
6411 @item ^C^COMMENTS1^
6412 @emph{Check comments, single space.}
6413 This is identical to @code{^c^COMMENTS^} except that only one space
6414 is required following the @code{--} of a comment instead of two.
6415
6416 @item ^d^DOS_LINE_ENDINGS^
6417 @emph{Check no DOS line terminators present.}
6418 All lines must be terminated by a single ASCII.LF
6419 character (in particular the DOS line terminator sequence CR/LF is not
6420 allowed).
6421
6422 @item ^e^END^
6423 @emph{Check end/exit labels.}
6424 Optional labels on @code{end} statements ending subprograms and on
6425 @code{exit} statements exiting named loops, are required to be present.
6426
6427 @item ^f^VTABS^
6428 @emph{No form feeds or vertical tabs.}
6429 Neither form feeds nor vertical tab characters are permitted
6430 in the source text.
6431
6432 @item ^g^GNAT^
6433 @emph{GNAT style mode.}
6434 The set of style check switches is set to match that used by the GNAT sources.
6435 This may be useful when developing code that is eventually intended to be
6436 incorporated into GNAT. For further details, see GNAT sources.
6437
6438 @item ^h^HTABS^
6439 @emph{No horizontal tabs.}
6440 Horizontal tab characters are not permitted in the source text.
6441 Together with the b (no blanks at end of line) check, this
6442 enforces a canonical form for the use of blanks to separate
6443 source tokens.
6444
6445 @item ^i^IF_THEN^
6446 @emph{Check if-then layout.}
6447 The keyword @code{then} must appear either on the same
6448 line as corresponding @code{if}, or on a line on its own, lined
6449 up under the @code{if} with at least one non-blank line in between
6450 containing all or part of the condition to be tested.
6451
6452 @item ^I^IN_MODE^
6453 @emph{check mode IN keywords.}
6454 Mode @code{in} (the default mode) is not
6455 allowed to be given explicitly. @code{in out} is fine,
6456 but not @code{in} on its own.
6457
6458 @item ^k^KEYWORD^
6459 @emph{Check keyword casing.}
6460 All keywords must be in lower case (with the exception of keywords
6461 such as @code{digits} used as attribute names to which this check
6462 does not apply).
6463
6464 @item ^l^LAYOUT^
6465 @emph{Check layout.}
6466 Layout of statement and declaration constructs must follow the
6467 recommendations in the Ada Reference Manual, as indicated by the
6468 form of the syntax rules. For example an @code{else} keyword must
6469 be lined up with the corresponding @code{if} keyword.
6470
6471 There are two respects in which the style rule enforced by this check
6472 option are more liberal than those in the Ada Reference Manual. First
6473 in the case of record declarations, it is permissible to put the
6474 @code{record} keyword on the same line as the @code{type} keyword, and
6475 then the @code{end} in @code{end record} must line up under @code{type}.
6476 This is also permitted when the type declaration is split on two lines.
6477 For example, any of the following three layouts is acceptable:
6478
6479 @smallexample @c ada
6480 @cartouche
6481 type q is record
6482    a : integer;
6483    b : integer;
6484 end record;
6485
6486 type q is
6487    record
6488       a : integer;
6489       b : integer;
6490    end record;
6491
6492 type q is
6493    record
6494       a : integer;
6495       b : integer;
6496 end record;
6497
6498 @end cartouche
6499 @end smallexample
6500
6501 @noindent
6502 Second, in the case of a block statement, a permitted alternative
6503 is to put the block label on the same line as the @code{declare} or
6504 @code{begin} keyword, and then line the @code{end} keyword up under
6505 the block label. For example both the following are permitted:
6506
6507 @smallexample @c ada
6508 @cartouche
6509 Block : declare
6510    A : Integer := 3;
6511 begin
6512    Proc (A, A);
6513 end Block;
6514
6515 Block :
6516    declare
6517       A : Integer := 3;
6518    begin
6519       Proc (A, A);
6520    end Block;
6521 @end cartouche
6522 @end smallexample
6523
6524 @noindent
6525 The same alternative format is allowed for loops. For example, both of
6526 the following are permitted:
6527
6528 @smallexample @c ada
6529 @cartouche
6530 Clear : while J < 10 loop
6531    A (J) := 0;
6532 end loop Clear;
6533
6534 Clear :
6535    while J < 10 loop
6536       A (J) := 0;
6537    end loop Clear;
6538 @end cartouche
6539 @end smallexample
6540
6541 @item ^Lnnn^MAX_NESTING=nnn^
6542 @emph{Set maximum nesting level.}
6543 The maximum level of nesting of constructs (including subprograms, loops,
6544 blocks, packages, and conditionals) may not exceed the given value
6545 @option{nnn}. A value of zero disconnects this style check.
6546
6547 @item ^m^LINE_LENGTH^
6548 @emph{Check maximum line length.}
6549 The length of source lines must not exceed 79 characters, including
6550 any trailing blanks. The value of 79 allows convenient display on an
6551 80 character wide device or window, allowing for possible special
6552 treatment of 80 character lines. Note that this count is of
6553 characters in the source text. This means that a tab character counts
6554 as one character in this count but a wide character sequence counts as
6555 a single character (however many bytes are needed in the encoding).
6556
6557 @item ^Mnnn^MAX_LENGTH=nnn^
6558 @emph{Set maximum line length.}
6559 The length of lines must not exceed the
6560 given value @option{nnn}. The maximum value that can be specified is 32767.
6561
6562 @item ^n^STANDARD_CASING^
6563 @emph{Check casing of entities in Standard.}
6564 Any identifier from Standard must be cased
6565 to match the presentation in the Ada Reference Manual (for example,
6566 @code{Integer} and @code{ASCII.NUL}).
6567
6568 @item ^N^NONE^
6569 @emph{Turn off all style checks.}
6570 All style check options are turned off.
6571
6572 @item ^o^ORDERED_SUBPROGRAMS^
6573 @emph{Check order of subprogram bodies.}
6574 All subprogram bodies in a given scope
6575 (e.g.@: a package body) must be in alphabetical order. The ordering
6576 rule uses normal Ada rules for comparing strings, ignoring casing
6577 of letters, except that if there is a trailing numeric suffix, then
6578 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6579 before Junk10).
6580
6581 @item ^O^OVERRIDING_INDICATORS^
6582 @emph{Check that overriding subprograms are explicitly marked as such.}
6583 The declaration of a primitive operation of a type extension that overrides
6584 an inherited operation must carry an overriding indicator.
6585
6586 @item ^p^PRAGMA^
6587 @emph{Check pragma casing.}
6588 Pragma names must be written in mixed case, that is, the
6589 initial letter and any letter following an underscore must be uppercase.
6590 All other letters must be lowercase.
6591
6592 @item ^r^REFERENCES^
6593 @emph{Check references.}
6594 All identifier references must be cased in the same way as the
6595 corresponding declaration. No specific casing style is imposed on
6596 identifiers. The only requirement is for consistency of references
6597 with declarations.
6598
6599 @item ^s^SPECS^
6600 @emph{Check separate specs.}
6601 Separate declarations (``specs'') are required for subprograms (a
6602 body is not allowed to serve as its own declaration). The only
6603 exception is that parameterless library level procedures are
6604 not required to have a separate declaration. This exception covers
6605 the most frequent form of main program procedures.
6606
6607 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6608 @emph{Check no statements after @code{then}/@code{else}.}
6609 No statements are allowed
6610 on the same line as a @code{then} or @code{else} keyword following the
6611 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6612 affected, and a special exception allows a pragma to appear after @code{else}.
6613
6614 @item ^t^TOKEN^
6615 @emph{Check token spacing.}
6616 The following token spacing rules are enforced:
6617
6618 @itemize @bullet
6619
6620 @item
6621 The keywords @code{abs} and @code{not} must be followed by a space.
6622
6623 @item
6624 The token @code{=>} must be surrounded by spaces.
6625
6626 @item
6627 The token @code{<>} must be preceded by a space or a left parenthesis.
6628
6629 @item
6630 Binary operators other than @code{**} must be surrounded by spaces.
6631 There is no restriction on the layout of the @code{**} binary operator.
6632
6633 @item
6634 Colon must be surrounded by spaces.
6635
6636 @item
6637 Colon-equal (assignment, initialization) must be surrounded by spaces.
6638
6639 @item
6640 Comma must be the first non-blank character on the line, or be
6641 immediately preceded by a non-blank character, and must be followed
6642 by a space.
6643
6644 @item
6645 If the token preceding a left parenthesis ends with a letter or digit, then
6646 a space must separate the two tokens.
6647
6648 @item
6649 if the token following a right parenthesis starts with a letter or digit, then
6650 a space must separate the two tokens.
6651
6652 @item
6653 A right parenthesis must either be the first non-blank character on
6654 a line, or it must be preceded by a non-blank character.
6655
6656 @item
6657 A semicolon must not be preceded by a space, and must not be followed by
6658 a non-blank character.
6659
6660 @item
6661 A unary plus or minus may not be followed by a space.
6662
6663 @item
6664 A vertical bar must be surrounded by spaces.
6665 @end itemize
6666
6667 @item ^u^UNNECESSARY_BLANK_LINES^
6668 @emph{Check unnecessary blank lines.}
6669 Unnecessary blank lines are not allowed. A blank line is considered
6670 unnecessary if it appears at the end of the file, or if more than
6671 one blank line occurs in sequence.
6672
6673 @item ^x^XTRA_PARENS^
6674 @emph{Check extra parentheses.}
6675 Unnecessary extra level of parentheses (C-style) are not allowed
6676 around conditions in @code{if} statements, @code{while} statements and
6677 @code{exit} statements.
6678
6679 @item ^y^ALL_BUILTIN^
6680 @emph{Set all standard style check options}
6681 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6682 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6683 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6684 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6685
6686 @ifclear vms
6687 @item -
6688 @emph{Remove style check options}
6689 This causes any subsequent options in the string to act as canceling the
6690 corresponding style check option. To cancel maximum nesting level control,
6691 use @option{L} parameter witout any integer value after that, because any
6692 digit following @option{-} in the parameter string of the @option{-gnaty}
6693 option will be threated as canceling indentation check. The same is true
6694 for @option{M} parameter. @option{y} and @option{N} parameters are not
6695 allowed after @option{-}.
6696
6697 @item +
6698 This causes any subsequent options in the string to enable the corresponding
6699 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6700 if any.
6701 @end ifclear
6702
6703 @ifset vms
6704 @item NOxxx
6705 @emph{Removing style check options}
6706 If the name of a style check is preceded by @option{NO} then the corresponding
6707 style check is turned off. For example @option{NOCOMMENTS} turns off style
6708 checking for comments.
6709 @end ifset
6710 @end table
6711
6712 @noindent
6713 In the above rules, appearing in column one is always permitted, that is,
6714 counts as meeting either a requirement for a required preceding space,
6715 or as meeting a requirement for no preceding space.
6716
6717 Appearing at the end of a line is also always permitted, that is, counts
6718 as meeting either a requirement for a following space, or as meeting
6719 a requirement for no following space.
6720
6721 @noindent
6722 If any of these style rules is violated, a message is generated giving
6723 details on the violation. The initial characters of such messages are
6724 always ``@code{(style)}''. Note that these messages are treated as warning
6725 messages, so they normally do not prevent the generation of an object
6726 file. The @option{-gnatwe} switch can be used to treat warning messages,
6727 including style messages, as fatal errors.
6728
6729 The switch
6730 @ifclear vms
6731 @option{-gnaty} on its own (that is not
6732 followed by any letters or digits) is equivalent
6733 to the use of @option{-gnatyy} as described above, that is all
6734 built-in standard style check options are enabled.
6735
6736 @end ifclear
6737 @ifset vms
6738 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6739 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6740 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6741 @end ifset
6742
6743 The switch
6744 @ifclear vms
6745 @option{-gnatyN}
6746 @end ifclear
6747 @ifset vms
6748 /STYLE_CHECKS=NONE
6749 @end ifset
6750 clears any previously set style checks.
6751
6752 @node Run-Time Checks
6753 @subsection Run-Time Checks
6754 @cindex Division by zero
6755 @cindex Access before elaboration
6756 @cindex Checks, division by zero
6757 @cindex Checks, access before elaboration
6758 @cindex Checks, stack overflow checking
6759
6760 @noindent
6761 By default, the following checks are suppressed: integer overflow
6762 checks, stack overflow checks, and checks for access before
6763 elaboration on subprogram calls. All other checks, including range
6764 checks and array bounds checks, are turned on by default. The
6765 following @command{gcc} switches refine this default behavior.
6766
6767 @table @option
6768 @c !sort!
6769 @item -gnatp
6770 @cindex @option{-gnatp} (@command{gcc})
6771 @cindex Suppressing checks
6772 @cindex Checks, suppressing
6773 @findex Suppress
6774 This switch causes the unit to be compiled
6775 as though @code{pragma Suppress (All_checks)}
6776 had been present in the source. Validity checks are also eliminated (in
6777 other words @option{-gnatp} also implies @option{-gnatVn}.
6778 Use this switch to improve the performance
6779 of the code at the expense of safety in the presence of invalid data or
6780 program bugs.
6781
6782 Note that when checks are suppressed, the compiler is allowed, but not
6783 required, to omit the checking code. If the run-time cost of the
6784 checking code is zero or near-zero, the compiler will generate it even
6785 if checks are suppressed. In particular, if the compiler can prove
6786 that a certain check will necessarily fail, it will generate code to
6787 do an unconditional ``raise'', even if checks are suppressed. The
6788 compiler warns in this case. Another case in which checks may not be
6789 eliminated is when they are embedded in certain run time routines such
6790 as math library routines.
6791
6792 Of course, run-time checks are omitted whenever the compiler can prove
6793 that they will not fail, whether or not checks are suppressed.
6794
6795 Note that if you suppress a check that would have failed, program
6796 execution is erroneous, which means the behavior is totally
6797 unpredictable. The program might crash, or print wrong answers, or
6798 do anything else. It might even do exactly what you wanted it to do
6799 (and then it might start failing mysteriously next week or next
6800 year). The compiler will generate code based on the assumption that
6801 the condition being checked is true, which can result in disaster if
6802 that assumption is wrong.
6803
6804 The @option{-gnatp} switch has no effect if a subsequent
6805 @option{-gnat-p} switch appears.
6806
6807 @item -gnat-p
6808 @cindex @option{-gnat-p} (@command{gcc})
6809 @cindex Suppressing checks
6810 @cindex Checks, suppressing
6811 @findex Suppress
6812 This switch cancels the effect of a previous @option{gnatp} switch.
6813
6814 @item -gnato
6815 @cindex @option{-gnato} (@command{gcc})
6816 @cindex Overflow checks
6817 @cindex Check, overflow
6818 Enables overflow checking for integer operations.
6819 This causes GNAT to generate slower and larger executable
6820 programs by adding code to check for overflow (resulting in raising
6821 @code{Constraint_Error} as required by standard Ada
6822 semantics). These overflow checks correspond to situations in which
6823 the true value of the result of an operation may be outside the base
6824 range of the result type. The following example shows the distinction:
6825
6826 @smallexample @c ada
6827 X1 : Integer := "Integer'Last";
6828 X2 : Integer range 1 .. 5 := "5";
6829 X3 : Integer := "Integer'Last";
6830 X4 : Integer range 1 .. 5 := "5";
6831 F  : Float := "2.0E+20";
6832 @dots{}
6833 X1 := X1 + 1;
6834 X2 := X2 + 1;
6835 X3 := Integer (F);
6836 X4 := Integer (F);
6837 @end smallexample
6838
6839 @noindent
6840 Note that if explicit values are assigned at compile time, the
6841 compiler may be able to detect overflow at compile time, in which case
6842 no actual run-time checking code is required, and Constraint_Error
6843 will be raised unconditionally, with or without
6844 @option{-gnato}. That's why the assigned values in the above fragment
6845 are in quotes, the meaning is "assign a value not known to the
6846 compiler that happens to be equal to ...". The remaining discussion
6847 assumes that the compiler cannot detect the values at compile time.
6848
6849 Here the first addition results in a value that is outside the base range
6850 of Integer, and hence requires an overflow check for detection of the
6851 constraint error. Thus the first assignment to @code{X1} raises a
6852 @code{Constraint_Error} exception only if @option{-gnato} is set.
6853
6854 The second increment operation results in a violation of the explicit
6855 range constraint; such range checks are performed by default, and are
6856 unaffected by @option{-gnato}.
6857
6858 The two conversions of @code{F} both result in values that are outside
6859 the base range of type @code{Integer} and thus will raise
6860 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6861 The fact that the result of the second conversion is assigned to
6862 variable @code{X4} with a restricted range is irrelevant, since the problem
6863 is in the conversion, not the assignment.
6864
6865 Basically the rule is that in the default mode (@option{-gnato} not
6866 used), the generated code assures that all integer variables stay
6867 within their declared ranges, or within the base range if there is
6868 no declared range. This prevents any serious problems like indexes
6869 out of range for array operations.
6870
6871 What is not checked in default mode is an overflow that results in
6872 an in-range, but incorrect value. In the above example, the assignments
6873 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6874 range of the target variable, but the result is wrong in the sense that
6875 it is too large to be represented correctly. Typically the assignment
6876 to @code{X1} will result in wrap around to the largest negative number.
6877 The conversions of @code{F} will result in some @code{Integer} value
6878 and if that integer value is out of the @code{X4} range then the
6879 subsequent assignment would generate an exception.
6880
6881 @findex Machine_Overflows
6882 Note that the @option{-gnato} switch does not affect the code generated
6883 for any floating-point operations; it applies only to integer
6884 semantics).
6885 For floating-point, GNAT has the @code{Machine_Overflows}
6886 attribute set to @code{False} and the normal mode of operation is to
6887 generate IEEE NaN and infinite values on overflow or invalid operations
6888 (such as dividing 0.0 by 0.0).
6889
6890 The reason that we distinguish overflow checking from other kinds of
6891 range constraint checking is that a failure of an overflow check, unlike
6892 for example the failure of a range check, can result in an incorrect
6893 value, but cannot cause random memory destruction (like an out of range
6894 subscript), or a wild jump (from an out of range case value). Overflow
6895 checking is also quite expensive in time and space, since in general it
6896 requires the use of double length arithmetic.
6897
6898 Note again that @option{-gnato} is off by default, so overflow checking is
6899 not performed in default mode. This means that out of the box, with the
6900 default settings, GNAT does not do all the checks expected from the
6901 language description in the Ada Reference Manual. If you want all constraint
6902 checks to be performed, as described in this Manual, then you must
6903 explicitly use the -gnato switch either on the @command{gnatmake} or
6904 @command{gcc} command.
6905
6906 @item -gnatE
6907 @cindex @option{-gnatE} (@command{gcc})
6908 @cindex Elaboration checks
6909 @cindex Check, elaboration
6910 Enables dynamic checks for access-before-elaboration
6911 on subprogram calls and generic instantiations.
6912 Note that @option{-gnatE} is not necessary for safety, because in the
6913 default mode, GNAT ensures statically that the checks would not fail.
6914 For full details of the effect and use of this switch,
6915 @xref{Compiling Using gcc}.
6916
6917 @item -fstack-check
6918 @cindex @option{-fstack-check} (@command{gcc})
6919 @cindex Stack Overflow Checking
6920 @cindex Checks, stack overflow checking
6921 Activates stack overflow checking. For full details of the effect and use of
6922 this switch see @ref{Stack Overflow Checking}.
6923 @end table
6924
6925 @findex Unsuppress
6926 @noindent
6927 The setting of these switches only controls the default setting of the
6928 checks. You may modify them using either @code{Suppress} (to remove
6929 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6930 the program source.
6931
6932 @node Using gcc for Syntax Checking
6933 @subsection Using @command{gcc} for Syntax Checking
6934 @table @option
6935 @item -gnats
6936 @cindex @option{-gnats} (@command{gcc})
6937 @ifclear vms
6938
6939 @noindent
6940 The @code{s} stands for ``syntax''.
6941 @end ifclear
6942
6943 Run GNAT in syntax checking only mode. For
6944 example, the command
6945
6946 @smallexample
6947 $ gcc -c -gnats x.adb
6948 @end smallexample
6949
6950 @noindent
6951 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6952 series of files in a single command
6953 @ifclear vms
6954 , and can use wild cards to specify such a group of files.
6955 Note that you must specify the @option{-c} (compile
6956 only) flag in addition to the @option{-gnats} flag.
6957 @end ifclear
6958 .
6959 You may use other switches in conjunction with @option{-gnats}. In
6960 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6961 format of any generated error messages.
6962
6963 When the source file is empty or contains only empty lines and/or comments,
6964 the output is a warning:
6965
6966 @smallexample
6967 $ gcc -c -gnats -x ada toto.txt
6968 toto.txt:1:01: warning: empty file, contains no compilation units
6969 $
6970 @end smallexample
6971
6972 Otherwise, the output is simply the error messages, if any. No object file or
6973 ALI file is generated by a syntax-only compilation. Also, no units other
6974 than the one specified are accessed. For example, if a unit @code{X}
6975 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6976 check only mode does not access the source file containing unit
6977 @code{Y}.
6978
6979 @cindex Multiple units, syntax checking
6980 Normally, GNAT allows only a single unit in a source file. However, this
6981 restriction does not apply in syntax-check-only mode, and it is possible
6982 to check a file containing multiple compilation units concatenated
6983 together. This is primarily used by the @code{gnatchop} utility
6984 (@pxref{Renaming Files Using gnatchop}).
6985 @end table
6986
6987 @node Using gcc for Semantic Checking
6988 @subsection Using @command{gcc} for Semantic Checking
6989 @table @option
6990 @item -gnatc
6991 @cindex @option{-gnatc} (@command{gcc})
6992
6993 @ifclear vms
6994 @noindent
6995 The @code{c} stands for ``check''.
6996 @end ifclear
6997 Causes the compiler to operate in semantic check mode,
6998 with full checking for all illegalities specified in the
6999 Ada Reference Manual, but without generation of any object code
7000 (no object file is generated).
7001
7002 Because dependent files must be accessed, you must follow the GNAT
7003 semantic restrictions on file structuring to operate in this mode:
7004
7005 @itemize @bullet
7006 @item
7007 The needed source files must be accessible
7008 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7009
7010 @item
7011 Each file must contain only one compilation unit.
7012
7013 @item
7014 The file name and unit name must match (@pxref{File Naming Rules}).
7015 @end itemize
7016
7017 The output consists of error messages as appropriate. No object file is
7018 generated. An @file{ALI} file is generated for use in the context of
7019 cross-reference tools, but this file is marked as not being suitable
7020 for binding (since no object file is generated).
7021 The checking corresponds exactly to the notion of
7022 legality in the Ada Reference Manual.
7023
7024 Any unit can be compiled in semantics-checking-only mode, including
7025 units that would not normally be compiled (subunits,
7026 and specifications where a separate body is present).
7027 @end table
7028
7029 @node Compiling Different Versions of Ada
7030 @subsection Compiling Different Versions of Ada
7031
7032 @noindent
7033 The switches described in this section allow you to explicitly specify
7034 the version of the Ada language that your programs are written in.
7035 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
7036 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
7037 indicate Ada 83 compatibility mode.
7038
7039 @table @option
7040 @cindex Compatibility with Ada 83
7041
7042 @item -gnat83 (Ada 83 Compatibility Mode)
7043 @cindex @option{-gnat83} (@command{gcc})
7044 @cindex ACVC, Ada 83 tests
7045 @cindex Ada 83 mode
7046
7047 @noindent
7048 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7049 specifies that the program is to be compiled in Ada 83 mode. With
7050 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7051 semantics where this can be done easily.
7052 It is not possible to guarantee this switch does a perfect
7053 job; some subtle tests, such as are
7054 found in earlier ACVC tests (and that have been removed from the ACATS suite
7055 for Ada 95), might not compile correctly.
7056 Nevertheless, this switch may be useful in some circumstances, for example
7057 where, due to contractual reasons, existing code needs to be maintained
7058 using only Ada 83 features.
7059
7060 With few exceptions (most notably the need to use @code{<>} on
7061 @cindex Generic formal parameters
7062 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7063 reserved words, and the use of packages
7064 with optional bodies), it is not necessary to specify the
7065 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7066 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7067 a correct Ada 83 program is usually also a correct program
7068 in these later versions of the language standard.
7069 For further information, please refer to @ref{Compatibility and Porting Guide}.
7070
7071 @item -gnat95 (Ada 95 mode)
7072 @cindex @option{-gnat95} (@command{gcc})
7073 @cindex Ada 95 mode
7074
7075 @noindent
7076 This switch directs the compiler to implement the Ada 95 version of the
7077 language.
7078 Since Ada 95 is almost completely upwards
7079 compatible with Ada 83, Ada 83 programs may generally be compiled using
7080 this switch (see the description of the @option{-gnat83} switch for further
7081 information about Ada 83 mode).
7082 If an Ada 2005 program is compiled in Ada 95 mode,
7083 uses of the new Ada 2005 features will cause error
7084 messages or warnings.
7085
7086 This switch also can be used to cancel the effect of a previous
7087 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7088 switch earlier in the command line.
7089
7090 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7091 @cindex @option{-gnat05} (@command{gcc})
7092 @cindex @option{-gnat2005} (@command{gcc})
7093 @cindex Ada 2005 mode
7094
7095 @noindent
7096 This switch directs the compiler to implement the Ada 2005 version of the
7097 language, as documented in the official Ada standards document.
7098 Since Ada 2005 is almost completely upwards
7099 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7100 may generally be compiled using this switch (see the description of the
7101 @option{-gnat83} and @option{-gnat95} switches for further
7102 information).
7103
7104 @ifset PROEDITION
7105 Note that even though Ada 2005 is the current official version of the
7106 language, GNAT still compiles in Ada 95 mode by default, so if you are
7107 using Ada 2005 features in your program, you must use this switch (or
7108 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7109 @end ifset
7110
7111 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7112 @cindex @option{-gnat12} (@command{gcc})
7113 @cindex @option{-gnat2012} (@command{gcc})
7114 @cindex Ada 2012 mode
7115
7116 @noindent
7117 This switch directs the compiler to implement the Ada 2012 version of the
7118 language.
7119 Since Ada 2012 is almost completely upwards
7120 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7121 Ada 83 and Ada 95 programs
7122 may generally be compiled using this switch (see the description of the
7123 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7124 for further information).
7125
7126 For information about the approved ``Ada Issues'' that have been incorporated
7127 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7128 Included with GNAT releases is a file @file{features-ada12} that describes
7129 the set of implemented Ada 2012 features.
7130
7131 @item -gnatX (Enable GNAT Extensions)
7132 @cindex @option{-gnatX} (@command{gcc})
7133 @cindex Ada language extensions
7134 @cindex GNAT extensions
7135
7136 @noindent
7137 This switch directs the compiler to implement the latest version of the
7138 language (currently Ada 2012) and also to enable certain GNAT implementation
7139 extensions that are not part of any Ada standard. For a full list of these
7140 extensions, see the GNAT reference manual.
7141
7142 @end table
7143
7144 @node Character Set Control
7145 @subsection Character Set Control
7146 @table @option
7147 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7148 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7149
7150 @noindent
7151 Normally GNAT recognizes the Latin-1 character set in source program
7152 identifiers, as described in the Ada Reference Manual.
7153 This switch causes
7154 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7155 single character ^^or word^ indicating the character set, as follows:
7156
7157 @table @code
7158 @item 1
7159 ISO 8859-1 (Latin-1) identifiers
7160
7161 @item 2
7162 ISO 8859-2 (Latin-2) letters allowed in identifiers
7163
7164 @item 3
7165 ISO 8859-3 (Latin-3) letters allowed in identifiers
7166
7167 @item 4
7168 ISO 8859-4 (Latin-4) letters allowed in identifiers
7169
7170 @item 5
7171 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7172
7173 @item 9
7174 ISO 8859-15 (Latin-9) letters allowed in identifiers
7175
7176 @item ^p^PC^
7177 IBM PC letters (code page 437) allowed in identifiers
7178
7179 @item ^8^PC850^
7180 IBM PC letters (code page 850) allowed in identifiers
7181
7182 @item ^f^FULL_UPPER^
7183 Full upper-half codes allowed in identifiers
7184
7185 @item ^n^NO_UPPER^
7186 No upper-half codes allowed in identifiers
7187
7188 @item ^w^WIDE^
7189 Wide-character codes (that is, codes greater than 255)
7190 allowed in identifiers
7191 @end table
7192
7193 @xref{Foreign Language Representation}, for full details on the
7194 implementation of these character sets.
7195
7196 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7197 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7198 Specify the method of encoding for wide characters.
7199 @var{e} is one of the following:
7200
7201 @table @code
7202
7203 @item ^h^HEX^
7204 Hex encoding (brackets coding also recognized)
7205
7206 @item ^u^UPPER^
7207 Upper half encoding (brackets encoding also recognized)
7208
7209 @item ^s^SHIFT_JIS^
7210 Shift/JIS encoding (brackets encoding also recognized)
7211
7212 @item ^e^EUC^
7213 EUC encoding (brackets encoding also recognized)
7214
7215 @item ^8^UTF8^
7216 UTF-8 encoding (brackets encoding also recognized)
7217
7218 @item ^b^BRACKETS^
7219 Brackets encoding only (default value)
7220 @end table
7221 For full details on these encoding
7222 methods see @ref{Wide Character Encodings}.
7223 Note that brackets coding is always accepted, even if one of the other
7224 options is specified, so for example @option{-gnatW8} specifies that both
7225 brackets and UTF-8 encodings will be recognized. The units that are
7226 with'ed directly or indirectly will be scanned using the specified
7227 representation scheme, and so if one of the non-brackets scheme is
7228 used, it must be used consistently throughout the program. However,
7229 since brackets encoding is always recognized, it may be conveniently
7230 used in standard libraries, allowing these libraries to be used with
7231 any of the available coding schemes.
7232
7233 Note that brackets encoding only applies to program text. Within comments,
7234 brackets are considered to be normal graphic characters, and bracket sequences
7235 are never recognized as wide characters.
7236
7237 If no @option{-gnatW?} parameter is present, then the default
7238 representation is normally Brackets encoding only. However, if the
7239 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7240 byte order mark or BOM for UTF-8), then these three characters are
7241 skipped and the default representation for the file is set to UTF-8.
7242
7243 Note that the wide character representation that is specified (explicitly
7244 or by default) for the main program also acts as the default encoding used
7245 for Wide_Text_IO files if not specifically overridden by a WCEM form
7246 parameter.
7247
7248 @end table
7249
7250 When no @option{-gnatW?} is specified, then characters (other than wide
7251 characters represented using brackets notation) are treated as 8-bit
7252 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7253 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7254 characters in the range 16#00#..16#1F# are not accepted in program text
7255 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7256 in program text, but allowed and ignored in comments. Note in particular
7257 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7258 as an end of line in this default mode. If your source program contains
7259 instances of the NEL character used as a line terminator,
7260 you must use UTF-8 encoding for the whole
7261 source program. In default mode, all lines must be ended by a standard
7262 end of line sequence (CR, CR/LF, or LF).
7263
7264 Note that the convention of simply accepting all upper half characters in
7265 comments means that programs that use standard ASCII for program text, but
7266 UTF-8 encoding for comments are accepted in default mode, providing that the
7267 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7268 This is a common mode for many programs with foreign language comments.
7269
7270 @node File Naming Control
7271 @subsection File Naming Control
7272
7273 @table @option
7274 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7275 @cindex @option{-gnatk} (@command{gcc})
7276 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7277 1-999, indicates the maximum allowable length of a file name (not
7278 including the @file{.ads} or @file{.adb} extension). The default is not
7279 to enable file name krunching.
7280
7281 For the source file naming rules, @xref{File Naming Rules}.
7282 @end table
7283
7284 @node Subprogram Inlining Control
7285 @subsection Subprogram Inlining Control
7286
7287 @table @option
7288 @c !sort!
7289 @item -gnatn
7290 @cindex @option{-gnatn} (@command{gcc})
7291 @ifclear vms
7292 The @code{n} here is intended to suggest the first syllable of the
7293 word ``inline''.
7294 @end ifclear
7295 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7296 inlining to actually occur, optimization must be enabled. To enable
7297 inlining of subprograms specified by pragma @code{Inline},
7298 you must also specify this switch.
7299 In the absence of this switch, GNAT does not attempt
7300 inlining and does not need to access the bodies of
7301 subprograms for which @code{pragma Inline} is specified if they are not
7302 in the current unit.
7303
7304 If you specify this switch the compiler will access these bodies,
7305 creating an extra source dependency for the resulting object file, and
7306 where possible, the call will be inlined.
7307 For further details on when inlining is possible
7308 see @ref{Inlining of Subprograms}.
7309
7310 @item -gnatN
7311 @cindex @option{-gnatN} (@command{gcc})
7312 This switch activates front-end inlining which also
7313 generates additional dependencies.
7314
7315 When using a gcc-based back end (in practice this means using any version
7316 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7317 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7318 Historically front end inlining was more extensive than the gcc back end
7319 inlining, but that is no longer the case.
7320 @end table
7321
7322 @node Auxiliary Output Control
7323 @subsection Auxiliary Output Control
7324
7325 @table @option
7326 @item -gnatt
7327 @cindex @option{-gnatt} (@command{gcc})
7328 @cindex Writing internal trees
7329 @cindex Internal trees, writing to file
7330 Causes GNAT to write the internal tree for a unit to a file (with the
7331 extension @file{.adt}.
7332 This not normally required, but is used by separate analysis tools.
7333 Typically
7334 these tools do the necessary compilations automatically, so you should
7335 not have to specify this switch in normal operation.
7336 Note that the combination of switches @option{-gnatct}
7337 generates a tree in the form required by ASIS applications.
7338
7339 @item -gnatu
7340 @cindex @option{-gnatu} (@command{gcc})
7341 Print a list of units required by this compilation on @file{stdout}.
7342 The listing includes all units on which the unit being compiled depends
7343 either directly or indirectly.
7344
7345 @ifclear vms
7346 @item -pass-exit-codes
7347 @cindex @option{-pass-exit-codes} (@command{gcc})
7348 If this switch is not used, the exit code returned by @command{gcc} when
7349 compiling multiple files indicates whether all source files have
7350 been successfully used to generate object files or not.
7351
7352 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7353 exit status and allows an integrated development environment to better
7354 react to a compilation failure. Those exit status are:
7355
7356 @table @asis
7357 @item 5
7358 There was an error in at least one source file.
7359 @item 3
7360 At least one source file did not generate an object file.
7361 @item 2
7362 The compiler died unexpectedly (internal error for example).
7363 @item 0
7364 An object file has been generated for every source file.
7365 @end table
7366 @end ifclear
7367 @end table
7368
7369 @node Debugging Control
7370 @subsection Debugging Control
7371
7372 @table @option
7373 @c !sort!
7374 @cindex Debugging options
7375 @ifclear vms
7376 @item -gnatd@var{x}
7377 @cindex @option{-gnatd} (@command{gcc})
7378 Activate internal debugging switches. @var{x} is a letter or digit, or
7379 string of letters or digits, which specifies the type of debugging
7380 outputs desired. Normally these are used only for internal development
7381 or system debugging purposes. You can find full documentation for these
7382 switches in the body of the @code{Debug} unit in the compiler source
7383 file @file{debug.adb}.
7384 @end ifclear
7385
7386 @item -gnatG[=nn]
7387 @cindex @option{-gnatG} (@command{gcc})
7388 This switch causes the compiler to generate auxiliary output containing
7389 a pseudo-source listing of the generated expanded code. Like most Ada
7390 compilers, GNAT works by first transforming the high level Ada code into
7391 lower level constructs. For example, tasking operations are transformed
7392 into calls to the tasking run-time routines. A unique capability of GNAT
7393 is to list this expanded code in a form very close to normal Ada source.
7394 This is very useful in understanding the implications of various Ada
7395 usage on the efficiency of the generated code. There are many cases in
7396 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7397 generate a lot of run-time code. By using @option{-gnatG} you can identify
7398 these cases, and consider whether it may be desirable to modify the coding
7399 approach to improve efficiency.
7400
7401 The optional parameter @code{nn} if present after -gnatG specifies an
7402 alternative maximum line length that overrides the normal default of 72.
7403 This value is in the range 40-999999, values less than 40 being silently
7404 reset to 40. The equal sign is optional.
7405
7406 The format of the output is very similar to standard Ada source, and is
7407 easily understood by an Ada programmer. The following special syntactic
7408 additions correspond to low level features used in the generated code that
7409 do not have any exact analogies in pure Ada source form. The following
7410 is a partial list of these special constructions. See the spec
7411 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7412
7413 If the switch @option{-gnatL} is used in conjunction with
7414 @cindex @option{-gnatL} (@command{gcc})
7415 @option{-gnatG}, then the original source lines are interspersed
7416 in the expanded source (as comment lines with the original line number).
7417
7418 @table @code
7419 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7420 Shows the storage pool being used for an allocator.
7421
7422 @item at end @var{procedure-name};
7423 Shows the finalization (cleanup) procedure for a scope.
7424
7425 @item (if @var{expr} then @var{expr} else @var{expr})
7426 Conditional expression equivalent to the @code{x?y:z} construction in C.
7427
7428 @item @var{target}^^^(@var{source})
7429 A conversion with floating-point truncation instead of rounding.
7430
7431 @item @var{target}?(@var{source})
7432 A conversion that bypasses normal Ada semantic checking. In particular
7433 enumeration types and fixed-point types are treated simply as integers.
7434
7435 @item @var{target}?^^^(@var{source})
7436 Combines the above two cases.
7437
7438 @item @var{x} #/ @var{y}
7439 @itemx @var{x} #mod @var{y}
7440 @itemx @var{x} #* @var{y}
7441 @itemx @var{x} #rem @var{y}
7442 A division or multiplication of fixed-point values which are treated as
7443 integers without any kind of scaling.
7444
7445 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7446 Shows the storage pool associated with a @code{free} statement.
7447
7448 @item [subtype or type declaration]
7449 Used to list an equivalent declaration for an internally generated
7450 type that is referenced elsewhere in the listing.
7451
7452 @c @item freeze @var{type-name} @ovar{actions}
7453 @c Expanding @ovar macro inline (explanation in macro def comments)
7454 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7455 Shows the point at which @var{type-name} is frozen, with possible
7456 associated actions to be performed at the freeze point.
7457
7458 @item reference @var{itype}
7459 Reference (and hence definition) to internal type @var{itype}.
7460
7461 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7462 Intrinsic function call.
7463
7464 @item @var{label-name} : label
7465 Declaration of label @var{labelname}.
7466
7467 @item #$ @var{subprogram-name}
7468 An implicit call to a run-time support routine
7469 (to meet the requirement of H.3.1(9) in a
7470 convenient manner).
7471
7472 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7473 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7474 @var{expr}, but handled more efficiently).
7475
7476 @item [constraint_error]
7477 Raise the @code{Constraint_Error} exception.
7478
7479 @item @var{expression}'reference
7480 A pointer to the result of evaluating @var{expression}.
7481
7482 @item @var{target-type}!(@var{source-expression})
7483 An unchecked conversion of @var{source-expression} to @var{target-type}.
7484
7485 @item [@var{numerator}/@var{denominator}]
7486 Used to represent internal real literals (that) have no exact
7487 representation in base 2-16 (for example, the result of compile time
7488 evaluation of the expression 1.0/27.0).
7489 @end table
7490
7491 @item -gnatD[=nn]
7492 @cindex @option{-gnatD} (@command{gcc})
7493 When used in conjunction with @option{-gnatG}, this switch causes
7494 the expanded source, as described above for
7495 @option{-gnatG} to be written to files with names
7496 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7497 instead of to the standard output file. For
7498 example, if the source file name is @file{hello.adb}, then a file
7499 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7500 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7501 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7502 you to do source level debugging using the generated code which is
7503 sometimes useful for complex code, for example to find out exactly
7504 which part of a complex construction raised an exception. This switch
7505 also suppress generation of cross-reference information (see
7506 @option{-gnatx}) since otherwise the cross-reference information
7507 would refer to the @file{^.dg^.DG^} file, which would cause
7508 confusion since this is not the original source file.
7509
7510 Note that @option{-gnatD} actually implies @option{-gnatG}
7511 automatically, so it is not necessary to give both options.
7512 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7513
7514 If the switch @option{-gnatL} is used in conjunction with
7515 @cindex @option{-gnatL} (@command{gcc})
7516 @option{-gnatDG}, then the original source lines are interspersed
7517 in the expanded source (as comment lines with the original line number).
7518
7519 The optional parameter @code{nn} if present after -gnatD specifies an
7520 alternative maximum line length that overrides the normal default of 72.
7521 This value is in the range 40-999999, values less than 40 being silently
7522 reset to 40. The equal sign is optional.
7523
7524 @item -gnatr
7525 @cindex @option{-gnatr} (@command{gcc})
7526 @cindex pragma Restrictions
7527 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7528 so that violation of restrictions causes warnings rather than illegalities.
7529 This is useful during the development process when new restrictions are added
7530 or investigated. The switch also causes pragma Profile to be treated as
7531 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7532 restriction warnings rather than restrictions.
7533
7534 @ifclear vms
7535 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7536 @cindex @option{-gnatR} (@command{gcc})
7537 This switch controls output from the compiler of a listing showing
7538 representation information for declared types and objects. For
7539 @option{-gnatR0}, no information is output (equivalent to omitting
7540 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7541 so @option{-gnatR} with no parameter has the same effect), size and alignment
7542 information is listed for declared array and record types. For
7543 @option{-gnatR2}, size and alignment information is listed for all
7544 declared types and objects. Finally @option{-gnatR3} includes symbolic
7545 expressions for values that are computed at run time for
7546 variant records. These symbolic expressions have a mostly obvious
7547 format with #n being used to represent the value of the n'th
7548 discriminant. See source files @file{repinfo.ads/adb} in the
7549 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7550 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7551 the output is to a file with the name @file{^file.rep^file_REP^} where
7552 file is the name of the corresponding source file.
7553 @end ifclear
7554 @ifset vms
7555 @item /REPRESENTATION_INFO
7556 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7557 This qualifier controls output from the compiler of a listing showing
7558 representation information for declared types and objects. For
7559 @option{/REPRESENTATION_INFO=NONE}, no information is output
7560 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7561 @option{/REPRESENTATION_INFO} without option is equivalent to
7562 @option{/REPRESENTATION_INFO=ARRAYS}.
7563 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7564 information is listed for declared array and record types. For
7565 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7566 is listed for all expression information for values that are computed
7567 at run time for variant records. These symbolic expressions have a mostly
7568 obvious format with #n being used to represent the value of the n'th
7569 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7570 @code{GNAT} sources for full details on the format of
7571 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7572 If _FILE is added at the end of an option
7573 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7574 then the output is to a file with the name @file{file_REP} where
7575 file is the name of the corresponding source file.
7576 @end ifset
7577 Note that it is possible for record components to have zero size. In
7578 this case, the component clause uses an obvious extension of permitted
7579 Ada syntax, for example @code{at 0 range 0 .. -1}.
7580
7581 Representation information requires that code be generated (since it is the
7582 code generator that lays out complex data structures). If an attempt is made
7583 to output representation information when no code is generated, for example
7584 when a subunit is compiled on its own, then no information can be generated
7585 and the compiler outputs a message to this effect.
7586
7587 @item -gnatS
7588 @cindex @option{-gnatS} (@command{gcc})
7589 The use of the switch @option{-gnatS} for an
7590 Ada compilation will cause the compiler to output a
7591 representation of package Standard in a form very
7592 close to standard Ada. It is not quite possible to
7593 do this entirely in standard Ada (since new
7594 numeric base types cannot be created in standard
7595 Ada), but the output is easily
7596 readable to any Ada programmer, and is useful to
7597 determine the characteristics of target dependent
7598 types in package Standard.
7599
7600 @item -gnatx
7601 @cindex @option{-gnatx} (@command{gcc})
7602 Normally the compiler generates full cross-referencing information in
7603 the @file{ALI} file. This information is used by a number of tools,
7604 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7605 suppresses this information. This saves some space and may slightly
7606 speed up compilation, but means that these tools cannot be used.
7607 @end table
7608
7609 @node Exception Handling Control
7610 @subsection Exception Handling Control
7611
7612 @noindent
7613 GNAT uses two methods for handling exceptions at run-time. The
7614 @code{setjmp/longjmp} method saves the context when entering
7615 a frame with an exception handler. Then when an exception is
7616 raised, the context can be restored immediately, without the
7617 need for tracing stack frames. This method provides very fast
7618 exception propagation, but introduces significant overhead for
7619 the use of exception handlers, even if no exception is raised.
7620
7621 The other approach is called ``zero cost'' exception handling.
7622 With this method, the compiler builds static tables to describe
7623 the exception ranges. No dynamic code is required when entering
7624 a frame containing an exception handler. When an exception is
7625 raised, the tables are used to control a back trace of the
7626 subprogram invocation stack to locate the required exception
7627 handler. This method has considerably poorer performance for
7628 the propagation of exceptions, but there is no overhead for
7629 exception handlers if no exception is raised. Note that in this
7630 mode and in the context of mixed Ada and C/C++ programming,
7631 to propagate an exception through a C/C++ code, the C/C++ code
7632 must be compiled with the @option{-funwind-tables} GCC's
7633 option.
7634
7635 The following switches may be used to control which of the
7636 two exception handling methods is used.
7637
7638 @table @option
7639 @c !sort!
7640
7641 @item --RTS=sjlj
7642 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7643 This switch causes the setjmp/longjmp run-time (when available) to be used
7644 for exception handling. If the default
7645 mechanism for the target is zero cost exceptions, then
7646 this switch can be used to modify this default, and must be
7647 used for all units in the partition.
7648 This option is rarely used. One case in which it may be
7649 advantageous is if you have an application where exception
7650 raising is common and the overall performance of the
7651 application is improved by favoring exception propagation.
7652
7653 @item --RTS=zcx
7654 @cindex @option{--RTS=zcx} (@command{gnatmake})
7655 @cindex Zero Cost Exceptions
7656 This switch causes the zero cost approach to be used
7657 for exception handling. If this is the default mechanism for the
7658 target (see below), then this switch is unneeded. If the default
7659 mechanism for the target is setjmp/longjmp exceptions, then
7660 this switch can be used to modify this default, and must be
7661 used for all units in the partition.
7662 This option can only be used if the zero cost approach
7663 is available for the target in use, otherwise it will generate an error.
7664 @end table
7665
7666 @noindent
7667 The same option @option{--RTS} must be used both for @command{gcc}
7668 and @command{gnatbind}. Passing this option to @command{gnatmake}
7669 (@pxref{Switches for gnatmake}) will ensure the required consistency
7670 through the compilation and binding steps.
7671
7672 @node Units to Sources Mapping Files
7673 @subsection Units to Sources Mapping Files
7674
7675 @table @option
7676
7677 @item -gnatem=@var{path}
7678 @cindex @option{-gnatem} (@command{gcc})
7679 A mapping file is a way to communicate to the compiler two mappings:
7680 from unit names to file names (without any directory information) and from
7681 file names to path names (with full directory information). These mappings
7682 are used by the compiler to short-circuit the path search.
7683
7684 The use of mapping files is not required for correct operation of the
7685 compiler, but mapping files can improve efficiency, particularly when
7686 sources are read over a slow network connection. In normal operation,
7687 you need not be concerned with the format or use of mapping files,
7688 and the @option{-gnatem} switch is not a switch that you would use
7689 explicitly. It is intended primarily for use by automatic tools such as
7690 @command{gnatmake} running under the project file facility. The
7691 description here of the format of mapping files is provided
7692 for completeness and for possible use by other tools.
7693
7694 A mapping file is a sequence of sets of three lines. In each set, the
7695 first line is the unit name, in lower case, with @code{%s} appended
7696 for specs and @code{%b} appended for bodies; the second line is the
7697 file name; and the third line is the path name.
7698
7699 Example:
7700 @smallexample
7701    main%b
7702    main.2.ada
7703    /gnat/project1/sources/main.2.ada
7704 @end smallexample
7705
7706 When the switch @option{-gnatem} is specified, the compiler will
7707 create in memory the two mappings from the specified file. If there is
7708 any problem (nonexistent file, truncated file or duplicate entries),
7709 no mapping will be created.
7710
7711 Several @option{-gnatem} switches may be specified; however, only the
7712 last one on the command line will be taken into account.
7713
7714 When using a project file, @command{gnatmake} creates a temporary
7715 mapping file and communicates it to the compiler using this switch.
7716
7717 @end table
7718
7719 @node Integrated Preprocessing
7720 @subsection Integrated Preprocessing
7721
7722 @noindent
7723 GNAT sources may be preprocessed immediately before compilation.
7724 In this case, the actual
7725 text of the source is not the text of the source file, but is derived from it
7726 through a process called preprocessing. Integrated preprocessing is specified
7727 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7728 indicates, through a text file, the preprocessing data to be used.
7729 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7730
7731 @noindent
7732 Note that when integrated preprocessing is used, the output from the
7733 preprocessor is not written to any external file. Instead it is passed
7734 internally to the compiler. If you need to preserve the result of
7735 preprocessing in a file, then you should use @command{gnatprep}
7736 to perform the desired preprocessing in stand-alone mode.
7737
7738 @noindent
7739 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7740 used when Integrated Preprocessing is used. The reason is that preprocessing
7741 with another Preprocessing Data file without changing the sources will
7742 not trigger recompilation without this switch.
7743
7744 @noindent
7745 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7746 always trigger recompilation for sources that are preprocessed,
7747 because @command{gnatmake} cannot compute the checksum of the source after
7748 preprocessing.
7749
7750 @noindent
7751 The actual preprocessing function is described in details in section
7752 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7753 preprocessing is triggered and parameterized.
7754
7755 @table @code
7756
7757 @item -gnatep=@var{file}
7758 @cindex @option{-gnatep} (@command{gcc})
7759 This switch indicates to the compiler the file name (without directory
7760 information) of the preprocessor data file to use. The preprocessor data file
7761 should be found in the source directories. Note that when the compiler is
7762 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7763 file, if the object directory is not also a source directory, the builder needs
7764 to be called with @option{-x}.
7765
7766 @noindent
7767 A preprocessing data file is a text file with significant lines indicating
7768 how should be preprocessed either a specific source or all sources not
7769 mentioned in other lines. A significant line is a nonempty, non-comment line.
7770 Comments are similar to Ada comments.
7771
7772 @noindent
7773 Each significant line starts with either a literal string or the character '*'.
7774 A literal string is the file name (without directory information) of the source
7775 to preprocess. A character '*' indicates the preprocessing for all the sources
7776 that are not specified explicitly on other lines (order of the lines is not
7777 significant). It is an error to have two lines with the same file name or two
7778 lines starting with the character '*'.
7779
7780 @noindent
7781 After the file name or the character '*', another optional literal string
7782 indicating the file name of the definition file to be used for preprocessing
7783 (@pxref{Form of Definitions File}). The definition files are found by the
7784 compiler in one of the source directories. In some cases, when compiling
7785 a source in a directory other than the current directory, if the definition
7786 file is in the current directory, it may be necessary to add the current
7787 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7788 the compiler would not find the definition file.
7789
7790 @noindent
7791 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7792 be found. Those ^switches^switches^ are:
7793
7794 @table @code
7795
7796 @item -b
7797 Causes both preprocessor lines and the lines deleted by
7798 preprocessing to be replaced by blank lines, preserving the line number.
7799 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7800 it cancels the effect of @option{-c}.
7801
7802 @item -c
7803 Causes both preprocessor lines and the lines deleted
7804 by preprocessing to be retained as comments marked
7805 with the special string ``@code{--! }''.
7806
7807 @item -Dsymbol=value
7808 Define or redefine a symbol, associated with value. A symbol is an Ada
7809 identifier, or an Ada reserved word, with the exception of @code{if},
7810 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7811 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7812 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7813 same name defined in a definition file.
7814
7815 @item -s
7816 Causes a sorted list of symbol names and values to be
7817 listed on the standard output file.
7818
7819 @item -u
7820 Causes undefined symbols to be treated as having the value @code{FALSE}
7821 in the context
7822 of a preprocessor test. In the absence of this option, an undefined symbol in
7823 a @code{#if} or @code{#elsif} test will be treated as an error.
7824
7825 @end table
7826
7827 @noindent
7828 Examples of valid lines in a preprocessor data file:
7829
7830 @smallexample
7831   "toto.adb"  "prep.def" -u
7832   --  preprocess "toto.adb", using definition file "prep.def",
7833   --  undefined symbol are False.
7834
7835   * -c -DVERSION=V101
7836   --  preprocess all other sources without a definition file;
7837   --  suppressed lined are commented; symbol VERSION has the value V101.
7838
7839   "titi.adb" "prep2.def" -s
7840   --  preprocess "titi.adb", using definition file "prep2.def";
7841   --  list all symbols with their values.
7842 @end smallexample
7843
7844 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7845 @cindex @option{-gnateD} (@command{gcc})
7846 Define or redefine a preprocessing symbol, associated with value. If no value
7847 is given on the command line, then the value of the symbol is @code{True}.
7848 A symbol is an identifier, following normal Ada (case-insensitive)
7849 rules for its syntax, and value is any sequence (including an empty sequence)
7850 of characters from the set (letters, digits, period, underline).
7851 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7852 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7853
7854 @noindent
7855 A symbol declared with this ^switch^switch^ on the command line replaces a
7856 symbol with the same name either in a definition file or specified with a
7857 ^switch^switch^ -D in the preprocessor data file.
7858
7859 @noindent
7860 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7861
7862 @item -gnateG
7863 When integrated preprocessing is performed and the preprocessor modifies
7864 the source text, write the result of this preprocessing into a file
7865 <source>^.prep^_prep^.
7866
7867 @end table
7868
7869 @node Code Generation Control
7870 @subsection Code Generation Control
7871
7872 @noindent
7873
7874 The GCC technology provides a wide range of target dependent
7875 @option{-m} switches for controlling
7876 details of code generation with respect to different versions of
7877 architectures. This includes variations in instruction sets (e.g.@:
7878 different members of the power pc family), and different requirements
7879 for optimal arrangement of instructions (e.g.@: different members of
7880 the x86 family). The list of available @option{-m} switches may be
7881 found in the GCC documentation.
7882
7883 Use of these @option{-m} switches may in some cases result in improved
7884 code performance.
7885
7886 The @value{EDITION} technology is tested and qualified without any
7887 @option{-m} switches,
7888 so generally the most reliable approach is to avoid the use of these
7889 switches. However, we generally expect most of these switches to work
7890 successfully with @value{EDITION}, and many customers have reported successful
7891 use of these options.
7892
7893 Our general advice is to avoid the use of @option{-m} switches unless
7894 special needs lead to requirements in this area. In particular,
7895 there is no point in using @option{-m} switches to improve performance
7896 unless you actually see a performance improvement.
7897
7898 @ifset vms
7899 @node Return Codes
7900 @subsection Return Codes
7901 @cindex Return Codes
7902 @cindex @option{/RETURN_CODES=VMS}
7903
7904 @noindent
7905 On VMS, GNAT compiled programs return POSIX-style codes by default,
7906 e.g.@: @option{/RETURN_CODES=POSIX}.
7907
7908 To enable VMS style return codes, use GNAT BIND and LINK with the option
7909 @option{/RETURN_CODES=VMS}. For example:
7910
7911 @smallexample
7912 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7913 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7914 @end smallexample
7915
7916 @noindent
7917 Programs built with /RETURN_CODES=VMS are suitable to be called in
7918 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7919 are suitable for spawning with appropriate GNAT RTL routines.
7920
7921 @end ifset
7922
7923 @node Search Paths and the Run-Time Library (RTL)
7924 @section Search Paths and the Run-Time Library (RTL)
7925
7926 @noindent
7927 With the GNAT source-based library system, the compiler must be able to
7928 find source files for units that are needed by the unit being compiled.
7929 Search paths are used to guide this process.
7930
7931 The compiler compiles one source file whose name must be given
7932 explicitly on the command line. In other words, no searching is done
7933 for this file. To find all other source files that are needed (the most
7934 common being the specs of units), the compiler examines the following
7935 directories, in the following order:
7936
7937 @enumerate
7938 @item
7939 The directory containing the source file of the main unit being compiled
7940 (the file name on the command line).
7941
7942 @item
7943 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7944 @command{gcc} command line, in the order given.
7945
7946 @item
7947 @findex ADA_PRJ_INCLUDE_FILE
7948 Each of the directories listed in the text file whose name is given
7949 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7950
7951 @noindent
7952 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7953 driver when project files are used. It should not normally be set
7954 by other means.
7955
7956 @item
7957 @findex ADA_INCLUDE_PATH
7958 Each of the directories listed in the value of the
7959 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7960 @ifclear vms
7961 Construct this value
7962 exactly as the @env{PATH} environment variable: a list of directory
7963 names separated by colons (semicolons when working with the NT version).
7964 @end ifclear
7965 @ifset vms
7966 Normally, define this value as a logical name containing a comma separated
7967 list of directory names.
7968
7969 This variable can also be defined by means of an environment string
7970 (an argument to the HP C exec* set of functions).
7971
7972 Logical Name:
7973 @smallexample
7974 DEFINE ANOTHER_PATH FOO:[BAG]
7975 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7976 @end smallexample
7977
7978 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7979 first, followed by the standard Ada
7980 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7981 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7982 (Text_IO, Sequential_IO, etc)
7983 instead of the standard Ada packages. Thus, in order to get the standard Ada
7984 packages by default, ADA_INCLUDE_PATH must be redefined.
7985 @end ifset
7986
7987 @item
7988 The content of the @file{ada_source_path} file which is part of the GNAT
7989 installation tree and is used to store standard libraries such as the
7990 GNAT Run Time Library (RTL) source files.
7991 @ifclear vms
7992 @ref{Installing a library}
7993 @end ifclear
7994 @end enumerate
7995
7996 @noindent
7997 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7998 inhibits the use of the directory
7999 containing the source file named in the command line. You can still
8000 have this directory on your search path, but in this case it must be
8001 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8002
8003 Specifying the switch @option{-nostdinc}
8004 inhibits the search of the default location for the GNAT Run Time
8005 Library (RTL) source files.
8006
8007 The compiler outputs its object files and ALI files in the current
8008 working directory.
8009 @ifclear vms
8010 Caution: The object file can be redirected with the @option{-o} switch;
8011 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8012 so the @file{ALI} file will not go to the right place. Therefore, you should
8013 avoid using the @option{-o} switch.
8014 @end ifclear
8015
8016 @findex System.IO
8017 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8018 children make up the GNAT RTL, together with the simple @code{System.IO}
8019 package used in the @code{"Hello World"} example. The sources for these units
8020 are needed by the compiler and are kept together in one directory. Not
8021 all of the bodies are needed, but all of the sources are kept together
8022 anyway. In a normal installation, you need not specify these directory
8023 names when compiling or binding. Either the environment variables or
8024 the built-in defaults cause these files to be found.
8025
8026 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8027 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8028 consisting of child units of @code{GNAT}. This is a collection of generally
8029 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8030 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8031
8032 Besides simplifying access to the RTL, a major use of search paths is
8033 in compiling sources from multiple directories. This can make
8034 development environments much more flexible.
8035
8036 @node Order of Compilation Issues
8037 @section Order of Compilation Issues
8038
8039 @noindent
8040 If, in our earlier example, there was a spec for the @code{hello}
8041 procedure, it would be contained in the file @file{hello.ads}; yet this
8042 file would not have to be explicitly compiled. This is the result of the
8043 model we chose to implement library management. Some of the consequences
8044 of this model are as follows:
8045
8046 @itemize @bullet
8047 @item
8048 There is no point in compiling specs (except for package
8049 specs with no bodies) because these are compiled as needed by clients. If
8050 you attempt a useless compilation, you will receive an error message.
8051 It is also useless to compile subunits because they are compiled as needed
8052 by the parent.
8053
8054 @item
8055 There are no order of compilation requirements: performing a
8056 compilation never obsoletes anything. The only way you can obsolete
8057 something and require recompilations is to modify one of the
8058 source files on which it depends.
8059
8060 @item
8061 There is no library as such, apart from the ALI files
8062 (@pxref{The Ada Library Information Files}, for information on the format
8063 of these files). For now we find it convenient to create separate ALI files,
8064 but eventually the information therein may be incorporated into the object
8065 file directly.
8066
8067 @item
8068 When you compile a unit, the source files for the specs of all units
8069 that it @code{with}'s, all its subunits, and the bodies of any generics it
8070 instantiates must be available (reachable by the search-paths mechanism
8071 described above), or you will receive a fatal error message.
8072 @end itemize
8073
8074 @node Examples
8075 @section Examples
8076
8077 @noindent
8078 The following are some typical Ada compilation command line examples:
8079
8080 @table @code
8081 @item $ gcc -c xyz.adb
8082 Compile body in file @file{xyz.adb} with all default options.
8083
8084 @ifclear vms
8085 @item $ gcc -c -O2 -gnata xyz-def.adb
8086 @end ifclear
8087 @ifset vms
8088 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8089 @end ifset
8090
8091 Compile the child unit package in file @file{xyz-def.adb} with extensive
8092 optimizations, and pragma @code{Assert}/@code{Debug} statements
8093 enabled.
8094
8095 @item $ gcc -c -gnatc abc-def.adb
8096 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8097 mode.
8098 @end table
8099
8100 @node Binding Using gnatbind
8101 @chapter Binding Using @code{gnatbind}
8102 @findex gnatbind
8103
8104 @menu
8105 * Running gnatbind::
8106 * Switches for gnatbind::
8107 * Command-Line Access::
8108 * Search Paths for gnatbind::
8109 * Examples of gnatbind Usage::
8110 @end menu
8111
8112 @noindent
8113 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8114 to bind compiled GNAT objects.
8115
8116 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8117 driver (see @ref{The GNAT Driver and Project Files}).
8118
8119 The @code{gnatbind} program performs four separate functions:
8120
8121 @enumerate
8122 @item
8123 Checks that a program is consistent, in accordance with the rules in
8124 Chapter 10 of the Ada Reference Manual. In particular, error
8125 messages are generated if a program uses inconsistent versions of a
8126 given unit.
8127
8128 @item
8129 Checks that an acceptable order of elaboration exists for the program
8130 and issues an error message if it cannot find an order of elaboration
8131 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8132
8133 @item
8134 Generates a main program incorporating the given elaboration order.
8135 This program is a small Ada package (body and spec) that
8136 must be subsequently compiled
8137 using the GNAT compiler. The necessary compilation step is usually
8138 performed automatically by @command{gnatlink}. The two most important
8139 functions of this program
8140 are to call the elaboration routines of units in an appropriate order
8141 and to call the main program.
8142
8143 @item
8144 Determines the set of object files required by the given main program.
8145 This information is output in the forms of comments in the generated program,
8146 to be read by the @command{gnatlink} utility used to link the Ada application.
8147 @end enumerate
8148
8149 @node Running gnatbind
8150 @section Running @code{gnatbind}
8151
8152 @noindent
8153 The form of the @code{gnatbind} command is
8154
8155 @smallexample
8156 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8157 @c Expanding @ovar macro inline (explanation in macro def comments)
8158 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8159 @end smallexample
8160
8161 @noindent
8162 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8163 unit body. @code{gnatbind} constructs an Ada
8164 package in two files whose names are
8165 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8166 For example, if given the
8167 parameter @file{hello.ali}, for a main program contained in file
8168 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8169 and @file{b~hello.adb}.
8170
8171 When doing consistency checking, the binder takes into consideration
8172 any source files it can locate. For example, if the binder determines
8173 that the given main program requires the package @code{Pack}, whose
8174 @file{.ALI}
8175 file is @file{pack.ali} and whose corresponding source spec file is
8176 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8177 (using the same search path conventions as previously described for the
8178 @command{gcc} command). If it can locate this source file, it checks that
8179 the time stamps
8180 or source checksums of the source and its references to in @file{ALI} files
8181 match. In other words, any @file{ALI} files that mentions this spec must have
8182 resulted from compiling this version of the source file (or in the case
8183 where the source checksums match, a version close enough that the
8184 difference does not matter).
8185
8186 @cindex Source files, use by binder
8187 The effect of this consistency checking, which includes source files, is
8188 that the binder ensures that the program is consistent with the latest
8189 version of the source files that can be located at bind time. Editing a
8190 source file without compiling files that depend on the source file cause
8191 error messages to be generated by the binder.
8192
8193 For example, suppose you have a main program @file{hello.adb} and a
8194 package @code{P}, from file @file{p.ads} and you perform the following
8195 steps:
8196
8197 @enumerate
8198 @item
8199 Enter @code{gcc -c hello.adb} to compile the main program.
8200
8201 @item
8202 Enter @code{gcc -c p.ads} to compile package @code{P}.
8203
8204 @item
8205 Edit file @file{p.ads}.
8206
8207 @item
8208 Enter @code{gnatbind hello}.
8209 @end enumerate
8210
8211 @noindent
8212 At this point, the file @file{p.ali} contains an out-of-date time stamp
8213 because the file @file{p.ads} has been edited. The attempt at binding
8214 fails, and the binder generates the following error messages:
8215
8216 @smallexample
8217 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8218 error: "p.ads" has been modified and must be recompiled
8219 @end smallexample
8220
8221 @noindent
8222 Now both files must be recompiled as indicated, and then the bind can
8223 succeed, generating a main program. You need not normally be concerned
8224 with the contents of this file, but for reference purposes a sample
8225 binder output file is given in @ref{Example of Binder Output File}.
8226
8227 In most normal usage, the default mode of @command{gnatbind} which is to
8228 generate the main package in Ada, as described in the previous section.
8229 In particular, this means that any Ada programmer can read and understand
8230 the generated main program. It can also be debugged just like any other
8231 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8232 @command{gnatbind} and @command{gnatlink}.
8233
8234 @node Switches for gnatbind
8235 @section Switches for @command{gnatbind}
8236
8237 @noindent
8238 The following switches are available with @code{gnatbind}; details will
8239 be presented in subsequent sections.
8240
8241 @menu
8242 * Consistency-Checking Modes::
8243 * Binder Error Message Control::
8244 * Elaboration Control::
8245 * Output Control::
8246 * Dynamic Allocation Control::
8247 * Binding with Non-Ada Main Programs::
8248 * Binding Programs with No Main Subprogram::
8249 @end menu
8250
8251 @table @option
8252 @c !sort!
8253
8254 @item --version
8255 @cindex @option{--version} @command{gnatbind}
8256 Display Copyright and version, then exit disregarding all other options.
8257
8258 @item --help
8259 @cindex @option{--help} @command{gnatbind}
8260 If @option{--version} was not used, display usage, then exit disregarding
8261 all other options.
8262
8263 @item -a
8264 @cindex @option{-a} @command{gnatbind}
8265 Indicates that, if supported by the platform, the adainit procedure should
8266 be treated as an initialisation routine by the linker (a constructor). This
8267 is intended to be used by the Project Manager to automatically initialize
8268 shared Stand-Alone Libraries.
8269
8270 @item ^-aO^/OBJECT_SEARCH^
8271 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8272 Specify directory to be searched for ALI files.
8273
8274 @item ^-aI^/SOURCE_SEARCH^
8275 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8276 Specify directory to be searched for source file.
8277
8278 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8279 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8280 Output ALI list (to standard output or to the named file).
8281
8282 @item ^-b^/REPORT_ERRORS=BRIEF^
8283 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8284 Generate brief messages to @file{stderr} even if verbose mode set.
8285
8286 @item ^-c^/NOOUTPUT^
8287 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8288 Check only, no generation of binder output file.
8289
8290 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8291 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8292 This switch can be used to change the default task stack size value
8293 to a specified size @var{nn}, which is expressed in bytes by default, or
8294 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8295 with @var{m}.
8296 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8297 in effect, to completing all task specs with
8298 @smallexample @c ada
8299    pragma Storage_Size (nn);
8300 @end smallexample
8301 When they do not already have such a pragma.
8302
8303 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8304 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8305 This switch can be used to change the default secondary stack size value
8306 to a specified size @var{nn}, which is expressed in bytes by default, or
8307 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8308 with @var{m}.
8309
8310 The secondary stack is used to deal with functions that return a variable
8311 sized result, for example a function returning an unconstrained
8312 String. There are two ways in which this secondary stack is allocated.
8313
8314 For most targets, the secondary stack is growing on demand and is allocated
8315 as a chain of blocks in the heap. The -D option is not very
8316 relevant. It only give some control over the size of the allocated
8317 blocks (whose size is the minimum of the default secondary stack size value,
8318 and the actual size needed for the current allocation request).
8319
8320 For certain targets, notably VxWorks 653,
8321 the secondary stack is allocated by carving off a fixed ratio chunk of the
8322 primary task stack. The -D option is used to define the
8323 size of the environment task's secondary stack.
8324
8325 @item ^-e^/ELABORATION_DEPENDENCIES^
8326 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8327 Output complete list of elaboration-order dependencies.
8328
8329 @item ^-E^/STORE_TRACEBACKS^
8330 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8331 Store tracebacks in exception occurrences when the target supports it.
8332 @ignore
8333 @c The following may get moved to an appendix
8334 This option is currently supported on the following targets:
8335 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8336 @end ignore
8337 See also the packages @code{GNAT.Traceback} and
8338 @code{GNAT.Traceback.Symbolic} for more information.
8339 @ifclear vms
8340 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8341 @command{gcc} option.
8342 @end ifclear
8343
8344 @item ^-F^/FORCE_ELABS_FLAGS^
8345 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8346 Force the checks of elaboration flags. @command{gnatbind} does not normally
8347 generate checks of elaboration flags for the main executable, except when
8348 a Stand-Alone Library is used. However, there are cases when this cannot be
8349 detected by gnatbind. An example is importing an interface of a Stand-Alone
8350 Library through a pragma Import and only specifying through a linker switch
8351 this Stand-Alone Library. This switch is used to guarantee that elaboration
8352 flag checks are generated.
8353
8354 @item ^-h^/HELP^
8355 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8356 Output usage (help) information
8357
8358 @item ^-H32^/32_MALLOC^
8359 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8360 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8361 For further details see @ref{Dynamic Allocation Control}.
8362
8363 @item ^-H64^/64_MALLOC^
8364 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8365 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8366 @cindex @code{__gnat_malloc}
8367 For further details see @ref{Dynamic Allocation Control}.
8368
8369 @item ^-I^/SEARCH^
8370 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8371 Specify directory to be searched for source and ALI files.
8372
8373 @item ^-I-^/NOCURRENT_DIRECTORY^
8374 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8375 Do not look for sources in the current directory where @code{gnatbind} was
8376 invoked, and do not look for ALI files in the directory containing the
8377 ALI file named in the @code{gnatbind} command line.
8378
8379 @item ^-l^/ORDER_OF_ELABORATION^
8380 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8381 Output chosen elaboration order.
8382
8383 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8384 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8385 Bind the units for library building. In this case the adainit and
8386 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8387 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8388 ^@var{xxx}final^@var{XXX}FINAL^.
8389 Implies ^-n^/NOCOMPILE^.
8390 @ifclear vms
8391 (@xref{GNAT and Libraries}, for more details.)
8392 @end ifclear
8393 @ifset vms
8394 On OpenVMS, these init and final procedures are exported in uppercase
8395 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8396 the init procedure will be "TOTOINIT" and the exported name of the final
8397 procedure will be "TOTOFINAL".
8398 @end ifset
8399
8400 @item ^-Mxyz^/RENAME_MAIN=xyz^
8401 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8402 Rename generated main program from main to xyz. This option is
8403 supported on cross environments only.
8404
8405 @item ^-m^/ERROR_LIMIT=^@var{n}
8406 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8407 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8408 in the range 1..999999. The default value if no switch is
8409 given is 9999. If the number of warnings reaches this limit, then a
8410 message is output and further warnings are suppressed, the bind
8411 continues in this case. If the number of errors reaches this
8412 limit, then a message is output and the bind is abandoned.
8413 A value of zero means that no limit is enforced. The equal
8414 sign is optional.
8415
8416 @ifset unw
8417 Furthermore, under Windows, the sources pointed to by the libraries path
8418 set in the registry are not searched for.
8419 @end ifset
8420
8421 @item ^-n^/NOMAIN^
8422 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8423 No main program.
8424
8425 @item -nostdinc
8426 @cindex @option{-nostdinc} (@command{gnatbind})
8427 Do not look for sources in the system default directory.
8428
8429 @item -nostdlib
8430 @cindex @option{-nostdlib} (@command{gnatbind})
8431 Do not look for library files in the system default directory.
8432
8433 @item --RTS=@var{rts-path}
8434 @cindex @option{--RTS} (@code{gnatbind})
8435 Specifies the default location of the runtime library. Same meaning as the
8436 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8437
8438 @item ^-o ^/OUTPUT=^@var{file}
8439 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8440 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8441 Note that if this option is used, then linking must be done manually,
8442 gnatlink cannot be used.
8443
8444 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8445 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8446 Output object list (to standard output or to the named file).
8447
8448 @item ^-p^/PESSIMISTIC_ELABORATION^
8449 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8450 Pessimistic (worst-case) elaboration order
8451
8452 @item ^-P^-P^
8453 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8454 Generate binder file suitable for CodePeer.
8455
8456 @item ^-R^-R^
8457 @cindex @option{^-R^-R^} (@command{gnatbind})
8458 Output closure source list.
8459
8460 @item ^-s^/READ_SOURCES=ALL^
8461 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8462 Require all source files to be present.
8463
8464 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8465 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8466 Specifies the value to be used when detecting uninitialized scalar
8467 objects with pragma Initialize_Scalars.
8468 The @var{xxx} ^string specified with the switch^option^ may be either
8469 @itemize @bullet
8470 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8471 @item ``@option{^lo^LOW^}'' for the lowest possible value
8472 @item ``@option{^hi^HIGH^}'' for the highest possible value
8473 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8474 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8475 @end itemize
8476
8477 In addition, you can specify @option{-Sev} to indicate that the value is
8478 to be set at run time. In this case, the program will look for an environment
8479 @cindex GNAT_INIT_SCALARS
8480 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8481 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8482 If no environment variable is found, or if it does not have a valid value,
8483 then the default is @option{in} (invalid values).
8484
8485 @ifclear vms
8486 @item -static
8487 @cindex @option{-static} (@code{gnatbind})
8488 Link against a static GNAT run time.
8489
8490 @item -shared
8491 @cindex @option{-shared} (@code{gnatbind})
8492 Link against a shared GNAT run time when available.
8493 @end ifclear
8494
8495 @item ^-t^/NOTIME_STAMP_CHECK^
8496 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8497 Tolerate time stamp and other consistency errors
8498
8499 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8500 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8501 Set the time slice value to @var{n} milliseconds. If the system supports
8502 the specification of a specific time slice value, then the indicated value
8503 is used. If the system does not support specific time slice values, but
8504 does support some general notion of round-robin scheduling, then any
8505 nonzero value will activate round-robin scheduling.
8506
8507 A value of zero is treated specially. It turns off time
8508 slicing, and in addition, indicates to the tasking run time that the
8509 semantics should match as closely as possible the Annex D
8510 requirements of the Ada RM, and in particular sets the default
8511 scheduling policy to @code{FIFO_Within_Priorities}.
8512
8513 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8514 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8515 Enable dynamic stack usage, with @var{n} results stored and displayed
8516 at program termination. A result is generated when a task
8517 terminates. Results that can't be stored are displayed on the fly, at
8518 task termination. This option is currently not supported on Itanium
8519 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8520
8521 @item ^-v^/REPORT_ERRORS=VERBOSE^
8522 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8523 Verbose mode. Write error messages, header, summary output to
8524 @file{stdout}.
8525
8526 @ifclear vms
8527 @item -w@var{x}
8528 @cindex @option{-w} (@code{gnatbind})
8529 Warning mode (@var{x}=s/e for suppress/treat as error)
8530 @end ifclear
8531
8532 @ifset vms
8533 @item /WARNINGS=NORMAL
8534 @cindex @option{/WARNINGS} (@code{gnatbind})
8535 Normal warnings mode. Warnings are issued but ignored
8536
8537 @item /WARNINGS=SUPPRESS
8538 @cindex @option{/WARNINGS} (@code{gnatbind})
8539 All warning messages are suppressed
8540
8541 @item /WARNINGS=ERROR
8542 @cindex @option{/WARNINGS} (@code{gnatbind})
8543 Warning messages are treated as fatal errors
8544 @end ifset
8545
8546 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8547 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8548 Override default wide character encoding for standard Text_IO files.
8549
8550 @item ^-x^/READ_SOURCES=NONE^
8551 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8552 Exclude source files (check object consistency only).
8553
8554 @ifset vms
8555 @item /READ_SOURCES=AVAILABLE
8556 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8557 Default mode, in which sources are checked for consistency only if
8558 they are available.
8559 @end ifset
8560
8561 @item ^-y^/ENABLE_LEAP_SECONDS^
8562 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8563 Enable leap seconds support in @code{Ada.Calendar} and its children.
8564
8565 @item ^-z^/ZERO_MAIN^
8566 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8567 No main subprogram.
8568 @end table
8569
8570 @ifclear vms
8571 @noindent
8572 You may obtain this listing of switches by running @code{gnatbind} with
8573 no arguments.
8574 @end ifclear
8575
8576 @node Consistency-Checking Modes
8577 @subsection Consistency-Checking Modes
8578
8579 @noindent
8580 As described earlier, by default @code{gnatbind} checks
8581 that object files are consistent with one another and are consistent
8582 with any source files it can locate. The following switches control binder
8583 access to sources.
8584
8585 @table @option
8586 @c !sort!
8587 @item ^-s^/READ_SOURCES=ALL^
8588 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8589 Require source files to be present. In this mode, the binder must be
8590 able to locate all source files that are referenced, in order to check
8591 their consistency. In normal mode, if a source file cannot be located it
8592 is simply ignored. If you specify this switch, a missing source
8593 file is an error.
8594
8595 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8596 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8597 Override default wide character encoding for standard Text_IO files.
8598 Normally the default wide character encoding method used for standard
8599 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8600 the main source input (see description of switch
8601 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8602 use of this switch for the binder (which has the same set of
8603 possible arguments) overrides this default as specified.
8604
8605 @item ^-x^/READ_SOURCES=NONE^
8606 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8607 Exclude source files. In this mode, the binder only checks that ALI
8608 files are consistent with one another. Source files are not accessed.
8609 The binder runs faster in this mode, and there is still a guarantee that
8610 the resulting program is self-consistent.
8611 If a source file has been edited since it was last compiled, and you
8612 specify this switch, the binder will not detect that the object
8613 file is out of date with respect to the source file. Note that this is the
8614 mode that is automatically used by @command{gnatmake} because in this
8615 case the checking against sources has already been performed by
8616 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8617
8618 @ifset vms
8619 @item /READ_SOURCES=AVAILABLE
8620 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8621 This is the default mode in which source files are checked if they are
8622 available, and ignored if they are not available.
8623 @end ifset
8624 @end table
8625
8626 @node Binder Error Message Control
8627 @subsection Binder Error Message Control
8628
8629 @noindent
8630 The following switches provide control over the generation of error
8631 messages from the binder:
8632
8633 @table @option
8634 @c !sort!
8635 @item ^-v^/REPORT_ERRORS=VERBOSE^
8636 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8637 Verbose mode. In the normal mode, brief error messages are generated to
8638 @file{stderr}. If this switch is present, a header is written
8639 to @file{stdout} and any error messages are directed to @file{stdout}.
8640 All that is written to @file{stderr} is a brief summary message.
8641
8642 @item ^-b^/REPORT_ERRORS=BRIEF^
8643 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8644 Generate brief error messages to @file{stderr} even if verbose mode is
8645 specified. This is relevant only when used with the
8646 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8647
8648 @ifclear vms
8649 @item -m@var{n}
8650 @cindex @option{-m} (@code{gnatbind})
8651 Limits the number of error messages to @var{n}, a decimal integer in the
8652 range 1-999. The binder terminates immediately if this limit is reached.
8653
8654 @item -M@var{xxx}
8655 @cindex @option{-M} (@code{gnatbind})
8656 Renames the generated main program from @code{main} to @code{xxx}.
8657 This is useful in the case of some cross-building environments, where
8658 the actual main program is separate from the one generated
8659 by @code{gnatbind}.
8660 @end ifclear
8661
8662 @item ^-ws^/WARNINGS=SUPPRESS^
8663 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8664 @cindex Warnings
8665 Suppress all warning messages.
8666
8667 @item ^-we^/WARNINGS=ERROR^
8668 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8669 Treat any warning messages as fatal errors.
8670
8671 @ifset vms
8672 @item /WARNINGS=NORMAL
8673 Standard mode with warnings generated, but warnings do not get treated
8674 as errors.
8675 @end ifset
8676
8677 @item ^-t^/NOTIME_STAMP_CHECK^
8678 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8679 @cindex Time stamp checks, in binder
8680 @cindex Binder consistency checks
8681 @cindex Consistency checks, in binder
8682 The binder performs a number of consistency checks including:
8683
8684 @itemize @bullet
8685 @item
8686 Check that time stamps of a given source unit are consistent
8687 @item
8688 Check that checksums of a given source unit are consistent
8689 @item
8690 Check that consistent versions of @code{GNAT} were used for compilation
8691 @item
8692 Check consistency of configuration pragmas as required
8693 @end itemize
8694
8695 @noindent
8696 Normally failure of such checks, in accordance with the consistency
8697 requirements of the Ada Reference Manual, causes error messages to be
8698 generated which abort the binder and prevent the output of a binder
8699 file and subsequent link to obtain an executable.
8700
8701 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8702 into warnings, so that
8703 binding and linking can continue to completion even in the presence of such
8704 errors. The result may be a failed link (due to missing symbols), or a
8705 non-functional executable which has undefined semantics.
8706 @emph{This means that
8707 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8708 with extreme care.}
8709 @end table
8710
8711 @node Elaboration Control
8712 @subsection Elaboration Control
8713
8714 @noindent
8715 The following switches provide additional control over the elaboration
8716 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8717
8718 @table @option
8719 @item ^-p^/PESSIMISTIC_ELABORATION^
8720 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8721 Normally the binder attempts to choose an elaboration order that is
8722 likely to minimize the likelihood of an elaboration order error resulting
8723 in raising a @code{Program_Error} exception. This switch reverses the
8724 action of the binder, and requests that it deliberately choose an order
8725 that is likely to maximize the likelihood of an elaboration error.
8726 This is useful in ensuring portability and avoiding dependence on
8727 accidental fortuitous elaboration ordering.
8728
8729 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8730 switch if dynamic
8731 elaboration checking is used (@option{-gnatE} switch used for compilation).
8732 This is because in the default static elaboration mode, all necessary
8733 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8734 These implicit pragmas are still respected by the binder in
8735 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8736 safe elaboration order is assured.
8737
8738 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8739 production use; it is more for debugging/experimental use.
8740 @end table
8741
8742 @node Output Control
8743 @subsection Output Control
8744
8745 @noindent
8746 The following switches allow additional control over the output
8747 generated by the binder.
8748
8749 @table @option
8750 @c !sort!
8751
8752 @item ^-c^/NOOUTPUT^
8753 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8754 Check only. Do not generate the binder output file. In this mode the
8755 binder performs all error checks but does not generate an output file.
8756
8757 @item ^-e^/ELABORATION_DEPENDENCIES^
8758 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8759 Output complete list of elaboration-order dependencies, showing the
8760 reason for each dependency. This output can be rather extensive but may
8761 be useful in diagnosing problems with elaboration order. The output is
8762 written to @file{stdout}.
8763
8764 @item ^-h^/HELP^
8765 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8766 Output usage information. The output is written to @file{stdout}.
8767
8768 @item ^-K^/LINKER_OPTION_LIST^
8769 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8770 Output linker options to @file{stdout}. Includes library search paths,
8771 contents of pragmas Ident and Linker_Options, and libraries added
8772 by @code{gnatbind}.
8773
8774 @item ^-l^/ORDER_OF_ELABORATION^
8775 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8776 Output chosen elaboration order. The output is written to @file{stdout}.
8777
8778 @item ^-O^/OBJECT_LIST^
8779 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8780 Output full names of all the object files that must be linked to provide
8781 the Ada component of the program. The output is written to @file{stdout}.
8782 This list includes the files explicitly supplied and referenced by the user
8783 as well as implicitly referenced run-time unit files. The latter are
8784 omitted if the corresponding units reside in shared libraries. The
8785 directory names for the run-time units depend on the system configuration.
8786
8787 @item ^-o ^/OUTPUT=^@var{file}
8788 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8789 Set name of output file to @var{file} instead of the normal
8790 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8791 binder generated body filename.
8792 Note that if this option is used, then linking must be done manually.
8793 It is not possible to use gnatlink in this case, since it cannot locate
8794 the binder file.
8795
8796 @item ^-r^/RESTRICTION_LIST^
8797 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8798 Generate list of @code{pragma Restrictions} that could be applied to
8799 the current unit. This is useful for code audit purposes, and also may
8800 be used to improve code generation in some cases.
8801
8802 @end table
8803
8804 @node Dynamic Allocation Control
8805 @subsection Dynamic Allocation Control
8806
8807 @noindent
8808 The heap control switches -- @option{-H32} and @option{-H64} --
8809 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8810 They only affect compiler-generated allocations via @code{__gnat_malloc};
8811 explicit calls to @code{malloc} and related functions from the C
8812 run-time library are unaffected.
8813
8814 @table @option
8815 @item -H32
8816 Allocate memory on 32-bit heap
8817
8818 @item -H64
8819 Allocate memory on 64-bit heap.  This is the default
8820 unless explicitly overridden by a @code{'Size} clause on the access type.
8821 @end table
8822
8823 @ifset vms
8824 @noindent
8825 See also @ref{Access types and 32/64-bit allocation}.
8826 @end ifset
8827 @ifclear vms
8828 @noindent
8829 These switches are only effective on VMS platforms.
8830 @end ifclear
8831
8832
8833 @node Binding with Non-Ada Main Programs
8834 @subsection Binding with Non-Ada Main Programs
8835
8836 @noindent
8837 In our description so far we have assumed that the main
8838 program is in Ada, and that the task of the binder is to generate a
8839 corresponding function @code{main} that invokes this Ada main
8840 program. GNAT also supports the building of executable programs where
8841 the main program is not in Ada, but some of the called routines are
8842 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8843 The following switch is used in this situation:
8844
8845 @table @option
8846 @item ^-n^/NOMAIN^
8847 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8848 No main program. The main program is not in Ada.
8849 @end table
8850
8851 @noindent
8852 In this case, most of the functions of the binder are still required,
8853 but instead of generating a main program, the binder generates a file
8854 containing the following callable routines:
8855
8856 @table @code
8857 @item adainit
8858 @findex adainit
8859 You must call this routine to initialize the Ada part of the program by
8860 calling the necessary elaboration routines. A call to @code{adainit} is
8861 required before the first call to an Ada subprogram.
8862
8863 Note that it is assumed that the basic execution environment must be setup
8864 to be appropriate for Ada execution at the point where the first Ada
8865 subprogram is called. In particular, if the Ada code will do any
8866 floating-point operations, then the FPU must be setup in an appropriate
8867 manner. For the case of the x86, for example, full precision mode is
8868 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8869 that the FPU is in the right state.
8870
8871 @item adafinal
8872 @findex adafinal
8873 You must call this routine to perform any library-level finalization
8874 required by the Ada subprograms. A call to @code{adafinal} is required
8875 after the last call to an Ada subprogram, and before the program
8876 terminates.
8877 @end table
8878
8879 @noindent
8880 If the @option{^-n^/NOMAIN^} switch
8881 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8882 @cindex Binder, multiple input files
8883 is given, more than one ALI file may appear on
8884 the command line for @code{gnatbind}. The normal @dfn{closure}
8885 calculation is performed for each of the specified units. Calculating
8886 the closure means finding out the set of units involved by tracing
8887 @code{with} references. The reason it is necessary to be able to
8888 specify more than one ALI file is that a given program may invoke two or
8889 more quite separate groups of Ada units.
8890
8891 The binder takes the name of its output file from the last specified ALI
8892 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8893 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8894 The output is an Ada unit in source form that can be compiled with GNAT.
8895 This compilation occurs automatically as part of the @command{gnatlink}
8896 processing.
8897
8898 Currently the GNAT run time requires a FPU using 80 bits mode
8899 precision. Under targets where this is not the default it is required to
8900 call GNAT.Float_Control.Reset before using floating point numbers (this
8901 include float computation, float input and output) in the Ada code. A
8902 side effect is that this could be the wrong mode for the foreign code
8903 where floating point computation could be broken after this call.
8904
8905 @node Binding Programs with No Main Subprogram
8906 @subsection Binding Programs with No Main Subprogram
8907
8908 @noindent
8909 It is possible to have an Ada program which does not have a main
8910 subprogram. This program will call the elaboration routines of all the
8911 packages, then the finalization routines.
8912
8913 The following switch is used to bind programs organized in this manner:
8914
8915 @table @option
8916 @item ^-z^/ZERO_MAIN^
8917 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8918 Normally the binder checks that the unit name given on the command line
8919 corresponds to a suitable main subprogram. When this switch is used,
8920 a list of ALI files can be given, and the execution of the program
8921 consists of elaboration of these units in an appropriate order. Note
8922 that the default wide character encoding method for standard Text_IO
8923 files is always set to Brackets if this switch is set (you can use
8924 the binder switch
8925 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8926 @end table
8927
8928 @node Command-Line Access
8929 @section Command-Line Access
8930
8931 @noindent
8932 The package @code{Ada.Command_Line} provides access to the command-line
8933 arguments and program name. In order for this interface to operate
8934 correctly, the two variables
8935
8936 @smallexample
8937 @group
8938 int gnat_argc;
8939 char **gnat_argv;
8940 @end group
8941 @end smallexample
8942
8943 @noindent
8944 @findex gnat_argv
8945 @findex gnat_argc
8946 are declared in one of the GNAT library routines. These variables must
8947 be set from the actual @code{argc} and @code{argv} values passed to the
8948 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8949 generates the C main program to automatically set these variables.
8950 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8951 set these variables. If they are not set, the procedures in
8952 @code{Ada.Command_Line} will not be available, and any attempt to use
8953 them will raise @code{Constraint_Error}. If command line access is
8954 required, your main program must set @code{gnat_argc} and
8955 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8956 it.
8957
8958 @node Search Paths for gnatbind
8959 @section Search Paths for @code{gnatbind}
8960
8961 @noindent
8962 The binder takes the name of an ALI file as its argument and needs to
8963 locate source files as well as other ALI files to verify object consistency.
8964
8965 For source files, it follows exactly the same search rules as @command{gcc}
8966 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8967 directories searched are:
8968
8969 @enumerate
8970 @item
8971 The directory containing the ALI file named in the command line, unless
8972 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8973
8974 @item
8975 All directories specified by @option{^-I^/SEARCH^}
8976 switches on the @code{gnatbind}
8977 command line, in the order given.
8978
8979 @item
8980 @findex ADA_PRJ_OBJECTS_FILE
8981 Each of the directories listed in the text file whose name is given
8982 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8983
8984 @noindent
8985 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8986 driver when project files are used. It should not normally be set
8987 by other means.
8988
8989 @item
8990 @findex ADA_OBJECTS_PATH
8991 Each of the directories listed in the value of the
8992 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8993 @ifset unw
8994 Construct this value
8995 exactly as the @env{PATH} environment variable: a list of directory
8996 names separated by colons (semicolons when working with the NT version
8997 of GNAT).
8998 @end ifset
8999 @ifset vms
9000 Normally, define this value as a logical name containing a comma separated
9001 list of directory names.
9002
9003 This variable can also be defined by means of an environment string
9004 (an argument to the HP C exec* set of functions).
9005
9006 Logical Name:
9007 @smallexample
9008 DEFINE ANOTHER_PATH FOO:[BAG]
9009 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9010 @end smallexample
9011
9012 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9013 first, followed by the standard Ada
9014 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9015 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9016 (Text_IO, Sequential_IO, etc)
9017 instead of the standard Ada packages. Thus, in order to get the standard Ada
9018 packages by default, ADA_OBJECTS_PATH must be redefined.
9019 @end ifset
9020
9021 @item
9022 The content of the @file{ada_object_path} file which is part of the GNAT
9023 installation tree and is used to store standard libraries such as the
9024 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9025 specified.
9026 @ifclear vms
9027 @ref{Installing a library}
9028 @end ifclear
9029 @end enumerate
9030
9031 @noindent
9032 In the binder the switch @option{^-I^/SEARCH^}
9033 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9034 is used to specify both source and
9035 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9036 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9037 instead if you want to specify
9038 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9039 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9040 if you want to specify library paths
9041 only. This means that for the binder
9042 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9043 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9044 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9045 The binder generates the bind file (a C language source file) in the
9046 current working directory.
9047
9048 @findex Ada
9049 @findex System
9050 @findex Interfaces
9051 @findex GNAT
9052 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9053 children make up the GNAT Run-Time Library, together with the package
9054 GNAT and its children, which contain a set of useful additional
9055 library functions provided by GNAT. The sources for these units are
9056 needed by the compiler and are kept together in one directory. The ALI
9057 files and object files generated by compiling the RTL are needed by the
9058 binder and the linker and are kept together in one directory, typically
9059 different from the directory containing the sources. In a normal
9060 installation, you need not specify these directory names when compiling
9061 or binding. Either the environment variables or the built-in defaults
9062 cause these files to be found.
9063
9064 Besides simplifying access to the RTL, a major use of search paths is
9065 in compiling sources from multiple directories. This can make
9066 development environments much more flexible.
9067
9068 @node Examples of gnatbind Usage
9069 @section Examples of @code{gnatbind} Usage
9070
9071 @noindent
9072 This section contains a number of examples of using the GNAT binding
9073 utility @code{gnatbind}.
9074
9075 @table @code
9076 @item gnatbind hello
9077 The main program @code{Hello} (source program in @file{hello.adb}) is
9078 bound using the standard switch settings. The generated main program is
9079 @file{b~hello.adb}. This is the normal, default use of the binder.
9080
9081 @ifclear vms
9082 @item gnatbind hello -o mainprog.adb
9083 @end ifclear
9084 @ifset vms
9085 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9086 @end ifset
9087 The main program @code{Hello} (source program in @file{hello.adb}) is
9088 bound using the standard switch settings. The generated main program is
9089 @file{mainprog.adb} with the associated spec in
9090 @file{mainprog.ads}. Note that you must specify the body here not the
9091 spec. Note that if this option is used, then linking must be done manually,
9092 since gnatlink will not be able to find the generated file.
9093 @end table
9094
9095 @c ------------------------------------
9096 @node Linking Using gnatlink
9097 @chapter Linking Using @command{gnatlink}
9098 @c ------------------------------------
9099 @findex gnatlink
9100
9101 @noindent
9102 This chapter discusses @command{gnatlink}, a tool that links
9103 an Ada program and builds an executable file. This utility
9104 invokes the system linker ^(via the @command{gcc} command)^^
9105 with a correct list of object files and library references.
9106 @command{gnatlink} automatically determines the list of files and
9107 references for the Ada part of a program. It uses the binder file
9108 generated by the @command{gnatbind} to determine this list.
9109
9110 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9111 driver (see @ref{The GNAT Driver and Project Files}).
9112
9113 @menu
9114 * Running gnatlink::
9115 * Switches for gnatlink::
9116 @end menu
9117
9118 @node Running gnatlink
9119 @section Running @command{gnatlink}
9120
9121 @noindent
9122 The form of the @command{gnatlink} command is
9123
9124 @smallexample
9125 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9126 @c            @ovar{non-Ada objects} @ovar{linker options}
9127 @c Expanding @ovar macro inline (explanation in macro def comments)
9128 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9129            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9130
9131 @end smallexample
9132
9133 @noindent
9134 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9135 non-Ada objects
9136 or linker options) may be in any order, provided that no non-Ada object may
9137 be mistaken for a main @file{ALI} file.
9138 Any file name @file{F} without the @file{.ali}
9139 extension will be taken as the main @file{ALI} file if a file exists
9140 whose name is the concatenation of @file{F} and @file{.ali}.
9141
9142 @noindent
9143 @file{@var{mainprog}.ali} references the ALI file of the main program.
9144 The @file{.ali} extension of this file can be omitted. From this
9145 reference, @command{gnatlink} locates the corresponding binder file
9146 @file{b~@var{mainprog}.adb} and, using the information in this file along
9147 with the list of non-Ada objects and linker options, constructs a
9148 linker command file to create the executable.
9149
9150 The arguments other than the @command{gnatlink} switches and the main
9151 @file{ALI} file are passed to the linker uninterpreted.
9152 They typically include the names of
9153 object files for units written in other languages than Ada and any library
9154 references required to resolve references in any of these foreign language
9155 units, or in @code{Import} pragmas in any Ada units.
9156
9157 @var{linker options} is an optional list of linker specific
9158 switches.
9159 The default linker called by gnatlink is @command{gcc} which in
9160 turn calls the appropriate system linker.
9161
9162 One useful option for the linker is @option{-s}: it reduces the size of the
9163 executable by removing all symbol table and relocation information from the
9164 executable.
9165
9166 Standard options for the linker such as @option{-lmy_lib} or
9167 @option{-Ldir} can be added as is.
9168 For options that are not recognized by
9169 @command{gcc} as linker options, use the @command{gcc} switches
9170 @option{-Xlinker} or @option{-Wl,}.
9171
9172 Refer to the GCC documentation for
9173 details.
9174
9175 Here is an example showing how to generate a linker map:
9176
9177 @smallexample
9178 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9179 @end smallexample
9180
9181 Using @var{linker options} it is possible to set the program stack and
9182 heap size.
9183 @ifset unw
9184 See @ref{Setting Stack Size from gnatlink} and
9185 @ref{Setting Heap Size from gnatlink}.
9186 @end ifset
9187
9188 @command{gnatlink} determines the list of objects required by the Ada
9189 program and prepends them to the list of objects passed to the linker.
9190 @command{gnatlink} also gathers any arguments set by the use of
9191 @code{pragma Linker_Options} and adds them to the list of arguments
9192 presented to the linker.
9193
9194 @ifset vms
9195 @command{gnatlink} accepts the following types of extra files on the command
9196 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9197 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9198 handled according to their extension.
9199 @end ifset
9200
9201 @node Switches for gnatlink
9202 @section Switches for @command{gnatlink}
9203
9204 @noindent
9205 The following switches are available with the @command{gnatlink} utility:
9206
9207 @table @option
9208 @c !sort!
9209
9210 @item --version
9211 @cindex @option{--version} @command{gnatlink}
9212 Display Copyright and version, then exit disregarding all other options.
9213
9214 @item --help
9215 @cindex @option{--help} @command{gnatlink}
9216 If @option{--version} was not used, display usage, then exit disregarding
9217 all other options.
9218
9219 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9220 @cindex Command line length
9221 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9222 On some targets, the command line length is limited, and @command{gnatlink}
9223 will generate a separate file for the linker if the list of object files
9224 is too long.
9225 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9226 to be generated even if
9227 the limit is not exceeded. This is useful in some cases to deal with
9228 special situations where the command line length is exceeded.
9229
9230 @item ^-g^/DEBUG^
9231 @cindex Debugging information, including
9232 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9233 The option to include debugging information causes the Ada bind file (in
9234 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9235 @option{^-g^/DEBUG^}.
9236 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9237 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9238 Without @option{^-g^/DEBUG^}, the binder removes these files by
9239 default. The same procedure apply if a C bind file was generated using
9240 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9241 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9242
9243 @item ^-n^/NOCOMPILE^
9244 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9245 Do not compile the file generated by the binder. This may be used when
9246 a link is rerun with different options, but there is no need to recompile
9247 the binder file.
9248
9249 @item ^-v^/VERBOSE^
9250 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9251 Causes additional information to be output, including a full list of the
9252 included object files. This switch option is most useful when you want
9253 to see what set of object files are being used in the link step.
9254
9255 @item ^-v -v^/VERBOSE/VERBOSE^
9256 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9257 Very verbose mode. Requests that the compiler operate in verbose mode when
9258 it compiles the binder file, and that the system linker run in verbose mode.
9259
9260 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9261 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9262 @var{exec-name} specifies an alternate name for the generated
9263 executable program. If this switch is omitted, the executable has the same
9264 name as the main unit. For example, @code{gnatlink try.ali} creates
9265 an executable called @file{^try^TRY.EXE^}.
9266
9267 @ifclear vms
9268 @item -b @var{target}
9269 @cindex @option{-b} (@command{gnatlink})
9270 Compile your program to run on @var{target}, which is the name of a
9271 system configuration. You must have a GNAT cross-compiler built if
9272 @var{target} is not the same as your host system.
9273
9274 @item -B@var{dir}
9275 @cindex @option{-B} (@command{gnatlink})
9276 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9277 from @var{dir} instead of the default location. Only use this switch
9278 when multiple versions of the GNAT compiler are available.
9279 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9280 for further details. You would normally use the @option{-b} or
9281 @option{-V} switch instead.
9282
9283 @item -M
9284 When linking an executable, create a map file. The name of the map file
9285 has the same name as the executable with extension ".map".
9286
9287 @item -M=mapfile
9288 When linking an executable, create a map file. The name of the map file is
9289 "mapfile".
9290
9291 @item --GCC=@var{compiler_name}
9292 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9293 Program used for compiling the binder file. The default is
9294 @command{gcc}. You need to use quotes around @var{compiler_name} if
9295 @code{compiler_name} contains spaces or other separator characters.
9296 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9297 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9298 inserted after your command name. Thus in the above example the compiler
9299 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9300 A limitation of this syntax is that the name and path name of the executable
9301 itself must not include any embedded spaces. If the compiler executable is
9302 different from the default one (gcc or <prefix>-gcc), then the back-end
9303 switches in the ALI file are not used to compile the binder generated source.
9304 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9305 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9306 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9307 is taken into account. However, all the additional switches are also taken
9308 into account. Thus,
9309 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9310 @option{--GCC="bar -x -y -z -t"}.
9311
9312 @item --LINK=@var{name}
9313 @cindex @option{--LINK=} (@command{gnatlink})
9314 @var{name} is the name of the linker to be invoked. This is especially
9315 useful in mixed language programs since languages such as C++ require
9316 their own linker to be used. When this switch is omitted, the default
9317 name for the linker is @command{gcc}. When this switch is used, the
9318 specified linker is called instead of @command{gcc} with exactly the same
9319 parameters that would have been passed to @command{gcc} so if the desired
9320 linker requires different parameters it is necessary to use a wrapper
9321 script that massages the parameters before invoking the real linker. It
9322 may be useful to control the exact invocation by using the verbose
9323 switch.
9324
9325 @end ifclear
9326
9327 @ifset vms
9328 @item /DEBUG=TRACEBACK
9329 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9330 This qualifier causes sufficient information to be included in the
9331 executable file to allow a traceback, but does not include the full
9332 symbol information needed by the debugger.
9333
9334 @item /IDENTIFICATION="<string>"
9335 @code{"<string>"} specifies the string to be stored in the image file
9336 identification field in the image header.
9337 It overrides any pragma @code{Ident} specified string.
9338
9339 @item /NOINHIBIT-EXEC
9340 Generate the executable file even if there are linker warnings.
9341
9342 @item /NOSTART_FILES
9343 Don't link in the object file containing the ``main'' transfer address.
9344 Used when linking with a foreign language main program compiled with an
9345 HP compiler.
9346
9347 @item /STATIC
9348 Prefer linking with object libraries over sharable images, even without
9349 /DEBUG.
9350 @end ifset
9351
9352 @end table
9353
9354 @node The GNAT Make Program gnatmake
9355 @chapter The GNAT Make Program @command{gnatmake}
9356 @findex gnatmake
9357
9358 @menu
9359 * Running gnatmake::
9360 * Switches for gnatmake::
9361 * Mode Switches for gnatmake::
9362 * Notes on the Command Line::
9363 * How gnatmake Works::
9364 * Examples of gnatmake Usage::
9365 @end menu
9366 @noindent
9367 A typical development cycle when working on an Ada program consists of
9368 the following steps:
9369
9370 @enumerate
9371 @item
9372 Edit some sources to fix bugs.
9373
9374 @item
9375 Add enhancements.
9376
9377 @item
9378 Compile all sources affected.
9379
9380 @item
9381 Rebind and relink.
9382
9383 @item
9384 Test.
9385 @end enumerate
9386
9387 @noindent
9388 The third step can be tricky, because not only do the modified files
9389 @cindex Dependency rules
9390 have to be compiled, but any files depending on these files must also be
9391 recompiled. The dependency rules in Ada can be quite complex, especially
9392 in the presence of overloading, @code{use} clauses, generics and inlined
9393 subprograms.
9394
9395 @command{gnatmake} automatically takes care of the third and fourth steps
9396 of this process. It determines which sources need to be compiled,
9397 compiles them, and binds and links the resulting object files.
9398
9399 Unlike some other Ada make programs, the dependencies are always
9400 accurately recomputed from the new sources. The source based approach of
9401 the GNAT compilation model makes this possible. This means that if
9402 changes to the source program cause corresponding changes in
9403 dependencies, they will always be tracked exactly correctly by
9404 @command{gnatmake}.
9405
9406 @node Running gnatmake
9407 @section Running @command{gnatmake}
9408
9409 @noindent
9410 The usual form of the @command{gnatmake} command is
9411
9412 @smallexample
9413 @c $ gnatmake @ovar{switches} @var{file_name}
9414 @c       @ovar{file_names} @ovar{mode_switches}
9415 @c Expanding @ovar macro inline (explanation in macro def comments)
9416 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9417       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9418 @end smallexample
9419
9420 @noindent
9421 The only required argument is one @var{file_name}, which specifies
9422 a compilation unit that is a main program. Several @var{file_names} can be
9423 specified: this will result in several executables being built.
9424 If @code{switches} are present, they can be placed before the first
9425 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9426 If @var{mode_switches} are present, they must always be placed after
9427 the last @var{file_name} and all @code{switches}.
9428
9429 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9430 extension may be omitted from the @var{file_name} arguments. However, if
9431 you are using non-standard extensions, then it is required that the
9432 extension be given. A relative or absolute directory path can be
9433 specified in a @var{file_name}, in which case, the input source file will
9434 be searched for in the specified directory only. Otherwise, the input
9435 source file will first be searched in the directory where
9436 @command{gnatmake} was invoked and if it is not found, it will be search on
9437 the source path of the compiler as described in
9438 @ref{Search Paths and the Run-Time Library (RTL)}.
9439
9440 All @command{gnatmake} output (except when you specify
9441 @option{^-M^/DEPENDENCIES_LIST^}) is to
9442 @file{stderr}. The output produced by the
9443 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9444 @file{stdout}.
9445
9446 @node Switches for gnatmake
9447 @section Switches for @command{gnatmake}
9448
9449 @noindent
9450 You may specify any of the following switches to @command{gnatmake}:
9451
9452 @table @option
9453 @c !sort!
9454
9455 @item --version
9456 @cindex @option{--version} @command{gnatmake}
9457 Display Copyright and version, then exit disregarding all other options.
9458
9459 @item --help
9460 @cindex @option{--help} @command{gnatmake}
9461 If @option{--version} was not used, display usage, then exit disregarding
9462 all other options.
9463
9464 @ifclear vms
9465 @item --GCC=@var{compiler_name}
9466 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9467 Program used for compiling. The default is `@command{gcc}'. You need to use
9468 quotes around @var{compiler_name} if @code{compiler_name} contains
9469 spaces or other separator characters. As an example @option{--GCC="foo -x
9470 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9471 compiler. A limitation of this syntax is that the name and path name of
9472 the executable itself must not include any embedded spaces. Note that
9473 switch @option{-c} is always inserted after your command name. Thus in the
9474 above example the compiler command that will be used by @command{gnatmake}
9475 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9476 used, only the last @var{compiler_name} is taken into account. However,
9477 all the additional switches are also taken into account. Thus,
9478 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9479 @option{--GCC="bar -x -y -z -t"}.
9480
9481 @item --GNATBIND=@var{binder_name}
9482 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9483 Program used for binding. The default is `@code{gnatbind}'. You need to
9484 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9485 or other separator characters. As an example @option{--GNATBIND="bar -x
9486 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9487 binder. Binder switches that are normally appended by @command{gnatmake}
9488 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9489 A limitation of this syntax is that the name and path name of the executable
9490 itself must not include any embedded spaces.
9491
9492 @item --GNATLINK=@var{linker_name}
9493 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9494 Program used for linking. The default is `@command{gnatlink}'. You need to
9495 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9496 or other separator characters. As an example @option{--GNATLINK="lan -x
9497 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9498 linker. Linker switches that are normally appended by @command{gnatmake} to
9499 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9500 A limitation of this syntax is that the name and path name of the executable
9501 itself must not include any embedded spaces.
9502
9503 @end ifclear
9504
9505 @item ^--subdirs^/SUBDIRS^=subdir
9506 Actual object directory of each project file is the subdirectory subdir of the
9507 object directory specified or defaulted in the project file.
9508
9509 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9510 Disallow simultaneous compilations in the same object directory when
9511 project files are used.
9512
9513 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9514 By default, shared library projects are not allowed to import static library
9515 projects. When this switch is used on the command line, this restriction is
9516 relaxed.
9517
9518 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9519 Specify a source info file. This switch is active only when project files
9520 are used. If the source info file is specified as a relative path, then it is
9521 relative to the object directory of the main project. If the source info file
9522 does not exist, then after the Project Manager has successfully parsed and
9523 processed the project files and found the sources, it creates the source info
9524 file. If the source info file already exists and can be read successfully,
9525 then the Project Manager will get all the needed information about the sources
9526 from the source info file and will not look for them. This reduces the time
9527 to process the project files, especially when looking for sources that take a
9528 long time. If the source info file exists but cannot be parsed successfully,
9529 the Project Manager will attempt to recreate it. If the Project Manager fails
9530 to create the source info file, a message is issued, but gnatmake does not
9531 fail. @command{gnatmake} "trusts" the source info file. This means that
9532 if the source files have changed (addition, deletion, moving to a different
9533 source directory), then the source info file need to be deleted and recreated.
9534
9535 @ifclear vms
9536 @item --create-map-file
9537 When linking an executable, create a map file. The name of the map file
9538 has the same name as the executable with extension ".map".
9539
9540 @item --create-map-file=mapfile
9541 When linking an executable, create a map file. The name of the map file is
9542 "mapfile".
9543
9544 @end ifclear
9545
9546 @item ^-a^/ALL_FILES^
9547 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9548 Consider all files in the make process, even the GNAT internal system
9549 files (for example, the predefined Ada library files), as well as any
9550 locked files. Locked files are files whose ALI file is write-protected.
9551 By default,
9552 @command{gnatmake} does not check these files,
9553 because the assumption is that the GNAT internal files are properly up
9554 to date, and also that any write protected ALI files have been properly
9555 installed. Note that if there is an installation problem, such that one
9556 of these files is not up to date, it will be properly caught by the
9557 binder.
9558 You may have to specify this switch if you are working on GNAT
9559 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9560 in conjunction with @option{^-f^/FORCE_COMPILE^}
9561 if you need to recompile an entire application,
9562 including run-time files, using special configuration pragmas,
9563 such as a @code{Normalize_Scalars} pragma.
9564
9565 By default
9566 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9567 internal files with
9568 @ifclear vms
9569 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9570 @end ifclear
9571 @ifset vms
9572 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9573 @end ifset
9574
9575 @item ^-b^/ACTIONS=BIND^
9576 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9577 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9578 compilation and binding, but no link.
9579 Can be combined with @option{^-l^/ACTIONS=LINK^}
9580 to do binding and linking. When not combined with
9581 @option{^-c^/ACTIONS=COMPILE^}
9582 all the units in the closure of the main program must have been previously
9583 compiled and must be up to date. The root unit specified by @var{file_name}
9584 may be given without extension, with the source extension or, if no GNAT
9585 Project File is specified, with the ALI file extension.
9586
9587 @item ^-c^/ACTIONS=COMPILE^
9588 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9589 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9590 is also specified. Do not perform linking, except if both
9591 @option{^-b^/ACTIONS=BIND^} and
9592 @option{^-l^/ACTIONS=LINK^} are also specified.
9593 If the root unit specified by @var{file_name} is not a main unit, this is the
9594 default. Otherwise @command{gnatmake} will attempt binding and linking
9595 unless all objects are up to date and the executable is more recent than
9596 the objects.
9597
9598 @item ^-C^/MAPPING^
9599 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9600 Use a temporary mapping file. A mapping file is a way to communicate
9601 to the compiler two mappings: from unit names to file names (without
9602 any directory information) and from file names to path names (with
9603 full directory information). A mapping file can make the compiler's
9604 file searches faster, especially if there are many source directories,
9605 or the sources are read over a slow network connection. If
9606 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9607 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9608 is initially populated based on the project file. If
9609 @option{^-C^/MAPPING^} is used without
9610 @option{^-P^/PROJECT_FILE^},
9611 the mapping file is initially empty. Each invocation of the compiler
9612 will add any newly accessed sources to the mapping file.
9613
9614 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9615 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9616 Use a specific mapping file. The file, specified as a path name (absolute or
9617 relative) by this switch, should already exist, otherwise the switch is
9618 ineffective. The specified mapping file will be communicated to the compiler.
9619 This switch is not compatible with a project file
9620 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9621 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9622
9623 @item ^-d^/DISPLAY_PROGRESS^
9624 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9625 Display progress for each source, up to date or not, as a single line
9626
9627 @smallexample
9628 completed x out of y (zz%)
9629 @end smallexample
9630
9631 If the file needs to be compiled this is displayed after the invocation of
9632 the compiler. These lines are displayed even in quiet output mode.
9633
9634 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9635 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9636 Put all object files and ALI file in directory @var{dir}.
9637 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9638 and ALI files go in the current working directory.
9639
9640 This switch cannot be used when using a project file.
9641
9642 @item -eInnn
9643 @cindex @option{-eI} (@command{gnatmake})
9644 Indicates that the main source is a multi-unit source and the rank of the unit
9645 in the source file is nnn. nnn needs to be a positive number and a valid
9646 index in the source. This switch cannot be used when @command{gnatmake} is
9647 invoked for several mains.
9648
9649 @ifclear vms
9650 @item -eL
9651 @cindex @option{-eL} (@command{gnatmake})
9652 @cindex symbolic links
9653 Follow all symbolic links when processing project files.
9654 This should be used if your project uses symbolic links for files or
9655 directories, but is not needed in other cases.
9656
9657 @cindex naming scheme
9658 This also assumes that no directory matches the naming scheme for files (for
9659 instance that you do not have a directory called "sources.ads" when using the
9660 default GNAT naming scheme).
9661
9662 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9663 save a lot of system calls (several per source file and object file), which
9664 can result in a significant speed up to load and manipulate a project file,
9665 especially when using source files from a remote system.
9666
9667 @end ifclear
9668
9669 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9670 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9671 Output the commands for the compiler, the binder and the linker
9672 on ^standard output^SYS$OUTPUT^,
9673 instead of ^standard error^SYS$ERROR^.
9674
9675 @item ^-f^/FORCE_COMPILE^
9676 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9677 Force recompilations. Recompile all sources, even though some object
9678 files may be up to date, but don't recompile predefined or GNAT internal
9679 files or locked files (files with a write-protected ALI file),
9680 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9681
9682 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9683 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9684 When using project files, if some errors or warnings are detected during
9685 parsing and verbose mode is not in effect (no use of switch
9686 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9687 file, rather than its simple file name.
9688
9689 @item ^-g^/DEBUG^
9690 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9691 Enable debugging. This switch is simply passed to the compiler and to the
9692 linker.
9693
9694 @item ^-i^/IN_PLACE^
9695 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9696 In normal mode, @command{gnatmake} compiles all object files and ALI files
9697 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9698 then instead object files and ALI files that already exist are overwritten
9699 in place. This means that once a large project is organized into separate
9700 directories in the desired manner, then @command{gnatmake} will automatically
9701 maintain and update this organization. If no ALI files are found on the
9702 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9703 the new object and ALI files are created in the
9704 directory containing the source being compiled. If another organization
9705 is desired, where objects and sources are kept in different directories,
9706 a useful technique is to create dummy ALI files in the desired directories.
9707 When detecting such a dummy file, @command{gnatmake} will be forced to
9708 recompile the corresponding source file, and it will be put the resulting
9709 object and ALI files in the directory where it found the dummy file.
9710
9711 @item ^-j^/PROCESSES=^@var{n}
9712 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9713 @cindex Parallel make
9714 Use @var{n} processes to carry out the (re)compilations. On a
9715 multiprocessor machine compilations will occur in parallel. In the
9716 event of compilation errors, messages from various compilations might
9717 get interspersed (but @command{gnatmake} will give you the full ordered
9718 list of failing compiles at the end). If this is problematic, rerun
9719 the make process with n set to 1 to get a clean list of messages.
9720
9721 @item ^-k^/CONTINUE_ON_ERROR^
9722 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9723 Keep going. Continue as much as possible after a compilation error. To
9724 ease the programmer's task in case of compilation errors, the list of
9725 sources for which the compile fails is given when @command{gnatmake}
9726 terminates.
9727
9728 If @command{gnatmake} is invoked with several @file{file_names} and with this
9729 switch, if there are compilation errors when building an executable,
9730 @command{gnatmake} will not attempt to build the following executables.
9731
9732 @item ^-l^/ACTIONS=LINK^
9733 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9734 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9735 and linking. Linking will not be performed if combined with
9736 @option{^-c^/ACTIONS=COMPILE^}
9737 but not with @option{^-b^/ACTIONS=BIND^}.
9738 When not combined with @option{^-b^/ACTIONS=BIND^}
9739 all the units in the closure of the main program must have been previously
9740 compiled and must be up to date, and the main program needs to have been bound.
9741 The root unit specified by @var{file_name}
9742 may be given without extension, with the source extension or, if no GNAT
9743 Project File is specified, with the ALI file extension.
9744
9745 @item ^-m^/MINIMAL_RECOMPILATION^
9746 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9747 Specify that the minimum necessary amount of recompilations
9748 be performed. In this mode @command{gnatmake} ignores time
9749 stamp differences when the only
9750 modifications to a source file consist in adding/removing comments,
9751 empty lines, spaces or tabs. This means that if you have changed the
9752 comments in a source file or have simply reformatted it, using this
9753 switch will tell @command{gnatmake} not to recompile files that depend on it
9754 (provided other sources on which these files depend have undergone no
9755 semantic modifications). Note that the debugging information may be
9756 out of date with respect to the sources if the @option{-m} switch causes
9757 a compilation to be switched, so the use of this switch represents a
9758 trade-off between compilation time and accurate debugging information.
9759
9760 @item ^-M^/DEPENDENCIES_LIST^
9761 @cindex Dependencies, producing list
9762 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9763 Check if all objects are up to date. If they are, output the object
9764 dependences to @file{stdout} in a form that can be directly exploited in
9765 a @file{Makefile}. By default, each source file is prefixed with its
9766 (relative or absolute) directory name. This name is whatever you
9767 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9768 and @option{^-I^/SEARCH^} switches. If you use
9769 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9770 @option{^-q^/QUIET^}
9771 (see below), only the source file names,
9772 without relative paths, are output. If you just specify the
9773 @option{^-M^/DEPENDENCIES_LIST^}
9774 switch, dependencies of the GNAT internal system files are omitted. This
9775 is typically what you want. If you also specify
9776 the @option{^-a^/ALL_FILES^} switch,
9777 dependencies of the GNAT internal files are also listed. Note that
9778 dependencies of the objects in external Ada libraries (see switch
9779 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9780 are never reported.
9781
9782 @item ^-n^/DO_OBJECT_CHECK^
9783 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9784 Don't compile, bind, or link. Checks if all objects are up to date.
9785 If they are not, the full name of the first file that needs to be
9786 recompiled is printed.
9787 Repeated use of this option, followed by compiling the indicated source
9788 file, will eventually result in recompiling all required units.
9789
9790 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9791 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9792 Output executable name. The name of the final executable program will be
9793 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9794 name for the executable will be the name of the input file in appropriate form
9795 for an executable file on the host system.
9796
9797 This switch cannot be used when invoking @command{gnatmake} with several
9798 @file{file_names}.
9799
9800 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9801 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9802 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9803 automatically missing object directories, library directories and exec
9804 directories.
9805
9806 @item ^-P^/PROJECT_FILE=^@var{project}
9807 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9808 Use project file @var{project}. Only one such switch can be used.
9809 @xref{gnatmake and Project Files}.
9810
9811 @item ^-q^/QUIET^
9812 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9813 Quiet. When this flag is not set, the commands carried out by
9814 @command{gnatmake} are displayed.
9815
9816 @item ^-s^/SWITCH_CHECK/^
9817 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9818 Recompile if compiler switches have changed since last compilation.
9819 All compiler switches but -I and -o are taken into account in the
9820 following way:
9821 orders between different ``first letter'' switches are ignored, but
9822 orders between same switches are taken into account. For example,
9823 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9824 is equivalent to @option{-O -g}.
9825
9826 This switch is recommended when Integrated Preprocessing is used.
9827
9828 @item ^-u^/UNIQUE^
9829 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9830 Unique. Recompile at most the main files. It implies -c. Combined with
9831 -f, it is equivalent to calling the compiler directly. Note that using
9832 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9833 (@pxref{Project Files and Main Subprograms}).
9834
9835 @item ^-U^/ALL_PROJECTS^
9836 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9837 When used without a project file or with one or several mains on the command
9838 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9839 on the command line, all sources of all project files are checked and compiled
9840 if not up to date, and libraries are rebuilt, if necessary.
9841
9842 @item ^-v^/REASONS^
9843 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9844 Verbose. Display the reason for all recompilations @command{gnatmake}
9845 decides are necessary, with the highest verbosity level.
9846
9847 @item ^-vl^/LOW_VERBOSITY^
9848 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9849 Verbosity level Low. Display fewer lines than in verbosity Medium.
9850
9851 @item ^-vm^/MEDIUM_VERBOSITY^
9852 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9853 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9854
9855 @item ^-vh^/HIGH_VERBOSITY^
9856 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9857 Verbosity level High. Equivalent to ^-v^/REASONS^.
9858
9859 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9860 Indicate the verbosity of the parsing of GNAT project files.
9861 @xref{Switches Related to Project Files}.
9862
9863 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9864 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9865 Indicate that sources that are not part of any Project File may be compiled.
9866 Normally, when using Project Files, only sources that are part of a Project
9867 File may be compile. When this switch is used, a source outside of all Project
9868 Files may be compiled. The ALI file and the object file will be put in the
9869 object directory of the main Project. The compilation switches used will only
9870 be those specified on the command line. Even when
9871 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9872 command line need to be sources of a project file.
9873
9874 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9875 Indicate that external variable @var{name} has the value @var{value}.
9876 The Project Manager will use this value for occurrences of
9877 @code{external(name)} when parsing the project file.
9878 @xref{Switches Related to Project Files}.
9879
9880 @item ^-z^/NOMAIN^
9881 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9882 No main subprogram. Bind and link the program even if the unit name
9883 given on the command line is a package name. The resulting executable
9884 will execute the elaboration routines of the package and its closure,
9885 then the finalization routines.
9886
9887 @end table
9888
9889 @table @asis
9890 @item @command{gcc} @asis{switches}
9891 @ifclear vms
9892 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9893 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9894 @end ifclear
9895 @ifset vms
9896 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9897 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9898 automatically treated as a compiler switch, and passed on to all
9899 compilations that are carried out.
9900 @end ifset
9901 @end table
9902
9903 @noindent
9904 Source and library search path switches:
9905
9906 @table @option
9907 @c !sort!
9908 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9909 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9910 When looking for source files also look in directory @var{dir}.
9911 The order in which source files search is undertaken is
9912 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9913
9914 @item ^-aL^/SKIP_MISSING=^@var{dir}
9915 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9916 Consider @var{dir} as being an externally provided Ada library.
9917 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9918 files have been located in directory @var{dir}. This allows you to have
9919 missing bodies for the units in @var{dir} and to ignore out of date bodies
9920 for the same units. You still need to specify
9921 the location of the specs for these units by using the switches
9922 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9923 or @option{^-I^/SEARCH=^@var{dir}}.
9924 Note: this switch is provided for compatibility with previous versions
9925 of @command{gnatmake}. The easier method of causing standard libraries
9926 to be excluded from consideration is to write-protect the corresponding
9927 ALI files.
9928
9929 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9930 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9931 When searching for library and object files, look in directory
9932 @var{dir}. The order in which library files are searched is described in
9933 @ref{Search Paths for gnatbind}.
9934
9935 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9936 @cindex Search paths, for @command{gnatmake}
9937 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9938 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9939 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9940
9941 @item ^-I^/SEARCH=^@var{dir}
9942 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9943 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9944 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9945
9946 @item ^-I-^/NOCURRENT_DIRECTORY^
9947 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9948 @cindex Source files, suppressing search
9949 Do not look for source files in the directory containing the source
9950 file named in the command line.
9951 Do not look for ALI or object files in the directory
9952 where @command{gnatmake} was invoked.
9953
9954 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9955 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9956 @cindex Linker libraries
9957 Add directory @var{dir} to the list of directories in which the linker
9958 will search for libraries. This is equivalent to
9959 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9960 @ifclear vms
9961 Furthermore, under Windows, the sources pointed to by the libraries path
9962 set in the registry are not searched for.
9963 @end ifclear
9964
9965 @item -nostdinc
9966 @cindex @option{-nostdinc} (@command{gnatmake})
9967 Do not look for source files in the system default directory.
9968
9969 @item -nostdlib
9970 @cindex @option{-nostdlib} (@command{gnatmake})
9971 Do not look for library files in the system default directory.
9972
9973 @item --RTS=@var{rts-path}
9974 @cindex @option{--RTS} (@command{gnatmake})
9975 Specifies the default location of the runtime library. GNAT looks for the
9976 runtime
9977 in the following directories, and stops as soon as a valid runtime is found
9978 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9979 @file{ada_object_path} present):
9980
9981 @itemize @bullet
9982 @item <current directory>/$rts_path
9983
9984 @item <default-search-dir>/$rts_path
9985
9986 @item <default-search-dir>/rts-$rts_path
9987 @end itemize
9988
9989 @noindent
9990 The selected path is handled like a normal RTS path.
9991
9992 @end table
9993
9994 @node Mode Switches for gnatmake
9995 @section Mode Switches for @command{gnatmake}
9996
9997 @noindent
9998 The mode switches (referred to as @code{mode_switches}) allow the
9999 inclusion of switches that are to be passed to the compiler itself, the
10000 binder or the linker. The effect of a mode switch is to cause all
10001 subsequent switches up to the end of the switch list, or up to the next
10002 mode switch, to be interpreted as switches to be passed on to the
10003 designated component of GNAT.
10004
10005 @table @option
10006 @c !sort!
10007 @item -cargs @var{switches}
10008 @cindex @option{-cargs} (@command{gnatmake})
10009 Compiler switches. Here @var{switches} is a list of switches
10010 that are valid switches for @command{gcc}. They will be passed on to
10011 all compile steps performed by @command{gnatmake}.
10012
10013 @item -bargs @var{switches}
10014 @cindex @option{-bargs} (@command{gnatmake})
10015 Binder switches. Here @var{switches} is a list of switches
10016 that are valid switches for @code{gnatbind}. They will be passed on to
10017 all bind steps performed by @command{gnatmake}.
10018
10019 @item -largs @var{switches}
10020 @cindex @option{-largs} (@command{gnatmake})
10021 Linker switches. Here @var{switches} is a list of switches
10022 that are valid switches for @command{gnatlink}. They will be passed on to
10023 all link steps performed by @command{gnatmake}.
10024
10025 @item -margs @var{switches}
10026 @cindex @option{-margs} (@command{gnatmake})
10027 Make switches. The switches are directly interpreted by @command{gnatmake},
10028 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10029 or @option{-largs}.
10030 @end table
10031
10032 @node Notes on the Command Line
10033 @section Notes on the Command Line
10034
10035 @noindent
10036 This section contains some additional useful notes on the operation
10037 of the @command{gnatmake} command.
10038
10039 @itemize @bullet
10040 @item
10041 @cindex Recompilation, by @command{gnatmake}
10042 If @command{gnatmake} finds no ALI files, it recompiles the main program
10043 and all other units required by the main program.
10044 This means that @command{gnatmake}
10045 can be used for the initial compile, as well as during subsequent steps of
10046 the development cycle.
10047
10048 @item
10049 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10050 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10051 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10052 warning.
10053
10054 @item
10055 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10056 is used to specify both source and
10057 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10058 instead if you just want to specify
10059 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10060 if you want to specify library paths
10061 only.
10062
10063 @item
10064 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10065 This may conveniently be used to exclude standard libraries from
10066 consideration and in particular it means that the use of the
10067 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10068 unless @option{^-a^/ALL_FILES^} is also specified.
10069
10070 @item
10071 @command{gnatmake} has been designed to make the use of Ada libraries
10072 particularly convenient. Assume you have an Ada library organized
10073 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10074 of your Ada compilation units,
10075 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10076 specs of these units, but no bodies. Then to compile a unit
10077 stored in @code{main.adb}, which uses this Ada library you would just type
10078
10079 @smallexample
10080 @ifclear vms
10081 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
10082 @end ifclear
10083 @ifset vms
10084 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10085            /SKIP_MISSING=@i{[OBJ_DIR]} main
10086 @end ifset
10087 @end smallexample
10088
10089 @item
10090 Using @command{gnatmake} along with the
10091 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10092 switch provides a mechanism for avoiding unnecessary recompilations. Using
10093 this switch,
10094 you can update the comments/format of your
10095 source files without having to recompile everything. Note, however, that
10096 adding or deleting lines in a source files may render its debugging
10097 info obsolete. If the file in question is a spec, the impact is rather
10098 limited, as that debugging info will only be useful during the
10099 elaboration phase of your program. For bodies the impact can be more
10100 significant. In all events, your debugger will warn you if a source file
10101 is more recent than the corresponding object, and alert you to the fact
10102 that the debugging information may be out of date.
10103 @end itemize
10104
10105 @node How gnatmake Works
10106 @section How @command{gnatmake} Works
10107
10108 @noindent
10109 Generally @command{gnatmake} automatically performs all necessary
10110 recompilations and you don't need to worry about how it works. However,
10111 it may be useful to have some basic understanding of the @command{gnatmake}
10112 approach and in particular to understand how it uses the results of
10113 previous compilations without incorrectly depending on them.
10114
10115 First a definition: an object file is considered @dfn{up to date} if the
10116 corresponding ALI file exists and if all the source files listed in the
10117 dependency section of this ALI file have time stamps matching those in
10118 the ALI file. This means that neither the source file itself nor any
10119 files that it depends on have been modified, and hence there is no need
10120 to recompile this file.
10121
10122 @command{gnatmake} works by first checking if the specified main unit is up
10123 to date. If so, no compilations are required for the main unit. If not,
10124 @command{gnatmake} compiles the main program to build a new ALI file that
10125 reflects the latest sources. Then the ALI file of the main unit is
10126 examined to find all the source files on which the main program depends,
10127 and @command{gnatmake} recursively applies the above procedure on all these
10128 files.
10129
10130 This process ensures that @command{gnatmake} only trusts the dependencies
10131 in an existing ALI file if they are known to be correct. Otherwise it
10132 always recompiles to determine a new, guaranteed accurate set of
10133 dependencies. As a result the program is compiled ``upside down'' from what may
10134 be more familiar as the required order of compilation in some other Ada
10135 systems. In particular, clients are compiled before the units on which
10136 they depend. The ability of GNAT to compile in any order is critical in
10137 allowing an order of compilation to be chosen that guarantees that
10138 @command{gnatmake} will recompute a correct set of new dependencies if
10139 necessary.
10140
10141 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10142 imported by several of the executables, it will be recompiled at most once.
10143
10144 Note: when using non-standard naming conventions
10145 (@pxref{Using Other File Names}), changing through a configuration pragmas
10146 file the version of a source and invoking @command{gnatmake} to recompile may
10147 have no effect, if the previous version of the source is still accessible
10148 by @command{gnatmake}. It may be necessary to use the switch
10149 ^-f^/FORCE_COMPILE^.
10150
10151 @node Examples of gnatmake Usage
10152 @section Examples of @command{gnatmake} Usage
10153
10154 @table @code
10155 @item gnatmake hello.adb
10156 Compile all files necessary to bind and link the main program
10157 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10158 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10159
10160 @item gnatmake main1 main2 main3
10161 Compile all files necessary to bind and link the main programs
10162 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10163 (containing unit @code{Main2}) and @file{main3.adb}
10164 (containing unit @code{Main3}) and bind and link the resulting object files
10165 to generate three executable files @file{^main1^MAIN1.EXE^},
10166 @file{^main2^MAIN2.EXE^}
10167 and @file{^main3^MAIN3.EXE^}.
10168
10169 @ifclear vms
10170 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10171 @end ifclear
10172
10173 @ifset vms
10174 @item gnatmake Main_Unit /QUIET
10175 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10176 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10177 @end ifset
10178 Compile all files necessary to bind and link the main program unit
10179 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10180 be done with optimization level 2 and the order of elaboration will be
10181 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10182 displaying commands it is executing.
10183 @end table
10184
10185 @c *************************
10186 @node Improving Performance
10187 @chapter Improving Performance
10188 @cindex Improving performance
10189
10190 @noindent
10191 This chapter presents several topics related to program performance.
10192 It first describes some of the tradeoffs that need to be considered
10193 and some of the techniques for making your program run faster.
10194 It then documents the @command{gnatelim} tool and unused subprogram/data
10195 elimination feature, which can reduce the size of program executables.
10196
10197 @ifnottex
10198 @menu
10199 * Performance Considerations::
10200 * Text_IO Suggestions::
10201 * Reducing Size of Ada Executables with gnatelim::
10202 * Reducing Size of Executables with unused subprogram/data elimination::
10203 @end menu
10204 @end ifnottex
10205
10206 @c *****************************
10207 @node Performance Considerations
10208 @section Performance Considerations
10209
10210 @noindent
10211 The GNAT system provides a number of options that allow a trade-off
10212 between
10213
10214 @itemize @bullet
10215 @item
10216 performance of the generated code
10217
10218 @item
10219 speed of compilation
10220
10221 @item
10222 minimization of dependences and recompilation
10223
10224 @item
10225 the degree of run-time checking.
10226 @end itemize
10227
10228 @noindent
10229 The defaults (if no options are selected) aim at improving the speed
10230 of compilation and minimizing dependences, at the expense of performance
10231 of the generated code:
10232
10233 @itemize @bullet
10234 @item
10235 no optimization
10236
10237 @item
10238 no inlining of subprogram calls
10239
10240 @item
10241 all run-time checks enabled except overflow and elaboration checks
10242 @end itemize
10243
10244 @noindent
10245 These options are suitable for most program development purposes. This
10246 chapter describes how you can modify these choices, and also provides
10247 some guidelines on debugging optimized code.
10248
10249 @menu
10250 * Controlling Run-Time Checks::
10251 * Use of Restrictions::
10252 * Optimization Levels::
10253 * Debugging Optimized Code::
10254 * Inlining of Subprograms::
10255 * Vectorization of loops::
10256 * Other Optimization Switches::
10257 * Optimization and Strict Aliasing::
10258
10259 @ifset vms
10260 * Coverage Analysis::
10261 @end ifset
10262 @end menu
10263
10264 @node Controlling Run-Time Checks
10265 @subsection Controlling Run-Time Checks
10266
10267 @noindent
10268 By default, GNAT generates all run-time checks, except integer overflow
10269 checks, stack overflow checks, and checks for access before elaboration on
10270 subprogram calls. The latter are not required in default mode, because all
10271 necessary checking is done at compile time.
10272 @cindex @option{-gnatp} (@command{gcc})
10273 @cindex @option{-gnato} (@command{gcc})
10274 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10275 be modified. @xref{Run-Time Checks}.
10276
10277 Our experience is that the default is suitable for most development
10278 purposes.
10279
10280 We treat integer overflow specially because these
10281 are quite expensive and in our experience are not as important as other
10282 run-time checks in the development process. Note that division by zero
10283 is not considered an overflow check, and divide by zero checks are
10284 generated where required by default.
10285
10286 Elaboration checks are off by default, and also not needed by default, since
10287 GNAT uses a static elaboration analysis approach that avoids the need for
10288 run-time checking. This manual contains a full chapter discussing the issue
10289 of elaboration checks, and if the default is not satisfactory for your use,
10290 you should read this chapter.
10291
10292 For validity checks, the minimal checks required by the Ada Reference
10293 Manual (for case statements and assignments to array elements) are on
10294 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10295 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10296 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10297 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10298 are also suppressed entirely if @option{-gnatp} is used.
10299
10300 @cindex Overflow checks
10301 @cindex Checks, overflow
10302 @findex Suppress
10303 @findex Unsuppress
10304 @cindex pragma Suppress
10305 @cindex pragma Unsuppress
10306 Note that the setting of the switches controls the default setting of
10307 the checks. They may be modified using either @code{pragma Suppress} (to
10308 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10309 checks) in the program source.
10310
10311 @node Use of Restrictions
10312 @subsection Use of Restrictions
10313
10314 @noindent
10315 The use of pragma Restrictions allows you to control which features are
10316 permitted in your program. Apart from the obvious point that if you avoid
10317 relatively expensive features like finalization (enforceable by the use
10318 of pragma Restrictions (No_Finalization), the use of this pragma does not
10319 affect the generated code in most cases.
10320
10321 One notable exception to this rule is that the possibility of task abort
10322 results in some distributed overhead, particularly if finalization or
10323 exception handlers are used. The reason is that certain sections of code
10324 have to be marked as non-abortable.
10325
10326 If you use neither the @code{abort} statement, nor asynchronous transfer
10327 of control (@code{select @dots{} then abort}), then this distributed overhead
10328 is removed, which may have a general positive effect in improving
10329 overall performance.  Especially code involving frequent use of tasking
10330 constructs and controlled types will show much improved performance.
10331 The relevant restrictions pragmas are
10332
10333 @smallexample @c ada
10334    pragma Restrictions (No_Abort_Statements);
10335    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10336 @end smallexample
10337
10338 @noindent
10339 It is recommended that these restriction pragmas be used if possible. Note
10340 that this also means that you can write code without worrying about the
10341 possibility of an immediate abort at any point.
10342
10343 @node Optimization Levels
10344 @subsection Optimization Levels
10345 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10346
10347 @noindent
10348 Without any optimization ^option,^qualifier,^
10349 the compiler's goal is to reduce the cost of
10350 compilation and to make debugging produce the expected results.
10351 Statements are independent: if you stop the program with a breakpoint between
10352 statements, you can then assign a new value to any variable or change
10353 the program counter to any other statement in the subprogram and get exactly
10354 the results you would expect from the source code.
10355
10356 Turning on optimization makes the compiler attempt to improve the
10357 performance and/or code size at the expense of compilation time and
10358 possibly the ability to debug the program.
10359
10360 If you use multiple
10361 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10362 the last such option is the one that is effective.
10363
10364 @noindent
10365 The default is optimization off. This results in the fastest compile
10366 times, but GNAT makes absolutely no attempt to optimize, and the
10367 generated programs are considerably larger and slower than when
10368 optimization is enabled. You can use the
10369 @ifclear vms
10370 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10371 @option{-O2}, @option{-O3}, and @option{-Os})
10372 @end ifclear
10373 @ifset vms
10374 @code{OPTIMIZE} qualifier
10375 @end ifset
10376 to @command{gcc} to control the optimization level:
10377
10378 @table @option
10379 @item ^-O0^/OPTIMIZE=NONE^
10380 No optimization (the default);
10381 generates unoptimized code but has
10382 the fastest compilation time.
10383
10384 Note that many other compilers do fairly extensive optimization
10385 even if ``no optimization'' is specified. With gcc, it is
10386 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10387 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10388 really does mean no optimization at all. This difference between
10389 gcc and other compilers should be kept in mind when doing
10390 performance comparisons.
10391
10392 @item ^-O1^/OPTIMIZE=SOME^
10393 Moderate optimization;
10394 optimizes reasonably well but does not
10395 degrade compilation time significantly.
10396
10397 @item ^-O2^/OPTIMIZE=ALL^
10398 @ifset vms
10399 @itemx /OPTIMIZE=DEVELOPMENT
10400 @end ifset
10401 Full optimization;
10402 generates highly optimized code and has
10403 the slowest compilation time.
10404
10405 @item ^-O3^/OPTIMIZE=INLINING^
10406 Full optimization as in @option{-O2};
10407 also uses more aggressive automatic inlining of subprograms within a unit
10408 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10409
10410 @item ^-Os^/OPTIMIZE=SPACE^
10411 Optimize space usage (code and data) of resulting program.
10412 @end table
10413
10414 @noindent
10415 Higher optimization levels perform more global transformations on the
10416 program and apply more expensive analysis algorithms in order to generate
10417 faster and more compact code. The price in compilation time, and the
10418 resulting improvement in execution time,
10419 both depend on the particular application and the hardware environment.
10420 You should experiment to find the best level for your application.
10421
10422 Since the precise set of optimizations done at each level will vary from
10423 release to release (and sometime from target to target), it is best to think
10424 of the optimization settings in general terms.
10425 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10426 the GNU Compiler Collection (GCC)}, for details about
10427 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10428 individually enable or disable specific optimizations.
10429
10430 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10431 been tested extensively at all optimization levels. There are some bugs
10432 which appear only with optimization turned on, but there have also been
10433 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10434 level of optimization does not improve the reliability of the code
10435 generator, which in practice is highly reliable at all optimization
10436 levels.
10437
10438 Note regarding the use of @option{-O3}: The use of this optimization level
10439 is generally discouraged with GNAT, since it often results in larger
10440 executables which may run more slowly. See further discussion of this point
10441 in @ref{Inlining of Subprograms}.
10442
10443 @node Debugging Optimized Code
10444 @subsection Debugging Optimized Code
10445 @cindex Debugging optimized code
10446 @cindex Optimization and debugging
10447
10448 @noindent
10449 Although it is possible to do a reasonable amount of debugging at
10450 @ifclear vms
10451 nonzero optimization levels,
10452 the higher the level the more likely that
10453 @end ifclear
10454 @ifset vms
10455 @option{/OPTIMIZE} settings other than @code{NONE},
10456 such settings will make it more likely that
10457 @end ifset
10458 source-level constructs will have been eliminated by optimization.
10459 For example, if a loop is strength-reduced, the loop
10460 control variable may be completely eliminated and thus cannot be
10461 displayed in the debugger.
10462 This can only happen at @option{-O2} or @option{-O3}.
10463 Explicit temporary variables that you code might be eliminated at
10464 ^level^setting^ @option{-O1} or higher.
10465
10466 The use of the @option{^-g^/DEBUG^} switch,
10467 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10468 which is needed for source-level debugging,
10469 affects the size of the program executable on disk,
10470 and indeed the debugging information can be quite large.
10471 However, it has no effect on the generated code (and thus does not
10472 degrade performance)
10473
10474 Since the compiler generates debugging tables for a compilation unit before
10475 it performs optimizations, the optimizing transformations may invalidate some
10476 of the debugging data.  You therefore need to anticipate certain
10477 anomalous situations that may arise while debugging optimized code.
10478 These are the most common cases:
10479
10480 @enumerate
10481 @item
10482 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10483 commands show
10484 the PC bouncing back and forth in the code.  This may result from any of
10485 the following optimizations:
10486
10487 @itemize @bullet
10488 @item
10489 @i{Common subexpression elimination:} using a single instance of code for a
10490 quantity that the source computes several times.  As a result you
10491 may not be able to stop on what looks like a statement.
10492
10493 @item
10494 @i{Invariant code motion:} moving an expression that does not change within a
10495 loop, to the beginning of the loop.
10496
10497 @item
10498 @i{Instruction scheduling:} moving instructions so as to
10499 overlap loads and stores (typically) with other code, or in
10500 general to move computations of values closer to their uses. Often
10501 this causes you to pass an assignment statement without the assignment
10502 happening and then later bounce back to the statement when the
10503 value is actually needed.  Placing a breakpoint on a line of code
10504 and then stepping over it may, therefore, not always cause all the
10505 expected side-effects.
10506 @end itemize
10507
10508 @item
10509 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10510 two identical pieces of code are merged and the program counter suddenly
10511 jumps to a statement that is not supposed to be executed, simply because
10512 it (and the code following) translates to the same thing as the code
10513 that @emph{was} supposed to be executed.  This effect is typically seen in
10514 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10515 a @code{break} in a C @code{^switch^switch^} statement.
10516
10517 @item
10518 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10519 There are various reasons for this effect:
10520
10521 @itemize @bullet
10522 @item
10523 In a subprogram prologue, a parameter may not yet have been moved to its
10524 ``home''.
10525
10526 @item
10527 A variable may be dead, and its register re-used.  This is
10528 probably the most common cause.
10529
10530 @item
10531 As mentioned above, the assignment of a value to a variable may
10532 have been moved.
10533
10534 @item
10535 A variable may be eliminated entirely by value propagation or
10536 other means.  In this case, GCC may incorrectly generate debugging
10537 information for the variable
10538 @end itemize
10539
10540 @noindent
10541 In general, when an unexpected value appears for a local variable or parameter
10542 you should first ascertain if that value was actually computed by
10543 your program, as opposed to being incorrectly reported by the debugger.
10544 Record fields or
10545 array elements in an object designated by an access value
10546 are generally less of a problem, once you have ascertained that the access
10547 value is sensible.
10548 Typically, this means checking variables in the preceding code and in the
10549 calling subprogram to verify that the value observed is explainable from other
10550 values (one must apply the procedure recursively to those
10551 other values); or re-running the code and stopping a little earlier
10552 (perhaps before the call) and stepping to better see how the variable obtained
10553 the value in question; or continuing to step @emph{from} the point of the
10554 strange value to see if code motion had simply moved the variable's
10555 assignments later.
10556 @end enumerate
10557
10558 @noindent
10559 In light of such anomalies, a recommended technique is to use @option{-O0}
10560 early in the software development cycle, when extensive debugging capabilities
10561 are most needed, and then move to @option{-O1} and later @option{-O2} as
10562 the debugger becomes less critical.
10563 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10564 a release management issue.
10565 @ifclear vms
10566 Note that if you use @option{-g} you can then use the @command{strip} program
10567 on the resulting executable,
10568 which removes both debugging information and global symbols.
10569 @end ifclear
10570
10571 @node Inlining of Subprograms
10572 @subsection Inlining of Subprograms
10573
10574 @noindent
10575 A call to a subprogram in the current unit is inlined if all the
10576 following conditions are met:
10577
10578 @itemize @bullet
10579 @item
10580 The optimization level is at least @option{-O1}.
10581
10582 @item
10583 The called subprogram is suitable for inlining: It must be small enough
10584 and not contain something that @command{gcc} cannot support in inlined
10585 subprograms.
10586
10587 @item
10588 @cindex pragma Inline
10589 @findex Inline
10590 Any one of the following applies: @code{pragma Inline} is applied to the
10591 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10592 subprogram is local to the unit and called once from within it; the
10593 subprogram is small and optimization level @option{-O2} is specified;
10594 optimization level @option{-O3}) is specified.
10595 @end itemize
10596
10597 @noindent
10598 Calls to subprograms in @code{with}'ed units are normally not inlined.
10599 To achieve actual inlining (that is, replacement of the call by the code
10600 in the body of the subprogram), the following conditions must all be true.
10601
10602 @itemize @bullet
10603 @item
10604 The optimization level is at least @option{-O1}.
10605
10606 @item
10607 The called subprogram is suitable for inlining: It must be small enough
10608 and not contain something that @command{gcc} cannot support in inlined
10609 subprograms.
10610
10611 @item
10612 The call appears in a body (not in a package spec).
10613
10614 @item
10615 There is a @code{pragma Inline} for the subprogram.
10616
10617 @item
10618 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10619 @end itemize
10620
10621 Even if all these conditions are met, it may not be possible for
10622 the compiler to inline the call, due to the length of the body,
10623 or features in the body that make it impossible for the compiler
10624 to do the inlining.
10625
10626 Note that specifying the @option{-gnatn} switch causes additional
10627 compilation dependencies. Consider the following:
10628
10629 @smallexample @c ada
10630 @cartouche
10631 package R is
10632    procedure Q;
10633    pragma Inline (Q);
10634 end R;
10635 package body R is
10636    @dots{}
10637 end R;
10638
10639 with R;
10640 procedure Main is
10641 begin
10642    @dots{}
10643    R.Q;
10644 end Main;
10645 @end cartouche
10646 @end smallexample
10647
10648 @noindent
10649 With the default behavior (no @option{-gnatn} switch specified), the
10650 compilation of the @code{Main} procedure depends only on its own source,
10651 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10652 means that editing the body of @code{R} does not require recompiling
10653 @code{Main}.
10654
10655 On the other hand, the call @code{R.Q} is not inlined under these
10656 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10657 is compiled, the call will be inlined if the body of @code{Q} is small
10658 enough, but now @code{Main} depends on the body of @code{R} in
10659 @file{r.adb} as well as on the spec. This means that if this body is edited,
10660 the main program must be recompiled. Note that this extra dependency
10661 occurs whether or not the call is in fact inlined by @command{gcc}.
10662
10663 The use of front end inlining with @option{-gnatN} generates similar
10664 additional dependencies.
10665
10666 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10667 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10668 can be used to prevent
10669 all inlining. This switch overrides all other conditions and ensures
10670 that no inlining occurs. The extra dependences resulting from
10671 @option{-gnatn} will still be active, even if
10672 this switch is used to suppress the resulting inlining actions.
10673
10674 @cindex @option{-fno-inline-functions} (@command{gcc})
10675 Note: The @option{-fno-inline-functions} switch can be used to prevent
10676 automatic inlining of subprograms if @option{-O3} is used.
10677
10678 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10679 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10680 automatic inlining of small subprograms if @option{-O2} is used.
10681
10682 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10683 Note: The @option{-fno-inline-functions-called-once} switch
10684 can be used to prevent inlining of subprograms local to the unit
10685 and called once from within it if @option{-O1} is used.
10686
10687 Note regarding the use of @option{-O3}: There is no difference in inlining
10688 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10689 pragma @code{Inline} assuming the use of @option{-gnatn}
10690 or @option{-gnatN} (the switches that activate inlining). If you have used
10691 pragma @code{Inline} in appropriate cases, then it is usually much better
10692 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10693 in this case only has the effect of inlining subprograms you did not
10694 think should be inlined. We often find that the use of @option{-O3} slows
10695 down code by performing excessive inlining, leading to increased instruction
10696 cache pressure from the increased code size. So the bottom line here is
10697 that you should not automatically assume that @option{-O3} is better than
10698 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10699 it actually improves performance.
10700
10701 @node Vectorization of loops
10702 @subsection Vectorization of loops
10703 @cindex Optimization Switches
10704
10705 You can take advantage of the auto-vectorizer present in the @command{gcc}
10706 back end to vectorize loops with GNAT.  The corresponding command line switch
10707 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10708 and other aggressive optimizations helpful for vectorization also are enabled
10709 by default at this level, using @option{-O3} directly is recommended.
10710
10711 You also need to make sure that the target architecture features a supported
10712 SIMD instruction set.  For example, for the x86 architecture, you should at
10713 least specify @option{-msse2} to get significant vectorization (but you don't
10714 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10715 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10716
10717 The preferred loop form for vectorization is the @code{for} iteration scheme.
10718 Loops with a @code{while} iteration scheme can also be vectorized if they are
10719 very simple, but the vectorizer will quickly give up otherwise.  With either
10720 iteration scheme, the flow of control must be straight, in particular no
10721 @code{exit} statement may appear in the loop body.  The loop may however
10722 contain a single nested loop, if it can be vectorized when considered alone:
10723
10724 @smallexample @c ada
10725 @cartouche
10726    A : array (1..4, 1..4) of Long_Float;
10727    S : array (1..4) of Long_Float;
10728
10729    procedure Sum is
10730    begin
10731       for I in A'Range(1) loop
10732          for J in A'Range(2) loop
10733             S (I) := S (I) + A (I, J);
10734          end loop;
10735       end loop;
10736    end Sum;
10737 @end cartouche
10738 @end smallexample
10739
10740 The vectorizable operations depend on the targeted SIMD instruction set, but
10741 the adding and some of the multiplying operators are generally supported, as
10742 well as the logical operators for modular types.  Note that, in the former
10743 case, enabling overflow checks, for example with @option{-gnato}, totally
10744 disables vectorization.  The other checks are not supposed to have the same
10745 definitive effect, although compiling with @option{-gnatp} might well reveal
10746 cases where some checks do thwart vectorization.
10747
10748 Type conversions may also prevent vectorization if they involve semantics that
10749 are not directly supported by the code generator or the SIMD instruction set.
10750 A typical example is direct conversion from floating-point to integer types.
10751 The solution in this case is to use the following idiom:
10752
10753 @smallexample @c ada
10754    Integer (S'Truncation (F))
10755 @end smallexample
10756
10757 @noindent
10758 if @code{S} is the subtype of floating-point object @code{F}.
10759
10760 In most cases, the vectorizable loops are loops that iterate over arrays.
10761 All kinds of array types are supported, i.e. constrained array types with
10762 static bounds:
10763
10764 @smallexample @c ada
10765    type Array_Type is array (1 .. 4) of Long_Float;
10766 @end smallexample
10767
10768 @noindent
10769 constrained array types with dynamic bounds:
10770
10771 @smallexample @c ada
10772    type Array_Type is array (1 .. Q.N) of Long_Float;
10773
10774    type Array_Type is array (Q.K .. 4) of Long_Float;
10775
10776    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10777 @end smallexample
10778
10779 @noindent
10780 or unconstrained array types:
10781
10782 @smallexample @c ada
10783   type Array_Type is array (Positive range <>) of Long_Float;
10784 @end smallexample
10785
10786 @noindent
10787 The quality of the generated code decreases when the dynamic aspect of the
10788 array type increases, the worst code being generated for unconstrained array
10789 types.  This is so because, the less information the compiler has about the
10790 bounds of the array, the more fallback code it needs to generate in order to
10791 fix things up at run time.
10792
10793 You can obtain information about the vectorization performed by the compiler
10794 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10795 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10796 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10797
10798 @node Other Optimization Switches
10799 @subsection Other Optimization Switches
10800 @cindex Optimization Switches
10801
10802 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10803 @command{gcc} optimization switches are potentially usable. These switches
10804 have not been extensively tested with GNAT but can generally be expected
10805 to work. Examples of switches in this category are @option{-funroll-loops}
10806 and the various target-specific @option{-m} options (in particular, it has
10807 been observed that @option{-march=xxx} can significantly improve performance
10808 on appropriate machines). For full details of these switches, see
10809 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10810 the GNU Compiler Collection (GCC)}.
10811
10812 @node Optimization and Strict Aliasing
10813 @subsection Optimization and Strict Aliasing
10814 @cindex Aliasing
10815 @cindex Strict Aliasing
10816 @cindex No_Strict_Aliasing
10817
10818 @noindent
10819 The strong typing capabilities of Ada allow an optimizer to generate
10820 efficient code in situations where other languages would be forced to
10821 make worst case assumptions preventing such optimizations. Consider
10822 the following example:
10823
10824 @smallexample @c ada
10825 @cartouche
10826 procedure R is
10827    type Int1 is new Integer;
10828    type Int2 is new Integer;
10829    type Int1A is access Int1;
10830    type Int2A is access Int2;
10831    Int1V : Int1A;
10832    Int2V : Int2A;
10833    @dots{}
10834
10835 begin
10836    @dots{}
10837    for J in Data'Range loop
10838       if Data (J) = Int1V.all then
10839          Int2V.all := Int2V.all + 1;
10840       end if;
10841    end loop;
10842    @dots{}
10843 end R;
10844 @end cartouche
10845 @end smallexample
10846
10847 @noindent
10848 In this example, since the variable @code{Int1V} can only access objects
10849 of type @code{Int1}, and @code{Int2V} can only access objects of type
10850 @code{Int2}, there is no possibility that the assignment to
10851 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10852 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10853 for all iterations of the loop and avoid the extra memory reference
10854 required to dereference it each time through the loop.
10855
10856 This kind of optimization, called strict aliasing analysis, is
10857 triggered by specifying an optimization level of @option{-O2} or
10858 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10859 when access values are involved.
10860
10861 However, although this optimization is always correct in terms of
10862 the formal semantics of the Ada Reference Manual, difficulties can
10863 arise if features like @code{Unchecked_Conversion} are used to break
10864 the typing system. Consider the following complete program example:
10865
10866 @smallexample @c ada
10867 @cartouche
10868 package p1 is
10869    type int1 is new integer;
10870    type int2 is new integer;
10871    type a1 is access int1;
10872    type a2 is access int2;
10873 end p1;
10874
10875 with p1; use p1;
10876 package p2 is
10877    function to_a2 (Input : a1) return a2;
10878 end p2;
10879
10880 with Unchecked_Conversion;
10881 package body p2 is
10882    function to_a2 (Input : a1) return a2 is
10883       function to_a2u is
10884         new Unchecked_Conversion (a1, a2);
10885    begin
10886       return to_a2u (Input);
10887    end to_a2;
10888 end p2;
10889
10890 with p2; use p2;
10891 with p1; use p1;
10892 with Text_IO; use Text_IO;
10893 procedure m is
10894    v1 : a1 := new int1;
10895    v2 : a2 := to_a2 (v1);
10896 begin
10897    v1.all := 1;
10898    v2.all := 0;
10899    put_line (int1'image (v1.all));
10900 end;
10901 @end cartouche
10902 @end smallexample
10903
10904 @noindent
10905 This program prints out 0 in @option{-O0} or @option{-O1}
10906 mode, but it prints out 1 in @option{-O2} mode. That's
10907 because in strict aliasing mode, the compiler can and
10908 does assume that the assignment to @code{v2.all} could not
10909 affect the value of @code{v1.all}, since different types
10910 are involved.
10911
10912 This behavior is not a case of non-conformance with the standard, since
10913 the Ada RM specifies that an unchecked conversion where the resulting
10914 bit pattern is not a correct value of the target type can result in an
10915 abnormal value and attempting to reference an abnormal value makes the
10916 execution of a program erroneous.  That's the case here since the result
10917 does not point to an object of type @code{int2}.  This means that the
10918 effect is entirely unpredictable.
10919
10920 However, although that explanation may satisfy a language
10921 lawyer, in practice an applications programmer expects an
10922 unchecked conversion involving pointers to create true
10923 aliases and the behavior of printing 1 seems plain wrong.
10924 In this case, the strict aliasing optimization is unwelcome.
10925
10926 Indeed the compiler recognizes this possibility, and the
10927 unchecked conversion generates a warning:
10928
10929 @smallexample
10930 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10931 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10932 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10933 @end smallexample
10934
10935 @noindent
10936 Unfortunately the problem is recognized when compiling the body of
10937 package @code{p2}, but the actual "bad" code is generated while
10938 compiling the body of @code{m} and this latter compilation does not see
10939 the suspicious @code{Unchecked_Conversion}.
10940
10941 As implied by the warning message, there are approaches you can use to
10942 avoid the unwanted strict aliasing optimization in a case like this.
10943
10944 One possibility is to simply avoid the use of @option{-O2}, but
10945 that is a bit drastic, since it throws away a number of useful
10946 optimizations that do not involve strict aliasing assumptions.
10947
10948 A less drastic approach is to compile the program using the
10949 option @option{-fno-strict-aliasing}. Actually it is only the
10950 unit containing the dereferencing of the suspicious pointer
10951 that needs to be compiled. So in this case, if we compile
10952 unit @code{m} with this switch, then we get the expected
10953 value of zero printed. Analyzing which units might need
10954 the switch can be painful, so a more reasonable approach
10955 is to compile the entire program with options @option{-O2}
10956 and @option{-fno-strict-aliasing}. If the performance is
10957 satisfactory with this combination of options, then the
10958 advantage is that the entire issue of possible "wrong"
10959 optimization due to strict aliasing is avoided.
10960
10961 To avoid the use of compiler switches, the configuration
10962 pragma @code{No_Strict_Aliasing} with no parameters may be
10963 used to specify that for all access types, the strict
10964 aliasing optimization should be suppressed.
10965
10966 However, these approaches are still overkill, in that they causes
10967 all manipulations of all access values to be deoptimized. A more
10968 refined approach is to concentrate attention on the specific
10969 access type identified as problematic.
10970
10971 First, if a careful analysis of uses of the pointer shows
10972 that there are no possible problematic references, then
10973 the warning can be suppressed by bracketing the
10974 instantiation of @code{Unchecked_Conversion} to turn
10975 the warning off:
10976
10977 @smallexample @c ada
10978    pragma Warnings (Off);
10979    function to_a2u is
10980      new Unchecked_Conversion (a1, a2);
10981    pragma Warnings (On);
10982 @end smallexample
10983
10984 @noindent
10985 Of course that approach is not appropriate for this particular
10986 example, since indeed there is a problematic reference. In this
10987 case we can take one of two other approaches.
10988
10989 The first possibility is to move the instantiation of unchecked
10990 conversion to the unit in which the type is declared. In
10991 this example, we would move the instantiation of
10992 @code{Unchecked_Conversion} from the body of package
10993 @code{p2} to the spec of package @code{p1}. Now the
10994 warning disappears. That's because any use of the
10995 access type knows there is a suspicious unchecked
10996 conversion, and the strict aliasing optimization
10997 is automatically suppressed for the type.
10998
10999 If it is not practical to move the unchecked conversion to the same unit
11000 in which the destination access type is declared (perhaps because the
11001 source type is not visible in that unit), you may use pragma
11002 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11003 same declarative sequence as the declaration of the access type:
11004
11005 @smallexample @c ada
11006    type a2 is access int2;
11007    pragma No_Strict_Aliasing (a2);
11008 @end smallexample
11009
11010 @noindent
11011 Here again, the compiler now knows that the strict aliasing optimization
11012 should be suppressed for any reference to type @code{a2} and the
11013 expected behavior is obtained.
11014
11015 Finally, note that although the compiler can generate warnings for
11016 simple cases of unchecked conversions, there are tricker and more
11017 indirect ways of creating type incorrect aliases which the compiler
11018 cannot detect. Examples are the use of address overlays and unchecked
11019 conversions involving composite types containing access types as
11020 components. In such cases, no warnings are generated, but there can
11021 still be aliasing problems. One safe coding practice is to forbid the
11022 use of address clauses for type overlaying, and to allow unchecked
11023 conversion only for primitive types. This is not really a significant
11024 restriction since any possible desired effect can be achieved by
11025 unchecked conversion of access values.
11026
11027 The aliasing analysis done in strict aliasing mode can certainly
11028 have significant benefits. We have seen cases of large scale
11029 application code where the time is increased by up to 5% by turning
11030 this optimization off. If you have code that includes significant
11031 usage of unchecked conversion, you might want to just stick with
11032 @option{-O1} and avoid the entire issue. If you get adequate
11033 performance at this level of optimization level, that's probably
11034 the safest approach. If tests show that you really need higher
11035 levels of optimization, then you can experiment with @option{-O2}
11036 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11037 has on size and speed of the code. If you really need to use
11038 @option{-O2} with strict aliasing in effect, then you should
11039 review any uses of unchecked conversion of access types,
11040 particularly if you are getting the warnings described above.
11041
11042 @ifset vms
11043 @node Coverage Analysis
11044 @subsection Coverage Analysis
11045
11046 @noindent
11047 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11048 the user to determine the distribution of execution time across a program,
11049 @pxref{Profiling} for details of usage.
11050 @end ifset
11051
11052
11053 @node Text_IO Suggestions
11054 @section @code{Text_IO} Suggestions
11055 @cindex @code{Text_IO} and performance
11056
11057 @noindent
11058 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11059 the requirement of maintaining page and line counts. If performance
11060 is critical, a recommendation is to use @code{Stream_IO} instead of
11061 @code{Text_IO} for volume output, since this package has less overhead.
11062
11063 If @code{Text_IO} must be used, note that by default output to the standard
11064 output and standard error files is unbuffered (this provides better
11065 behavior when output statements are used for debugging, or if the
11066 progress of a program is observed by tracking the output, e.g. by
11067 using the Unix @command{tail -f} command to watch redirected output.
11068
11069 If you are generating large volumes of output with @code{Text_IO} and
11070 performance is an important factor, use a designated file instead
11071 of the standard output file, or change the standard output file to
11072 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11073
11074
11075
11076 @node Reducing Size of Ada Executables with gnatelim
11077 @section Reducing Size of Ada Executables with @code{gnatelim}
11078 @findex gnatelim
11079
11080 @noindent
11081 This section describes @command{gnatelim}, a tool which detects unused
11082 subprograms and helps the compiler to create a smaller executable for your
11083 program.
11084
11085 @menu
11086 * About gnatelim::
11087 * Running gnatelim::
11088 * Processing Precompiled Libraries::
11089 * Correcting the List of Eliminate Pragmas::
11090 * Making Your Executables Smaller::
11091 * Summary of the gnatelim Usage Cycle::
11092 @end menu
11093
11094 @node About gnatelim
11095 @subsection About @code{gnatelim}
11096
11097 @noindent
11098 When a program shares a set of Ada
11099 packages with other programs, it may happen that this program uses
11100 only a fraction of the subprograms defined in these packages. The code
11101 created for these unused subprograms increases the size of the executable.
11102
11103 @code{gnatelim} tracks unused subprograms in an Ada program and
11104 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11105 subprograms that are declared but never called. By placing the list of
11106 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11107 recompiling your program, you may decrease the size of its executable,
11108 because the compiler will not generate the code for 'eliminated' subprograms.
11109 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11110 information about this pragma.
11111
11112 @code{gnatelim} needs as its input data the name of the main subprogram.
11113
11114 If a set of source files is specified as @code{gnatelim} arguments, it
11115 treats these files as a complete set of sources making up a program to
11116 analyse, and analyses only these sources.
11117
11118 After a full successful build of the main subprogram @code{gnatelim} can be
11119 called without  specifying sources to analyse, in this case it computes
11120 the source closure of the main unit from the @file{ALI} files.
11121
11122 The following command will create the set of @file{ALI} files needed for
11123 @code{gnatelim}:
11124
11125 @smallexample
11126 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11127 @end smallexample
11128
11129 Note that @code{gnatelim} does not need object files.
11130
11131 @node Running gnatelim
11132 @subsection Running @code{gnatelim}
11133
11134 @noindent
11135 @code{gnatelim} has the following command-line interface:
11136
11137 @smallexample
11138 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11139 @end smallexample
11140
11141 @noindent
11142 @var{main_unit_name} should be a name of a source file that contains the main
11143 subprogram of a program (partition).
11144
11145 Each @var{filename} is the name (including the extension) of a source
11146 file to process. ``Wildcards'' are allowed, and
11147 the file name may contain path information.
11148
11149 @samp{@var{gcc_switches}} is a list of switches for
11150 @command{gcc}. They will be passed on to all compiler invocations made by
11151 @command{gnatelim} to generate the ASIS trees. Here you can provide
11152 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11153 use the @option{-gnatec} switch to set the configuration file,
11154 use the @option{-gnat05} switch if sources should be compiled in
11155 Ada 2005 mode etc.
11156
11157 @code{gnatelim} has the following switches:
11158
11159 @table @option
11160 @c !sort!
11161 @item ^-files^/FILES^=@var{filename}
11162 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11163 Take the argument source files from the specified file. This file should be an
11164 ordinary text file containing file names separated by spaces or
11165 line breaks. You can use this switch more than once in the same call to
11166 @command{gnatelim}. You also can combine this switch with
11167 an explicit list of files.
11168
11169 @item ^-log^/LOG^
11170 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11171 Duplicate all the output sent to @file{stderr} into a log file. The log file
11172 is named @file{gnatelim.log} and is located in the current directory.
11173
11174 @item ^-log^/LOGFILE^=@var{filename}
11175 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11176 Duplicate all the output sent to @file{stderr} into a specified log file.
11177
11178 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11179 @item ^--no-elim-dispatch^/NO_DISPATCH^
11180 Do not generate pragmas for dispatching operations.
11181
11182 @item ^--ignore^/IGNORE^=@var{filename}
11183 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11184 Do not generate pragmas for subprograms declared in the sources
11185 listed in a specified file
11186
11187 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11188 @item ^-o^/OUTPUT^=@var{report_file}
11189 Put @command{gnatelim} output into a specified file. If this file already exists,
11190 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11191 into @file{stderr}
11192
11193 @item ^-q^/QUIET^
11194 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11195 Quiet mode: by default @code{gnatelim} outputs to the standard error
11196 stream the number of program units left to be processed. This option turns
11197 this trace off.
11198
11199 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11200 @item ^-t^/TIME^
11201 Print out execution time.
11202
11203 @item ^-v^/VERBOSE^
11204 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11205 Verbose mode: @code{gnatelim} version information is printed as Ada
11206 comments to the standard output stream. Also, in addition to the number of
11207 program units left @code{gnatelim} will output the name of the current unit
11208 being processed.
11209
11210 @item ^-wq^/WARNINGS=QUIET^
11211 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11212 Quiet warning mode - some warnings are suppressed. In particular warnings that
11213 indicate that the analysed set of sources is incomplete to make up a
11214 partition and that some subprogram bodies are missing are not generated.
11215 @end table
11216
11217 @noindent
11218 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11219 driver (see @ref{The GNAT Driver and Project Files}).
11220
11221 @node Processing Precompiled Libraries
11222 @subsection Processing Precompiled Libraries
11223
11224 @noindent
11225 If some program uses a precompiled Ada library, it can be processed by
11226 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11227 Eliminate pragma for a subprogram if the body of this subprogram has not
11228 been analysed, this is a typical case for subprograms from precompiled
11229 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11230 warnings about missing source files and non-analyzed subprogram bodies
11231 that can be generated when processing precompiled Ada libraries.
11232
11233 @node Correcting the List of Eliminate Pragmas
11234 @subsection Correcting the List of Eliminate Pragmas
11235
11236 @noindent
11237 In some rare cases @code{gnatelim} may try to eliminate
11238 subprograms that are actually called in the program. In this case, the
11239 compiler will generate an error message of the form:
11240
11241 @smallexample
11242 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11243 @end smallexample
11244
11245 @noindent
11246 You will need to manually remove the wrong @code{Eliminate} pragmas from
11247 the configuration file indicated in the error message. You should recompile
11248 your program from scratch after that, because you need a consistent
11249 configuration file(s) during the entire compilation.
11250
11251 @node Making Your Executables Smaller
11252 @subsection Making Your Executables Smaller
11253
11254 @noindent
11255 In order to get a smaller executable for your program you now have to
11256 recompile the program completely with the configuration file containing
11257 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11258 @file{gnat.adc} file located in your current directory, just do:
11259
11260 @smallexample
11261 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11262 @end smallexample
11263
11264 @noindent
11265 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11266 recompile everything
11267 with the set of pragmas @code{Eliminate} that you have obtained with
11268 @command{gnatelim}).
11269
11270 Be aware that the set of @code{Eliminate} pragmas is specific to each
11271 program. It is not recommended to merge sets of @code{Eliminate}
11272 pragmas created for different programs in one configuration file.
11273
11274 @node Summary of the gnatelim Usage Cycle
11275 @subsection Summary of the @code{gnatelim} Usage Cycle
11276
11277 @noindent
11278 Here is a quick summary of the steps to be taken in order to reduce
11279 the size of your executables with @code{gnatelim}. You may use
11280 other GNAT options to control the optimization level,
11281 to produce the debugging information, to set search path, etc.
11282
11283 @enumerate
11284 @item
11285 Create a complete set of @file{ALI} files (if the program has not been
11286 built already)
11287
11288 @smallexample
11289 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11290 @end smallexample
11291
11292 @item
11293 Generate a list of @code{Eliminate} pragmas in default configuration file
11294 @file{gnat.adc} in the current directory
11295 @smallexample
11296 @ifset vms
11297 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11298 @end ifset
11299 @ifclear vms
11300 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11301 @end ifclear
11302 @end smallexample
11303
11304 @item
11305 Recompile the application
11306
11307 @smallexample
11308 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11309 @end smallexample
11310
11311 @end enumerate
11312
11313 @node Reducing Size of Executables with unused subprogram/data elimination
11314 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11315 @findex unused subprogram/data elimination
11316
11317 @noindent
11318 This section describes how you can eliminate unused subprograms and data from
11319 your executable just by setting options at compilation time.
11320
11321 @menu
11322 * About unused subprogram/data elimination::
11323 * Compilation options::
11324 * Example of unused subprogram/data elimination::
11325 @end menu
11326
11327 @node About unused subprogram/data elimination
11328 @subsection About unused subprogram/data elimination
11329
11330 @noindent
11331 By default, an executable contains all code and data of its composing objects
11332 (directly linked or coming from statically linked libraries), even data or code
11333 never used by this executable.
11334
11335 This feature will allow you to eliminate such unused code from your
11336 executable, making it smaller (in disk and in memory).
11337
11338 This functionality is available on all Linux platforms except for the IA-64
11339 architecture and on all cross platforms using the ELF binary file format.
11340 In both cases GNU binutils version 2.16 or later are required to enable it.
11341
11342 @node Compilation options
11343 @subsection Compilation options
11344
11345 @noindent
11346 The operation of eliminating the unused code and data from the final executable
11347 is directly performed by the linker.
11348
11349 In order to do this, it has to work with objects compiled with the
11350 following options:
11351 @option{-ffunction-sections} @option{-fdata-sections}.
11352 @cindex @option{-ffunction-sections} (@command{gcc})
11353 @cindex @option{-fdata-sections} (@command{gcc})
11354 These options are usable with C and Ada files.
11355 They will place respectively each
11356 function or data in a separate section in the resulting object file.
11357
11358 Once the objects and static libraries are created with these options, the
11359 linker can perform the dead code elimination. You can do this by setting
11360 the @option{-Wl,--gc-sections} option to gcc command or in the
11361 @option{-largs} section of @command{gnatmake}. This will perform a
11362 garbage collection of code and data never referenced.
11363
11364 If the linker performs a partial link (@option{-r} ld linker option), then you
11365 will need to provide one or several entry point using the
11366 @option{-e} / @option{--entry} ld option.
11367
11368 Note that objects compiled without the @option{-ffunction-sections} and
11369 @option{-fdata-sections} options can still be linked with the executable.
11370 However, no dead code elimination will be performed on those objects (they will
11371 be linked as is).
11372
11373 The GNAT static library is now compiled with -ffunction-sections and
11374 -fdata-sections on some platforms. This allows you to eliminate the unused code
11375 and data of the GNAT library from your executable.
11376
11377 @node Example of unused subprogram/data elimination
11378 @subsection Example of unused subprogram/data elimination
11379
11380 @noindent
11381 Here is a simple example:
11382
11383 @smallexample @c ada
11384 with Aux;
11385
11386 procedure Test is
11387 begin
11388    Aux.Used (10);
11389 end Test;
11390
11391 package Aux is
11392    Used_Data   : Integer;
11393    Unused_Data : Integer;
11394
11395    procedure Used   (Data : Integer);
11396    procedure Unused (Data : Integer);
11397 end Aux;
11398
11399 package body Aux is
11400    procedure Used (Data : Integer) is
11401    begin
11402       Used_Data := Data;
11403    end Used;
11404
11405    procedure Unused (Data : Integer) is
11406    begin
11407       Unused_Data := Data;
11408    end Unused;
11409 end Aux;
11410 @end smallexample
11411
11412 @noindent
11413 @code{Unused} and @code{Unused_Data} are never referenced in this code
11414 excerpt, and hence they may be safely removed from the final executable.
11415
11416 @smallexample
11417 $ gnatmake test
11418
11419 $ nm test | grep used
11420 020015f0 T aux__unused
11421 02005d88 B aux__unused_data
11422 020015cc T aux__used
11423 02005d84 B aux__used_data
11424
11425 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11426      -largs -Wl,--gc-sections
11427
11428 $ nm test | grep used
11429 02005350 T aux__used
11430 0201ffe0 B aux__used_data
11431 @end smallexample
11432
11433 @noindent
11434 It can be observed that the procedure @code{Unused} and the object
11435 @code{Unused_Data} are removed by the linker when using the
11436 appropriate options.
11437
11438 @c ********************************
11439 @node Renaming Files Using gnatchop
11440 @chapter Renaming Files Using @code{gnatchop}
11441 @findex gnatchop
11442
11443 @noindent
11444 This chapter discusses how to handle files with multiple units by using
11445 the @code{gnatchop} utility. This utility is also useful in renaming
11446 files to meet the standard GNAT default file naming conventions.
11447
11448 @menu
11449 * Handling Files with Multiple Units::
11450 * Operating gnatchop in Compilation Mode::
11451 * Command Line for gnatchop::
11452 * Switches for gnatchop::
11453 * Examples of gnatchop Usage::
11454 @end menu
11455
11456 @node Handling Files with Multiple Units
11457 @section Handling Files with Multiple Units
11458
11459 @noindent
11460 The basic compilation model of GNAT requires that a file submitted to the
11461 compiler have only one unit and there be a strict correspondence
11462 between the file name and the unit name.
11463
11464 The @code{gnatchop} utility allows both of these rules to be relaxed,
11465 allowing GNAT to process files which contain multiple compilation units
11466 and files with arbitrary file names. @code{gnatchop}
11467 reads the specified file and generates one or more output files,
11468 containing one unit per file. The unit and the file name correspond,
11469 as required by GNAT.
11470
11471 If you want to permanently restructure a set of ``foreign'' files so that
11472 they match the GNAT rules, and do the remaining development using the
11473 GNAT structure, you can simply use @command{gnatchop} once, generate the
11474 new set of files and work with them from that point on.
11475
11476 Alternatively, if you want to keep your files in the ``foreign'' format,
11477 perhaps to maintain compatibility with some other Ada compilation
11478 system, you can set up a procedure where you use @command{gnatchop} each
11479 time you compile, regarding the source files that it writes as temporary
11480 files that you throw away.
11481
11482 Note that if your file containing multiple units starts with a byte order
11483 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11484 will each start with a copy of this BOM, meaning that they can be compiled
11485 automatically in UTF-8 mode without needing to specify an explicit encoding.
11486
11487 @node Operating gnatchop in Compilation Mode
11488 @section Operating gnatchop in Compilation Mode
11489
11490 @noindent
11491 The basic function of @code{gnatchop} is to take a file with multiple units
11492 and split it into separate files. The boundary between files is reasonably
11493 clear, except for the issue of comments and pragmas. In default mode, the
11494 rule is that any pragmas between units belong to the previous unit, except
11495 that configuration pragmas always belong to the following unit. Any comments
11496 belong to the following unit. These rules
11497 almost always result in the right choice of
11498 the split point without needing to mark it explicitly and most users will
11499 find this default to be what they want. In this default mode it is incorrect to
11500 submit a file containing only configuration pragmas, or one that ends in
11501 configuration pragmas, to @code{gnatchop}.
11502
11503 However, using a special option to activate ``compilation mode'',
11504 @code{gnatchop}
11505 can perform another function, which is to provide exactly the semantics
11506 required by the RM for handling of configuration pragmas in a compilation.
11507 In the absence of configuration pragmas (at the main file level), this
11508 option has no effect, but it causes such configuration pragmas to be handled
11509 in a quite different manner.
11510
11511 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11512 only configuration pragmas, then this file is appended to the
11513 @file{gnat.adc} file in the current directory. This behavior provides
11514 the required behavior described in the RM for the actions to be taken
11515 on submitting such a file to the compiler, namely that these pragmas
11516 should apply to all subsequent compilations in the same compilation
11517 environment. Using GNAT, the current directory, possibly containing a
11518 @file{gnat.adc} file is the representation
11519 of a compilation environment. For more information on the
11520 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11521
11522 Second, in compilation mode, if @code{gnatchop}
11523 is given a file that starts with
11524 configuration pragmas, and contains one or more units, then these
11525 configuration pragmas are prepended to each of the chopped files. This
11526 behavior provides the required behavior described in the RM for the
11527 actions to be taken on compiling such a file, namely that the pragmas
11528 apply to all units in the compilation, but not to subsequently compiled
11529 units.
11530
11531 Finally, if configuration pragmas appear between units, they are appended
11532 to the previous unit. This results in the previous unit being illegal,
11533 since the compiler does not accept configuration pragmas that follow
11534 a unit. This provides the required RM behavior that forbids configuration
11535 pragmas other than those preceding the first compilation unit of a
11536 compilation.
11537
11538 For most purposes, @code{gnatchop} will be used in default mode. The
11539 compilation mode described above is used only if you need exactly
11540 accurate behavior with respect to compilations, and you have files
11541 that contain multiple units and configuration pragmas. In this
11542 circumstance the use of @code{gnatchop} with the compilation mode
11543 switch provides the required behavior, and is for example the mode
11544 in which GNAT processes the ACVC tests.
11545
11546 @node Command Line for gnatchop
11547 @section Command Line for @code{gnatchop}
11548
11549 @noindent
11550 The @code{gnatchop} command has the form:
11551
11552 @smallexample
11553 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11554 @c      @ovar{directory}
11555 @c Expanding @ovar macro inline (explanation in macro def comments)
11556 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11557       @r{[}@var{directory}@r{]}
11558 @end smallexample
11559
11560 @noindent
11561 The only required argument is the file name of the file to be chopped.
11562 There are no restrictions on the form of this file name. The file itself
11563 contains one or more Ada units, in normal GNAT format, concatenated
11564 together. As shown, more than one file may be presented to be chopped.
11565
11566 When run in default mode, @code{gnatchop} generates one output file in
11567 the current directory for each unit in each of the files.
11568
11569 @var{directory}, if specified, gives the name of the directory to which
11570 the output files will be written. If it is not specified, all files are
11571 written to the current directory.
11572
11573 For example, given a
11574 file called @file{hellofiles} containing
11575
11576 @smallexample @c ada
11577 @group
11578 @cartouche
11579 procedure hello;
11580
11581 with Text_IO; use Text_IO;
11582 procedure hello is
11583 begin
11584    Put_Line ("Hello");
11585 end hello;
11586 @end cartouche
11587 @end group
11588 @end smallexample
11589
11590 @noindent
11591 the command
11592
11593 @smallexample
11594 $ gnatchop ^hellofiles^HELLOFILES.^
11595 @end smallexample
11596
11597 @noindent
11598 generates two files in the current directory, one called
11599 @file{hello.ads} containing the single line that is the procedure spec,
11600 and the other called @file{hello.adb} containing the remaining text. The
11601 original file is not affected. The generated files can be compiled in
11602 the normal manner.
11603
11604 @noindent
11605 When gnatchop is invoked on a file that is empty or that contains only empty
11606 lines and/or comments, gnatchop will not fail, but will not produce any
11607 new sources.
11608
11609 For example, given a
11610 file called @file{toto.txt} containing
11611
11612 @smallexample @c ada
11613 @group
11614 @cartouche
11615 --  Just a comment
11616 @end cartouche
11617 @end group
11618 @end smallexample
11619
11620 @noindent
11621 the command
11622
11623 @smallexample
11624 $ gnatchop ^toto.txt^TOT.TXT^
11625 @end smallexample
11626
11627 @noindent
11628 will not produce any new file and will result in the following warnings:
11629
11630 @smallexample
11631 toto.txt:1:01: warning: empty file, contains no compilation units
11632 no compilation units found
11633 no source files written
11634 @end smallexample
11635
11636 @node Switches for gnatchop
11637 @section Switches for @code{gnatchop}
11638
11639 @noindent
11640 @command{gnatchop} recognizes the following switches:
11641
11642 @table @option
11643 @c !sort!
11644
11645 @item --version
11646 @cindex @option{--version} @command{gnatchop}
11647 Display Copyright and version, then exit disregarding all other options.
11648
11649 @item --help
11650 @cindex @option{--help} @command{gnatchop}
11651 If @option{--version} was not used, display usage, then exit disregarding
11652 all other options.
11653
11654 @item ^-c^/COMPILATION^
11655 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11656 Causes @code{gnatchop} to operate in compilation mode, in which
11657 configuration pragmas are handled according to strict RM rules. See
11658 previous section for a full description of this mode.
11659
11660 @ifclear vms
11661 @item -gnat@var{xxx}
11662 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11663 used to parse the given file. Not all @var{xxx} options make sense,
11664 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11665 process a source file that uses Latin-2 coding for identifiers.
11666 @end ifclear
11667
11668 @item ^-h^/HELP^
11669 Causes @code{gnatchop} to generate a brief help summary to the standard
11670 output file showing usage information.
11671
11672 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11673 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11674 Limit generated file names to the specified number @code{mm}
11675 of characters.
11676 This is useful if the
11677 resulting set of files is required to be interoperable with systems
11678 which limit the length of file names.
11679 @ifset vms
11680 If no value is given, or
11681 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11682 a default of 39, suitable for OpenVMS Alpha
11683 Systems, is assumed
11684 @end ifset
11685 @ifclear vms
11686 No space is allowed between the @option{-k} and the numeric value. The numeric
11687 value may be omitted in which case a default of @option{-k8},
11688 suitable for use
11689 with DOS-like file systems, is used. If no @option{-k} switch
11690 is present then
11691 there is no limit on the length of file names.
11692 @end ifclear
11693
11694 @item ^-p^/PRESERVE^
11695 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11696 Causes the file ^modification^creation^ time stamp of the input file to be
11697 preserved and used for the time stamp of the output file(s). This may be
11698 useful for preserving coherency of time stamps in an environment where
11699 @code{gnatchop} is used as part of a standard build process.
11700
11701 @item ^-q^/QUIET^
11702 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11703 Causes output of informational messages indicating the set of generated
11704 files to be suppressed. Warnings and error messages are unaffected.
11705
11706 @item ^-r^/REFERENCE^
11707 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11708 @findex Source_Reference
11709 Generate @code{Source_Reference} pragmas. Use this switch if the output
11710 files are regarded as temporary and development is to be done in terms
11711 of the original unchopped file. This switch causes
11712 @code{Source_Reference} pragmas to be inserted into each of the
11713 generated files to refers back to the original file name and line number.
11714 The result is that all error messages refer back to the original
11715 unchopped file.
11716 In addition, the debugging information placed into the object file (when
11717 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11718 specified)
11719 also refers back to this original file so that tools like profilers and
11720 debuggers will give information in terms of the original unchopped file.
11721
11722 If the original file to be chopped itself contains
11723 a @code{Source_Reference}
11724 pragma referencing a third file, then gnatchop respects
11725 this pragma, and the generated @code{Source_Reference} pragmas
11726 in the chopped file refer to the original file, with appropriate
11727 line numbers. This is particularly useful when @code{gnatchop}
11728 is used in conjunction with @code{gnatprep} to compile files that
11729 contain preprocessing statements and multiple units.
11730
11731 @item ^-v^/VERBOSE^
11732 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11733 Causes @code{gnatchop} to operate in verbose mode. The version
11734 number and copyright notice are output, as well as exact copies of
11735 the gnat1 commands spawned to obtain the chop control information.
11736
11737 @item ^-w^/OVERWRITE^
11738 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11739 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11740 fatal error if there is already a file with the same name as a
11741 file it would otherwise output, in other words if the files to be
11742 chopped contain duplicated units. This switch bypasses this
11743 check, and causes all but the last instance of such duplicated
11744 units to be skipped.
11745
11746 @ifclear vms
11747 @item --GCC=@var{xxxx}
11748 @cindex @option{--GCC=} (@code{gnatchop})
11749 Specify the path of the GNAT parser to be used. When this switch is used,
11750 no attempt is made to add the prefix to the GNAT parser executable.
11751 @end ifclear
11752 @end table
11753
11754 @node Examples of gnatchop Usage
11755 @section Examples of @code{gnatchop} Usage
11756
11757 @table @code
11758 @ifset vms
11759 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11760 @end ifset
11761 @ifclear vms
11762 @item gnatchop -w hello_s.ada prerelease/files
11763 @end ifclear
11764
11765 Chops the source file @file{hello_s.ada}. The output files will be
11766 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11767 overwriting any
11768 files with matching names in that directory (no files in the current
11769 directory are modified).
11770
11771 @item gnatchop ^archive^ARCHIVE.^
11772 Chops the source file @file{^archive^ARCHIVE.^}
11773 into the current directory. One
11774 useful application of @code{gnatchop} is in sending sets of sources
11775 around, for example in email messages. The required sources are simply
11776 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11777 command), and then
11778 @command{gnatchop} is used at the other end to reconstitute the original
11779 file names.
11780
11781 @item gnatchop file1 file2 file3 direc
11782 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11783 the resulting files in the directory @file{direc}. Note that if any units
11784 occur more than once anywhere within this set of files, an error message
11785 is generated, and no files are written. To override this check, use the
11786 @option{^-w^/OVERWRITE^} switch,
11787 in which case the last occurrence in the last file will
11788 be the one that is output, and earlier duplicate occurrences for a given
11789 unit will be skipped.
11790 @end table
11791
11792 @node Configuration Pragmas
11793 @chapter Configuration Pragmas
11794 @cindex Configuration pragmas
11795 @cindex Pragmas, configuration
11796
11797 @noindent
11798 Configuration pragmas include those pragmas described as
11799 such in the Ada Reference Manual, as well as
11800 implementation-dependent pragmas that are configuration pragmas.
11801 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11802 for details on these additional GNAT-specific configuration pragmas.
11803 Most notably, the pragma @code{Source_File_Name}, which allows
11804 specifying non-default names for source files, is a configuration
11805 pragma. The following is a complete list of configuration pragmas
11806 recognized by GNAT:
11807
11808 @smallexample
11809    Ada_83
11810    Ada_95
11811    Ada_05
11812    Ada_2005
11813    Ada_12
11814    Ada_2012
11815    Annotate
11816    Assertion_Policy
11817    Assume_No_Invalid_Values
11818    C_Pass_By_Copy
11819    Check_Name
11820    Check_Policy
11821    Compile_Time_Error
11822    Compile_Time_Warning
11823    Compiler_Unit
11824    Component_Alignment
11825    Convention_Identifier
11826    Debug_Policy
11827    Detect_Blocking
11828    Default_Storage_Pool
11829    Discard_Names
11830    Elaboration_Checks
11831    Eliminate
11832    Extend_System
11833    Extensions_Allowed
11834    External_Name_Casing
11835    Fast_Math
11836    Favor_Top_Level
11837    Float_Representation
11838    Implicit_Packing
11839    Initialize_Scalars
11840    Interrupt_State
11841    License
11842    Locking_Policy
11843    Long_Float
11844    No_Run_Time
11845    No_Strict_Aliasing
11846    Normalize_Scalars
11847    Optimize_Alignment
11848    Persistent_BSS
11849    Polling
11850    Priority_Specific_Dispatching
11851    Profile
11852    Profile_Warnings
11853    Propagate_Exceptions
11854    Queuing_Policy
11855    Ravenscar
11856    Restricted_Run_Time
11857    Restrictions
11858    Restrictions_Warnings
11859    Reviewable
11860    Short_Circuit_And_Or
11861    Source_File_Name
11862    Source_File_Name_Project
11863    Style_Checks
11864    Suppress
11865    Suppress_Exception_Locations
11866    Task_Dispatching_Policy
11867    Universal_Data
11868    Unsuppress
11869    Use_VADS_Size
11870    Validity_Checks
11871    Warnings
11872    Wide_Character_Encoding
11873
11874 @end smallexample
11875
11876 @menu
11877 * Handling of Configuration Pragmas::
11878 * The Configuration Pragmas Files::
11879 @end menu
11880
11881 @node Handling of Configuration Pragmas
11882 @section Handling of Configuration Pragmas
11883
11884 Configuration pragmas may either appear at the start of a compilation
11885 unit, or they can appear in a configuration pragma file to apply to
11886 all compilations performed in a given compilation environment.
11887
11888 GNAT also provides the @code{gnatchop} utility to provide an automatic
11889 way to handle configuration pragmas following the semantics for
11890 compilations (that is, files with multiple units), described in the RM.
11891 See @ref{Operating gnatchop in Compilation Mode} for details.
11892 However, for most purposes, it will be more convenient to edit the
11893 @file{gnat.adc} file that contains configuration pragmas directly,
11894 as described in the following section.
11895
11896 In the case of @code{Restrictions} pragmas appearing as configuration
11897 pragmas in individual compilation units, the exact handling depends on
11898 the type of restriction.
11899
11900 Restrictions that require partition-wide consistency (like
11901 @code{No_Tasking}) are
11902 recognized wherever they appear
11903 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11904 unit. This makes sense since the binder will in any case insist on seeing
11905 consistent use, so any unit not conforming to any restrictions that are
11906 anywhere in the partition will be rejected, and you might as well find
11907 that out at compile time rather than at bind time.
11908
11909 For restrictions that do not require partition-wide consistency, e.g.
11910 SPARK or No_Implementation_Attributes, in general the restriction applies
11911 only to the unit in which the pragma appears, and not to any other units.
11912
11913 The exception is No_Elaboration_Code which always applies to the entire
11914 object file from a compilation, i.e. to the body, spec, and all subunits.
11915 This restriction can be specified in a configuration pragma file, or it
11916 can be on the body and/or the spec (in eithe case it applies to all the
11917 relevant units). It can appear on a subunit only if it has previously
11918 appeared in the body of spec.
11919
11920 @node The Configuration Pragmas Files
11921 @section The Configuration Pragmas Files
11922 @cindex @file{gnat.adc}
11923
11924 @noindent
11925 In GNAT a compilation environment is defined by the current
11926 directory at the time that a compile command is given. This current
11927 directory is searched for a file whose name is @file{gnat.adc}. If
11928 this file is present, it is expected to contain one or more
11929 configuration pragmas that will be applied to the current compilation.
11930 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11931 considered.
11932
11933 Configuration pragmas may be entered into the @file{gnat.adc} file
11934 either by running @code{gnatchop} on a source file that consists only of
11935 configuration pragmas, or more conveniently  by
11936 direct editing of the @file{gnat.adc} file, which is a standard format
11937 source file.
11938
11939 In addition to @file{gnat.adc}, additional files containing configuration
11940 pragmas may be applied to the current compilation using the switch
11941 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11942 contains only configuration pragmas. These configuration pragmas are
11943 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11944 is present and switch @option{-gnatA} is not used).
11945
11946 It is allowed to specify several switches @option{-gnatec}, all of which
11947 will be taken into account.
11948
11949 If you are using project file, a separate mechanism is provided using
11950 project attributes, see @ref{Specifying Configuration Pragmas} for more
11951 details.
11952
11953 @ifset vms
11954 Of special interest to GNAT OpenVMS Alpha is the following
11955 configuration pragma:
11956
11957 @smallexample @c ada
11958 @cartouche
11959 pragma Extend_System (Aux_DEC);
11960 @end cartouche
11961 @end smallexample
11962
11963 @noindent
11964 In the presence of this pragma, GNAT adds to the definition of the
11965 predefined package SYSTEM all the additional types and subprograms that are
11966 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11967 @end ifset
11968
11969 @node Handling Arbitrary File Naming Conventions Using gnatname
11970 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11971 @cindex Arbitrary File Naming Conventions
11972
11973 @menu
11974 * Arbitrary File Naming Conventions::
11975 * Running gnatname::
11976 * Switches for gnatname::
11977 * Examples of gnatname Usage::
11978 @end menu
11979
11980 @node Arbitrary File Naming Conventions
11981 @section Arbitrary File Naming Conventions
11982
11983 @noindent
11984 The GNAT compiler must be able to know the source file name of a compilation
11985 unit.  When using the standard GNAT default file naming conventions
11986 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11987 does not need additional information.
11988
11989 @noindent
11990 When the source file names do not follow the standard GNAT default file naming
11991 conventions, the GNAT compiler must be given additional information through
11992 a configuration pragmas file (@pxref{Configuration Pragmas})
11993 or a project file.
11994 When the non-standard file naming conventions are well-defined,
11995 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11996 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11997 if the file naming conventions are irregular or arbitrary, a number
11998 of pragma @code{Source_File_Name} for individual compilation units
11999 must be defined.
12000 To help maintain the correspondence between compilation unit names and
12001 source file names within the compiler,
12002 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12003 set of files.
12004
12005 @node Running gnatname
12006 @section Running @code{gnatname}
12007
12008 @noindent
12009 The usual form of the @code{gnatname} command is
12010
12011 @smallexample
12012 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12013 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12014 @c Expanding @ovar macro inline (explanation in macro def comments)
12015 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12016       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12017 @end smallexample
12018
12019 @noindent
12020 All of the arguments are optional. If invoked without any argument,
12021 @code{gnatname} will display its usage.
12022
12023 @noindent
12024 When used with at least one naming pattern, @code{gnatname} will attempt to
12025 find all the compilation units in files that follow at least one of the
12026 naming patterns. To find these compilation units,
12027 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12028 regular files.
12029
12030 @noindent
12031 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12032 Each Naming Pattern is enclosed between double quotes (or single
12033 quotes on Windows).
12034 A Naming Pattern is a regular expression similar to the wildcard patterns
12035 used in file names by the Unix shells or the DOS prompt.
12036
12037 @noindent
12038 @code{gnatname} may be called with several sections of directories/patterns.
12039 Sections are separated by switch @code{--and}. In each section, there must be
12040 at least one pattern. If no directory is specified in a section, the current
12041 directory (or the project directory is @code{-P} is used) is implied.
12042 The options other that the directory switches and the patterns apply globally
12043 even if they are in different sections.
12044
12045 @noindent
12046 Examples of Naming Patterns are
12047
12048 @smallexample
12049    "*.[12].ada"
12050    "*.ad[sb]*"
12051    "body_*"    "spec_*"
12052 @end smallexample
12053
12054 @noindent
12055 For a more complete description of the syntax of Naming Patterns,
12056 see the second kind of regular expressions described in @file{g-regexp.ads}
12057 (the ``Glob'' regular expressions).
12058
12059 @noindent
12060 When invoked with no switch @code{-P}, @code{gnatname} will create a
12061 configuration pragmas file @file{gnat.adc} in the current working directory,
12062 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12063 unit.
12064
12065 @node Switches for gnatname
12066 @section Switches for @code{gnatname}
12067
12068 @noindent
12069 Switches for @code{gnatname} must precede any specified Naming Pattern.
12070
12071 @noindent
12072 You may specify any of the following switches to @code{gnatname}:
12073
12074 @table @option
12075 @c !sort!
12076
12077 @item --version
12078 @cindex @option{--version} @command{gnatname}
12079 Display Copyright and version, then exit disregarding all other options.
12080
12081 @item --help
12082 @cindex @option{--help} @command{gnatname}
12083 If @option{--version} was not used, display usage, then exit disregarding
12084 all other options.
12085
12086 @item --and
12087 Start another section of directories/patterns.
12088
12089 @item ^-c^/CONFIG_FILE=^@file{file}
12090 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12091 Create a configuration pragmas file @file{file} (instead of the default
12092 @file{gnat.adc}).
12093 @ifclear vms
12094 There may be zero, one or more space between @option{-c} and
12095 @file{file}.
12096 @end ifclear
12097 @file{file} may include directory information. @file{file} must be
12098 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12099 When a switch @option{^-c^/CONFIG_FILE^} is
12100 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12101
12102 @item ^-d^/SOURCE_DIRS=^@file{dir}
12103 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12104 Look for source files in directory @file{dir}. There may be zero, one or more
12105 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12106 When a switch @option{^-d^/SOURCE_DIRS^}
12107 is specified, the current working directory will not be searched for source
12108 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12109 or @option{^-D^/DIR_FILES^} switch.
12110 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12111 If @file{dir} is a relative path, it is relative to the directory of
12112 the configuration pragmas file specified with switch
12113 @option{^-c^/CONFIG_FILE^},
12114 or to the directory of the project file specified with switch
12115 @option{^-P^/PROJECT_FILE^} or,
12116 if neither switch @option{^-c^/CONFIG_FILE^}
12117 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12118 current working directory. The directory
12119 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12120
12121 @item ^-D^/DIRS_FILE=^@file{file}
12122 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12123 Look for source files in all directories listed in text file @file{file}.
12124 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12125 and @file{file}.
12126 @file{file} must be an existing, readable text file.
12127 Each nonempty line in @file{file} must be a directory.
12128 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12129 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12130 @file{file}.
12131
12132 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12133 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12134 Foreign patterns. Using this switch, it is possible to add sources of languages
12135 other than Ada to the list of sources of a project file.
12136 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12137 For example,
12138 @smallexample
12139 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12140 @end smallexample
12141 @noindent
12142 will look for Ada units in all files with the @file{.ada} extension,
12143 and will add to the list of file for project @file{prj.gpr} the C files
12144 with extension @file{.^c^C^}.
12145
12146 @item ^-h^/HELP^
12147 @cindex @option{^-h^/HELP^} (@code{gnatname})
12148 Output usage (help) information. The output is written to @file{stdout}.
12149
12150 @item ^-P^/PROJECT_FILE=^@file{proj}
12151 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12152 Create or update project file @file{proj}. There may be zero, one or more space
12153 between @option{-P} and @file{proj}. @file{proj} may include directory
12154 information. @file{proj} must be writable.
12155 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12156 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12157 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12158
12159 @item ^-v^/VERBOSE^
12160 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12161 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12162 This includes name of the file written, the name of the directories to search
12163 and, for each file in those directories whose name matches at least one of
12164 the Naming Patterns, an indication of whether the file contains a unit,
12165 and if so the name of the unit.
12166
12167 @item ^-v -v^/VERBOSE /VERBOSE^
12168 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12169 Very Verbose mode. In addition to the output produced in verbose mode,
12170 for each file in the searched directories whose name matches none of
12171 the Naming Patterns, an indication is given that there is no match.
12172
12173 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12174 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12175 Excluded patterns. Using this switch, it is possible to exclude some files
12176 that would match the name patterns. For example,
12177 @smallexample
12178 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12179 @end smallexample
12180 @noindent
12181 will look for Ada units in all files with the @file{.ada} extension,
12182 except those whose names end with @file{_nt.ada}.
12183
12184 @end table
12185
12186 @node Examples of gnatname Usage
12187 @section Examples of @code{gnatname} Usage
12188
12189 @ifset vms
12190 @smallexample
12191 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12192 @end smallexample
12193 @end ifset
12194
12195 @ifclear vms
12196 @smallexample
12197 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12198 @end smallexample
12199 @end ifclear
12200
12201 @noindent
12202 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12203 and be writable. In addition, the directory
12204 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12205 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12206
12207 @ifclear vms
12208 Note the optional spaces after @option{-c} and @option{-d}.
12209 @end ifclear
12210
12211 @smallexample
12212 @ifclear vms
12213 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12214   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12215 @end ifclear
12216 @ifset vms
12217 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12218   /EXCLUDED_PATTERN=*_nt_body.ada
12219   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12220   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12221 @end ifset
12222 @end smallexample
12223
12224 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12225 even in conjunction with one or several switches
12226 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12227 are used in this example.
12228
12229 @c *****************************************
12230 @c * G N A T  P r o j e c t  M a n a g e r *
12231 @c *****************************************
12232
12233 @c ------ macros for projects.texi
12234 @c These macros are needed when building the gprbuild documentation, but
12235 @c should have no effect in the gnat user's guide
12236
12237 @macro CODESAMPLE{TXT}
12238 @smallexample
12239 @group
12240 \TXT\
12241 @end group
12242 @end smallexample
12243 @end macro
12244
12245 @macro PROJECTFILE{TXT}
12246 @CODESAMPLE{\TXT\}
12247 @end macro
12248
12249 @c simulates a newline when in a @CODESAMPLE
12250 @macro NL{}
12251 @end macro
12252
12253 @macro TIP{TXT}
12254 @quotation
12255 @noindent
12256 \TXT\
12257 @end quotation
12258 @end macro
12259
12260 @macro TIPHTML{TXT}
12261 \TXT\
12262 @end macro
12263
12264 @macro IMPORTANT{TXT}
12265 @quotation
12266 @noindent
12267 \TXT\
12268 @end quotation
12269
12270 @end macro
12271
12272 @macro NOTE{TXT}
12273 @quotation
12274 @noindent
12275 \TXT\
12276 @end quotation
12277 @end macro
12278
12279 @include projects.texi
12280
12281 @c *****************************************
12282 @c * Cross-referencing tools
12283 @c *****************************************
12284
12285 @node The Cross-Referencing Tools gnatxref and gnatfind
12286 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12287 @findex gnatxref
12288 @findex gnatfind
12289
12290 @noindent
12291 The compiler generates cross-referencing information (unless
12292 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12293 This information indicates where in the source each entity is declared and
12294 referenced. Note that entities in package Standard are not included, but
12295 entities in all other predefined units are included in the output.
12296
12297 Before using any of these two tools, you need to compile successfully your
12298 application, so that GNAT gets a chance to generate the cross-referencing
12299 information.
12300
12301 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12302 information to provide the user with the capability to easily locate the
12303 declaration and references to an entity. These tools are quite similar,
12304 the difference being that @code{gnatfind} is intended for locating
12305 definitions and/or references to a specified entity or entities, whereas
12306 @code{gnatxref} is oriented to generating a full report of all
12307 cross-references.
12308
12309 To use these tools, you must not compile your application using the
12310 @option{-gnatx} switch on the @command{gnatmake} command line
12311 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12312 information will not be generated.
12313
12314 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12315 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12316
12317 @menu
12318 * Switches for gnatxref::
12319 * Switches for gnatfind::
12320 * Project Files for gnatxref and gnatfind::
12321 * Regular Expressions in gnatfind and gnatxref::
12322 * Examples of gnatxref Usage::
12323 * Examples of gnatfind Usage::
12324 @end menu
12325
12326 @node Switches for gnatxref
12327 @section @code{gnatxref} Switches
12328
12329 @noindent
12330 The command invocation for @code{gnatxref} is:
12331 @smallexample
12332 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12333 @c Expanding @ovar macro inline (explanation in macro def comments)
12334 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12335 @end smallexample
12336
12337 @noindent
12338 where
12339
12340 @table @var
12341 @item sourcefile1
12342 @itemx sourcefile2
12343 identifies the source files for which a report is to be generated. The
12344 ``with''ed units will be processed too. You must provide at least one file.
12345
12346 These file names are considered to be regular expressions, so for instance
12347 specifying @file{source*.adb} is the same as giving every file in the current
12348 directory whose name starts with @file{source} and whose extension is
12349 @file{adb}.
12350
12351 You shouldn't specify any directory name, just base names. @command{gnatxref}
12352 and @command{gnatfind} will be able to locate these files by themselves using
12353 the source path. If you specify directories, no result is produced.
12354
12355 @end table
12356
12357 @noindent
12358 The switches can be:
12359 @table @option
12360 @c !sort!
12361 @item --version
12362 @cindex @option{--version} @command{gnatxref}
12363 Display Copyright and version, then exit disregarding all other options.
12364
12365 @item --help
12366 @cindex @option{--help} @command{gnatxref}
12367 If @option{--version} was not used, display usage, then exit disregarding
12368 all other options.
12369
12370 @item ^-a^/ALL_FILES^
12371 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12372 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12373 the read-only files found in the library search path. Otherwise, these files
12374 will be ignored. This option can be used to protect Gnat sources or your own
12375 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12376 much faster, and their output much smaller. Read-only here refers to access
12377 or permissions status in the file system for the current user.
12378
12379 @item -aIDIR
12380 @cindex @option{-aIDIR} (@command{gnatxref})
12381 When looking for source files also look in directory DIR. The order in which
12382 source file search is undertaken is the same as for @command{gnatmake}.
12383
12384 @item -aODIR
12385 @cindex @option{-aODIR} (@command{gnatxref})
12386 When searching for library and object files, look in directory
12387 DIR. The order in which library files are searched is the same as for
12388 @command{gnatmake}.
12389
12390 @item -nostdinc
12391 @cindex @option{-nostdinc} (@command{gnatxref})
12392 Do not look for sources in the system default directory.
12393
12394 @item -nostdlib
12395 @cindex @option{-nostdlib} (@command{gnatxref})
12396 Do not look for library files in the system default directory.
12397
12398 @item --ext=@var{extension}
12399 @cindex @option{--ext} (@command{gnatxref})
12400 Specify an alternate ali file extension. The default is @code{ali} and other
12401 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12402 switch. Note that if this switch overrides the default, which means that only
12403 the new extension will be considered.
12404
12405 @item --RTS=@var{rts-path}
12406 @cindex @option{--RTS} (@command{gnatxref})
12407 Specifies the default location of the runtime library. Same meaning as the
12408 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12409
12410 @item ^-d^/DERIVED_TYPES^
12411 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12412 If this switch is set @code{gnatxref} will output the parent type
12413 reference for each matching derived types.
12414
12415 @item ^-f^/FULL_PATHNAME^
12416 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12417 If this switch is set, the output file names will be preceded by their
12418 directory (if the file was found in the search path). If this switch is
12419 not set, the directory will not be printed.
12420
12421 @item ^-g^/IGNORE_LOCALS^
12422 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12423 If this switch is set, information is output only for library-level
12424 entities, ignoring local entities. The use of this switch may accelerate
12425 @code{gnatfind} and @code{gnatxref}.
12426
12427 @item -IDIR
12428 @cindex @option{-IDIR} (@command{gnatxref})
12429 Equivalent to @samp{-aODIR -aIDIR}.
12430
12431 @item -pFILE
12432 @cindex @option{-pFILE} (@command{gnatxref})
12433 Specify a project file to use @xref{GNAT Project Manager}.
12434 If you need to use the @file{.gpr}
12435 project files, you should use gnatxref through the GNAT driver
12436 (@command{gnat xref -Pproject}).
12437
12438 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12439 project file in the current directory.
12440
12441 If a project file is either specified or found by the tools, then the content
12442 of the source directory and object directory lines are added as if they
12443 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12444 and @samp{^-aO^OBJECT_SEARCH^}.
12445 @item ^-u^/UNUSED^
12446 Output only unused symbols. This may be really useful if you give your
12447 main compilation unit on the command line, as @code{gnatxref} will then
12448 display every unused entity and 'with'ed package.
12449
12450 @ifclear vms
12451 @item -v
12452 Instead of producing the default output, @code{gnatxref} will generate a
12453 @file{tags} file that can be used by vi. For examples how to use this
12454 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12455 to the standard output, thus you will have to redirect it to a file.
12456 @end ifclear
12457
12458 @end table
12459
12460 @noindent
12461 All these switches may be in any order on the command line, and may even
12462 appear after the file names. They need not be separated by spaces, thus
12463 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12464 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12465
12466 @node Switches for gnatfind
12467 @section @code{gnatfind} Switches
12468
12469 @noindent
12470 The command line for @code{gnatfind} is:
12471
12472 @smallexample
12473 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12474 @c       @r{[}@var{file1} @var{file2} @dots{}]
12475 @c Expanding @ovar macro inline (explanation in macro def comments)
12476 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12477       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12478 @end smallexample
12479
12480 @noindent
12481 where
12482
12483 @table @var
12484 @item pattern
12485 An entity will be output only if it matches the regular expression found
12486 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12487
12488 Omitting the pattern is equivalent to specifying @samp{*}, which
12489 will match any entity. Note that if you do not provide a pattern, you
12490 have to provide both a sourcefile and a line.
12491
12492 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12493 for matching purposes. At the current time there is no support for
12494 8-bit codes other than Latin-1, or for wide characters in identifiers.
12495
12496 @item sourcefile
12497 @code{gnatfind} will look for references, bodies or declarations
12498 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12499 and column @var{column}. See @ref{Examples of gnatfind Usage}
12500 for syntax examples.
12501
12502 @item line
12503 is a decimal integer identifying the line number containing
12504 the reference to the entity (or entities) to be located.
12505
12506 @item column
12507 is a decimal integer identifying the exact location on the
12508 line of the first character of the identifier for the
12509 entity reference. Columns are numbered from 1.
12510
12511 @item file1 file2 @dots{}
12512 The search will be restricted to these source files. If none are given, then
12513 the search will be done for every library file in the search path.
12514 These file must appear only after the pattern or sourcefile.
12515
12516 These file names are considered to be regular expressions, so for instance
12517 specifying @file{source*.adb} is the same as giving every file in the current
12518 directory whose name starts with @file{source} and whose extension is
12519 @file{adb}.
12520
12521 The location of the spec of the entity will always be displayed, even if it
12522 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12523 occurrences of the entity in the separate units of the ones given on the
12524 command line will also be displayed.
12525
12526 Note that if you specify at least one file in this part, @code{gnatfind} may
12527 sometimes not be able to find the body of the subprograms.
12528
12529 @end table
12530
12531 @noindent
12532 At least one of 'sourcefile' or 'pattern' has to be present on
12533 the command line.
12534
12535 The following switches are available:
12536 @table @option
12537 @c !sort!
12538
12539 @cindex @option{--version} @command{gnatfind}
12540 Display Copyright and version, then exit disregarding all other options.
12541
12542 @item --help
12543 @cindex @option{--help} @command{gnatfind}
12544 If @option{--version} was not used, display usage, then exit disregarding
12545 all other options.
12546
12547 @item ^-a^/ALL_FILES^
12548 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12549 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12550 the read-only files found in the library search path. Otherwise, these files
12551 will be ignored. This option can be used to protect Gnat sources or your own
12552 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12553 much faster, and their output much smaller. Read-only here refers to access
12554 or permission status in the file system for the current user.
12555
12556 @item -aIDIR
12557 @cindex @option{-aIDIR} (@command{gnatfind})
12558 When looking for source files also look in directory DIR. The order in which
12559 source file search is undertaken is the same as for @command{gnatmake}.
12560
12561 @item -aODIR
12562 @cindex @option{-aODIR} (@command{gnatfind})
12563 When searching for library and object files, look in directory
12564 DIR. The order in which library files are searched is the same as for
12565 @command{gnatmake}.
12566
12567 @item -nostdinc
12568 @cindex @option{-nostdinc} (@command{gnatfind})
12569 Do not look for sources in the system default directory.
12570
12571 @item -nostdlib
12572 @cindex @option{-nostdlib} (@command{gnatfind})
12573 Do not look for library files in the system default directory.
12574
12575 @item --ext=@var{extension}
12576 @cindex @option{--ext} (@command{gnatfind})
12577 Specify an alternate ali file extension. The default is @code{ali} and other
12578 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12579 switch. Note that if this switch overrides the default, which means that only
12580 the new extension will be considered.
12581
12582 @item --RTS=@var{rts-path}
12583 @cindex @option{--RTS} (@command{gnatfind})
12584 Specifies the default location of the runtime library. Same meaning as the
12585 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12586
12587 @item ^-d^/DERIVED_TYPE_INFORMATION^
12588 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12589 If this switch is set, then @code{gnatfind} will output the parent type
12590 reference for each matching derived types.
12591
12592 @item ^-e^/EXPRESSIONS^
12593 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12594 By default, @code{gnatfind} accept the simple regular expression set for
12595 @samp{pattern}. If this switch is set, then the pattern will be
12596 considered as full Unix-style regular expression.
12597
12598 @item ^-f^/FULL_PATHNAME^
12599 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12600 If this switch is set, the output file names will be preceded by their
12601 directory (if the file was found in the search path). If this switch is
12602 not set, the directory will not be printed.
12603
12604 @item ^-g^/IGNORE_LOCALS^
12605 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12606 If this switch is set, information is output only for library-level
12607 entities, ignoring local entities. The use of this switch may accelerate
12608 @code{gnatfind} and @code{gnatxref}.
12609
12610 @item -IDIR
12611 @cindex @option{-IDIR} (@command{gnatfind})
12612 Equivalent to @samp{-aODIR -aIDIR}.
12613
12614 @item -pFILE
12615 @cindex @option{-pFILE} (@command{gnatfind})
12616 Specify a project file (@pxref{GNAT Project Manager}) to use.
12617 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12618 project file in the current directory.
12619
12620 If a project file is either specified or found by the tools, then the content
12621 of the source directory and object directory lines are added as if they
12622 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12623 @samp{^-aO^/OBJECT_SEARCH^}.
12624
12625 @item ^-r^/REFERENCES^
12626 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12627 By default, @code{gnatfind} will output only the information about the
12628 declaration, body or type completion of the entities. If this switch is
12629 set, the @code{gnatfind} will locate every reference to the entities in
12630 the files specified on the command line (or in every file in the search
12631 path if no file is given on the command line).
12632
12633 @item ^-s^/PRINT_LINES^
12634 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12635 If this switch is set, then @code{gnatfind} will output the content
12636 of the Ada source file lines were the entity was found.
12637
12638 @item ^-t^/TYPE_HIERARCHY^
12639 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12640 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12641 the specified type. It act like -d option but recursively from parent
12642 type to parent type. When this switch is set it is not possible to
12643 specify more than one file.
12644
12645 @end table
12646
12647 @noindent
12648 All these switches may be in any order on the command line, and may even
12649 appear after the file names. They need not be separated by spaces, thus
12650 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12651 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12652
12653 As stated previously, gnatfind will search in every directory in the
12654 search path. You can force it to look only in the current directory if
12655 you specify @code{*} at the end of the command line.
12656
12657 @node Project Files for gnatxref and gnatfind
12658 @section Project Files for @command{gnatxref} and @command{gnatfind}
12659
12660 @noindent
12661 Project files allow a programmer to specify how to compile its
12662 application, where to find sources, etc.  These files are used
12663 @ifclear vms
12664 primarily by GPS, but they can also be used
12665 @end ifclear
12666 by the two tools
12667 @code{gnatxref} and @code{gnatfind}.
12668
12669 A project file name must end with @file{.gpr}. If a single one is
12670 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12671 extract the information from it. If multiple project files are found, none of
12672 them is read, and you have to use the @samp{-p} switch to specify the one
12673 you want to use.
12674
12675 The following lines can be included, even though most of them have default
12676 values which can be used in most cases.
12677 The lines can be entered in any order in the file.
12678 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12679 each line. If you have multiple instances, only the last one is taken into
12680 account.
12681
12682 @table @code
12683 @item src_dir=DIR
12684 [default: @code{"^./^[]^"}]
12685 specifies a directory where to look for source files. Multiple @code{src_dir}
12686 lines can be specified and they will be searched in the order they
12687 are specified.
12688
12689 @item obj_dir=DIR
12690 [default: @code{"^./^[]^"}]
12691 specifies a directory where to look for object and library files. Multiple
12692 @code{obj_dir} lines can be specified, and they will be searched in the order
12693 they are specified
12694
12695 @item comp_opt=SWITCHES
12696 [default: @code{""}]
12697 creates a variable which can be referred to subsequently by using
12698 the @code{$@{comp_opt@}} notation. This is intended to store the default
12699 switches given to @command{gnatmake} and @command{gcc}.
12700
12701 @item bind_opt=SWITCHES
12702 [default: @code{""}]
12703 creates a variable which can be referred to subsequently by using
12704 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12705 switches given to @command{gnatbind}.
12706
12707 @item link_opt=SWITCHES
12708 [default: @code{""}]
12709 creates a variable which can be referred to subsequently by using
12710 the @samp{$@{link_opt@}} notation. This is intended to store the default
12711 switches given to @command{gnatlink}.
12712
12713 @item main=EXECUTABLE
12714 [default: @code{""}]
12715 specifies the name of the executable for the application. This variable can
12716 be referred to in the following lines by using the @samp{$@{main@}} notation.
12717
12718 @ifset vms
12719 @item comp_cmd=COMMAND
12720 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12721 @end ifset
12722 @ifclear vms
12723 @item comp_cmd=COMMAND
12724 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12725 @end ifclear
12726 specifies the command used to compile a single file in the application.
12727
12728 @ifset vms
12729 @item make_cmd=COMMAND
12730 [default: @code{"GNAT MAKE $@{main@}
12731 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12732 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12733 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12734 @end ifset
12735 @ifclear vms
12736 @item make_cmd=COMMAND
12737 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12738 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12739 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12740 @end ifclear
12741 specifies the command used to recompile the whole application.
12742
12743 @item run_cmd=COMMAND
12744 [default: @code{"$@{main@}"}]
12745 specifies the command used to run the application.
12746
12747 @item debug_cmd=COMMAND
12748 [default: @code{"gdb $@{main@}"}]
12749 specifies the command used to debug the application
12750
12751 @end table
12752
12753 @noindent
12754 @command{gnatxref} and @command{gnatfind} only take into account the
12755 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12756
12757 @node Regular Expressions in gnatfind and gnatxref
12758 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12759
12760 @noindent
12761 As specified in the section about @command{gnatfind}, the pattern can be a
12762 regular expression. Actually, there are to set of regular expressions
12763 which are recognized by the program:
12764
12765 @table @code
12766 @item globbing patterns
12767 These are the most usual regular expression. They are the same that you
12768 generally used in a Unix shell command line, or in a DOS session.
12769
12770 Here is a more formal grammar:
12771 @smallexample
12772 @group
12773 @iftex
12774 @leftskip=.5cm
12775 @end iftex
12776 regexp ::= term
12777 term   ::= elmt            -- matches elmt
12778 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12779 term   ::= *               -- any string of 0 or more characters
12780 term   ::= ?               -- matches any character
12781 term   ::= [char @{char@}]   -- matches any character listed
12782 term   ::= [char - char]   -- matches any character in range
12783 @end group
12784 @end smallexample
12785
12786 @item full regular expression
12787 The second set of regular expressions is much more powerful. This is the
12788 type of regular expressions recognized by utilities such a @file{grep}.
12789
12790 The following is the form of a regular expression, expressed in Ada
12791 reference manual style BNF is as follows
12792
12793 @smallexample
12794 @iftex
12795 @leftskip=.5cm
12796 @end iftex
12797 @group
12798 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12799
12800 term ::= item @{item@}       -- concatenation (item then item)
12801
12802 item ::= elmt              -- match elmt
12803 item ::= elmt *            -- zero or more elmt's
12804 item ::= elmt +            -- one or more elmt's
12805 item ::= elmt ?            -- matches elmt or nothing
12806 @end group
12807 @group
12808 elmt ::= nschar            -- matches given character
12809 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12810 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12811 elmt ::= [char - char]     -- matches chars in given range
12812 elmt ::= \ char            -- matches given character
12813 elmt ::= .                 -- matches any single character
12814 elmt ::= ( regexp )        -- parens used for grouping
12815
12816 char ::= any character, including special characters
12817 nschar ::= any character except ()[].*+?^^^
12818 @end group
12819 @end smallexample
12820
12821 Following are a few examples:
12822
12823 @table @samp
12824 @item abcde|fghi
12825 will match any of the two strings @samp{abcde} and @samp{fghi},
12826
12827 @item abc*d
12828 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12829 @samp{abcccd}, and so on,
12830
12831 @item [a-z]+
12832 will match any string which has only lowercase characters in it (and at
12833 least one character.
12834
12835 @end table
12836 @end table
12837
12838 @node Examples of gnatxref Usage
12839 @section Examples of @code{gnatxref} Usage
12840
12841 @subsection General Usage
12842
12843 @noindent
12844 For the following examples, we will consider the following units:
12845
12846 @smallexample @c ada
12847 @group
12848 @cartouche
12849 main.ads:
12850 1: with Bar;
12851 2: package Main is
12852 3:     procedure Foo (B : in Integer);
12853 4:     C : Integer;
12854 5: private
12855 6:     D : Integer;
12856 7: end Main;
12857
12858 main.adb:
12859 1: package body Main is
12860 2:     procedure Foo (B : in Integer) is
12861 3:     begin
12862 4:        C := B;
12863 5:        D := B;
12864 6:        Bar.Print (B);
12865 7:        Bar.Print (C);
12866 8:     end Foo;
12867 9: end Main;
12868
12869 bar.ads:
12870 1: package Bar is
12871 2:     procedure Print (B : Integer);
12872 3: end bar;
12873 @end cartouche
12874 @end group
12875 @end smallexample
12876
12877 @table @code
12878
12879 @noindent
12880 The first thing to do is to recompile your application (for instance, in
12881 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12882 the cross-referencing information.
12883 You can then issue any of the following commands:
12884
12885 @item gnatxref main.adb
12886 @code{gnatxref} generates cross-reference information for main.adb
12887 and every unit 'with'ed by main.adb.
12888
12889 The output would be:
12890 @smallexample
12891 @iftex
12892 @leftskip=0cm
12893 @end iftex
12894 B                                                      Type: Integer
12895   Decl: bar.ads           2:22
12896 B                                                      Type: Integer
12897   Decl: main.ads          3:20
12898   Body: main.adb          2:20
12899   Ref:  main.adb          4:13     5:13     6:19
12900 Bar                                                    Type: Unit
12901   Decl: bar.ads           1:9
12902   Ref:  main.adb          6:8      7:8
12903        main.ads           1:6
12904 C                                                      Type: Integer
12905   Decl: main.ads          4:5
12906   Modi: main.adb          4:8
12907   Ref:  main.adb          7:19
12908 D                                                      Type: Integer
12909   Decl: main.ads          6:5
12910   Modi: main.adb          5:8
12911 Foo                                                    Type: Unit
12912   Decl: main.ads          3:15
12913   Body: main.adb          2:15
12914 Main                                                    Type: Unit
12915   Decl: main.ads          2:9
12916   Body: main.adb          1:14
12917 Print                                                   Type: Unit
12918   Decl: bar.ads           2:15
12919   Ref:  main.adb          6:12     7:12
12920 @end smallexample
12921
12922 @noindent
12923 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12924 its body is in main.adb, line 1, column 14 and is not referenced any where.
12925
12926 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12927 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12928
12929 @item gnatxref package1.adb package2.ads
12930 @code{gnatxref} will generates cross-reference information for
12931 package1.adb, package2.ads and any other package 'with'ed by any
12932 of these.
12933
12934 @end table
12935
12936 @ifclear vms
12937 @subsection Using gnatxref with vi
12938
12939 @code{gnatxref} can generate a tags file output, which can be used
12940 directly from @command{vi}. Note that the standard version of @command{vi}
12941 will not work properly with overloaded symbols. Consider using another
12942 free implementation of @command{vi}, such as @command{vim}.
12943
12944 @smallexample
12945 $ gnatxref -v gnatfind.adb > tags
12946 @end smallexample
12947
12948 @noindent
12949 will generate the tags file for @code{gnatfind} itself (if the sources
12950 are in the search path!).
12951
12952 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12953 (replacing @var{entity} by whatever you are looking for), and vi will
12954 display a new file with the corresponding declaration of entity.
12955 @end ifclear
12956
12957 @node Examples of gnatfind Usage
12958 @section Examples of @code{gnatfind} Usage
12959
12960 @table @code
12961
12962 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12963 Find declarations for all entities xyz referenced at least once in
12964 main.adb. The references are search in every library file in the search
12965 path.
12966
12967 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12968 switch is set)
12969
12970 The output will look like:
12971 @smallexample
12972 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12973 ^directory/^[directory]^main.adb:24:10: xyz <= body
12974 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12975 @end smallexample
12976
12977 @noindent
12978 that is to say, one of the entities xyz found in main.adb is declared at
12979 line 12 of main.ads (and its body is in main.adb), and another one is
12980 declared at line 45 of foo.ads
12981
12982 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12983 This is the same command as the previous one, instead @code{gnatfind} will
12984 display the content of the Ada source file lines.
12985
12986 The output will look like:
12987
12988 @smallexample
12989 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12990    procedure xyz;
12991 ^directory/^[directory]^main.adb:24:10: xyz <= body
12992    procedure xyz is
12993 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12994    xyz : Integer;
12995 @end smallexample
12996
12997 @noindent
12998 This can make it easier to find exactly the location your are looking
12999 for.
13000
13001 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13002 Find references to all entities containing an x that are
13003 referenced on line 123 of main.ads.
13004 The references will be searched only in main.ads and foo.adb.
13005
13006 @item gnatfind main.ads:123
13007 Find declarations and bodies for all entities that are referenced on
13008 line 123 of main.ads.
13009
13010 This is the same as @code{gnatfind "*":main.adb:123}.
13011
13012 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13013 Find the declaration for the entity referenced at column 45 in
13014 line 123 of file main.adb in directory mydir. Note that it
13015 is usual to omit the identifier name when the column is given,
13016 since the column position identifies a unique reference.
13017
13018 The column has to be the beginning of the identifier, and should not
13019 point to any character in the middle of the identifier.
13020
13021 @end table
13022
13023 @c *********************************
13024 @node The GNAT Pretty-Printer gnatpp
13025 @chapter The GNAT Pretty-Printer @command{gnatpp}
13026 @findex gnatpp
13027 @cindex Pretty-Printer
13028
13029 @noindent
13030 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13031 for source reformatting / pretty-printing.
13032 It takes an Ada source file as input and generates a reformatted
13033 version as output.
13034 You can specify various style directives via switches; e.g.,
13035 identifier case conventions, rules of indentation, and comment layout.
13036
13037 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13038 tree for the input source and thus requires the input to be syntactically and
13039 semantically legal.
13040 If this condition is not met, @command{gnatpp} will terminate with an
13041 error message; no output file will be generated.
13042
13043 If the source files presented to @command{gnatpp} contain
13044 preprocessing directives, then the output file will
13045 correspond to the generated source after all
13046 preprocessing is carried out. There is no way
13047 using @command{gnatpp} to obtain pretty printed files that
13048 include the preprocessing directives.
13049
13050 If the compilation unit
13051 contained in the input source depends semantically upon units located
13052 outside the current directory, you have to provide the source search path
13053 when invoking @command{gnatpp}, if these units are contained in files with
13054 names that do not follow the GNAT file naming rules, you have to provide
13055 the configuration file describing the corresponding naming scheme;
13056 see the description of the @command{gnatpp}
13057 switches below. Another possibility is to use a project file and to
13058 call @command{gnatpp} through the @command{gnat} driver
13059 (see @ref{The GNAT Driver and Project Files}).
13060
13061 The @command{gnatpp} command has the form
13062
13063 @smallexample
13064 @c $ gnatpp @ovar{switches} @var{filename}
13065 @c Expanding @ovar macro inline (explanation in macro def comments)
13066 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13067 @end smallexample
13068
13069 @noindent
13070 where
13071 @itemize @bullet
13072 @item
13073 @var{switches} is an optional sequence of switches defining such properties as
13074 the formatting rules, the source search path, and the destination for the
13075 output source file
13076
13077 @item
13078 @var{filename} is the name (including the extension) of the source file to
13079 reformat; ``wildcards'' or several file names on the same gnatpp command are
13080 allowed.  The file name may contain path information; it does not have to
13081 follow the GNAT file naming rules
13082
13083 @item
13084 @samp{@var{gcc_switches}} is a list of switches for
13085 @command{gcc}. They will be passed on to all compiler invocations made by
13086 @command{gnatelim} to generate the ASIS trees. Here you can provide
13087 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13088 use the @option{-gnatec} switch to set the configuration file,
13089 use the @option{-gnat05} switch if sources should be compiled in
13090 Ada 2005 mode  etc.
13091 @end itemize
13092
13093 @menu
13094 * Switches for gnatpp::
13095 * Formatting Rules::
13096 @end menu
13097
13098 @node Switches for gnatpp
13099 @section Switches for @command{gnatpp}
13100
13101 @noindent
13102 The following subsections describe the various switches accepted by
13103 @command{gnatpp}, organized by category.
13104
13105 @ifclear vms
13106 You specify a switch by supplying a name and generally also a value.
13107 In many cases the values for a switch with a given name are incompatible with
13108 each other
13109 (for example the switch that controls the casing of a reserved word may have
13110 exactly one value: upper case, lower case, or
13111 mixed case) and thus exactly one such switch can be in effect for an
13112 invocation of @command{gnatpp}.
13113 If more than one is supplied, the last one is used.
13114 However, some values for the same switch are mutually compatible.
13115 You may supply several such switches to @command{gnatpp}, but then
13116 each must be specified in full, with both the name and the value.
13117 Abbreviated forms (the name appearing once, followed by each value) are
13118 not permitted.
13119 For example, to set
13120 the alignment of the assignment delimiter both in declarations and in
13121 assignment statements, you must write @option{-A2A3}
13122 (or @option{-A2 -A3}), but not @option{-A23}.
13123 @end ifclear
13124
13125 @ifset vms
13126 In many cases the set of options for a given qualifier are incompatible with
13127 each other (for example the qualifier that controls the casing of a reserved
13128 word may have exactly one option, which specifies either upper case, lower
13129 case, or mixed case), and thus exactly one such option can be in effect for
13130 an invocation of @command{gnatpp}.
13131 If more than one is supplied, the last one is used.
13132 However, some qualifiers have options that are mutually compatible,
13133 and then you may then supply several such options when invoking
13134 @command{gnatpp}.
13135 @end ifset
13136
13137 In most cases, it is obvious whether or not the
13138 ^values for a switch with a given name^options for a given qualifier^
13139 are compatible with each other.
13140 When the semantics might not be evident, the summaries below explicitly
13141 indicate the effect.
13142
13143 @menu
13144 * Alignment Control::
13145 * Casing Control::
13146 * Construct Layout Control::
13147 * General Text Layout Control::
13148 * Other Formatting Options::
13149 * Setting the Source Search Path::
13150 * Output File Control::
13151 * Other gnatpp Switches::
13152 @end menu
13153
13154 @node Alignment Control
13155 @subsection Alignment Control
13156 @cindex Alignment control in @command{gnatpp}
13157
13158 @noindent
13159 Programs can be easier to read if certain constructs are vertically aligned.
13160 By default all alignments are set ON.
13161 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13162 OFF, and then use one or more of the other
13163 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13164 to activate alignment for specific constructs.
13165
13166 @table @option
13167 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13168
13169 @ifset vms
13170 @item /ALIGN=ON
13171 Set all alignments to ON
13172 @end ifset
13173
13174 @item ^-A0^/ALIGN=OFF^
13175 Set all alignments to OFF
13176
13177 @item ^-A1^/ALIGN=COLONS^
13178 Align @code{:} in declarations
13179
13180 @item ^-A2^/ALIGN=DECLARATIONS^
13181 Align @code{:=} in initializations in declarations
13182
13183 @item ^-A3^/ALIGN=STATEMENTS^
13184 Align @code{:=} in assignment statements
13185
13186 @item ^-A4^/ALIGN=ARROWS^
13187 Align @code{=>} in associations
13188
13189 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13190 Align @code{at} keywords in the component clauses in record
13191 representation clauses
13192 @end table
13193
13194 @noindent
13195 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13196 is allowed.
13197
13198 @node Casing Control
13199 @subsection Casing Control
13200 @cindex Casing control in @command{gnatpp}
13201
13202 @noindent
13203 @command{gnatpp} allows you to specify the casing for reserved words,
13204 pragma names, attribute designators and identifiers.
13205 For identifiers you may define a
13206 general rule for name casing but also override this rule
13207 via a set of dictionary files.
13208
13209 Three types of casing are supported: lower case, upper case, and mixed case.
13210 Lower and upper case are self-explanatory (but since some letters in
13211 Latin1 and other GNAT-supported character sets
13212 exist only in lower-case form, an upper case conversion will have no
13213 effect on them.)
13214 ``Mixed case'' means that the first letter, and also each letter immediately
13215 following an underscore, are converted to their uppercase forms;
13216 all the other letters are converted to their lowercase forms.
13217
13218 @table @option
13219 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13220 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13221 Attribute designators are lower case
13222
13223 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13224 Attribute designators are upper case
13225
13226 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13227 Attribute designators are mixed case (this is the default)
13228
13229 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13230 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13231 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13232 lower case (this is the default)
13233
13234 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13235 Keywords are upper case
13236
13237 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13238 @item ^-nD^/NAME_CASING=AS_DECLARED^
13239 Name casing for defining occurrences are as they appear in the source file
13240 (this is the default)
13241
13242 @item ^-nU^/NAME_CASING=UPPER_CASE^
13243 Names are in upper case
13244
13245 @item ^-nL^/NAME_CASING=LOWER_CASE^
13246 Names are in lower case
13247
13248 @item ^-nM^/NAME_CASING=MIXED_CASE^
13249 Names are in mixed case
13250
13251 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13252 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13253 Enumeration literal casing for defining occurrences are as they appear in the
13254 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13255
13256 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13257 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13258 setting.
13259
13260 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13261 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13262 setting.
13263
13264 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13265 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13266 setting.
13267
13268 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13269 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13270 Names introduced by type and subtype declarations are always
13271 cased as they appear in the declaration in the source file.
13272 Overrides ^-n^/NAME_CASING^ casing setting.
13273
13274 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13275 Names introduced by type and subtype declarations are always in
13276 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13277
13278 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13279 Names introduced by type and subtype declarations are always in
13280 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13281
13282 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13283 Names introduced by type and subtype declarations are always in
13284 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13285
13286 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13287 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13288 Pragma names are lower case
13289
13290 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13291 Pragma names are upper case
13292
13293 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13294 Pragma names are mixed case (this is the default)
13295
13296 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13297 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13298 Use @var{file} as a @emph{dictionary file} that defines
13299 the casing for a set of specified names,
13300 thereby overriding the effect on these names by
13301 any explicit or implicit
13302 ^-n^/NAME_CASING^ switch.
13303 To supply more than one dictionary file,
13304 use ^several @option{-D} switches^a list of files as options^.
13305
13306 @noindent
13307 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13308 to define the casing for the Ada predefined names and
13309 the names declared in the GNAT libraries.
13310
13311 @item ^-D-^/SPECIFIC_CASING^
13312 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13313 Do not use the default dictionary file;
13314 instead, use the casing
13315 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13316 dictionary file(s)
13317 @end table
13318
13319 @noindent
13320 The structure of a dictionary file, and details on the conventions
13321 used in the default dictionary file, are defined in @ref{Name Casing}.
13322
13323 The @option{^-D-^/SPECIFIC_CASING^} and
13324 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13325 compatible.
13326
13327 @node Construct Layout Control
13328 @subsection Construct Layout Control
13329 @cindex Layout control in @command{gnatpp}
13330
13331 @noindent
13332 This group of @command{gnatpp} switches controls the layout of comments and
13333 complex syntactic constructs.  See @ref{Formatting Comments} for details
13334 on their effect.
13335
13336 @table @option
13337 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13338 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13339 All the comments remain unchanged
13340
13341 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13342 GNAT-style comment line indentation (this is the default).
13343
13344 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13345 Reference-manual comment line indentation.
13346
13347 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13348 GNAT-style comment beginning
13349
13350 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13351 Reformat comment blocks
13352
13353 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13354 Keep unchanged special form comments
13355
13356 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13357 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13358 GNAT-style layout (this is the default)
13359
13360 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13361 Compact layout
13362
13363 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13364 Uncompact layout
13365
13366 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13367 @item ^-N^/NOTABS^
13368 All the VT characters are removed from the comment text. All the HT characters
13369 are expanded with the sequences of space characters to get to the next tab
13370 stops.
13371
13372 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13373 @item ^--no-separate-is^/NO_SEPARATE_IS^
13374 Do not place the keyword @code{is} on a separate line in a subprogram body in
13375 case if the spec occupies more then one line.
13376
13377 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13378 @item ^--separate-label^/SEPARATE_LABEL^
13379 Place statement label(s) on a separate line, with the following statement
13380 on the next line.
13381
13382 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13383 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13384 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13385 keyword @code{then} in IF statements on a separate line.
13386
13387 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13388 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13389 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13390 keyword @code{then} in IF statements on a separate line. This option is
13391 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13392
13393 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13394 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13395 Start each USE clause in a context clause from a separate line.
13396
13397 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13398 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13399 Use a separate line for a loop or block statement name, but do not use an extra
13400 indentation level for the statement itself.
13401
13402 @end table
13403
13404 @ifclear vms
13405 @noindent
13406 The @option{-c1} and @option{-c2} switches are incompatible.
13407 The @option{-c3} and @option{-c4} switches are compatible with each other and
13408 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13409 the other comment formatting switches.
13410
13411 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13412 @end ifclear
13413
13414 @ifset vms
13415 @noindent
13416 For the @option{/COMMENTS_LAYOUT} qualifier:
13417 @itemize @bullet
13418 @item
13419 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13420 @item
13421 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13422 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13423 @end itemize
13424
13425 @noindent
13426 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13427 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13428 @end ifset
13429
13430 @node General Text Layout Control
13431 @subsection General Text Layout Control
13432
13433 @noindent
13434 These switches allow control over line length and indentation.
13435
13436 @table @option
13437 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13438 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13439 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13440
13441 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13442 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13443 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13444
13445 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13446 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13447 Indentation level for continuation lines (relative to the line being
13448 continued), @var{nnn} from 1@dots{}9.
13449 The default
13450 value is one less then the (normal) indentation level, unless the
13451 indentation is set to 1 (in which case the default value for continuation
13452 line indentation is also 1)
13453 @end table
13454
13455 @node Other Formatting Options
13456 @subsection Other Formatting Options
13457
13458 @noindent
13459 These switches control the inclusion of missing end/exit labels, and
13460 the indentation level in @b{case} statements.
13461
13462 @table @option
13463 @item ^-e^/NO_MISSED_LABELS^
13464 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13465 Do not insert missing end/exit labels. An end label is the name of
13466 a construct that may optionally be repeated at the end of the
13467 construct's declaration;
13468 e.g., the names of packages, subprograms, and tasks.
13469 An exit label is the name of a loop that may appear as target
13470 of an exit statement within the loop.
13471 By default, @command{gnatpp} inserts these end/exit labels when
13472 they are absent from the original source. This option suppresses such
13473 insertion, so that the formatted source reflects the original.
13474
13475 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13476 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13477 Insert a Form Feed character after a pragma Page.
13478
13479 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13480 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13481 Do not use an additional indentation level for @b{case} alternatives
13482 and variants if there are @var{nnn} or more (the default
13483 value is 10).
13484 If @var{nnn} is 0, an additional indentation level is
13485 used for @b{case} alternatives and variants regardless of their number.
13486
13487 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
13488 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
13489 If the number of parameter associations is greater than @var{nnn} and if at
13490 least one association uses named notation, start each association from
13491 a new line. If @var{nnn} is 0, no check for the number of associations
13492 is made, this is the default.
13493
13494 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
13495 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
13496 If the number of parameter specifications is greater than @var{nnn}
13497 (or equal to @var{nnn} in case of a function), start each specification from
13498 a new line. The default for @var{nnn} is 3.
13499 @end table
13500
13501 @node Setting the Source Search Path
13502 @subsection Setting the Source Search Path
13503
13504 @noindent
13505 To define the search path for the input source file, @command{gnatpp}
13506 uses the same switches as the GNAT compiler, with the same effects.
13507
13508 @table @option
13509 @item ^-I^/SEARCH=^@var{dir}
13510 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13511 The same as the corresponding gcc switch
13512
13513 @item ^-I-^/NOCURRENT_DIRECTORY^
13514 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13515 The same as the corresponding gcc switch
13516
13517 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13518 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13519 The same as the corresponding gcc switch
13520
13521 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13522 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13523 The same as the corresponding gcc switch
13524
13525 @end table
13526
13527 @node Output File Control
13528 @subsection Output File Control
13529
13530 @noindent
13531 By default the output is sent to the file whose name is obtained by appending
13532 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13533 (if the file with this name already exists, it is unconditionally overwritten).
13534 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13535 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13536 as output file.
13537 The output may be redirected by the following switches:
13538
13539 @table @option
13540 @item ^-pipe^/STANDARD_OUTPUT^
13541 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13542 Send the output to @code{Standard_Output}
13543
13544 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13545 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13546 Write the output into @var{output_file}.
13547 If @var{output_file} already exists, @command{gnatpp} terminates without
13548 reading or processing the input file.
13549
13550 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13551 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13552 Write the output into @var{output_file}, overwriting the existing file
13553 (if one is present).
13554
13555 @item ^-r^/REPLACE^
13556 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13557 Replace the input source file with the reformatted output, and copy the
13558 original input source into the file whose name is obtained by appending the
13559 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13560 If a file with this name already exists, @command{gnatpp} terminates without
13561 reading or processing the input file.
13562
13563 @item ^-rf^/OVERRIDING_REPLACE^
13564 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13565 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13566 already exists, it is overwritten.
13567
13568 @item ^-rnb^/REPLACE_NO_BACKUP^
13569 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13570 Replace the input source file with the reformatted output without
13571 creating any backup copy of the input source.
13572
13573 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13574 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13575 Specifies the format of the reformatted output file. The @var{xxx}
13576 ^string specified with the switch^option^ may be either
13577 @itemize @bullet
13578 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13579 @item ``@option{^crlf^CRLF^}''
13580 the same as @option{^crlf^CRLF^}
13581 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13582 @item ``@option{^lf^LF^}''
13583 the same as @option{^unix^UNIX^}
13584 @end itemize
13585
13586 @item ^-W^/RESULT_ENCODING=^@var{e}
13587 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13588 Specify the wide character encoding method used to write the code in the
13589 result file
13590 @var{e} is one of the following:
13591
13592 @itemize @bullet
13593
13594 @item ^h^HEX^
13595 Hex encoding
13596
13597 @item ^u^UPPER^
13598 Upper half encoding
13599
13600 @item ^s^SHIFT_JIS^
13601 Shift/JIS encoding
13602
13603 @item ^e^EUC^
13604 EUC encoding
13605
13606 @item ^8^UTF8^
13607 UTF-8 encoding
13608
13609 @item ^b^BRACKETS^
13610 Brackets encoding (default value)
13611 @end itemize
13612
13613 @end table
13614
13615 @noindent
13616 Options @option{^-pipe^/STANDARD_OUTPUT^},
13617 @option{^-o^/OUTPUT^} and
13618 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13619 contains only one file to reformat.
13620 Option
13621 @option{^--eol^/END_OF_LINE^}
13622 and
13623 @option{^-W^/RESULT_ENCODING^}
13624 cannot be used together
13625 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13626
13627 @node Other gnatpp Switches
13628 @subsection Other @code{gnatpp} Switches
13629
13630 @noindent
13631 The additional @command{gnatpp} switches are defined in this subsection.
13632
13633 @table @option
13634 @item ^-files @var{filename}^/FILES=@var{filename}^
13635 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13636 Take the argument source files from the specified file. This file should be an
13637 ordinary text file containing file names separated by spaces or
13638 line breaks. You can use this switch more than once in the same call to
13639 @command{gnatpp}. You also can combine this switch with an explicit list of
13640 files.
13641
13642 @item ^-v^/VERBOSE^
13643 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13644 Verbose mode;
13645 @command{gnatpp} generates version information and then
13646 a trace of the actions it takes to produce or obtain the ASIS tree.
13647
13648 @item ^-w^/WARNINGS^
13649 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13650 Warning mode;
13651 @command{gnatpp} generates a warning whenever it cannot provide
13652 a required layout in the result source.
13653 @end table
13654
13655 @node Formatting Rules
13656 @section Formatting Rules
13657
13658 @noindent
13659 The following subsections show how @command{gnatpp} treats ``white space'',
13660 comments, program layout, and name casing.
13661 They provide the detailed descriptions of the switches shown above.
13662
13663 @menu
13664 * White Space and Empty Lines::
13665 * Formatting Comments::
13666 * Construct Layout::
13667 * Name Casing::
13668 @end menu
13669
13670 @node White Space and Empty Lines
13671 @subsection White Space and Empty Lines
13672
13673 @noindent
13674 @command{gnatpp} does not have an option to control space characters.
13675 It will add or remove spaces according to the style illustrated by the
13676 examples in the @cite{Ada Reference Manual}.
13677
13678 The only format effectors
13679 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13680 that will appear in the output file are platform-specific line breaks,
13681 and also format effectors within (but not at the end of) comments.
13682 In particular, each horizontal tab character that is not inside
13683 a comment will be treated as a space and thus will appear in the
13684 output file as zero or more spaces depending on
13685 the reformatting of the line in which it appears.
13686 The only exception is a Form Feed character, which is inserted after a
13687 pragma @code{Page} when @option{-ff} is set.
13688
13689 The output file will contain no lines with trailing ``white space'' (spaces,
13690 format effectors).
13691
13692 Empty lines in the original source are preserved
13693 only if they separate declarations or statements.
13694 In such contexts, a
13695 sequence of two or more empty lines is replaced by exactly one empty line.
13696 Note that a blank line will be removed if it separates two ``comment blocks''
13697 (a comment block is a sequence of whole-line comments).
13698 In order to preserve a visual separation between comment blocks, use an
13699 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13700 Likewise, if for some reason you wish to have a sequence of empty lines,
13701 use a sequence of empty comments instead.
13702
13703 @node Formatting Comments
13704 @subsection Formatting Comments
13705
13706 @noindent
13707 Comments in Ada code are of two kinds:
13708 @itemize @bullet
13709 @item
13710 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13711 ``white space'') on a line
13712
13713 @item
13714 an @emph{end-of-line comment}, which follows some other Ada lexical element
13715 on the same line.
13716 @end itemize
13717
13718 @noindent
13719 The indentation of a whole-line comment is that of either
13720 the preceding or following line in
13721 the formatted source, depending on switch settings as will be described below.
13722
13723 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13724 between the end of the preceding Ada lexical element and the beginning
13725 of the comment as appear in the original source,
13726 unless either the comment has to be split to
13727 satisfy the line length limitation, or else the next line contains a
13728 whole line comment that is considered a continuation of this end-of-line
13729 comment (because it starts at the same position).
13730 In the latter two
13731 cases, the start of the end-of-line comment is moved right to the nearest
13732 multiple of the indentation level.
13733 This may result in a ``line overflow'' (the right-shifted comment extending
13734 beyond the maximum line length), in which case the comment is split as
13735 described below.
13736
13737 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13738 (GNAT-style comment line indentation)
13739 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13740 (reference-manual comment line indentation).
13741 With reference-manual style, a whole-line comment is indented as if it
13742 were a declaration or statement at the same place
13743 (i.e., according to the indentation of the preceding line(s)).
13744 With GNAT style, a whole-line comment that is immediately followed by an
13745 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13746 word @b{begin}, is indented based on the construct that follows it.
13747
13748 For example:
13749 @smallexample @c ada
13750 @cartouche
13751 if A then
13752     null;
13753        -- some comment
13754 else
13755    null;
13756 end if;
13757 @end cartouche
13758 @end smallexample
13759
13760 @noindent
13761 Reference-manual indentation produces:
13762
13763 @smallexample @c ada
13764 @cartouche
13765 if A then
13766    null;
13767    --  some comment
13768 else
13769    null;
13770 end if;
13771 @end cartouche
13772 @end smallexample
13773
13774 @noindent
13775 while GNAT-style indentation produces:
13776
13777 @smallexample @c ada
13778 @cartouche
13779 if A then
13780    null;
13781 --  some comment
13782 else
13783    null;
13784 end if;
13785 @end cartouche
13786 @end smallexample
13787
13788 @noindent
13789 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13790 (GNAT style comment beginning) has the following
13791 effect:
13792
13793 @itemize @bullet
13794 @item
13795 For each whole-line comment that does not end with two hyphens,
13796 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13797 to ensure that there are at least two spaces between these hyphens and the
13798 first non-blank character of the comment.
13799 @end itemize
13800
13801 @noindent
13802 For an end-of-line comment, if in the original source the next line is a
13803 whole-line comment that starts at the same position
13804 as the end-of-line comment,
13805 then the whole-line comment (and all whole-line comments
13806 that follow it and that start at the same position)
13807 will start at this position in the output file.
13808
13809 @noindent
13810 That is, if in the original source we have:
13811
13812 @smallexample @c ada
13813 @cartouche
13814 begin
13815 A := B + C;            --  B must be in the range Low1..High1
13816                        --  C must be in the range Low2..High2
13817              --B+C will be in the range Low1+Low2..High1+High2
13818 X := X + 1;
13819 @end cartouche
13820 @end smallexample
13821
13822 @noindent
13823 Then in the formatted source we get
13824
13825 @smallexample @c ada
13826 @cartouche
13827 begin
13828    A := B + C;            --  B must be in the range Low1..High1
13829                           --  C must be in the range Low2..High2
13830    --  B+C will be in the range Low1+Low2..High1+High2
13831    X := X + 1;
13832 @end cartouche
13833 @end smallexample
13834
13835 @noindent
13836 A comment that exceeds the line length limit will be split.
13837 Unless switch
13838 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13839 the line belongs to a reformattable block, splitting the line generates a
13840 @command{gnatpp} warning.
13841 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13842 comments may be reformatted in typical
13843 word processor style (that is, moving words between lines and putting as
13844 many words in a line as possible).
13845
13846 @noindent
13847 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13848 that has a special format (that is, a character that is neither a letter nor digit
13849 not white space nor line break immediately following the leading @code{--} of
13850 the comment) should be without any change moved from the argument source
13851 into reformatted source. This switch allows to preserve comments that are used
13852 as a special marks in the code (e.g.@: SPARK annotation).
13853
13854 @node Construct Layout
13855 @subsection Construct Layout
13856
13857 @noindent
13858 In several cases the suggested layout in the Ada Reference Manual includes
13859 an extra level of indentation that many programmers prefer to avoid. The
13860 affected cases include:
13861
13862 @itemize @bullet
13863
13864 @item Record type declaration (RM 3.8)
13865
13866 @item Record representation clause (RM 13.5.1)
13867
13868 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13869
13870 @item Block statement in case if a block has a statement identifier (RM 5.6)
13871 @end itemize
13872
13873 @noindent
13874 In compact mode (when GNAT style layout or compact layout is set),
13875 the pretty printer uses one level of indentation instead
13876 of two. This is achieved in the record definition and record representation
13877 clause cases by putting the @code{record} keyword on the same line as the
13878 start of the declaration or representation clause, and in the block and loop
13879 case by putting the block or loop header on the same line as the statement
13880 identifier.
13881
13882 @noindent
13883 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13884 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13885 layout on the one hand, and uncompact layout
13886 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13887 can be illustrated by the following examples:
13888
13889 @iftex
13890 @cartouche
13891 @multitable @columnfractions .5 .5
13892 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13893
13894 @item
13895 @smallexample @c ada
13896 type q is record
13897    a : integer;
13898    b : integer;
13899 end record;
13900 @end smallexample
13901 @tab
13902 @smallexample @c ada
13903 type q is
13904    record
13905       a : integer;
13906       b : integer;
13907    end record;
13908 @end smallexample
13909
13910 @item
13911 @smallexample @c ada
13912 for q use record
13913    a at 0 range  0 .. 31;
13914    b at 4 range  0 .. 31;
13915 end record;
13916 @end smallexample
13917 @tab
13918 @smallexample @c ada
13919 for q use
13920    record
13921       a at 0 range  0 .. 31;
13922       b at 4 range  0 .. 31;
13923    end record;
13924 @end smallexample
13925
13926 @item
13927 @smallexample @c ada
13928 Block : declare
13929    A : Integer := 3;
13930 begin
13931    Proc (A, A);
13932 end Block;
13933 @end smallexample
13934 @tab
13935 @smallexample @c ada
13936 Block :
13937    declare
13938       A : Integer := 3;
13939    begin
13940       Proc (A, A);
13941    end Block;
13942 @end smallexample
13943
13944 @item
13945 @smallexample @c ada
13946 Clear : for J in 1 .. 10 loop
13947    A (J) := 0;
13948 end loop Clear;
13949 @end smallexample
13950 @tab
13951 @smallexample @c ada
13952 Clear :
13953    for J in 1 .. 10 loop
13954       A (J) := 0;
13955    end loop Clear;
13956 @end smallexample
13957 @end multitable
13958 @end cartouche
13959 @end iftex
13960
13961 @ifnottex
13962 @smallexample
13963 @cartouche
13964 GNAT style, compact layout              Uncompact layout
13965
13966 type q is record                        type q is
13967    a : integer;                            record
13968    b : integer;                               a : integer;
13969 end record;                                   b : integer;
13970                                            end record;
13971
13972 for q use record                        for q use
13973    a at 0 range  0 .. 31;                  record
13974    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13975 end record;                                   b at 4 range  0 .. 31;
13976                                            end record;
13977
13978 Block : declare                         Block :
13979    A : Integer := 3;                       declare
13980 begin                                         A : Integer := 3;
13981    Proc (A, A);                            begin
13982 end Block;                                    Proc (A, A);
13983                                            end Block;
13984
13985 Clear : for J in 1 .. 10 loop           Clear :
13986    A (J) := 0;                             for J in 1 .. 10 loop
13987 end loop Clear;                               A (J) := 0;
13988                                            end loop Clear;
13989 @end cartouche
13990 @end smallexample
13991 @end ifnottex
13992
13993 @noindent
13994 A further difference between GNAT style layout and compact layout is that
13995 GNAT style layout inserts empty lines as separation for
13996 compound statements, return statements and bodies.
13997
13998 Note that the layout specified by
13999 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14000 for named block and loop statements overrides the layout defined by these
14001 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14002 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14003 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14004
14005 @node Name Casing
14006 @subsection Name Casing
14007
14008 @noindent
14009 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14010 the same casing as the corresponding defining identifier.
14011
14012 You control the casing for defining occurrences via the
14013 @option{^-n^/NAME_CASING^} switch.
14014 @ifclear vms
14015 With @option{-nD} (``as declared'', which is the default),
14016 @end ifclear
14017 @ifset vms
14018 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14019 @end ifset
14020 defining occurrences appear exactly as in the source file
14021 where they are declared.
14022 The other ^values for this switch^options for this qualifier^ ---
14023 @option{^-nU^UPPER_CASE^},
14024 @option{^-nL^LOWER_CASE^},
14025 @option{^-nM^MIXED_CASE^} ---
14026 result in
14027 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14028 If @command{gnatpp} changes the casing of a defining
14029 occurrence, it analogously changes the casing of all the
14030 usage occurrences of this name.
14031
14032 If the defining occurrence of a name is not in the source compilation unit
14033 currently being processed by @command{gnatpp}, the casing of each reference to
14034 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14035 switch (subject to the dictionary file mechanism described below).
14036 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14037 had affected the
14038 casing for the defining occurrence of the name.
14039
14040 Some names may need to be spelled with casing conventions that are not
14041 covered by the upper-, lower-, and mixed-case transformations.
14042 You can arrange correct casing by placing such names in a
14043 @emph{dictionary file},
14044 and then supplying a @option{^-D^/DICTIONARY^} switch.
14045 The casing of names from dictionary files overrides
14046 any @option{^-n^/NAME_CASING^} switch.
14047
14048 To handle the casing of Ada predefined names and the names from GNAT libraries,
14049 @command{gnatpp} assumes a default dictionary file.
14050 The name of each predefined entity is spelled with the same casing as is used
14051 for the entity in the @cite{Ada Reference Manual}.
14052 The name of each entity in the GNAT libraries is spelled with the same casing
14053 as is used in the declaration of that entity.
14054
14055 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14056 default dictionary file.
14057 Instead, the casing for predefined and GNAT-defined names will be established
14058 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14059 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14060 will appear as just shown,
14061 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14062 To ensure that even such names are rendered in uppercase,
14063 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14064 (or else, less conveniently, place these names in upper case in a dictionary
14065 file).
14066
14067 A dictionary file is
14068 a plain text file; each line in this file can be either a blank line
14069 (containing only space characters and ASCII.HT characters), an Ada comment
14070 line, or the specification of exactly one @emph{casing schema}.
14071
14072 A casing schema is a string that has the following syntax:
14073
14074 @smallexample
14075 @cartouche
14076   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14077
14078   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14079 @end cartouche
14080 @end smallexample
14081
14082 @noindent
14083 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14084 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14085
14086 The casing schema string can be followed by white space and/or an Ada-style
14087 comment; any amount of white space is allowed before the string.
14088
14089 If a dictionary file is passed as
14090 @ifclear vms
14091 the value of a @option{-D@var{file}} switch
14092 @end ifclear
14093 @ifset vms
14094 an option to the @option{/DICTIONARY} qualifier
14095 @end ifset
14096 then for every
14097 simple name and every identifier, @command{gnatpp} checks if the dictionary
14098 defines the casing for the name or for some of its parts (the term ``subword''
14099 is used below to denote the part of a name which is delimited by ``_'' or by
14100 the beginning or end of the word and which does not contain any ``_'' inside):
14101
14102 @itemize @bullet
14103 @item
14104 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14105 the casing defined by the dictionary; no subwords are checked for this word
14106
14107 @item
14108 for every subword @command{gnatpp} checks if the dictionary contains the
14109 corresponding string of the form @code{*@var{simple_identifier}*},
14110 and if it does, the casing of this @var{simple_identifier} is used
14111 for this subword
14112
14113 @item
14114 if the whole name does not contain any ``_'' inside, and if for this name
14115 the dictionary contains two entries - one of the form @var{identifier},
14116 and another - of the form *@var{simple_identifier}*, then the first one
14117 is applied to define the casing of this name
14118
14119 @item
14120 if more than one dictionary file is passed as @command{gnatpp} switches, each
14121 dictionary adds new casing exceptions and overrides all the existing casing
14122 exceptions set by the previous dictionaries
14123
14124 @item
14125 when @command{gnatpp} checks if the word or subword is in the dictionary,
14126 this check is not case sensitive
14127 @end itemize
14128
14129 @noindent
14130 For example, suppose we have the following source to reformat:
14131
14132 @smallexample @c ada
14133 @cartouche
14134 procedure test is
14135    name1 : integer := 1;
14136    name4_name3_name2 : integer := 2;
14137    name2_name3_name4 : Boolean;
14138    name1_var : Float;
14139 begin
14140    name2_name3_name4 := name4_name3_name2 > name1;
14141 end;
14142 @end cartouche
14143 @end smallexample
14144
14145 @noindent
14146 And suppose we have two dictionaries:
14147
14148 @smallexample
14149 @cartouche
14150 @i{dict1:}
14151    NAME1
14152    *NaMe3*
14153    *Name1*
14154 @end cartouche
14155
14156 @cartouche
14157 @i{dict2:}
14158   *NAME3*
14159 @end cartouche
14160 @end smallexample
14161
14162 @noindent
14163 If @command{gnatpp} is called with the following switches:
14164
14165 @smallexample
14166 @ifclear vms
14167 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14168 @end ifclear
14169 @ifset vms
14170 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14171 @end ifset
14172 @end smallexample
14173
14174 @noindent
14175 then we will get the following name casing in the @command{gnatpp} output:
14176
14177 @smallexample @c ada
14178 @cartouche
14179 procedure Test is
14180    NAME1             : Integer := 1;
14181    Name4_NAME3_Name2 : Integer := 2;
14182    Name2_NAME3_Name4 : Boolean;
14183    Name1_Var         : Float;
14184 begin
14185    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14186 end Test;
14187 @end cartouche
14188 @end smallexample
14189
14190 @c *********************************
14191 @node The GNAT Metric Tool gnatmetric
14192 @chapter The GNAT Metric Tool @command{gnatmetric}
14193 @findex gnatmetric
14194 @cindex Metric tool
14195
14196 @noindent
14197 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14198 for computing various program metrics.
14199 It takes an Ada source file as input and generates a file containing the
14200 metrics data as output. Various switches control which
14201 metrics are computed and output.
14202
14203 @command{gnatmetric} generates and uses the ASIS
14204 tree for the input source and thus requires the input to be syntactically and
14205 semantically legal.
14206 If this condition is not met, @command{gnatmetric} will generate
14207 an error message; no metric information for this file will be
14208 computed and reported.
14209
14210 If the compilation unit contained in the input source depends semantically
14211 upon units in files located outside the current directory, you have to provide
14212 the source search path when invoking @command{gnatmetric}.
14213 If it depends semantically upon units that are contained
14214 in files with names that do not follow the GNAT file naming rules, you have to
14215 provide the configuration file describing the corresponding naming scheme (see
14216 the description of the @command{gnatmetric} switches below.)
14217 Alternatively, you may use a project file and invoke @command{gnatmetric}
14218 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14219
14220 The @command{gnatmetric} command has the form
14221
14222 @smallexample
14223 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14224 @c Expanding @ovar macro inline (explanation in macro def comments)
14225 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14226 @end smallexample
14227
14228 @noindent
14229 where
14230 @itemize @bullet
14231 @item
14232 @var{switches} specify the metrics to compute and define the destination for
14233 the output
14234
14235 @item
14236 Each @var{filename} is the name (including the extension) of a source
14237 file to process. ``Wildcards'' are allowed, and
14238 the file name may contain path information.
14239 If no @var{filename} is supplied, then the @var{switches} list must contain
14240 at least one
14241 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14242 Including both a @option{-files} switch and one or more
14243 @var{filename} arguments is permitted.
14244
14245 @item
14246 @samp{@var{gcc_switches}} is a list of switches for
14247 @command{gcc}. They will be passed on to all compiler invocations made by
14248 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14249 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14250 and use the @option{-gnatec} switch to set the configuration file,
14251 use the @option{-gnat05} switch if sources should be compiled in
14252 Ada 2005 mode etc.
14253 @end itemize
14254
14255 @menu
14256 * Switches for gnatmetric::
14257 @end menu
14258
14259 @node Switches for gnatmetric
14260 @section Switches for @command{gnatmetric}
14261
14262 @noindent
14263 The following subsections describe the various switches accepted by
14264 @command{gnatmetric}, organized by category.
14265
14266 @menu
14267 * Output Files Control::
14268 * Disable Metrics For Local Units::
14269 * Specifying a set of metrics to compute::
14270 * Other gnatmetric Switches::
14271 * Generate project-wide metrics::
14272 @end menu
14273
14274 @node Output Files Control
14275 @subsection Output File Control
14276 @cindex Output file control in @command{gnatmetric}
14277
14278 @noindent
14279 @command{gnatmetric} has two output formats. It can generate a
14280 textual (human-readable) form, and also XML. By default only textual
14281 output is generated.
14282
14283 When generating the output in textual form, @command{gnatmetric} creates
14284 for each Ada source file a corresponding text file
14285 containing the computed metrics, except for the case when the set of metrics
14286 specified by gnatmetric parameters consists only of metrics that are computed
14287 for the whole set of analyzed sources, but not for each Ada source.
14288 By default, this file is placed in the same directory as where the source
14289 file is located, and its name is obtained
14290 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14291 input file.
14292
14293 All the output information generated in XML format is placed in a single
14294 file. By default this file is placed in the current directory and has the
14295 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14296
14297 Some of the computed metrics are summed over the units passed to
14298 @command{gnatmetric}; for example, the total number of lines of code.
14299 By default this information is sent to @file{stdout}, but a file
14300 can be specified with the @option{-og} switch.
14301
14302 The following switches control the @command{gnatmetric} output:
14303
14304 @table @option
14305 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14306 @item ^-x^/XML^
14307 Generate the XML output
14308
14309 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14310 @item ^-xs^/XSD^
14311 Generate the XML output and the XML schema file that describes the structure
14312 of the XML metric report, this schema is assigned to the XML file. The schema
14313 file has the same name as the XML output file with @file{.xml} suffix replaced
14314 with @file{.xsd}
14315
14316 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14317 @item ^-nt^/NO_TEXT^
14318 Do not generate the output in text form (implies @option{^-x^/XML^})
14319
14320 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14321 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14322 Put text files with detailed metrics into @var{output_dir}
14323
14324 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14325 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14326 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14327 in the name of the output file.
14328
14329 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14330 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14331 Put global metrics into @var{file_name}
14332
14333 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14334 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14335 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14336
14337 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14338 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14339 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14340 output includes the name(s) of the Ada source file(s) from which the metrics
14341 are computed.  By default each name includes the absolute path. The
14342 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14343 to exclude all directory information from the file names that are output.)
14344
14345 @end table
14346
14347 @node Disable Metrics For Local Units
14348 @subsection Disable Metrics For Local Units
14349 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14350
14351 @noindent
14352 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14353 one compilation
14354 unit per one source file. It computes line metrics for the whole source
14355 file, and it also computes syntax
14356 and complexity metrics for the file's outermost unit.
14357
14358 By default, @command{gnatmetric} will also compute all metrics for certain
14359 kinds of locally declared program units:
14360
14361 @itemize @bullet
14362 @item
14363 subprogram (and generic subprogram) bodies;
14364
14365 @item
14366 package (and generic package) specs and bodies;
14367
14368 @item
14369 task object and type specifications and bodies;
14370
14371 @item
14372 protected object and type specifications and bodies.
14373 @end itemize
14374
14375 @noindent
14376 These kinds of entities will be referred to as
14377 @emph{eligible local program units}, or simply @emph{eligible local units},
14378 @cindex Eligible local unit (for @command{gnatmetric})
14379 in the discussion below.
14380
14381 Note that a subprogram declaration, generic instantiation,
14382 or renaming declaration only receives metrics
14383 computation when it appear as the outermost entity
14384 in a source file.
14385
14386 Suppression of metrics computation for eligible local units can be
14387 obtained via the following switch:
14388
14389 @table @option
14390 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14391 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14392 Do not compute detailed metrics for eligible local program units
14393
14394 @end table
14395
14396 @node Specifying a set of metrics to compute
14397 @subsection Specifying a set of metrics to compute
14398
14399 @noindent
14400 By default all the metrics are computed and reported. The switches
14401 described in this subsection allow you to control, on an individual
14402 basis, whether metrics are computed and
14403 reported. If at least one positive metric
14404 switch is specified (that is, a switch that defines that a given
14405 metric or set of metrics is to be computed), then only
14406 explicitly specified metrics are reported.
14407
14408 @menu
14409 * Line Metrics Control::
14410 * Syntax Metrics Control::
14411 * Complexity Metrics Control::
14412 * Coupling Metrics Control::
14413 @end menu
14414
14415 @node Line Metrics Control
14416 @subsubsection Line Metrics Control
14417 @cindex Line metrics control in @command{gnatmetric}
14418
14419 @noindent
14420 For any (legal) source file, and for each of its
14421 eligible local program units, @command{gnatmetric} computes the following
14422 metrics:
14423
14424 @itemize @bullet
14425 @item
14426 the total number of lines;
14427
14428 @item
14429 the total number of code lines (i.e., non-blank lines that are not comments)
14430
14431 @item
14432 the number of comment lines
14433
14434 @item
14435 the number of code lines containing end-of-line comments;
14436
14437 @item
14438 the comment percentage: the ratio between the number of lines that contain
14439 comments and the number of all non-blank lines, expressed as a percentage;
14440
14441 @item
14442 the number of empty lines and lines containing only space characters and/or
14443 format effectors (blank lines)
14444
14445 @item
14446 the average number of code lines in subprogram bodies, task bodies, entry
14447 bodies and statement sequences in package bodies (this metric is only computed
14448 across the whole set of the analyzed units)
14449
14450 @end itemize
14451
14452 @noindent
14453 @command{gnatmetric} sums the values of the line metrics for all the
14454 files being processed and then generates the cumulative results. The tool
14455 also computes for all the files being processed the average number of code
14456 lines in bodies.
14457
14458 You can use the following switches to select the specific line metrics
14459 to be computed and reported.
14460
14461 @table @option
14462 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14463
14464 @ifclear vms
14465 @cindex @option{--no-lines@var{x}}
14466 @end ifclear
14467
14468 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14469 Report all the line metrics
14470
14471 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14472 Do not report any of line metrics
14473
14474 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14475 Report the number of all lines
14476
14477 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14478 Do not report the number of all lines
14479
14480 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14481 Report the number of code lines
14482
14483 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14484 Do not report the number of code lines
14485
14486 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14487 Report the number of comment lines
14488
14489 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14490 Do not report the number of comment lines
14491
14492 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14493 Report the number of code lines containing
14494 end-of-line comments
14495
14496 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14497 Do not report the number of code lines containing
14498 end-of-line comments
14499
14500 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14501 Report the comment percentage in the program text
14502
14503 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14504 Do not report the comment percentage in the program text
14505
14506 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14507 Report the number of blank lines
14508
14509 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14510 Do not report the number of blank lines
14511
14512 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14513 Report the average number of code lines in subprogram bodies, task bodies,
14514 entry bodies and statement sequences in package bodies. The metric is computed
14515 and reported for the whole set of processed Ada sources only.
14516
14517 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14518 Do not report the average number of code lines in subprogram bodies,
14519 task bodies, entry bodies and statement sequences in package bodies.
14520
14521 @end table
14522
14523 @node Syntax Metrics Control
14524 @subsubsection Syntax Metrics Control
14525 @cindex Syntax metrics control in @command{gnatmetric}
14526
14527 @noindent
14528 @command{gnatmetric} computes various syntactic metrics for the
14529 outermost unit and for each eligible local unit:
14530
14531 @table @emph
14532 @item LSLOC (``Logical Source Lines Of Code'')
14533 The total number of declarations and the total number of statements. Note
14534 that the definition of declarations is the one given in the reference
14535 manual:
14536
14537 @noindent
14538 ``Each of the following is defined to be a declaration: any basic_declaration;
14539 an enumeration_literal_specification; a discriminant_specification;
14540 a component_declaration; a loop_parameter_specification; a
14541 parameter_specification; a subprogram_body; an entry_declaration;
14542 an entry_index_specification; a choice_parameter_specification;
14543 a generic_formal_parameter_declaration.''
14544
14545 This means for example that each enumeration literal adds one to the count,
14546 as well as each subprogram parameter.
14547
14548 Thus the results from this metric will be significantly greater than might
14549 be expected from a naive view of counting semicolons.
14550
14551 @item Maximal static nesting level of inner program units
14552 According to
14553 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14554 package, a task unit, a protected unit, a
14555 protected entry, a generic unit, or an explicitly declared subprogram other
14556 than an enumeration literal.''
14557
14558 @item Maximal nesting level of composite syntactic constructs
14559 This corresponds to the notion of the
14560 maximum nesting level in the GNAT built-in style checks
14561 (@pxref{Style Checking})
14562 @end table
14563
14564 @noindent
14565 For the outermost unit in the file, @command{gnatmetric} additionally computes
14566 the following metrics:
14567
14568 @table @emph
14569 @item Public subprograms
14570 This metric is computed for package specs. It is the
14571 number of subprograms and generic subprograms declared in the visible
14572 part (including the visible part of nested packages, protected objects, and
14573 protected types).
14574
14575 @item All subprograms
14576 This metric is computed for bodies and subunits. The
14577 metric is equal to a total number of subprogram bodies in the compilation
14578 unit.
14579 Neither generic instantiations nor renamings-as-a-body nor body stubs
14580 are counted. Any subprogram body is counted, independently of its nesting
14581 level and enclosing constructs. Generic bodies and bodies of protected
14582 subprograms are counted in the same way as ``usual'' subprogram bodies.
14583
14584 @item Public types
14585 This metric is computed for package specs and
14586 generic package declarations. It is the total number of types
14587 that can be referenced from outside this compilation unit, plus the
14588 number of types from all the visible parts of all the visible generic
14589 packages. Generic formal types are not counted.  Only types, not subtypes,
14590 are included.
14591
14592 @noindent
14593 Along with the total number of public types, the following
14594 types are counted and reported separately:
14595
14596 @itemize @bullet
14597 @item
14598 Abstract types
14599
14600 @item
14601 Root tagged types (abstract, non-abstract, private, non-private). Type
14602 extensions are @emph{not} counted
14603
14604 @item
14605 Private types (including private extensions)
14606
14607 @item
14608 Task types
14609
14610 @item
14611 Protected types
14612
14613 @end itemize
14614
14615 @item All types
14616 This metric is computed for any compilation unit. It is equal to the total
14617 number of the declarations of different types given in the compilation unit.
14618 The private and the corresponding full type declaration are counted as one
14619 type declaration. Incomplete type declarations and generic formal types
14620 are not counted.
14621 No distinction is made among different kinds of types (abstract,
14622 private etc.); the total number of types is computed and reported.
14623
14624 @end table
14625
14626 @noindent
14627 By default, all the syntax metrics are computed and reported. You can use the
14628 following switches to select specific syntax metrics.
14629
14630 @table @option
14631
14632 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14633
14634 @ifclear vms
14635 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14636 @end ifclear
14637
14638 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14639 Report all the syntax metrics
14640
14641 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14642 Do not report any of syntax metrics
14643
14644 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14645 Report the total number of declarations
14646
14647 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14648 Do not report the total number of declarations
14649
14650 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14651 Report the total number of statements
14652
14653 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14654 Do not report the total number of statements
14655
14656 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14657 Report the number of public subprograms in a compilation unit
14658
14659 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14660 Do not report the number of public subprograms in a compilation unit
14661
14662 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14663 Report the number of all the subprograms in a compilation unit
14664
14665 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14666 Do not report the number of all the subprograms in a compilation unit
14667
14668 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14669 Report the number of public types in a compilation unit
14670
14671 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14672 Do not report the number of public types in a compilation unit
14673
14674 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14675 Report the number of all the types in a compilation unit
14676
14677 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14678 Do not report the number of all the types in a compilation unit
14679
14680 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14681 Report the maximal program unit nesting level
14682
14683 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14684 Do not report the maximal program unit nesting level
14685
14686 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14687 Report the maximal construct nesting level
14688
14689 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14690 Do not report the maximal construct nesting level
14691
14692 @end table
14693
14694 @node Complexity Metrics Control
14695 @subsubsection Complexity Metrics Control
14696 @cindex Complexity metrics control in @command{gnatmetric}
14697
14698 @noindent
14699 For a program unit that is an executable body (a subprogram body (including
14700 generic bodies), task body, entry body or a package body containing
14701 its own statement sequence) @command{gnatmetric} computes the following
14702 complexity metrics:
14703
14704 @itemize @bullet
14705 @item
14706 McCabe cyclomatic complexity;
14707
14708 @item
14709 McCabe essential complexity;
14710
14711 @item
14712 maximal loop nesting level;
14713
14714 @item
14715 extra exit points (for subprograms);
14716 @end itemize
14717
14718 @noindent
14719 The McCabe cyclomatic complexity metric is defined
14720 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14721
14722 According to McCabe, both control statements and short-circuit control forms
14723 should be taken into account when computing cyclomatic complexity. For each
14724 body, we compute three metric values:
14725
14726 @itemize @bullet
14727 @item
14728 the complexity introduced by control
14729 statements only, without taking into account short-circuit forms,
14730
14731 @item
14732 the complexity introduced by short-circuit control forms only, and
14733
14734 @item
14735 the total
14736 cyclomatic complexity, which is the sum of these two values.
14737 @end itemize
14738
14739 @noindent
14740
14741 The origin of cyclomatic complexity metric is the need to estimate the number
14742 of independent paths in the control flow graph that in turn gives the number
14743 of tests needed to satisfy paths coverage testing completeness criterion.
14744 Considered from the testing point of view, a static Ada @code{loop} (that is,
14745 the @code{loop} statement having static subtype in loop parameter
14746 specification) does not add to cyclomatic complexity. By providing
14747 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14748 may specify that such loops should not be counted when computing the
14749 cyclomatic complexity metric
14750
14751 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14752 counted for the code that is reduced by excluding all the pure structural Ada
14753 control statements. An compound statement is considered as a non-structural
14754 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14755 or if it contains a @code{goto} statement that transfers the control outside
14756 the operator. A selective accept statement with @code{terminate} alternative
14757 is considered as non-structural statement. When computing this metric,
14758 @code{exit} statements are treated in the same way as @code{goto}
14759 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14760
14761 The Ada essential complexity metric defined here is intended to quantify
14762 the extent to which the software is unstructured. It is adapted from
14763 the McCabe essential complexity metric defined in
14764 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14765 suitable for typical Ada usage. For example, short circuit forms
14766 are not penalized as unstructured in the Ada essential complexity metric.
14767
14768 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14769 the code in the exception handlers and in all the nested program units.
14770
14771 By default, all the complexity metrics are computed and reported.
14772 For more fine-grained control you can use
14773 the following switches:
14774
14775 @table @option
14776 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14777
14778 @ifclear vms
14779 @cindex @option{--no-complexity@var{x}}
14780 @end ifclear
14781
14782 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14783 Report all the complexity metrics
14784
14785 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14786 Do not report any of complexity metrics
14787
14788 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14789 Report the McCabe Cyclomatic Complexity
14790
14791 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14792 Do not report the McCabe Cyclomatic Complexity
14793
14794 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14795 Report the Essential Complexity
14796
14797 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14798 Do not report the Essential Complexity
14799
14800 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14801 Report maximal loop nesting level
14802
14803 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14804 Do not report maximal loop nesting level
14805
14806 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14807 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14808 task bodies, entry bodies and statement sequences in package bodies.
14809 The metric is computed and reported for whole set of processed Ada sources
14810 only.
14811
14812 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14813 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14814 bodies, task bodies, entry bodies and statement sequences in package bodies
14815
14816 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14817 @item ^-ne^/NO_EXITS_AS_GOTOS^
14818 Do not consider @code{exit} statements as @code{goto}s when
14819 computing Essential Complexity
14820
14821 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14822 @item ^--no-static-loop^/NO_STATIC_LOOP^
14823 Do not consider static loops when computing cyclomatic complexity
14824
14825 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14826 Report the extra exit points for subprogram bodies. As an exit point, this
14827 metric counts @code{return} statements and raise statements in case when the
14828 raised exception is not handled in the same body. In case of a function this
14829 metric subtracts 1 from the number of exit points, because a function body
14830 must contain at least one @code{return} statement.
14831
14832 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14833 Do not report the extra exit points for subprogram bodies
14834 @end table
14835
14836
14837 @node Coupling Metrics Control
14838 @subsubsection Coupling Metrics Control
14839 @cindex Coupling metrics control in @command{gnatmetric}
14840
14841 @noindent
14842 @cindex Coupling metrics (in in @command{gnatmetric})
14843 Coupling metrics measure the dependencies between a given entity and other
14844 entities the program consists of. The goal of these metrics is to estimate the
14845 stability of the whole program considered as the collection of entities
14846 (modules, classes etc.).
14847
14848 Gnatmetric computes the following coupling metrics:
14849
14850 @itemize @bullet
14851
14852 @item
14853 @emph{object-oriented coupling} - for classes in traditional object-oriented
14854 sense;
14855
14856 @item
14857 @emph{unit coupling} - for all the program units making up a program;
14858
14859 @item
14860 @emph{control coupling} - this metric counts dependencies between a unit and
14861 only those units that define subprograms;
14862 @end itemize
14863
14864 @noindent
14865 Two kinds of coupling metrics are computed:
14866
14867 @table @asis
14868 @item fan-out coupling (efferent coupling)
14869 @cindex fan-out coupling
14870 @cindex efferent coupling
14871 the number of entities the given entity depends upon. It
14872 estimates in what extent the given entity depends on the changes in
14873 ``external world''
14874
14875 @item fan-in coupling (afferent coupling)
14876 @cindex fan-in coupling
14877 @cindex afferent coupling
14878 the number of entities that depend on a given entity.
14879 It estimates in what extent the ``external world'' depends on the changes in a
14880 given entity
14881 @end table
14882
14883 @noindent
14884
14885 Object-oriented coupling metrics are metrics that measure the dependencies
14886 between a given class (or a group of classes) and the other classes in the
14887 program. In this subsection the term ``class'' is used in its traditional
14888 object-oriented programming sense (an instantiable module that contains data
14889 and/or method members). A @emph{category} (of classes) is a group of closely
14890 related classes that are reused and/or modified together.
14891
14892 A class @code{K}'s fan-out coupling is the number of classes
14893 that @code{K} depends upon.
14894 A category's fan-out coupling is the number of classes outside the
14895 category that the classes inside the category depend upon.
14896
14897 A class @code{K}'s fan-in coupling is the number of classes
14898 that depend upon @code{K}.
14899 A category's fan-in coupling is the number of classes outside the
14900 category that depend on classes belonging to the category.
14901
14902 Ada's implementation of the object-oriented paradigm does not use the
14903 traditional class notion, so the definition of the coupling
14904 metrics for Ada maps the class and class category notions
14905 onto Ada constructs.
14906
14907 For the coupling metrics, several kinds of modules -- a library package,
14908 a library generic package, and a library generic package instantiation --
14909 that define a tagged type or an interface type are
14910 considered to be a class. A category consists of a library package (or
14911 a library generic package) that defines a tagged or an interface type,
14912 together with all its descendant (generic) packages that define tagged
14913 or interface types. That is a
14914 category is an Ada hierarchy of library-level program units. So class coupling
14915 in case of Ada is called as tagged coupling, and category coupling - as
14916 hierarchy coupling.
14917
14918 For any package counted as a class, its body and subunits (if any) are
14919 considered together with its spec when counting the dependencies, and coupling
14920 metrics are reported for spec units only. For dependencies between classes,
14921 the Ada semantic dependencies are considered. For object-oriented coupling
14922 metrics, only dependencies on units that are considered as classes, are
14923 considered.
14924
14925 For unit and control coupling also not compilation units but program units are
14926 counted. That is, for a package, its spec, its body and its subunits (if any)
14927 are considered as making up one unit, and the dependencies that are counted
14928 are the dependencies of all these compilation units collected together as
14929 the dependencies as a (whole) unit. And metrics are reported for spec
14930 compilation units only (or for a subprogram body unit in case if there is no
14931 separate spec for the given subprogram).
14932
14933 For unit coupling, dependencies between all kinds of program units are
14934 considered. For control coupling, for each unit the dependencies of this unit
14935 upon units that define subprograms are counted, so control fan-out coupling
14936 is reported for all units, but control fan-in coupling - only for the units
14937 that define subprograms.
14938
14939
14940
14941
14942
14943
14944 When computing coupling metrics, @command{gnatmetric} counts only
14945 dependencies between units that are arguments of the gnatmetric call.
14946 Coupling metrics are program-wide (or project-wide) metrics, so to
14947 get a valid result, you should call @command{gnatmetric} for
14948 the whole set of sources that make up your program. It can be done
14949 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14950 option (see @ref{The GNAT Driver and Project Files} for details).
14951
14952 By default, all the coupling metrics are disabled. You can use the following
14953 switches to specify the coupling metrics to be computed and reported:
14954
14955 @table @option
14956
14957 @ifclear vms
14958 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14959 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14960 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14961 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14962 @end ifclear
14963
14964 @ifset vms
14965 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14966 @end ifset
14967
14968 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14969 Report all the coupling metrics
14970
14971 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14972 Report tagged (class) fan-out coupling
14973
14974 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14975 Report tagged (class) fan-in coupling
14976
14977 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14978 Report hierarchy (category) fan-out coupling
14979
14980 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14981 Report hierarchy (category) fan-in coupling
14982
14983 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14984 Report unit fan-out coupling
14985
14986 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14987 Report unit fan-in coupling
14988
14989 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14990 Report control fan-out coupling
14991
14992 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14993 Report control fan-in coupling
14994 @end table
14995
14996 @node Other gnatmetric Switches
14997 @subsection Other @code{gnatmetric} Switches
14998
14999 @noindent
15000 Additional @command{gnatmetric} switches are as follows:
15001
15002 @table @option
15003 @item ^-files @var{filename}^/FILES=@var{filename}^
15004 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15005 Take the argument source files from the specified file. This file should be an
15006 ordinary text file containing file names separated by spaces or
15007 line breaks. You can use this switch more than once in the same call to
15008 @command{gnatmetric}. You also can combine this switch with
15009 an explicit list of files.
15010
15011 @item ^-v^/VERBOSE^
15012 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15013 Verbose mode;
15014 @command{gnatmetric} generates version information and then
15015 a trace of sources being processed.
15016
15017 @item ^-q^/QUIET^
15018 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15019 Quiet mode.
15020 @end table
15021
15022 @node Generate project-wide metrics
15023 @subsection Generate project-wide metrics
15024
15025 In order to compute metrics on all units of a given project, you can use
15026 the @command{gnat} driver along with the @option{-P} option:
15027 @smallexample
15028    gnat metric -Pproj
15029 @end smallexample
15030
15031 @noindent
15032 If the project @code{proj} depends upon other projects, you can compute
15033 the metrics on the project closure using the @option{-U} option:
15034 @smallexample
15035    gnat metric -Pproj -U
15036 @end smallexample
15037
15038 @noindent
15039 Finally, if not all the units are relevant to a particular main
15040 program in the project closure, you can generate metrics for the set
15041 of units needed to create a given main program (unit closure) using
15042 the @option{-U} option followed by the name of the main unit:
15043 @smallexample
15044    gnat metric -Pproj -U main
15045 @end smallexample
15046
15047
15048 @c ***********************************
15049 @node File Name Krunching Using gnatkr
15050 @chapter File Name Krunching Using @code{gnatkr}
15051 @findex gnatkr
15052
15053 @noindent
15054 This chapter discusses the method used by the compiler to shorten
15055 the default file names chosen for Ada units so that they do not
15056 exceed the maximum length permitted. It also describes the
15057 @code{gnatkr} utility that can be used to determine the result of
15058 applying this shortening.
15059 @menu
15060 * About gnatkr::
15061 * Using gnatkr::
15062 * Krunching Method::
15063 * Examples of gnatkr Usage::
15064 @end menu
15065
15066 @node About gnatkr
15067 @section About @code{gnatkr}
15068
15069 @noindent
15070 The default file naming rule in GNAT
15071 is that the file name must be derived from
15072 the unit name. The exact default rule is as follows:
15073 @itemize @bullet
15074 @item
15075 Take the unit name and replace all dots by hyphens.
15076 @item
15077 If such a replacement occurs in the
15078 second character position of a name, and the first character is
15079 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
15080 then replace the dot by the character
15081 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
15082 instead of a minus.
15083 @end itemize
15084 The reason for this exception is to avoid clashes
15085 with the standard names for children of System, Ada, Interfaces,
15086 and GNAT, which use the prefixes
15087 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
15088 respectively.
15089
15090 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15091 switch of the compiler activates a ``krunching''
15092 circuit that limits file names to nn characters (where nn is a decimal
15093 integer). For example, using OpenVMS,
15094 where the maximum file name length is
15095 39, the value of nn is usually set to 39, but if you want to generate
15096 a set of files that would be usable if ported to a system with some
15097 different maximum file length, then a different value can be specified.
15098 The default value of 39 for OpenVMS need not be specified.
15099
15100 The @code{gnatkr} utility can be used to determine the krunched name for
15101 a given file, when krunched to a specified maximum length.
15102
15103 @node Using gnatkr
15104 @section Using @code{gnatkr}
15105
15106 @noindent
15107 The @code{gnatkr} command has the form
15108
15109 @ifclear vms
15110 @smallexample
15111 @c $ gnatkr @var{name} @ovar{length}
15112 @c Expanding @ovar macro inline (explanation in macro def comments)
15113 $ gnatkr @var{name} @r{[}@var{length}@r{]}
15114 @end smallexample
15115 @end ifclear
15116
15117 @ifset vms
15118 @smallexample
15119 $ gnatkr @var{name} /COUNT=nn
15120 @end smallexample
15121 @end ifset
15122
15123 @noindent
15124 @var{name} is the uncrunched file name, derived from the name of the unit
15125 in the standard manner described in the previous section (i.e., in particular
15126 all dots are replaced by hyphens). The file name may or may not have an
15127 extension (defined as a suffix of the form period followed by arbitrary
15128 characters other than period). If an extension is present then it will
15129 be preserved in the output. For example, when krunching @file{hellofile.ads}
15130 to eight characters, the result will be hellofil.ads.
15131
15132 Note: for compatibility with previous versions of @code{gnatkr} dots may
15133 appear in the name instead of hyphens, but the last dot will always be
15134 taken as the start of an extension. So if @code{gnatkr} is given an argument
15135 such as @file{Hello.World.adb} it will be treated exactly as if the first
15136 period had been a hyphen, and for example krunching to eight characters
15137 gives the result @file{hellworl.adb}.
15138
15139 Note that the result is always all lower case (except on OpenVMS where it is
15140 all upper case). Characters of the other case are folded as required.
15141
15142 @var{length} represents the length of the krunched name. The default
15143 when no argument is given is ^8^39^ characters. A length of zero stands for
15144 unlimited, in other words do not chop except for system files where the
15145 implied crunching length is always eight characters.
15146
15147 @noindent
15148 The output is the krunched name. The output has an extension only if the
15149 original argument was a file name with an extension.
15150
15151 @node Krunching Method
15152 @section Krunching Method
15153
15154 @noindent
15155 The initial file name is determined by the name of the unit that the file
15156 contains. The name is formed by taking the full expanded name of the
15157 unit and replacing the separating dots with hyphens and
15158 using ^lowercase^uppercase^
15159 for all letters, except that a hyphen in the second character position is
15160 replaced by a ^tilde^dollar sign^ if the first character is
15161 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15162 The extension is @code{.ads} for a
15163 spec and @code{.adb} for a body.
15164 Krunching does not affect the extension, but the file name is shortened to
15165 the specified length by following these rules:
15166
15167 @itemize @bullet
15168 @item
15169 The name is divided into segments separated by hyphens, tildes or
15170 underscores and all hyphens, tildes, and underscores are
15171 eliminated. If this leaves the name short enough, we are done.
15172
15173 @item
15174 If the name is too long, the longest segment is located (left-most
15175 if there are two of equal length), and shortened by dropping
15176 its last character. This is repeated until the name is short enough.
15177
15178 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15179 to fit the name into 8 characters as required by some operating systems.
15180
15181 @smallexample
15182 our-strings-wide_fixed 22
15183 our strings wide fixed 19
15184 our string  wide fixed 18
15185 our strin   wide fixed 17
15186 our stri    wide fixed 16
15187 our stri    wide fixe  15
15188 our str     wide fixe  14
15189 our str     wid  fixe  13
15190 our str     wid  fix   12
15191 ou  str     wid  fix   11
15192 ou  st      wid  fix   10
15193 ou  st      wi   fix   9
15194 ou  st      wi   fi    8
15195 Final file name: oustwifi.adb
15196 @end smallexample
15197
15198 @item
15199 The file names for all predefined units are always krunched to eight
15200 characters. The krunching of these predefined units uses the following
15201 special prefix replacements:
15202
15203 @table @file
15204 @item ada-
15205 replaced by @file{^a^A^-}
15206
15207 @item gnat-
15208 replaced by @file{^g^G^-}
15209
15210 @item interfaces-
15211 replaced by @file{^i^I^-}
15212
15213 @item system-
15214 replaced by @file{^s^S^-}
15215 @end table
15216
15217 These system files have a hyphen in the second character position. That
15218 is why normal user files replace such a character with a
15219 ^tilde^dollar sign^, to
15220 avoid confusion with system file names.
15221
15222 As an example of this special rule, consider
15223 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15224
15225 @smallexample
15226 ada-strings-wide_fixed 22
15227 a-  strings wide fixed 18
15228 a-  string  wide fixed 17
15229 a-  strin   wide fixed 16
15230 a-  stri    wide fixed 15
15231 a-  stri    wide fixe  14
15232 a-  str     wide fixe  13
15233 a-  str     wid  fixe  12
15234 a-  str     wid  fix   11
15235 a-  st      wid  fix   10
15236 a-  st      wi   fix   9
15237 a-  st      wi   fi    8
15238 Final file name: a-stwifi.adb
15239 @end smallexample
15240 @end itemize
15241
15242 Of course no file shortening algorithm can guarantee uniqueness over all
15243 possible unit names, and if file name krunching is used then it is your
15244 responsibility to ensure that no name clashes occur. The utility
15245 program @code{gnatkr} is supplied for conveniently determining the
15246 krunched name of a file.
15247
15248 @node Examples of gnatkr Usage
15249 @section Examples of @code{gnatkr} Usage
15250
15251 @smallexample
15252 @iftex
15253 @leftskip=0cm
15254 @end iftex
15255 @ifclear vms
15256 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15257 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15258 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15259 $ gnatkr grandparent-parent-child     --> grparchi
15260 @end ifclear
15261 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15262 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15263 @end smallexample
15264
15265 @node Preprocessing Using gnatprep
15266 @chapter Preprocessing Using @code{gnatprep}
15267 @findex gnatprep
15268
15269 @noindent
15270 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15271 preprocessing.
15272 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15273 special GNAT features.
15274 For further discussion of conditional compilation in general, see
15275 @ref{Conditional Compilation}.
15276
15277 @menu
15278 * Preprocessing Symbols::
15279 * Using gnatprep::
15280 * Switches for gnatprep::
15281 * Form of Definitions File::
15282 * Form of Input Text for gnatprep::
15283 @end menu
15284
15285 @node Preprocessing Symbols
15286 @section Preprocessing Symbols
15287
15288 @noindent
15289 Preprocessing symbols are defined in definition files and referred to in
15290 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15291 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15292 all characters need to be in the ASCII set (no accented letters).
15293
15294 @node Using gnatprep
15295 @section Using @code{gnatprep}
15296
15297 @noindent
15298 To call @code{gnatprep} use
15299
15300 @smallexample
15301 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15302 @c Expanding @ovar macro inline (explanation in macro def comments)
15303 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15304 @end smallexample
15305
15306 @noindent
15307 where
15308 @table @var
15309 @item switches
15310 is an optional sequence of switches as described in the next section.
15311
15312 @item infile
15313 is the full name of the input file, which is an Ada source
15314 file containing preprocessor directives.
15315
15316 @item outfile
15317 is the full name of the output file, which is an Ada source
15318 in standard Ada form. When used with GNAT, this file name will
15319 normally have an ads or adb suffix.
15320
15321 @item deffile
15322 is the full name of a text file containing definitions of
15323 preprocessing symbols to be referenced by the preprocessor. This argument is
15324 optional, and can be replaced by the use of the @option{-D} switch.
15325
15326 @end table
15327
15328 @node Switches for gnatprep
15329 @section Switches for @code{gnatprep}
15330
15331 @table @option
15332 @c !sort!
15333
15334 @item ^-b^/BLANK_LINES^
15335 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15336 Causes both preprocessor lines and the lines deleted by
15337 preprocessing to be replaced by blank lines in the output source file,
15338 preserving line numbers in the output file.
15339
15340 @item ^-c^/COMMENTS^
15341 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15342 Causes both preprocessor lines and the lines deleted
15343 by preprocessing to be retained in the output source as comments marked
15344 with the special string @code{"--! "}. This option will result in line numbers
15345 being preserved in the output file.
15346
15347 @item ^-C^/REPLACE_IN_COMMENTS^
15348 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15349 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15350 If this option is specified, then comments are scanned and any $symbol
15351 substitutions performed as in program text. This is particularly useful
15352 when structured comments are used (e.g., when writing programs in the
15353 SPARK dialect of Ada). Note that this switch is not available when
15354 doing integrated preprocessing (it would be useless in this context
15355 since comments are ignored by the compiler in any case).
15356
15357 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15358 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15359 Defines a new preprocessing symbol, associated with value. If no value is given
15360 on the command line, then symbol is considered to be @code{True}. This switch
15361 can be used in place of a definition file.
15362
15363 @ifset vms
15364 @item /REMOVE
15365 @cindex @option{/REMOVE} (@command{gnatprep})
15366 This is the default setting which causes lines deleted by preprocessing
15367 to be entirely removed from the output file.
15368 @end ifset
15369
15370 @item ^-r^/REFERENCE^
15371 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15372 Causes a @code{Source_Reference} pragma to be generated that
15373 references the original input file, so that error messages will use
15374 the file name of this original file. The use of this switch implies
15375 that preprocessor lines are not to be removed from the file, so its
15376 use will force @option{^-b^/BLANK_LINES^} mode if
15377 @option{^-c^/COMMENTS^}
15378 has not been specified explicitly.
15379
15380 Note that if the file to be preprocessed contains multiple units, then
15381 it will be necessary to @code{gnatchop} the output file from
15382 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15383 in the preprocessed file, it will be respected by
15384 @code{gnatchop ^-r^/REFERENCE^}
15385 so that the final chopped files will correctly refer to the original
15386 input source file for @code{gnatprep}.
15387
15388 @item ^-s^/SYMBOLS^
15389 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15390 Causes a sorted list of symbol names and values to be
15391 listed on the standard output file.
15392
15393 @item ^-u^/UNDEFINED^
15394 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15395 Causes undefined symbols to be treated as having the value FALSE in the context
15396 of a preprocessor test. In the absence of this option, an undefined symbol in
15397 a @code{#if} or @code{#elsif} test will be treated as an error.
15398
15399 @end table
15400
15401 @ifclear vms
15402 @noindent
15403 Note: if neither @option{-b} nor @option{-c} is present,
15404 then preprocessor lines and
15405 deleted lines are completely removed from the output, unless -r is
15406 specified, in which case -b is assumed.
15407 @end ifclear
15408
15409 @node Form of Definitions File
15410 @section Form of Definitions File
15411
15412 @noindent
15413 The definitions file contains lines of the form
15414
15415 @smallexample
15416 symbol := value
15417 @end smallexample
15418
15419 @noindent
15420 where symbol is a preprocessing symbol, and value is one of the following:
15421
15422 @itemize @bullet
15423 @item
15424 Empty, corresponding to a null substitution
15425 @item
15426 A string literal using normal Ada syntax
15427 @item
15428 Any sequence of characters from the set
15429 (letters, digits, period, underline).
15430 @end itemize
15431
15432 @noindent
15433 Comment lines may also appear in the definitions file, starting with
15434 the usual @code{--},
15435 and comments may be added to the definitions lines.
15436
15437 @node Form of Input Text for gnatprep
15438 @section Form of Input Text for @code{gnatprep}
15439
15440 @noindent
15441 The input text may contain preprocessor conditional inclusion lines,
15442 as well as general symbol substitution sequences.
15443
15444 The preprocessor conditional inclusion commands have the form
15445
15446 @smallexample
15447 @group
15448 @cartouche
15449 #if @i{expression} @r{[}then@r{]}
15450    lines
15451 #elsif @i{expression} @r{[}then@r{]}
15452    lines
15453 #elsif @i{expression} @r{[}then@r{]}
15454    lines
15455 @dots{}
15456 #else
15457    lines
15458 #end if;
15459 @end cartouche
15460 @end group
15461 @end smallexample
15462
15463 @noindent
15464 In this example, @i{expression} is defined by the following grammar:
15465 @smallexample
15466 @i{expression} ::=  <symbol>
15467 @i{expression} ::=  <symbol> = "<value>"
15468 @i{expression} ::=  <symbol> = <symbol>
15469 @i{expression} ::=  <symbol> 'Defined
15470 @i{expression} ::=  not @i{expression}
15471 @i{expression} ::=  @i{expression} and @i{expression}
15472 @i{expression} ::=  @i{expression} or @i{expression}
15473 @i{expression} ::=  @i{expression} and then @i{expression}
15474 @i{expression} ::=  @i{expression} or else @i{expression}
15475 @i{expression} ::=  ( @i{expression} )
15476 @end smallexample
15477
15478 The following restriction exists: it is not allowed to have "and" or "or"
15479 following "not" in the same expression without parentheses. For example, this
15480 is not allowed:
15481
15482 @smallexample
15483    not X or Y
15484 @end smallexample
15485
15486 This should be one of the following:
15487
15488 @smallexample
15489    (not X) or Y
15490    not (X or Y)
15491 @end smallexample
15492
15493 @noindent
15494 For the first test (@i{expression} ::= <symbol>) the symbol must have
15495 either the value true or false, that is to say the right-hand of the
15496 symbol definition must be one of the (case-insensitive) literals
15497 @code{True} or @code{False}. If the value is true, then the
15498 corresponding lines are included, and if the value is false, they are
15499 excluded.
15500
15501 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15502 the symbol has been defined in the definition file or by a @option{-D}
15503 switch on the command line. Otherwise, the test is false.
15504
15505 The equality tests are case insensitive, as are all the preprocessor lines.
15506
15507 If the symbol referenced is not defined in the symbol definitions file,
15508 then the effect depends on whether or not switch @option{-u}
15509 is specified. If so, then the symbol is treated as if it had the value
15510 false and the test fails. If this switch is not specified, then
15511 it is an error to reference an undefined symbol. It is also an error to
15512 reference a symbol that is defined with a value other than @code{True}
15513 or @code{False}.
15514
15515 The use of the @code{not} operator inverts the sense of this logical test.
15516 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15517 operators, without parentheses. For example, "if not X or Y then" is not
15518 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15519
15520 The @code{then} keyword is optional as shown
15521
15522 The @code{#} must be the first non-blank character on a line, but
15523 otherwise the format is free form. Spaces or tabs may appear between
15524 the @code{#} and the keyword. The keywords and the symbols are case
15525 insensitive as in normal Ada code. Comments may be used on a
15526 preprocessor line, but other than that, no other tokens may appear on a
15527 preprocessor line. Any number of @code{elsif} clauses can be present,
15528 including none at all. The @code{else} is optional, as in Ada.
15529
15530 The @code{#} marking the start of a preprocessor line must be the first
15531 non-blank character on the line, i.e., it must be preceded only by
15532 spaces or horizontal tabs.
15533
15534 Symbol substitution outside of preprocessor lines is obtained by using
15535 the sequence
15536
15537 @smallexample
15538 $symbol
15539 @end smallexample
15540
15541 @noindent
15542 anywhere within a source line, except in a comment or within a
15543 string literal. The identifier
15544 following the @code{$} must match one of the symbols defined in the symbol
15545 definition file, and the result is to substitute the value of the
15546 symbol in place of @code{$symbol} in the output file.
15547
15548 Note that although the substitution of strings within a string literal
15549 is not possible, it is possible to have a symbol whose defined value is
15550 a string literal. So instead of setting XYZ to @code{hello} and writing:
15551
15552 @smallexample
15553 Header : String := "$XYZ";
15554 @end smallexample
15555
15556 @noindent
15557 you should set XYZ to @code{"hello"} and write:
15558
15559 @smallexample
15560 Header : String := $XYZ;
15561 @end smallexample
15562
15563 @noindent
15564 and then the substitution will occur as desired.
15565
15566 @node The GNAT Library Browser gnatls
15567 @chapter The GNAT Library Browser @code{gnatls}
15568 @findex gnatls
15569 @cindex Library browser
15570
15571 @noindent
15572 @code{gnatls} is a tool that outputs information about compiled
15573 units. It gives the relationship between objects, unit names and source
15574 files. It can also be used to check the source dependencies of a unit
15575 as well as various characteristics.
15576
15577 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15578 driver (see @ref{The GNAT Driver and Project Files}).
15579
15580 @menu
15581 * Running gnatls::
15582 * Switches for gnatls::
15583 * Examples of gnatls Usage::
15584 @end menu
15585
15586 @node Running gnatls
15587 @section Running @code{gnatls}
15588
15589 @noindent
15590 The @code{gnatls} command has the form
15591
15592 @smallexample
15593 $ gnatls switches @var{object_or_ali_file}
15594 @end smallexample
15595
15596 @noindent
15597 The main argument is the list of object or @file{ali} files
15598 (@pxref{The Ada Library Information Files})
15599 for which information is requested.
15600
15601 In normal mode, without additional option, @code{gnatls} produces a
15602 four-column listing. Each line represents information for a specific
15603 object. The first column gives the full path of the object, the second
15604 column gives the name of the principal unit in this object, the third
15605 column gives the status of the source and the fourth column gives the
15606 full path of the source representing this unit.
15607 Here is a simple example of use:
15608
15609 @smallexample
15610 $ gnatls *.o
15611 ^./^[]^demo1.o            demo1            DIF demo1.adb
15612 ^./^[]^demo2.o            demo2             OK demo2.adb
15613 ^./^[]^hello.o            h1                OK hello.adb
15614 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15615 ^./^[]^instr.o            instr             OK instr.adb
15616 ^./^[]^tef.o              tef              DIF tef.adb
15617 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15618 ^./^[]^tgef.o             tgef             DIF tgef.adb
15619 @end smallexample
15620
15621 @noindent
15622 The first line can be interpreted as follows: the main unit which is
15623 contained in
15624 object file @file{demo1.o} is demo1, whose main source is in
15625 @file{demo1.adb}. Furthermore, the version of the source used for the
15626 compilation of demo1 has been modified (DIF). Each source file has a status
15627 qualifier which can be:
15628
15629 @table @code
15630 @item OK (unchanged)
15631 The version of the source file used for the compilation of the
15632 specified unit corresponds exactly to the actual source file.
15633
15634 @item MOK (slightly modified)
15635 The version of the source file used for the compilation of the
15636 specified unit differs from the actual source file but not enough to
15637 require recompilation. If you use gnatmake with the qualifier
15638 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15639 MOK will not be recompiled.
15640
15641 @item DIF (modified)
15642 No version of the source found on the path corresponds to the source
15643 used to build this object.
15644
15645 @item ??? (file not found)
15646 No source file was found for this unit.
15647
15648 @item HID (hidden,  unchanged version not first on PATH)
15649 The version of the source that corresponds exactly to the source used
15650 for compilation has been found on the path but it is hidden by another
15651 version of the same source that has been modified.
15652
15653 @end table
15654
15655 @node Switches for gnatls
15656 @section Switches for @code{gnatls}
15657
15658 @noindent
15659 @code{gnatls} recognizes the following switches:
15660
15661 @table @option
15662 @c !sort!
15663 @cindex @option{--version} @command{gnatls}
15664 Display Copyright and version, then exit disregarding all other options.
15665
15666 @item --help
15667 @cindex @option{--help} @command{gnatls}
15668 If @option{--version} was not used, display usage, then exit disregarding
15669 all other options.
15670
15671 @item ^-a^/ALL_UNITS^
15672 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15673 Consider all units, including those of the predefined Ada library.
15674 Especially useful with @option{^-d^/DEPENDENCIES^}.
15675
15676 @item ^-d^/DEPENDENCIES^
15677 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15678 List sources from which specified units depend on.
15679
15680 @item ^-h^/OUTPUT=OPTIONS^
15681 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15682 Output the list of options.
15683
15684 @item ^-o^/OUTPUT=OBJECTS^
15685 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15686 Only output information about object files.
15687
15688 @item ^-s^/OUTPUT=SOURCES^
15689 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15690 Only output information about source files.
15691
15692 @item ^-u^/OUTPUT=UNITS^
15693 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15694 Only output information about compilation units.
15695
15696 @item ^-files^/FILES^=@var{file}
15697 @cindex @option{^-files^/FILES^} (@code{gnatls})
15698 Take as arguments the files listed in text file @var{file}.
15699 Text file @var{file} may contain empty lines that are ignored.
15700 Each nonempty line should contain the name of an existing file.
15701 Several such switches may be specified simultaneously.
15702
15703 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15704 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15705 @itemx ^-I^/SEARCH=^@var{dir}
15706 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15707 @itemx -nostdinc
15708 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15709 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15710 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15711 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15712 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15713 flags (@pxref{Switches for gnatmake}).
15714
15715 @item --RTS=@var{rts-path}
15716 @cindex @option{--RTS} (@code{gnatls})
15717 Specifies the default location of the runtime library. Same meaning as the
15718 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15719
15720 @item ^-v^/OUTPUT=VERBOSE^
15721 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15722 Verbose mode. Output the complete source, object and project paths. Do not use
15723 the default column layout but instead use long format giving as much as
15724 information possible on each requested units, including special
15725 characteristics such as:
15726
15727 @table @code
15728 @item  Preelaborable
15729 The unit is preelaborable in the Ada sense.
15730
15731 @item No_Elab_Code
15732 No elaboration code has been produced by the compiler for this unit.
15733
15734 @item Pure
15735 The unit is pure in the Ada sense.
15736
15737 @item Elaborate_Body
15738 The unit contains a pragma Elaborate_Body.
15739
15740 @item Remote_Types
15741 The unit contains a pragma Remote_Types.
15742
15743 @item Shared_Passive
15744 The unit contains a pragma Shared_Passive.
15745
15746 @item Predefined
15747 This unit is part of the predefined environment and cannot be modified
15748 by the user.
15749
15750 @item Remote_Call_Interface
15751 The unit contains a pragma Remote_Call_Interface.
15752
15753 @end table
15754
15755 @end table
15756
15757 @node Examples of gnatls Usage
15758 @section Example of @code{gnatls} Usage
15759 @ifclear vms
15760
15761 @noindent
15762 Example of using the verbose switch. Note how the source and
15763 object paths are affected by the -I switch.
15764
15765 @smallexample
15766 $ gnatls -v -I.. demo1.o
15767
15768 GNATLS 5.03w (20041123-34)
15769 Copyright 1997-2004 Free Software Foundation, Inc.
15770
15771 Source Search Path:
15772    <Current_Directory>
15773    ../
15774    /home/comar/local/adainclude/
15775
15776 Object Search Path:
15777    <Current_Directory>
15778    ../
15779    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15780
15781 Project Search Path:
15782    <Current_Directory>
15783    /home/comar/local/lib/gnat/
15784
15785 ./demo1.o
15786    Unit =>
15787      Name   => demo1
15788      Kind   => subprogram body
15789      Flags  => No_Elab_Code
15790      Source => demo1.adb    modified
15791 @end smallexample
15792
15793 @noindent
15794 The following is an example of use of the dependency list.
15795 Note the use of the -s switch
15796 which gives a straight list of source files. This can be useful for
15797 building specialized scripts.
15798
15799 @smallexample
15800 $ gnatls -d demo2.o
15801 ./demo2.o   demo2        OK demo2.adb
15802                          OK gen_list.ads
15803                          OK gen_list.adb
15804                          OK instr.ads
15805                          OK instr-child.ads
15806
15807 $ gnatls -d -s -a demo1.o
15808 demo1.adb
15809 /home/comar/local/adainclude/ada.ads
15810 /home/comar/local/adainclude/a-finali.ads
15811 /home/comar/local/adainclude/a-filico.ads
15812 /home/comar/local/adainclude/a-stream.ads
15813 /home/comar/local/adainclude/a-tags.ads
15814 gen_list.ads
15815 gen_list.adb
15816 /home/comar/local/adainclude/gnat.ads
15817 /home/comar/local/adainclude/g-io.ads
15818 instr.ads
15819 /home/comar/local/adainclude/system.ads
15820 /home/comar/local/adainclude/s-exctab.ads
15821 /home/comar/local/adainclude/s-finimp.ads
15822 /home/comar/local/adainclude/s-finroo.ads
15823 /home/comar/local/adainclude/s-secsta.ads
15824 /home/comar/local/adainclude/s-stalib.ads
15825 /home/comar/local/adainclude/s-stoele.ads
15826 /home/comar/local/adainclude/s-stratt.ads
15827 /home/comar/local/adainclude/s-tasoli.ads
15828 /home/comar/local/adainclude/s-unstyp.ads
15829 /home/comar/local/adainclude/unchconv.ads
15830 @end smallexample
15831 @end ifclear
15832
15833 @ifset vms
15834 @smallexample
15835 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15836
15837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15842 demo1.adb
15843 gen_list.ads
15844 gen_list.adb
15845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15847 instr.ads
15848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15859 @end smallexample
15860 @end ifset
15861
15862 @node Cleaning Up Using gnatclean
15863 @chapter Cleaning Up Using @code{gnatclean}
15864 @findex gnatclean
15865 @cindex Cleaning tool
15866
15867 @noindent
15868 @code{gnatclean} is a tool that allows the deletion of files produced by the
15869 compiler, binder and linker, including ALI files, object files, tree files,
15870 expanded source files, library files, interface copy source files, binder
15871 generated files and executable files.
15872
15873 @menu
15874 * Running gnatclean::
15875 * Switches for gnatclean::
15876 @c * Examples of gnatclean Usage::
15877 @end menu
15878
15879 @node Running gnatclean
15880 @section Running @code{gnatclean}
15881
15882 @noindent
15883 The @code{gnatclean} command has the form:
15884
15885 @smallexample
15886 $ gnatclean switches @var{names}
15887 @end smallexample
15888
15889 @noindent
15890 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15891 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15892 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15893
15894 @noindent
15895 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15896 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15897 the linker. In informative-only mode, specified by switch
15898 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15899 normal mode is listed, but no file is actually deleted.
15900
15901 @node Switches for gnatclean
15902 @section Switches for @code{gnatclean}
15903
15904 @noindent
15905 @code{gnatclean} recognizes the following switches:
15906
15907 @table @option
15908 @c !sort!
15909 @cindex @option{--version} @command{gnatclean}
15910 Display Copyright and version, then exit disregarding all other options.
15911
15912 @item --help
15913 @cindex @option{--help} @command{gnatclean}
15914 If @option{--version} was not used, display usage, then exit disregarding
15915 all other options.
15916
15917 @item ^--subdirs^/SUBDIRS^=subdir
15918 Actual object directory of each project file is the subdirectory subdir of the
15919 object directory specified or defaulted in the project file.
15920
15921 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15922 By default, shared library projects are not allowed to import static library
15923 projects. When this switch is used on the command line, this restriction is
15924 relaxed.
15925
15926 @item ^-c^/COMPILER_FILES_ONLY^
15927 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15928 Only attempt to delete the files produced by the compiler, not those produced
15929 by the binder or the linker. The files that are not to be deleted are library
15930 files, interface copy files, binder generated files and executable files.
15931
15932 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15933 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15934 Indicate that ALI and object files should normally be found in directory
15935 @var{dir}.
15936
15937 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15938 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15939 When using project files, if some errors or warnings are detected during
15940 parsing and verbose mode is not in effect (no use of switch
15941 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15942 file, rather than its simple file name.
15943
15944 @item ^-h^/HELP^
15945 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15946 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15947
15948 @item ^-n^/NODELETE^
15949 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15950 Informative-only mode. Do not delete any files. Output the list of the files
15951 that would have been deleted if this switch was not specified.
15952
15953 @item ^-P^/PROJECT_FILE=^@var{project}
15954 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15955 Use project file @var{project}. Only one such switch can be used.
15956 When cleaning a project file, the files produced by the compilation of the
15957 immediate sources or inherited sources of the project files are to be
15958 deleted. This is not depending on the presence or not of executable names
15959 on the command line.
15960
15961 @item ^-q^/QUIET^
15962 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15963 Quiet output. If there are no errors, do not output anything, except in
15964 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15965 (switch ^-n^/NODELETE^).
15966
15967 @item ^-r^/RECURSIVE^
15968 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15969 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15970 clean all imported and extended project files, recursively. If this switch
15971 is not specified, only the files related to the main project file are to be
15972 deleted. This switch has no effect if no project file is specified.
15973
15974 @item ^-v^/VERBOSE^
15975 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15976 Verbose mode.
15977
15978 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15979 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15980 Indicates the verbosity of the parsing of GNAT project files.
15981 @xref{Switches Related to Project Files}.
15982
15983 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15984 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15985 Indicates that external variable @var{name} has the value @var{value}.
15986 The Project Manager will use this value for occurrences of
15987 @code{external(name)} when parsing the project file.
15988 @xref{Switches Related to Project Files}.
15989
15990 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15991 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15992 When searching for ALI and object files, look in directory
15993 @var{dir}.
15994
15995 @item ^-I^/SEARCH=^@var{dir}
15996 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15997 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15998
15999 @item ^-I-^/NOCURRENT_DIRECTORY^
16000 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16001 @cindex Source files, suppressing search
16002 Do not look for ALI or object files in the directory
16003 where @code{gnatclean} was invoked.
16004
16005 @end table
16006
16007 @c @node Examples of gnatclean Usage
16008 @c @section Examples of @code{gnatclean} Usage
16009
16010 @ifclear vms
16011 @node GNAT and Libraries
16012 @chapter GNAT and Libraries
16013 @cindex Library, building, installing, using
16014
16015 @noindent
16016 This chapter describes how to build and use libraries with GNAT, and also shows
16017 how to recompile the GNAT run-time library. You should be familiar with the
16018 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16019 chapter.
16020
16021 @menu
16022 * Introduction to Libraries in GNAT::
16023 * General Ada Libraries::
16024 * Stand-alone Ada Libraries::
16025 * Rebuilding the GNAT Run-Time Library::
16026 @end menu
16027
16028 @node Introduction to Libraries in GNAT
16029 @section Introduction to Libraries in GNAT
16030
16031 @noindent
16032 A library is, conceptually, a collection of objects which does not have its
16033 own main thread of execution, but rather provides certain services to the
16034 applications that use it. A library can be either statically linked with the
16035 application, in which case its code is directly included in the application,
16036 or, on platforms that support it, be dynamically linked, in which case
16037 its code is shared by all applications making use of this library.
16038
16039 GNAT supports both types of libraries.
16040 In the static case, the compiled code can be provided in different ways. The
16041 simplest approach is to provide directly the set of objects resulting from
16042 compilation of the library source files. Alternatively, you can group the
16043 objects into an archive using whatever commands are provided by the operating
16044 system. For the latter case, the objects are grouped into a shared library.
16045
16046 In the GNAT environment, a library has three types of components:
16047 @itemize @bullet
16048 @item
16049 Source files.
16050 @item
16051 @file{ALI} files.
16052 @xref{The Ada Library Information Files}.
16053 @item
16054 Object files, an archive or a shared library.
16055 @end itemize
16056
16057 @noindent
16058 A GNAT library may expose all its source files, which is useful for
16059 documentation purposes. Alternatively, it may expose only the units needed by
16060 an external user to make use of the library. That is to say, the specs
16061 reflecting the library services along with all the units needed to compile
16062 those specs, which can include generic bodies or any body implementing an
16063 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16064 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
16065
16066 All compilation units comprising an application, including those in a library,
16067 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16068 computes the elaboration order from the @file{ALI} files and this is why they
16069 constitute a mandatory part of GNAT libraries.
16070 @emph{Stand-alone libraries} are the exception to this rule because a specific
16071 library elaboration routine is produced independently of the application(s)
16072 using the library.
16073
16074 @node General Ada Libraries
16075 @section General Ada Libraries
16076
16077 @menu
16078 * Building a library::
16079 * Installing a library::
16080 * Using a library::
16081 @end menu
16082
16083 @node Building a library
16084 @subsection Building a library
16085
16086 @noindent
16087 The easiest way to build a library is to use the Project Manager,
16088 which supports a special type of project called a @emph{Library Project}
16089 (@pxref{Library Projects}).
16090
16091 A project is considered a library project, when two project-level attributes
16092 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16093 control different aspects of library configuration, additional optional
16094 project-level attributes can be specified:
16095 @table @code
16096 @item Library_Kind
16097 This attribute controls whether the library is to be static or dynamic
16098
16099 @item Library_Version
16100 This attribute specifies the library version; this value is used
16101 during dynamic linking of shared libraries to determine if the currently
16102 installed versions of the binaries are compatible.
16103
16104 @item Library_Options
16105 @item Library_GCC
16106 These attributes specify additional low-level options to be used during
16107 library generation, and redefine the actual application used to generate
16108 library.
16109 @end table
16110
16111 @noindent
16112 The GNAT Project Manager takes full care of the library maintenance task,
16113 including recompilation of the source files for which objects do not exist
16114 or are not up to date, assembly of the library archive, and installation of
16115 the library (i.e., copying associated source, object and @file{ALI} files
16116 to the specified location).
16117
16118 Here is a simple library project file:
16119 @smallexample @c ada
16120 project My_Lib is
16121    for Source_Dirs use ("src1", "src2");
16122    for Object_Dir use "obj";
16123    for Library_Name use "mylib";
16124    for Library_Dir use "lib";
16125    for Library_Kind use "dynamic";
16126 end My_lib;
16127 @end smallexample
16128
16129 @noindent
16130 and the compilation command to build and install the library:
16131
16132 @smallexample @c ada
16133   $ gnatmake -Pmy_lib
16134 @end smallexample
16135
16136 @noindent
16137 It is not entirely trivial to perform manually all the steps required to
16138 produce a library. We recommend that you use the GNAT Project Manager
16139 for this task. In special cases where this is not desired, the necessary
16140 steps are discussed below.
16141
16142 There are various possibilities for compiling the units that make up the
16143 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
16144 with a conventional script. For simple libraries, it is also possible to create
16145 a dummy main program which depends upon all the packages that comprise the
16146 interface of the library. This dummy main program can then be given to
16147 @command{gnatmake}, which will ensure that all necessary objects are built.
16148
16149 After this task is accomplished, you should follow the standard procedure
16150 of the underlying operating system to produce the static or shared library.
16151
16152 Here is an example of such a dummy program:
16153 @smallexample @c ada
16154 @group
16155 with My_Lib.Service1;
16156 with My_Lib.Service2;
16157 with My_Lib.Service3;
16158 procedure My_Lib_Dummy is
16159 begin
16160    null;
16161 end;
16162 @end group
16163 @end smallexample
16164
16165 @noindent
16166 Here are the generic commands that will build an archive or a shared library.
16167
16168 @smallexample
16169 # compiling the library
16170 $ gnatmake -c my_lib_dummy.adb
16171
16172 # we don't need the dummy object itself
16173 $ rm my_lib_dummy.o my_lib_dummy.ali
16174
16175 # create an archive with the remaining objects
16176 $ ar rc libmy_lib.a *.o
16177 # some systems may require "ranlib" to be run as well
16178
16179 # or create a shared library
16180 $ gcc -shared -o libmy_lib.so *.o
16181 # some systems may require the code to have been compiled with -fPIC
16182
16183 # remove the object files that are now in the library
16184 $ rm *.o
16185
16186 # Make the ALI files read-only so that gnatmake will not try to
16187 # regenerate the objects that are in the library
16188 $ chmod -w *.ali
16189 @end smallexample
16190
16191 @noindent
16192 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16193 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16194 be accessed by the directive @option{-l@var{xxx}} at link time.
16195
16196 @node Installing a library
16197 @subsection Installing a library
16198 @cindex @code{ADA_PROJECT_PATH}
16199 @cindex @code{GPR_PROJECT_PATH}
16200
16201 @noindent
16202 If you use project files, library installation is part of the library build
16203 process (@pxref{Installing a library with project files}).
16204
16205 When project files are not an option, it is also possible, but not recommended,
16206 to install the library so that the sources needed to use the library are on the
16207 Ada source path and the ALI files & libraries be on the Ada Object path (see
16208 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16209 administrator can place general-purpose libraries in the default compiler
16210 paths, by specifying the libraries' location in the configuration files
16211 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16212 must be located in the GNAT installation tree at the same place as the gcc spec
16213 file. The location of the gcc spec file can be determined as follows:
16214 @smallexample
16215 $ gcc -v
16216 @end smallexample
16217
16218 @noindent
16219 The configuration files mentioned above have a simple format: each line
16220 must contain one unique directory name.
16221 Those names are added to the corresponding path
16222 in their order of appearance in the file. The names can be either absolute
16223 or relative; in the latter case, they are relative to where theses files
16224 are located.
16225
16226 The files @file{ada_source_path} and @file{ada_object_path} might not be
16227 present in a
16228 GNAT installation, in which case, GNAT will look for its run-time library in
16229 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16230 objects and @file{ALI} files). When the files exist, the compiler does not
16231 look in @file{adainclude} and @file{adalib}, and thus the
16232 @file{ada_source_path} file
16233 must contain the location for the GNAT run-time sources (which can simply
16234 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16235 contain the location for the GNAT run-time objects (which can simply
16236 be @file{adalib}).
16237
16238 You can also specify a new default path to the run-time library at compilation
16239 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16240 the run-time library you want your program to be compiled with. This switch is
16241 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16242 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16243
16244 It is possible to install a library before or after the standard GNAT
16245 library, by reordering the lines in the configuration files. In general, a
16246 library must be installed before the GNAT library if it redefines
16247 any part of it.
16248
16249 @node Using a library
16250 @subsection Using a library
16251
16252 @noindent Once again, the project facility greatly simplifies the use of
16253 libraries. In this context, using a library is just a matter of adding a
16254 @code{with} clause in the user project. For instance, to make use of the
16255 library @code{My_Lib} shown in examples in earlier sections, you can
16256 write:
16257
16258 @smallexample @c projectfile
16259 with "my_lib";
16260 project My_Proj is
16261   @dots{}
16262 end My_Proj;
16263 @end smallexample
16264
16265 Even if you have a third-party, non-Ada library, you can still use GNAT's
16266 Project Manager facility to provide a wrapper for it. For example, the
16267 following project, when @code{with}ed by your main project, will link with the
16268 third-party library @file{liba.a}:
16269
16270 @smallexample @c projectfile
16271 @group
16272 project Liba is
16273    for Externally_Built use "true";
16274    for Source_Files use ();
16275    for Library_Dir use "lib";
16276    for Library_Name use "a";
16277    for Library_Kind use "static";
16278 end Liba;
16279 @end group
16280 @end smallexample
16281 This is an alternative to the use of @code{pragma Linker_Options}. It is
16282 especially interesting in the context of systems with several interdependent
16283 static libraries where finding a proper linker order is not easy and best be
16284 left to the tools having visibility over project dependence information.
16285
16286 @noindent
16287 In order to use an Ada library manually, you need to make sure that this
16288 library is on both your source and object path
16289 (see @ref{Search Paths and the Run-Time Library (RTL)}
16290 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16291 in an archive or a shared library, you need to specify the desired
16292 library at link time.
16293
16294 For example, you can use the library @file{mylib} installed in
16295 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16296
16297 @smallexample
16298 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16299   -largs -lmy_lib
16300 @end smallexample
16301
16302 @noindent
16303 This can be expressed more simply:
16304 @smallexample
16305 $ gnatmake my_appl
16306 @end smallexample
16307 @noindent
16308 when the following conditions are met:
16309 @itemize @bullet
16310 @item
16311 @file{/dir/my_lib_src} has been added by the user to the environment
16312 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16313 @file{ada_source_path}
16314 @item
16315 @file{/dir/my_lib_obj} has been added by the user to the environment
16316 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16317 @file{ada_object_path}
16318 @item
16319 a pragma @code{Linker_Options} has been added to one of the sources.
16320 For example:
16321
16322 @smallexample @c ada
16323 pragma Linker_Options ("-lmy_lib");
16324 @end smallexample
16325 @end itemize
16326
16327 @node Stand-alone Ada Libraries
16328 @section Stand-alone Ada Libraries
16329 @cindex Stand-alone library, building, using
16330
16331 @menu
16332 * Introduction to Stand-alone Libraries::
16333 * Building a Stand-alone Library::
16334 * Creating a Stand-alone Library to be used in a non-Ada context::
16335 * Restrictions in Stand-alone Libraries::
16336 @end menu
16337
16338 @node Introduction to Stand-alone Libraries
16339 @subsection Introduction to Stand-alone Libraries
16340
16341 @noindent
16342 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16343 necessary code to
16344 elaborate the Ada units that are included in the library. In contrast with
16345 an ordinary library, which consists of all sources, objects and @file{ALI}
16346 files of the
16347 library, a SAL may specify a restricted subset of compilation units
16348 to serve as a library interface. In this case, the fully
16349 self-sufficient set of files will normally consist of an objects
16350 archive, the sources of interface units' specs, and the @file{ALI}
16351 files of interface units.
16352 If an interface spec contains a generic unit or an inlined subprogram,
16353 the body's
16354 source must also be provided; if the units that must be provided in the source
16355 form depend on other units, the source and @file{ALI} files of those must
16356 also be provided.
16357
16358 The main purpose of a SAL is to minimize the recompilation overhead of client
16359 applications when a new version of the library is installed. Specifically,
16360 if the interface sources have not changed, client applications do not need to
16361 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16362 version, controlled by @code{Library_Version} attribute, is not changed,
16363 then the clients do not need to be relinked.
16364
16365 SALs also allow the library providers to minimize the amount of library source
16366 text exposed to the clients.  Such ``information hiding'' might be useful or
16367 necessary for various reasons.
16368
16369 Stand-alone libraries are also well suited to be used in an executable whose
16370 main routine is not written in Ada.
16371
16372 @node Building a Stand-alone Library
16373 @subsection Building a Stand-alone Library
16374
16375 @noindent
16376 GNAT's Project facility provides a simple way of building and installing
16377 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16378 To be a Stand-alone Library Project, in addition to the two attributes
16379 that make a project a Library Project (@code{Library_Name} and
16380 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16381 @code{Library_Interface} must be defined.  For example:
16382
16383 @smallexample @c projectfile
16384 @group
16385    for Library_Dir use "lib_dir";
16386    for Library_Name use "dummy";
16387    for Library_Interface use ("int1", "int1.child");
16388 @end group
16389 @end smallexample
16390
16391 @noindent
16392 Attribute @code{Library_Interface} has a non-empty string list value,
16393 each string in the list designating a unit contained in an immediate source
16394 of the project file.
16395
16396 When a Stand-alone Library is built, first the binder is invoked to build
16397 a package whose name depends on the library name
16398 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16399 This binder-generated package includes initialization and
16400 finalization procedures whose
16401 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16402 in the example
16403 above). The object corresponding to this package is included in the library.
16404
16405 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16406 calling of these procedures if a static SAL is built, or if a shared SAL
16407 is built
16408 with the project-level attribute @code{Library_Auto_Init} set to
16409 @code{"false"}.
16410
16411 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16412 (those that are listed in attribute @code{Library_Interface}) are copied to
16413 the Library Directory. As a consequence, only the Interface Units may be
16414 imported from Ada units outside of the library. If other units are imported,
16415 the binding phase will fail.
16416
16417 @noindent
16418 It is also possible to build an encapsulated library where not only
16419 the code to elaborate and finalize the library is embedded but also
16420 ensuring that the library is linked only against static
16421 libraries. So an encapsulated library only depends on system
16422 libraries, all other code, including the GNAT runtime, is embedded. To
16423 build an encapsulated library the attribute
16424 @code{Library_Standalone} must be set to @code{encapsulated}:
16425
16426 @smallexample @c projectfile
16427 @group
16428    for Library_Dir use "lib_dir";
16429    for Library_Name use "dummy";
16430    for Library_Interface use ("int1", "int1.child");
16431    for Library_Standalone use "encapsulated";
16432 @end group
16433 @end smallexample
16434
16435 @noindent
16436 The default value for this attribute is @code{standard} in which case
16437 a stand-alone library is built.
16438
16439 The attribute @code{Library_Src_Dir} may be specified for a
16440 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16441 single string value. Its value must be the path (absolute or relative to the
16442 project directory) of an existing directory. This directory cannot be the
16443 object directory or one of the source directories, but it can be the same as
16444 the library directory. The sources of the Interface
16445 Units of the library that are needed by an Ada client of the library will be
16446 copied to the designated directory, called the Interface Copy directory.
16447 These sources include the specs of the Interface Units, but they may also
16448 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16449 are used, or when there is a generic unit in the spec. Before the sources
16450 are copied to the Interface Copy directory, an attempt is made to delete all
16451 files in the Interface Copy directory.
16452
16453 Building stand-alone libraries by hand is somewhat tedious, but for those
16454 occasions when it is necessary here are the steps that you need to perform:
16455 @itemize @bullet
16456 @item
16457 Compile all library sources.
16458
16459 @item
16460 Invoke the binder with the switch @option{-n} (No Ada main program),
16461 with all the @file{ALI} files of the interfaces, and
16462 with the switch @option{-L} to give specific names to the @code{init}
16463 and @code{final} procedures.  For example:
16464 @smallexample
16465   gnatbind -n int1.ali int2.ali -Lsal1
16466 @end smallexample
16467
16468 @item
16469 Compile the binder generated file:
16470 @smallexample
16471   gcc -c b~int2.adb
16472 @end smallexample
16473
16474 @item
16475 Link the dynamic library with all the necessary object files,
16476 indicating to the linker the names of the @code{init} (and possibly
16477 @code{final}) procedures for automatic initialization (and finalization).
16478 The built library should be placed in a directory different from
16479 the object directory.
16480
16481 @item
16482 Copy the @code{ALI} files of the interface to the library directory,
16483 add in this copy an indication that it is an interface to a SAL
16484 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16485 with letter ``P'') and make the modified copy of the @file{ALI} file
16486 read-only.
16487 @end itemize
16488
16489 @noindent
16490 Using SALs is not different from using other libraries
16491 (see @ref{Using a library}).
16492
16493 @node Creating a Stand-alone Library to be used in a non-Ada context
16494 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16495
16496 @noindent
16497 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16498 a non-Ada context.
16499
16500 The only extra step required is to ensure that library interface subprograms
16501 are compatible with the main program, by means of @code{pragma Export}
16502 or @code{pragma Convention}.
16503
16504 Here is an example of simple library interface for use with C main program:
16505
16506 @smallexample @c ada
16507 package My_Package is
16508
16509    procedure Do_Something;
16510    pragma Export (C, Do_Something, "do_something");
16511
16512    procedure Do_Something_Else;
16513    pragma Export (C, Do_Something_Else, "do_something_else");
16514
16515 end My_Package;
16516 @end smallexample
16517
16518 @noindent
16519 On the foreign language side, you must provide a ``foreign'' view of the
16520 library interface; remember that it should contain elaboration routines in
16521 addition to interface subprograms.
16522
16523 The example below shows the content of @code{mylib_interface.h} (note
16524 that there is no rule for the naming of this file, any name can be used)
16525 @smallexample
16526 /* the library elaboration procedure */
16527 extern void mylibinit (void);
16528
16529 /* the library finalization procedure */
16530 extern void mylibfinal (void);
16531
16532 /* the interface exported by the library */
16533 extern void do_something (void);
16534 extern void do_something_else (void);
16535 @end smallexample
16536
16537 @noindent
16538 Libraries built as explained above can be used from any program, provided
16539 that the elaboration procedures (named @code{mylibinit} in the previous
16540 example) are called before the library services are used. Any number of
16541 libraries can be used simultaneously, as long as the elaboration
16542 procedure of each library is called.
16543
16544 Below is an example of a C program that uses the @code{mylib} library.
16545
16546 @smallexample
16547 #include "mylib_interface.h"
16548
16549 int
16550 main (void)
16551 @{
16552    /* First, elaborate the library before using it */
16553    mylibinit ();
16554
16555    /* Main program, using the library exported entities */
16556    do_something ();
16557    do_something_else ();
16558
16559    /* Library finalization at the end of the program */
16560    mylibfinal ();
16561    return 0;
16562 @}
16563 @end smallexample
16564
16565 @noindent
16566 Note that invoking any library finalization procedure generated by
16567 @code{gnatbind} shuts down the Ada run-time environment.
16568 Consequently, the
16569 finalization of all Ada libraries must be performed at the end of the program.
16570 No call to these libraries or to the Ada run-time library should be made
16571 after the finalization phase.
16572
16573 @node Restrictions in Stand-alone Libraries
16574 @subsection Restrictions in Stand-alone Libraries
16575
16576 @noindent
16577 The pragmas listed below should be used with caution inside libraries,
16578 as they can create incompatibilities with other Ada libraries:
16579 @itemize @bullet
16580 @item pragma @code{Locking_Policy}
16581 @item pragma @code{Queuing_Policy}
16582 @item pragma @code{Task_Dispatching_Policy}
16583 @item pragma @code{Unreserve_All_Interrupts}
16584 @end itemize
16585
16586 @noindent
16587 When using a library that contains such pragmas, the user must make sure
16588 that all libraries use the same pragmas with the same values. Otherwise,
16589 @code{Program_Error} will
16590 be raised during the elaboration of the conflicting
16591 libraries. The usage of these pragmas and its consequences for the user
16592 should therefore be well documented.
16593
16594 Similarly, the traceback in the exception occurrence mechanism should be
16595 enabled or disabled in a consistent manner across all libraries.
16596 Otherwise, Program_Error will be raised during the elaboration of the
16597 conflicting libraries.
16598
16599 If the @code{Version} or @code{Body_Version}
16600 attributes are used inside a library, then you need to
16601 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16602 libraries, so that version identifiers can be properly computed.
16603 In practice these attributes are rarely used, so this is unlikely
16604 to be a consideration.
16605
16606 @node  Rebuilding the GNAT Run-Time Library
16607 @section Rebuilding the GNAT Run-Time Library
16608 @cindex GNAT Run-Time Library, rebuilding
16609 @cindex Building the GNAT Run-Time Library
16610 @cindex Rebuilding the GNAT Run-Time Library
16611 @cindex Run-Time Library, rebuilding
16612
16613 @noindent
16614 It may be useful to recompile the GNAT library in various contexts, the
16615 most important one being the use of partition-wide configuration pragmas
16616 such as @code{Normalize_Scalars}. A special Makefile called
16617 @code{Makefile.adalib} is provided to that effect and can be found in
16618 the directory containing the GNAT library. The location of this
16619 directory depends on the way the GNAT environment has been installed and can
16620 be determined by means of the command:
16621
16622 @smallexample
16623 $ gnatls -v
16624 @end smallexample
16625
16626 @noindent
16627 The last entry in the object search path usually contains the
16628 gnat library. This Makefile contains its own documentation and in
16629 particular the set of instructions needed to rebuild a new library and
16630 to use it.
16631
16632 @node Using the GNU make Utility
16633 @chapter Using the GNU @code{make} Utility
16634 @findex make
16635
16636 @noindent
16637 This chapter offers some examples of makefiles that solve specific
16638 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16639 make, make, GNU @code{make}}), nor does it try to replace the
16640 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16641
16642 All the examples in this section are specific to the GNU version of
16643 make. Although @command{make} is a standard utility, and the basic language
16644 is the same, these examples use some advanced features found only in
16645 @code{GNU make}.
16646
16647 @menu
16648 * Using gnatmake in a Makefile::
16649 * Automatically Creating a List of Directories::
16650 * Generating the Command Line Switches::
16651 * Overcoming Command Line Length Limits::
16652 @end menu
16653
16654 @node Using gnatmake in a Makefile
16655 @section Using gnatmake in a Makefile
16656 @findex makefile
16657 @cindex GNU make
16658
16659 @noindent
16660 Complex project organizations can be handled in a very powerful way by
16661 using GNU make combined with gnatmake. For instance, here is a Makefile
16662 which allows you to build each subsystem of a big project into a separate
16663 shared library. Such a makefile allows you to significantly reduce the link
16664 time of very big applications while maintaining full coherence at
16665 each step of the build process.
16666
16667 The list of dependencies are handled automatically by
16668 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16669 the appropriate directories.
16670
16671 Note that you should also read the example on how to automatically
16672 create the list of directories
16673 (@pxref{Automatically Creating a List of Directories})
16674 which might help you in case your project has a lot of subdirectories.
16675
16676 @smallexample
16677 @iftex
16678 @leftskip=0cm
16679 @font@heightrm=cmr8
16680 @heightrm
16681 @end iftex
16682 ## This Makefile is intended to be used with the following directory
16683 ## configuration:
16684 ##  - The sources are split into a series of csc (computer software components)
16685 ##    Each of these csc is put in its own directory.
16686 ##    Their name are referenced by the directory names.
16687 ##    They will be compiled into shared library (although this would also work
16688 ##    with static libraries
16689 ##  - The main program (and possibly other packages that do not belong to any
16690 ##    csc is put in the top level directory (where the Makefile is).
16691 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16692 ##                    \_ second_csc (sources) __ lib (will contain the library)
16693 ##                    \_ @dots{}
16694 ## Although this Makefile is build for shared library, it is easy to modify
16695 ## to build partial link objects instead (modify the lines with -shared and
16696 ## gnatlink below)
16697 ##
16698 ## With this makefile, you can change any file in the system or add any new
16699 ## file, and everything will be recompiled correctly (only the relevant shared
16700 ## objects will be recompiled, and the main program will be re-linked).
16701
16702 # The list of computer software component for your project. This might be
16703 # generated automatically.
16704 CSC_LIST=aa bb cc
16705
16706 # Name of the main program (no extension)
16707 MAIN=main
16708
16709 # If we need to build objects with -fPIC, uncomment the following line
16710 #NEED_FPIC=-fPIC
16711
16712 # The following variable should give the directory containing libgnat.so
16713 # You can get this directory through 'gnatls -v'. This is usually the last
16714 # directory in the Object_Path.
16715 GLIB=@dots{}
16716
16717 # The directories for the libraries
16718 # (This macro expands the list of CSC to the list of shared libraries, you
16719 # could simply use the expanded form:
16720 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16721 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16722
16723 $@{MAIN@}: objects $@{LIB_DIR@}
16724     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16725     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16726
16727 objects::
16728     # recompile the sources
16729     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16730
16731 # Note: In a future version of GNAT, the following commands will be simplified
16732 # by a new tool, gnatmlib
16733 $@{LIB_DIR@}:
16734     mkdir -p $@{dir $@@ @}
16735     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16736     cd $@{dir $@@ @} && cp -f ../*.ali .
16737
16738 # The dependencies for the modules
16739 # Note that we have to force the expansion of *.o, since in some cases
16740 # make won't be able to do it itself.
16741 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16742 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16743 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16744
16745 # Make sure all of the shared libraries are in the path before starting the
16746 # program
16747 run::
16748     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16749
16750 clean::
16751     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16752     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16753     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16754     $@{RM@} *.o *.ali $@{MAIN@}
16755 @end smallexample
16756
16757 @node Automatically Creating a List of Directories
16758 @section Automatically Creating a List of Directories
16759
16760 @noindent
16761 In most makefiles, you will have to specify a list of directories, and
16762 store it in a variable. For small projects, it is often easier to
16763 specify each of them by hand, since you then have full control over what
16764 is the proper order for these directories, which ones should be
16765 included.
16766
16767 However, in larger projects, which might involve hundreds of
16768 subdirectories, it might be more convenient to generate this list
16769 automatically.
16770
16771 The example below presents two methods. The first one, although less
16772 general, gives you more control over the list. It involves wildcard
16773 characters, that are automatically expanded by @command{make}. Its
16774 shortcoming is that you need to explicitly specify some of the
16775 organization of your project, such as for instance the directory tree
16776 depth, whether some directories are found in a separate tree, @enddots{}
16777
16778 The second method is the most general one. It requires an external
16779 program, called @command{find}, which is standard on all Unix systems. All
16780 the directories found under a given root directory will be added to the
16781 list.
16782
16783 @smallexample
16784 @iftex
16785 @leftskip=0cm
16786 @font@heightrm=cmr8
16787 @heightrm
16788 @end iftex
16789 # The examples below are based on the following directory hierarchy:
16790 # All the directories can contain any number of files
16791 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16792 #                       ->  ab
16793 #                       ->  ac
16794 #                ->  b  ->  ba  ->  baa
16795 #                       ->  bb
16796 #                       ->  bc
16797 # This Makefile creates a variable called DIRS, that can be reused any time
16798 # you need this list (see the other examples in this section)
16799
16800 # The root of your project's directory hierarchy
16801 ROOT_DIRECTORY=.
16802
16803 ####
16804 # First method: specify explicitly the list of directories
16805 # This allows you to specify any subset of all the directories you need.
16806 ####
16807
16808 DIRS := a/aa/ a/ab/ b/ba/
16809
16810 ####
16811 # Second method: use wildcards
16812 # Note that the argument(s) to wildcard below should end with a '/'.
16813 # Since wildcards also return file names, we have to filter them out
16814 # to avoid duplicate directory names.
16815 # We thus use make's @code{dir} and @code{sort} functions.
16816 # It sets DIRs to the following value (note that the directories aaa and baa
16817 # are not given, unless you change the arguments to wildcard).
16818 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16819 ####
16820
16821 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16822                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16823
16824 ####
16825 # Third method: use an external program
16826 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16827 # This is the most complete command: it sets DIRs to the following value:
16828 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16829 ####
16830
16831 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16832
16833 @end smallexample
16834
16835 @node Generating the Command Line Switches
16836 @section Generating the Command Line Switches
16837
16838 @noindent
16839 Once you have created the list of directories as explained in the
16840 previous section (@pxref{Automatically Creating a List of Directories}),
16841 you can easily generate the command line arguments to pass to gnatmake.
16842
16843 For the sake of completeness, this example assumes that the source path
16844 is not the same as the object path, and that you have two separate lists
16845 of directories.
16846
16847 @smallexample
16848 # see "Automatically creating a list of directories" to create
16849 # these variables
16850 SOURCE_DIRS=
16851 OBJECT_DIRS=
16852
16853 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16854 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16855
16856 all:
16857         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16858 @end smallexample
16859
16860 @node Overcoming Command Line Length Limits
16861 @section Overcoming Command Line Length Limits
16862
16863 @noindent
16864 One problem that might be encountered on big projects is that many
16865 operating systems limit the length of the command line. It is thus hard to give
16866 gnatmake the list of source and object directories.
16867
16868 This example shows how you can set up environment variables, which will
16869 make @command{gnatmake} behave exactly as if the directories had been
16870 specified on the command line, but have a much higher length limit (or
16871 even none on most systems).
16872
16873 It assumes that you have created a list of directories in your Makefile,
16874 using one of the methods presented in
16875 @ref{Automatically Creating a List of Directories}.
16876 For the sake of completeness, we assume that the object
16877 path (where the ALI files are found) is different from the sources patch.
16878
16879 Note a small trick in the Makefile below: for efficiency reasons, we
16880 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16881 expanded immediately by @code{make}. This way we overcome the standard
16882 make behavior which is to expand the variables only when they are
16883 actually used.
16884
16885 On Windows, if you are using the standard Windows command shell, you must
16886 replace colons with semicolons in the assignments to these variables.
16887
16888 @smallexample
16889 @iftex
16890 @leftskip=0cm
16891 @font@heightrm=cmr8
16892 @heightrm
16893 @end iftex
16894 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16895 # This is the same thing as putting the -I arguments on the command line.
16896 # (the equivalent of using -aI on the command line would be to define
16897 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16898 # You can of course have different values for these variables.
16899 #
16900 # Note also that we need to keep the previous values of these variables, since
16901 # they might have been set before running 'make' to specify where the GNAT
16902 # library is installed.
16903
16904 # see "Automatically creating a list of directories" to create these
16905 # variables
16906 SOURCE_DIRS=
16907 OBJECT_DIRS=
16908
16909 empty:=
16910 space:=$@{empty@} $@{empty@}
16911 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16912 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16913 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16914 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16915 export ADA_INCLUDE_PATH
16916 export ADA_OBJECTS_PATH
16917
16918 all:
16919         gnatmake main_unit
16920 @end smallexample
16921 @end ifclear
16922
16923 @node Memory Management Issues
16924 @chapter Memory Management Issues
16925
16926 @noindent
16927 This chapter describes some useful memory pools provided in the GNAT library
16928 and in particular the GNAT Debug Pool facility, which can be used to detect
16929 incorrect uses of access values (including ``dangling references'').
16930 @ifclear vms
16931 It also describes the @command{gnatmem} tool, which can be used to track down
16932 ``memory leaks''.
16933 @end ifclear
16934
16935 @menu
16936 * Some Useful Memory Pools::
16937 * The GNAT Debug Pool Facility::
16938 @ifclear vms
16939 * The gnatmem Tool::
16940 @end ifclear
16941 @end menu
16942
16943 @node Some Useful Memory Pools
16944 @section Some Useful Memory Pools
16945 @findex Memory Pool
16946 @cindex storage, pool
16947
16948 @noindent
16949 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16950 storage pool. Allocations use the standard system call @code{malloc} while
16951 deallocations use the standard system call @code{free}. No reclamation is
16952 performed when the pool goes out of scope. For performance reasons, the
16953 standard default Ada allocators/deallocators do not use any explicit storage
16954 pools but if they did, they could use this storage pool without any change in
16955 behavior. That is why this storage pool is used  when the user
16956 manages to make the default implicit allocator explicit as in this example:
16957 @smallexample @c ada
16958    type T1 is access Something;
16959     -- no Storage pool is defined for T2
16960    type T2 is access Something_Else;
16961    for T2'Storage_Pool use T1'Storage_Pool;
16962    -- the above is equivalent to
16963    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16964 @end smallexample
16965
16966 @noindent
16967 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16968 pool. The allocation strategy is similar to @code{Pool_Local}'s
16969 except that the all
16970 storage allocated with this pool is reclaimed when the pool object goes out of
16971 scope. This pool provides a explicit mechanism similar to the implicit one
16972 provided by several Ada 83 compilers for allocations performed through a local
16973 access type and whose purpose was to reclaim memory when exiting the
16974 scope of a given local access. As an example, the following program does not
16975 leak memory even though it does not perform explicit deallocation:
16976
16977 @smallexample @c ada
16978 with System.Pool_Local;
16979 procedure Pooloc1 is
16980    procedure Internal is
16981       type A is access Integer;
16982       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16983       for A'Storage_Pool use X;
16984       v : A;
16985    begin
16986       for I in  1 .. 50 loop
16987          v := new Integer;
16988       end loop;
16989    end Internal;
16990 begin
16991    for I in  1 .. 100 loop
16992       Internal;
16993    end loop;
16994 end Pooloc1;
16995 @end smallexample
16996
16997 @noindent
16998 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16999 @code{Storage_Size} is specified for an access type.
17000 The whole storage for the pool is
17001 allocated at once, usually on the stack at the point where the access type is
17002 elaborated. It is automatically reclaimed when exiting the scope where the
17003 access type is defined. This package is not intended to be used directly by the
17004 user and it is implicitly used for each such declaration:
17005
17006 @smallexample @c ada
17007    type T1 is access Something;
17008    for T1'Storage_Size use 10_000;
17009 @end smallexample
17010
17011 @node The GNAT Debug Pool Facility
17012 @section The GNAT Debug Pool Facility
17013 @findex Debug Pool
17014 @cindex storage, pool, memory corruption
17015
17016 @noindent
17017 The use of unchecked deallocation and unchecked conversion can easily
17018 lead to incorrect memory references. The problems generated by such
17019 references are usually difficult to tackle because the symptoms can be
17020 very remote from the origin of the problem. In such cases, it is
17021 very helpful to detect the problem as early as possible. This is the
17022 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17023
17024 In order to use the GNAT specific debugging pool, the user must
17025 associate a debug pool object with each of the access types that may be
17026 related to suspected memory problems. See Ada Reference Manual 13.11.
17027 @smallexample @c ada
17028 type Ptr is access Some_Type;
17029 Pool : GNAT.Debug_Pools.Debug_Pool;
17030 for Ptr'Storage_Pool use Pool;
17031 @end smallexample
17032
17033 @noindent
17034 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17035 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17036 allow the user to redefine allocation and deallocation strategies. They
17037 also provide a checkpoint for each dereference, through the use of
17038 the primitive operation @code{Dereference} which is implicitly called at
17039 each dereference of an access value.
17040
17041 Once an access type has been associated with a debug pool, operations on
17042 values of the type may raise four distinct exceptions,
17043 which correspond to four potential kinds of memory corruption:
17044 @itemize @bullet
17045 @item
17046 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17047 @item
17048 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17049 @item
17050 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17051 @item
17052 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17053 @end itemize
17054
17055 @noindent
17056 For types associated with a Debug_Pool, dynamic allocation is performed using
17057 the standard GNAT allocation routine. References to all allocated chunks of
17058 memory are kept in an internal dictionary. Several deallocation strategies are
17059 provided, whereupon the user can choose to release the memory to the system,
17060 keep it allocated for further invalid access checks, or fill it with an easily
17061 recognizable pattern for debug sessions. The memory pattern is the old IBM
17062 hexadecimal convention: @code{16#DEADBEEF#}.
17063
17064 See the documentation in the file g-debpoo.ads for more information on the
17065 various strategies.
17066
17067 Upon each dereference, a check is made that the access value denotes a
17068 properly allocated memory location. Here is a complete example of use of
17069 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17070 @smallexample @c ada
17071 @iftex
17072 @leftskip=0cm
17073 @end iftex
17074 with Gnat.Io; use Gnat.Io;
17075 with Unchecked_Deallocation;
17076 with Unchecked_Conversion;
17077 with GNAT.Debug_Pools;
17078 with System.Storage_Elements;
17079 with Ada.Exceptions; use Ada.Exceptions;
17080 procedure Debug_Pool_Test is
17081
17082    type T is access Integer;
17083    type U is access all T;
17084
17085    P : GNAT.Debug_Pools.Debug_Pool;
17086    for T'Storage_Pool use P;
17087
17088    procedure Free is new Unchecked_Deallocation (Integer, T);
17089    function UC is new Unchecked_Conversion (U, T);
17090    A, B : aliased T;
17091
17092    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17093
17094 begin
17095    Info (P);
17096    A := new Integer;
17097    B := new Integer;
17098    B := A;
17099    Info (P);
17100    Free (A);
17101    begin
17102       Put_Line (Integer'Image(B.all));
17103    exception
17104       when E : others => Put_Line ("raised: " & Exception_Name (E));
17105    end;
17106    begin
17107       Free (B);
17108    exception
17109       when E : others => Put_Line ("raised: " & Exception_Name (E));
17110    end;
17111    B := UC(A'Access);
17112    begin
17113       Put_Line (Integer'Image(B.all));
17114    exception
17115       when E : others => Put_Line ("raised: " & Exception_Name (E));
17116    end;
17117    begin
17118       Free (B);
17119    exception
17120       when E : others => Put_Line ("raised: " & Exception_Name (E));
17121    end;
17122    Info (P);
17123 end Debug_Pool_Test;
17124 @end smallexample
17125
17126 @noindent
17127 The debug pool mechanism provides the following precise diagnostics on the
17128 execution of this erroneous program:
17129 @smallexample
17130 Debug Pool info:
17131   Total allocated bytes :  0
17132   Total deallocated bytes :  0
17133   Current Water Mark:  0
17134   High Water Mark:  0
17135
17136 Debug Pool info:
17137   Total allocated bytes :  8
17138   Total deallocated bytes :  0
17139   Current Water Mark:  8
17140   High Water Mark:  8
17141
17142 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17143 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17144 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17145 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17146 Debug Pool info:
17147   Total allocated bytes :  8
17148   Total deallocated bytes :  4
17149   Current Water Mark:  4
17150   High Water Mark:  8
17151 @end smallexample
17152
17153 @ifclear vms
17154 @node The gnatmem Tool
17155 @section The @command{gnatmem} Tool
17156 @findex gnatmem
17157
17158 @noindent
17159 The @code{gnatmem} utility monitors dynamic allocation and
17160 deallocation activity in a program, and displays information about
17161 incorrect deallocations and possible sources of memory leaks.
17162 It is designed to work in association with a static runtime library
17163 only and in this context provides three types of information:
17164 @itemize @bullet
17165 @item
17166 General information concerning memory management, such as the total
17167 number of allocations and deallocations, the amount of allocated
17168 memory and the high water mark, i.e.@: the largest amount of allocated
17169 memory in the course of program execution.
17170
17171 @item
17172 Backtraces for all incorrect deallocations, that is to say deallocations
17173 which do not correspond to a valid allocation.
17174
17175 @item
17176 Information on each allocation that is potentially the origin of a memory
17177 leak.
17178 @end itemize
17179
17180 @menu
17181 * Running gnatmem::
17182 * Switches for gnatmem::
17183 * Example of gnatmem Usage::
17184 @end menu
17185
17186 @node Running gnatmem
17187 @subsection Running @code{gnatmem}
17188
17189 @noindent
17190 @code{gnatmem} makes use of the output created by the special version of
17191 allocation and deallocation routines that record call information. This
17192 allows to obtain accurate dynamic memory usage history at a minimal cost to
17193 the execution speed. Note however, that @code{gnatmem} is not supported on
17194 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17195 Solaris and Windows NT/2000/XP (x86).
17196
17197 @noindent
17198 The @code{gnatmem} command has the form
17199
17200 @smallexample
17201 @c    $ gnatmem @ovar{switches} user_program
17202 @c Expanding @ovar macro inline (explanation in macro def comments)
17203       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17204 @end smallexample
17205
17206 @noindent
17207 The program must have been linked with the instrumented version of the
17208 allocation and deallocation routines. This is done by linking with the
17209 @file{libgmem.a} library. For correct symbolic backtrace information,
17210 the user program should be compiled with debugging options
17211 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17212
17213 @smallexample
17214 $ gnatmake -g my_program -largs -lgmem
17215 @end smallexample
17216
17217 @noindent
17218 As library @file{libgmem.a} contains an alternate body for package
17219 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17220 when an executable is linked with library @file{libgmem.a}. It is then not
17221 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17222
17223 @noindent
17224 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17225 This file contains information about all allocations and deallocations
17226 performed by the program. It is produced by the instrumented allocations and
17227 deallocations routines and will be used by @code{gnatmem}.
17228
17229 In order to produce symbolic backtrace information for allocations and
17230 deallocations performed by the GNAT run-time library, you need to use a
17231 version of that library that has been compiled with the @option{-g} switch
17232 (see @ref{Rebuilding the GNAT Run-Time Library}).
17233
17234 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17235 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17236 @option{-i} switch, gnatmem will assume that this file can be found in the
17237 current directory. For example, after you have executed @file{my_program},
17238 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17239
17240 @smallexample
17241 $ gnatmem my_program
17242 @end smallexample
17243
17244 @noindent
17245 This will produce the output with the following format:
17246
17247 *************** debut cc
17248 @smallexample
17249 $ gnatmem my_program
17250
17251 Global information
17252 ------------------
17253    Total number of allocations        :  45
17254    Total number of deallocations      :   6
17255    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17256    High Water Mark                    :  11.40 Kilobytes
17257
17258 .
17259 .
17260 .
17261 Allocation Root # 2
17262 -------------------
17263  Number of non freed allocations    :  11
17264  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17265  High Water Mark                    :   1.27 Kilobytes
17266  Backtrace                          :
17267    my_program.adb:23 my_program.alloc
17268 .
17269 .
17270 .
17271 @end smallexample
17272
17273 The first block of output gives general information. In this case, the
17274 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17275 Unchecked_Deallocation routine occurred.
17276
17277 @noindent
17278 Subsequent paragraphs display  information on all allocation roots.
17279 An allocation root is a specific point in the execution of the program
17280 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17281 construct. This root is represented by an execution backtrace (or subprogram
17282 call stack). By default the backtrace depth for allocations roots is 1, so
17283 that a root corresponds exactly to a source location. The backtrace can
17284 be made deeper, to make the root more specific.
17285
17286 @node Switches for gnatmem
17287 @subsection Switches for @code{gnatmem}
17288
17289 @noindent
17290 @code{gnatmem} recognizes the following switches:
17291
17292 @table @option
17293
17294 @item -q
17295 @cindex @option{-q} (@code{gnatmem})
17296 Quiet. Gives the minimum output needed to identify the origin of the
17297 memory leaks. Omits statistical information.
17298
17299 @item @var{N}
17300 @cindex @var{N} (@code{gnatmem})
17301 N is an integer literal (usually between 1 and 10) which controls the
17302 depth of the backtraces defining allocation root. The default value for
17303 N is 1. The deeper the backtrace, the more precise the localization of
17304 the root. Note that the total number of roots can depend on this
17305 parameter. This parameter must be specified @emph{before} the name of the
17306 executable to be analyzed, to avoid ambiguity.
17307
17308 @item -b n
17309 @cindex @option{-b} (@code{gnatmem})
17310 This switch has the same effect as just depth parameter.
17311
17312 @item -i @var{file}
17313 @cindex @option{-i} (@code{gnatmem})
17314 Do the @code{gnatmem} processing starting from @file{file}, rather than
17315 @file{gmem.out} in the current directory.
17316
17317 @item -m n
17318 @cindex @option{-m} (@code{gnatmem})
17319 This switch causes @code{gnatmem} to mask the allocation roots that have less
17320 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17321 examine even the roots that didn't result in leaks.
17322
17323 @item -s order
17324 @cindex @option{-s} (@code{gnatmem})
17325 This switch causes @code{gnatmem} to sort the allocation roots according to the
17326 specified order of sort criteria, each identified by a single letter. The
17327 currently supported criteria are @code{n, h, w} standing respectively for
17328 number of unfreed allocations, high watermark, and final watermark
17329 corresponding to a specific root. The default order is @code{nwh}.
17330
17331 @end table
17332
17333 @node Example of gnatmem Usage
17334 @subsection Example of @code{gnatmem} Usage
17335
17336 @noindent
17337 The following example shows the use of @code{gnatmem}
17338 on a simple memory-leaking program.
17339 Suppose that we have the following Ada program:
17340
17341 @smallexample @c ada
17342 @group
17343 @cartouche
17344 with Unchecked_Deallocation;
17345 procedure Test_Gm is
17346
17347    type T is array (1..1000) of Integer;
17348    type Ptr is access T;
17349    procedure Free is new Unchecked_Deallocation (T, Ptr);
17350    A : Ptr;
17351
17352    procedure My_Alloc is
17353    begin
17354       A := new T;
17355    end My_Alloc;
17356
17357    procedure My_DeAlloc is
17358       B : Ptr := A;
17359    begin
17360       Free (B);
17361    end My_DeAlloc;
17362
17363 begin
17364    My_Alloc;
17365    for I in 1 .. 5 loop
17366       for J in I .. 5 loop
17367          My_Alloc;
17368       end loop;
17369       My_Dealloc;
17370    end loop;
17371 end;
17372 @end cartouche
17373 @end group
17374 @end smallexample
17375
17376 @noindent
17377 The program needs to be compiled with debugging option and linked with
17378 @code{gmem} library:
17379
17380 @smallexample
17381 $ gnatmake -g test_gm -largs -lgmem
17382 @end smallexample
17383
17384 @noindent
17385 Then we execute the program as usual:
17386
17387 @smallexample
17388 $ test_gm
17389 @end smallexample
17390
17391 @noindent
17392 Then @code{gnatmem} is invoked simply with
17393 @smallexample
17394 $ gnatmem test_gm
17395 @end smallexample
17396
17397 @noindent
17398 which produces the following output (result may vary on different platforms):
17399
17400 @smallexample
17401 Global information
17402 ------------------
17403    Total number of allocations        :  18
17404    Total number of deallocations      :   5
17405    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17406    High Water Mark                    :  56.90 Kilobytes
17407
17408 Allocation Root # 1
17409 -------------------
17410  Number of non freed allocations    :  11
17411  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17412  High Water Mark                    :  46.88 Kilobytes
17413  Backtrace                          :
17414    test_gm.adb:11 test_gm.my_alloc
17415
17416 Allocation Root # 2
17417 -------------------
17418  Number of non freed allocations    :   1
17419  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17420  High Water Mark                    :  10.02 Kilobytes
17421  Backtrace                          :
17422    s-secsta.adb:81 system.secondary_stack.ss_init
17423
17424 Allocation Root # 3
17425 -------------------
17426  Number of non freed allocations    :   1
17427  Final Water Mark (non freed mem)   :  12 Bytes
17428  High Water Mark                    :  12 Bytes
17429  Backtrace                          :
17430    s-secsta.adb:181 system.secondary_stack.ss_init
17431 @end smallexample
17432
17433 @noindent
17434 Note that the GNAT run time contains itself a certain number of
17435 allocations that have no  corresponding deallocation,
17436 as shown here for root #2 and root
17437 #3. This is a normal behavior when the number of non-freed allocations
17438 is one, it allocates dynamic data structures that the run time needs for
17439 the complete lifetime of the program. Note also that there is only one
17440 allocation root in the user program with a single line back trace:
17441 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17442 program shows that 'My_Alloc' is called at 2 different points in the
17443 source (line 21 and line 24). If those two allocation roots need to be
17444 distinguished, the backtrace depth parameter can be used:
17445
17446 @smallexample
17447 $ gnatmem 3 test_gm
17448 @end smallexample
17449
17450 @noindent
17451 which will give the following output:
17452
17453 @smallexample
17454 Global information
17455 ------------------
17456    Total number of allocations        :  18
17457    Total number of deallocations      :   5
17458    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17459    High Water Mark                    :  56.90 Kilobytes
17460
17461 Allocation Root # 1
17462 -------------------
17463  Number of non freed allocations    :  10
17464  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17465  High Water Mark                    :  42.97 Kilobytes
17466  Backtrace                          :
17467    test_gm.adb:11 test_gm.my_alloc
17468    test_gm.adb:24 test_gm
17469    b_test_gm.c:52 main
17470
17471 Allocation Root # 2
17472 -------------------
17473  Number of non freed allocations    :   1
17474  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17475  High Water Mark                    :  10.02 Kilobytes
17476  Backtrace                          :
17477    s-secsta.adb:81  system.secondary_stack.ss_init
17478    s-secsta.adb:283 <system__secondary_stack___elabb>
17479    b_test_gm.c:33   adainit
17480
17481 Allocation Root # 3
17482 -------------------
17483  Number of non freed allocations    :   1
17484  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17485  High Water Mark                    :   3.91 Kilobytes
17486  Backtrace                          :
17487    test_gm.adb:11 test_gm.my_alloc
17488    test_gm.adb:21 test_gm
17489    b_test_gm.c:52 main
17490
17491 Allocation Root # 4
17492 -------------------
17493  Number of non freed allocations    :   1
17494  Final Water Mark (non freed mem)   :  12 Bytes
17495  High Water Mark                    :  12 Bytes
17496  Backtrace                          :
17497    s-secsta.adb:181 system.secondary_stack.ss_init
17498    s-secsta.adb:283 <system__secondary_stack___elabb>
17499    b_test_gm.c:33   adainit
17500 @end smallexample
17501
17502 @noindent
17503 The allocation root #1 of the first example has been split in 2 roots #1
17504 and #3 thanks to the more precise associated backtrace.
17505
17506 @end ifclear
17507
17508 @node Stack Related Facilities
17509 @chapter Stack Related Facilities
17510
17511 @noindent
17512 This chapter describes some useful tools associated with stack
17513 checking and analysis. In
17514 particular, it deals with dynamic and static stack usage measurements.
17515
17516 @menu
17517 * Stack Overflow Checking::
17518 * Static Stack Usage Analysis::
17519 * Dynamic Stack Usage Analysis::
17520 @end menu
17521
17522 @node Stack Overflow Checking
17523 @section Stack Overflow Checking
17524 @cindex Stack Overflow Checking
17525 @cindex -fstack-check
17526
17527 @noindent
17528 For most operating systems, @command{gcc} does not perform stack overflow
17529 checking by default. This means that if the main environment task or
17530 some other task exceeds the available stack space, then unpredictable
17531 behavior will occur. Most native systems offer some level of protection by
17532 adding a guard page at the end of each task stack. This mechanism is usually
17533 not enough for dealing properly with stack overflow situations because
17534 a large local variable could ``jump'' above the guard page.
17535 Furthermore, when the
17536 guard page is hit, there may not be any space left on the stack for executing
17537 the exception propagation code. Enabling stack checking avoids
17538 such situations.
17539
17540 To activate stack checking, compile all units with the gcc option
17541 @option{-fstack-check}. For example:
17542
17543 @smallexample
17544 gcc -c -fstack-check package1.adb
17545 @end smallexample
17546
17547 @noindent
17548 Units compiled with this option will generate extra instructions to check
17549 that any use of the stack (for procedure calls or for declaring local
17550 variables in declare blocks) does not exceed the available stack space.
17551 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17552
17553 For declared tasks, the stack size is controlled by the size
17554 given in an applicable @code{Storage_Size} pragma or by the value specified
17555 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17556 the default size as defined in the GNAT runtime otherwise.
17557
17558 For the environment task, the stack size depends on
17559 system defaults and is unknown to the compiler. Stack checking
17560 may still work correctly if a fixed
17561 size stack is allocated, but this cannot be guaranteed.
17562 @ifclear vms
17563 To ensure that a clean exception is signalled for stack
17564 overflow, set the environment variable
17565 @env{GNAT_STACK_LIMIT} to indicate the maximum
17566 stack area that can be used, as in:
17567 @cindex GNAT_STACK_LIMIT
17568
17569 @smallexample
17570 SET GNAT_STACK_LIMIT 1600
17571 @end smallexample
17572
17573 @noindent
17574 The limit is given in kilobytes, so the above declaration would
17575 set the stack limit of the environment task to 1.6 megabytes.
17576 Note that the only purpose of this usage is to limit the amount
17577 of stack used by the environment task. If it is necessary to
17578 increase the amount of stack for the environment task, then this
17579 is an operating systems issue, and must be addressed with the
17580 appropriate operating systems commands.
17581 @end ifclear
17582 @ifset vms
17583 To have a fixed size stack in the environment task, the stack must be put
17584 in the P0 address space and its size specified.  Use these switches to
17585 create a p0 image:
17586
17587 @smallexample
17588 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17589 @end smallexample
17590
17591 @noindent
17592 The quotes are required to keep case.  The number after @samp{STACK=} is the
17593 size of the environmental task stack in pagelets (512 bytes).  In this example
17594 the stack size is about 2 megabytes.
17595
17596 @noindent
17597 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17598 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17599 more details about the @option{/p0image} qualifier and the @option{stack}
17600 option.
17601
17602 @noindent
17603 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17604 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17605 stack in kilobytes.  For example:
17606
17607 @smallexample
17608 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17609 @end smallexample
17610 @end ifset
17611
17612 @node Static Stack Usage Analysis
17613 @section Static Stack Usage Analysis
17614 @cindex Static Stack Usage Analysis
17615 @cindex -fstack-usage
17616
17617 @noindent
17618 A unit compiled with @option{-fstack-usage} will generate an extra file
17619 that specifies
17620 the maximum amount of stack used, on a per-function basis.
17621 The file has the same
17622 basename as the target object file with a @file{.su} extension.
17623 Each line of this file is made up of three fields:
17624
17625 @itemize
17626 @item
17627 The name of the function.
17628 @item
17629 A number of bytes.
17630 @item
17631 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17632 @end itemize
17633
17634 The second field corresponds to the size of the known part of the function
17635 frame.
17636
17637 The qualifier @code{static} means that the function frame size
17638 is purely static.
17639 It usually means that all local variables have a static size.
17640 In this case, the second field is a reliable measure of the function stack
17641 utilization.
17642
17643 The qualifier @code{dynamic} means that the function frame size is not static.
17644 It happens mainly when some local variables have a dynamic size. When this
17645 qualifier appears alone, the second field is not a reliable measure
17646 of the function stack analysis. When it is qualified with  @code{bounded}, it
17647 means that the second field is a reliable maximum of the function stack
17648 utilization.
17649
17650 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17651 subprogram whose stack usage might be larger than the specified amount of
17652 bytes.  The wording is in keeping with the qualifier documented above.
17653
17654 @node Dynamic Stack Usage Analysis
17655 @section Dynamic Stack Usage Analysis
17656
17657 @noindent
17658 It is possible to measure the maximum amount of stack used by a task, by
17659 adding a switch to @command{gnatbind}, as:
17660
17661 @smallexample
17662 $ gnatbind -u0 file
17663 @end smallexample
17664
17665 @noindent
17666 With this option, at each task termination, its stack usage is  output on
17667 @file{stderr}.
17668 It is not always convenient to output the stack usage when the program
17669 is still running. Hence, it is possible to delay this output until program
17670 termination. for a given number of tasks specified as the argument of the
17671 @option{-u} option. For instance:
17672
17673 @smallexample
17674 $ gnatbind -u100 file
17675 @end smallexample
17676
17677 @noindent
17678 will buffer the stack usage information of the first 100 tasks to terminate and
17679 output this info at program termination. Results are displayed in four
17680 columns:
17681
17682 @noindent
17683 Index | Task Name | Stack Size | Stack Usage
17684
17685 @noindent
17686 where:
17687
17688 @table @emph
17689 @item Index
17690 is a number associated with each task.
17691
17692 @item Task Name
17693 is the name of the task analyzed.
17694
17695 @item Stack Size
17696 is the maximum size for the stack.
17697
17698 @item Stack Usage
17699 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17700 is not entirely analyzed, and it's not possible to know exactly how
17701 much has actually been used.
17702
17703 @end table
17704
17705 @noindent
17706 The environment task stack, e.g., the stack that contains the main unit, is
17707 only processed when the environment variable GNAT_STACK_LIMIT is set.
17708
17709 @noindent
17710 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17711 stack usage reports at run-time. See its body for the details.
17712
17713 @c *********************************
17714 @c *            GNATCHECK          *
17715 @c *********************************
17716 @node Verifying Properties Using gnatcheck
17717 @chapter Verifying Properties Using @command{gnatcheck}
17718 @findex gnatcheck
17719 @cindex @command{gnatcheck}
17720
17721 @noindent
17722 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17723 of Ada source files according to a given set of semantic rules.
17724 @cindex ASIS
17725
17726 In order to check compliance with a given rule, @command{gnatcheck} has to
17727 semantically analyze the Ada sources.
17728 Therefore, checks can only be performed on
17729 legal Ada units. Moreover, when a unit depends semantically upon units located
17730 outside the current directory, the source search path has to be provided when
17731 calling @command{gnatcheck}, either through a specified project file or
17732 through @command{gnatcheck} switches.
17733
17734 For full details, refer to @cite{GNATcheck Reference Manual} document.
17735
17736
17737 @c *********************************
17738 @node Creating Sample Bodies Using gnatstub
17739 @chapter Creating Sample Bodies Using @command{gnatstub}
17740 @findex gnatstub
17741
17742 @noindent
17743 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17744 for library unit declarations.
17745
17746 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17747 driver (see @ref{The GNAT Driver and Project Files}).
17748
17749 To create a body stub, @command{gnatstub} has to compile the library
17750 unit declaration. Therefore, bodies can be created only for legal
17751 library units. Moreover, if a library unit depends semantically upon
17752 units located outside the current directory, you have to provide
17753 the source search path when calling @command{gnatstub}, see the description
17754 of @command{gnatstub} switches below.
17755
17756 By default, all the program unit body stubs generated by @code{gnatstub}
17757 raise the predefined @code{Program_Error} exception, which will catch
17758 accidental calls of generated stubs. This behavior can be changed with
17759 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17760
17761 @menu
17762 * Running gnatstub::
17763 * Switches for gnatstub::
17764 @end menu
17765
17766 @node Running gnatstub
17767 @section Running @command{gnatstub}
17768
17769 @noindent
17770 @command{gnatstub} has a command-line interface of the form:
17771
17772 @smallexample
17773 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17774 @c Expanding @ovar macro inline (explanation in macro def comments)
17775 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17776 @end smallexample
17777
17778 @noindent
17779 where
17780 @table @var
17781 @item filename
17782 is the name of the source file that contains a library unit declaration
17783 for which a body must be created. The file name may contain the path
17784 information.
17785 The file name does not have to follow the GNAT file name conventions. If the
17786 name
17787 does not follow GNAT file naming conventions, the name of the body file must
17788 be provided
17789 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17790 If the file name follows the GNAT file naming
17791 conventions and the name of the body file is not provided,
17792 @command{gnatstub}
17793 creates the name
17794 of the body file from the argument file name by replacing the @file{.ads}
17795 suffix
17796 with the @file{.adb} suffix.
17797
17798 @item directory
17799 indicates the directory in which the body stub is to be placed (the default
17800 is the
17801 current directory)
17802
17803 @item @samp{@var{gcc_switches}} is a list of switches for
17804 @command{gcc}. They will be passed on to all compiler invocations made by
17805 @command{gnatstub} to generate the ASIS trees. Here you can provide
17806 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17807 use the @option{-gnatec} switch to set the configuration file,
17808 use the @option{-gnat05} switch if sources should be compiled in
17809 Ada 2005 mode etc.
17810
17811 @item switches
17812 is an optional sequence of switches as described in the next section
17813 @end table
17814
17815 @node Switches for gnatstub
17816 @section Switches for @command{gnatstub}
17817
17818 @table @option
17819 @c !sort!
17820
17821 @item ^-f^/FULL^
17822 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17823 If the destination directory already contains a file with the name of the
17824 body file
17825 for the argument spec file, replace it with the generated body stub.
17826
17827 @item ^-hs^/HEADER=SPEC^
17828 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17829 Put the comment header (i.e., all the comments preceding the
17830 compilation unit) from the source of the library unit declaration
17831 into the body stub.
17832
17833 @item ^-hg^/HEADER=GENERAL^
17834 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17835 Put a sample comment header into the body stub.
17836
17837 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17838 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17839 Use the content of the file as the comment header for a generated body stub.
17840
17841 @ifclear vms
17842 @item -IDIR
17843 @cindex @option{-IDIR} (@command{gnatstub})
17844 @itemx -I-
17845 @cindex @option{-I-} (@command{gnatstub})
17846 @end ifclear
17847 @ifset vms
17848 @item /NOCURRENT_DIRECTORY
17849 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17850 @end ifset
17851 ^These switches have ^This switch has^ the same meaning as in calls to
17852 @command{gcc}.
17853 ^They define ^It defines ^ the source search path in the call to
17854 @command{gcc} issued
17855 by @command{gnatstub} to compile an argument source file.
17856
17857 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17858 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17859 This switch has the same meaning as in calls to @command{gcc}.
17860 It defines the additional configuration file to be passed to the call to
17861 @command{gcc} issued
17862 by @command{gnatstub} to compile an argument source file.
17863
17864 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17865 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17866 (@var{n} is a non-negative integer). Set the maximum line length in the
17867 body stub to @var{n}; the default is 79. The maximum value that can be
17868 specified is 32767. Note that in the special case of configuration
17869 pragma files, the maximum is always 32767 regardless of whether or
17870 not this switch appears.
17871
17872 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17873 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17874 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17875 the generated body sample to @var{n}.
17876 The default indentation is 3.
17877
17878 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17879 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17880 Order local bodies alphabetically. (By default local bodies are ordered
17881 in the same way as the corresponding local specs in the argument spec file.)
17882
17883 @item ^-i^/INDENTATION=^@var{n}
17884 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17885 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17886
17887 @item ^-k^/TREE_FILE=SAVE^
17888 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17889 Do not remove the tree file (i.e., the snapshot of the compiler internal
17890 structures used by @command{gnatstub}) after creating the body stub.
17891
17892 @item ^-l^/LINE_LENGTH=^@var{n}
17893 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17894 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17895
17896 @item ^--no-exception^/NO_EXCEPTION^
17897 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17898 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17899 This is not always possible for function stubs.
17900
17901 @item ^--no-local-header^/NO_LOCAL_HEADER^
17902 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17903 Do not place local comment header with unit name before body stub for a
17904 unit.
17905
17906 @item ^-o ^/BODY=^@var{body-name}
17907 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17908 Body file name.  This should be set if the argument file name does not
17909 follow
17910 the GNAT file naming
17911 conventions. If this switch is omitted the default name for the body will be
17912 obtained
17913 from the argument file name according to the GNAT file naming conventions.
17914
17915 @item ^-q^/QUIET^
17916 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17917 Quiet mode: do not generate a confirmation when a body is
17918 successfully created, and do not generate a message when a body is not
17919 required for an
17920 argument unit.
17921
17922 @item ^-r^/TREE_FILE=REUSE^
17923 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17924 Reuse the tree file (if it exists) instead of creating it.  Instead of
17925 creating the tree file for the library unit declaration, @command{gnatstub}
17926 tries to find it in the current directory and use it for creating
17927 a body. If the tree file is not found, no body is created. This option
17928 also implies @option{^-k^/SAVE^}, whether or not
17929 the latter is set explicitly.
17930
17931 @item ^-t^/TREE_FILE=OVERWRITE^
17932 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17933 Overwrite the existing tree file.  If the current directory already
17934 contains the file which, according to the GNAT file naming rules should
17935 be considered as a tree file for the argument source file,
17936 @command{gnatstub}
17937 will refuse to create the tree file needed to create a sample body
17938 unless this option is set.
17939
17940 @item ^-v^/VERBOSE^
17941 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17942 Verbose mode: generate version information.
17943
17944 @end table
17945
17946 @c *********************************
17947 @node Creating Unit Tests Using gnattest
17948 @chapter Creating Unit Tests Using @command{gnattest}
17949 @findex gnattest
17950
17951 @noindent
17952 @command{gnattest} is an ASIS-based utility that creates unit-test stubs
17953 as well as a test driver infrastructure (harness). @command{gnattest} creates
17954 a stub for each visible subprogram in the packages under consideration when
17955 they do not exist already.
17956
17957 In order to process source files from a project, @command{gnattest} has to
17958 semantically analyze the sources. Therefore, test stubs can only be
17959 generated for legal Ada units. If a unit is dependent on other units,
17960 those units should be among the source files of the project or of other projects
17961 imported by this one.
17962
17963 Generated stubs and harnesses are based on the AUnit testing framework. AUnit is
17964 an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit for Java
17965 or CppUnit for C++. While it is advised that gnattest users read the AUnit
17966 manual, deep knowledge of AUnit is not necessary for using gnattest. For correct
17967 operation of @command{gnattest}, AUnit should be installed and aunit.gpr must be
17968 on the project path. This happens automatically when Aunit is installed at its
17969 default location.
17970 @menu
17971 * Running gnattest::
17972 * Switches for gnattest::
17973 * Project Attributes for gnattest::
17974 * Simple Example::
17975 * Setting Up and Tearing Down the Testing Environment::
17976 * Regenerating Tests::
17977 * Default Test Behavior::
17978 * Testing Primitive Operations of Tagged Types::
17979 * Testing Inheritance::
17980 * Tagged Types Substitutability Testing::
17981 * Testing with Contracts::
17982 * Additional Tests::
17983 * Current Limitations::
17984 @end menu
17985
17986 @node Running gnattest
17987 @section Running @command{gnattest}
17988
17989 @noindent
17990 @command{gnattest} has a command-line interface of the form
17991
17992 @smallexample
17993 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17994 @c Expanding @ovar macro inline (explanation in macro def comments)
17995 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17996 @end smallexample
17997
17998 @noindent
17999 where
18000 @table @var
18001
18002 @item -Pprojname
18003 specifies the project defining the location of source files. When no
18004 file names are provided on the command line, all sources in the project
18005 are used as input. This switch is required.
18006
18007 @item --harness-dir=dirname
18008 specifies the directory that will hold the harness packages and project file
18009 for the test driver. The harness directory should be specified either by that
18010 switch or by the corresponding attribute in the project file.
18011
18012 @item filename
18013 is the name of the source file containing the library unit package declaration
18014 for which a test package will be created. The file name may be given with a
18015 path.
18016
18017 @item @samp{@var{gcc_switches}}
18018 is a list of switches for
18019 @command{gcc}. These switches will be passed on to all compiler invocations
18020 made by @command{gnatstub} to generate a set of ASIS trees. Here you can provide
18021 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18022 use the @option{-gnatec} switch to set the configuration file,
18023 use the @option{-gnat05} switch if sources should be compiled in
18024 Ada 2005 mode, etc.
18025
18026 @item switches
18027 is an optional sequence of switches as described in the next section.
18028
18029 @end table
18030
18031 @command{gnattest} results can be found in two different places.
18032
18033 @itemize @bullet
18034 @item automatic harness:
18035 the harness code, which is located either in the harness-dir as specified on
18036 the command line or in the project file. All of this code is generated
18037 completely automatically and can be destroyed and regenerated at will. It is not
18038 recommended to modify this code manually, since it could easily be overridden
18039 by mistake. The entry point in the harness code is the project file named
18040 @command{test_driver.gpr}. Tests can be compiled and run using a command
18041 such as:
18042
18043 @smallexample
18044 gnatmake -P<harness-dir>/test_driver
18045 test_runner
18046 @end smallexample
18047
18048 Note that you might need to specify the necessary values of scenario variables
18049 when you are not using the AUnit defaults.
18050
18051 @item actual unit test stubs:
18052 a test stub for each visible subprogram is created in a separate file, if it
18053 doesn't exist already. By default, those separate test files are located in a
18054 "tests" directory that is created in the directory containing the source file
18055 itself. If it is not appropriate to create the tests in subdirectories of the
18056 source, option @option{--separate-root} can be used. For example, if a source
18057 file my_unit.ads in directory src contains a visible subprogram Proc, then
18058 the corresponding unit test will be found in file
18059 src/tests/my_unit-tests-proc_<code>.adb. <code> is a signature encoding used to
18060 differentiate test names in case of overloading.
18061
18062 Note that if the project already has both my_unit.ads and my_unit-tests.ads,
18063 this will cause a name conflict with the generated test package.
18064 @end itemize
18065
18066 @node Switches for gnattest
18067 @section Switches for @command{gnattest}
18068
18069 @table @option
18070 @c !sort!
18071
18072 @item --harness-only
18073 @cindex @option{--harness-only} (@command{gnattest})
18074 When this option is given, @command{gnattest} creates a harness for all
18075 sources, treating them as test packages.
18076
18077 @item --additional-tests=@var{projname}
18078 @cindex @option{--additional-tests} (@command{gnattest})
18079 Sources described in @var{projname} are considered potential additional
18080 manual tests to be added to the test suite.
18081
18082 @item -r
18083 @cindex @option{-r} (@command{gnattest})
18084 Recursively consider all sources from all projects.
18085
18086 @item -X@var{name=value}
18087 @cindex @option{-X} (@command{gnattest})
18088 Indicate that external variable @var{name} has the value @var{value}.
18089
18090 @item -q
18091 @cindex @option{-q} (@command{gnattest})
18092 Suppresses noncritical output messages.
18093
18094 @item -v
18095 @cindex @option{-v} (@command{gnattest})
18096 Verbose mode: generates version information.
18097
18098 @item --liskov
18099 @cindex @option{--liskov} (@command{gnattest})
18100 Enables Liskov verification: run all tests from all parents in order
18101 to check substitutability.
18102
18103 @item --stub-default=@var{val}
18104 @cindex @option{--stub-default} (@command{gnattest})
18105 Specifies the default behavior of generated stubs. @var{val} can be either
18106 "fail" or "pass", "fail" being the default.
18107
18108 @item --separate-root=@var{dirname}
18109 @cindex @option{--separate-root} (@command{gnattest})
18110 The directory hierarchy of tested sources is recreated in the @var{dirname}
18111 directory, and test packages are placed in corresponding directories.
18112
18113 @item --subdir=@var{dirname}
18114 @cindex @option{--subdir} (@command{gnattest})
18115 Test packages are placed in subdirectories. This is the default output mode
18116 since it does not require any additional input from the user. Subdirectories
18117 named "tests" will be created by default.
18118
18119 @end table
18120
18121 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
18122
18123 @node Project Attributes for gnattest
18124 @section Project Attributes for @command{gnattest}
18125
18126 @noindent
18127
18128 Most of the command-line options can also be passed to the tool by adding
18129 special attributes to the project file. Those attributes should be put in
18130 package gnattest. Here is the list of attributes:
18131
18132 @itemize @bullet
18133
18134 @item Separate_Stub_Root
18135 is used to select the same output mode as with the --separate-root option.
18136 This attribute cannot be used together with Stub_Subdir.
18137
18138 @item Stub_Subdir
18139 is used to select the same output mode as with the --subdir option.
18140 This attribute cannot be used together with Separate_Stub_Root.
18141
18142 @item Harness_Dir
18143 is used to specify the directory in which to place harness packages and project
18144 file for the test driver, otherwise specified by --harness-dir.
18145
18146 @item Additional_Tests
18147 is used to specify the project file, otherwise given by
18148 --additional-tests switch.
18149
18150 @item Stubs_Default
18151 is used to specify the default behaviour of test stubs, otherwise
18152 specified by --stub-default option. The value of this attribute
18153 should be either "pass" or "fail".
18154
18155 @end itemize
18156
18157 Each of those attributes can be overridden from the command line if needed.
18158 Other @command{gnattest} switches can also be passed via the project
18159 file as an attribute list called GNATtest_Switches.
18160
18161 @node Simple Example
18162 @section Simple Example
18163
18164 @noindent
18165
18166 Let's take a very simple example using the first @command{gnattest} example
18167 located in:
18168
18169 @smallexample
18170 <install_prefix>/share/examples/gnattest/simple
18171 @end smallexample
18172
18173 This project contains a simple package containing one subprogram. By running gnattest:
18174
18175 @smallexample
18176 $ gnattest --harness-dir=driver -Psimple.gpr
18177 @end smallexample
18178
18179 a test driver is created in directory "driver". It can be compiled and run:
18180
18181 @smallexample
18182 $ cd driver
18183 $ gprbuild -Ptest_driver
18184 $ test_runner
18185 @end smallexample
18186
18187 One failed test with diagnosis "test not implemented" is reported.
18188 Since no special output option was specified, the test package Simple.Tests
18189 is located in:
18190
18191 @smallexample
18192 <install_prefix>/share/examples/gnattest/simple/src/tests
18193 @end smallexample
18194
18195 For each package containing visible subprograms, a child test package is
18196 generated. It contains one test routine per tested subprogram. Each
18197 declaration of a test subprogram has a comment specifying which tested
18198 subprogram it corresponds to. All of the test routines have separate bodies.
18199 The test routine located at simple-tests-test_inc_5eaee3.adb contains a single
18200 statement: a call to procedure Assert. It has two arguments: the Boolean
18201 expression we want to check and the diagnosis message to display if
18202 the condition is false.
18203
18204 That is where actual testing code should be written after a proper setup.
18205 An actual check can be performed by replacing the Assert call with:
18206
18207 @smallexample @c ada
18208 Assert (Inc (1) = 2, "wrong incrementation");
18209 @end smallexample
18210
18211 After recompiling and running the test driver, one successfully passed test
18212 is reported.
18213
18214 @node Setting Up and Tearing Down the Testing Environment
18215 @section Setting Up and Tearing Down the Testing Environment
18216
18217 @noindent
18218
18219 Besides test routines themselves, each test package has an inner package
18220 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
18221 User_Set_Up is called before each test routine of the package and
18222 User_Tear_Down is called after each test routine. Those two procedures can
18223 be used to perform necessary initialization and finalization,
18224 memory allocation, etc.
18225
18226 @node Regenerating Tests
18227 @section Regenerating Tests
18228
18229 @noindent
18230
18231 Bodies of test routines and env_mgmt packages are never overridden after they
18232 have been created once. As long as the name of the subprogram, full expanded Ada
18233 names, and the order of its parameters is the same, the old test routine will
18234 fit in its place and no test stub will be generated for the subprogram.
18235
18236 This can be demonstrated with the previous example. By uncommenting declaration
18237 and body of function Dec in simple.ads and simple.adb, running
18238 @command{gnattest} on the project, and then running the test driver:
18239
18240 @smallexample
18241 gnattest --harness-dir=driver -Psimple.gpr
18242 cd driver
18243 gprbuild -Ptest_driver
18244 test_runner
18245 @end smallexample
18246
18247 the old test is not replaced with a stub, nor is it lost, but a new test stub is
18248 created for function Dec.
18249
18250 The only way of regenerating tests stubs is to remove the previously created
18251 tests.
18252
18253 @node Default Test Behavior
18254 @section Default Test Behavior
18255
18256 @noindent
18257
18258 The generated test driver can treat unimplemented tests in two ways:
18259 either count them all as failed (this is useful to see which tests are still
18260 left to implement) or as passed (to sort out unimplemented ones from those
18261 actually failing).
18262
18263 The test driver accepts a switch to specify this behavior: --stub-default=val,
18264 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
18265
18266 The default behavior of the test driver is set with the same switch
18267 as passed to gnattest when generating the test driver.
18268
18269 Passing it to the driver generated on the first example:
18270
18271 @smallexample
18272 test_runner --stub-default=pass
18273 @end smallexample
18274
18275 makes both tests pass, even the unimplemented one.
18276
18277 @node Testing Primitive Operations of Tagged Types
18278 @section Testing Primitive Operations of Tagged Types
18279
18280 @noindent
18281
18282 Creation of test stubs for primitive operations of tagged types entails a number
18283 of features. Test routines for all primitives of a given tagged type are
18284 placed in a separate child package named according to the tagged type. For
18285 example, if you have tagged type T in package P, all tests for primitives
18286 of T will be in P.T_Tests.
18287
18288 Consider running gnattest on the second example (note: actual tests for this
18289 example already exist, so there's no need to worry if the tool reports that
18290 no new stubs were generated):
18291
18292 @smallexample
18293 cd <install_prefix>/share/examples/gnattest/tagged_rec
18294 gnattest --harness-dir=driver -Ptagged_rec.gpr
18295 @end smallexample
18296
18297 Taking a closer look at the test type declared in the test package
18298 Speed1.Controller_Tests is necessary. It is declared in:
18299
18300 @smallexample
18301 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18302 @end smallexample
18303
18304 Test types are direct or indirect descendants of
18305 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18306 subprograms, the user doesn't need to be concerned with them. However,
18307 when generating test packages for primitive operations, there are some things
18308 the user needs to know.
18309
18310 Type Test_Controller has components that allow assignment of various
18311 derivations of type Controller. And if you look at the specification of
18312 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18313 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18314 Thus, test types mirror the hierarchy of tested types.
18315
18316 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18317 of primitive operations of type T assigns to Fixture a reference to an
18318 object of that exact type T. Notice, however, that if the tagged type has
18319 discriminants, the User_Set_Up only has a commented template for setting
18320 up the fixture, since filling the discriminant with actual value is up
18321 to the user.
18322
18323 The knowledge of the structure of test types allows additional testing
18324 without additional effort. Those possibilities are described below.
18325
18326 @node Testing Inheritance
18327 @section Testing Inheritance
18328
18329 @noindent
18330
18331 Since the test type hierarchy mimics the hierarchy of tested types, the
18332 inheritance of tests takes place. An example of such inheritance can be
18333 seen by running the test driver generated for the second example. As previously
18334 mentioned, actual tests are already written for this example.
18335
18336 @smallexample
18337 cd driver
18338 gprbuild -Ptest_driver
18339 test_runner
18340 @end smallexample
18341
18342 There are 6 passed tests while there are only 5 testable subprograms. The test
18343 routine for function Speed has been inherited and run against objects of the
18344 derived type.
18345
18346 @node Tagged Types Substitutability Testing
18347 @section Tagged Types Substitutability Testing
18348
18349 @noindent
18350
18351 Tagged Types Substitutability Testing is a way of verifying the Liskov
18352 substitution principle (LSP) by testing. LSP is a principle stating that if
18353 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18354 then objects of type T may be replaced with objects of type S (that is,
18355 objects of type S may be substituted for objects of type T), without
18356 altering any of the desirable properties of the program. When the properties
18357 of the program are expressed in the form of subprogram preconditions and
18358 postconditions (let's call them pre and post), LSP is formulated as relations
18359 between the pre and post of primitive operations and the pre and post of their
18360 derived operations. The pre of a derived operation should not be stronger than
18361 the original pre, and the post of the derived operation should not be weaker
18362 than the original post. Those relations ensure that verifying if a dispatching
18363 call is safe can be done just by using the pre and post of the root operation.
18364
18365 Verifying LSP by testing consists of running all the unit tests associated with
18366 the primitives of a given tagged type with objects of its derived types.
18367
18368 In the example used in the previous section, there was clearly a violation of
18369 LSP. The overriding primitive Adjust_Speed in package Speed2 removes the
18370 functionality of the overridden primitive and thus doesn't respect LSP.
18371 Gnattest has a special option to run overridden parent tests against objects
18372 of the type which have overriding primitives:
18373
18374 @smallexample
18375 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18376 cd driver
18377 gprbuild -Ptest_driver
18378 test_runner
18379 @end smallexample
18380
18381 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18382 against objects of the derived type.
18383
18384 @node Testing with Contracts
18385 @section Testing with Contracts
18386
18387 @noindent
18388
18389 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case.
18390 Test routines are generated, one per each Test_Case associated with a tested
18391 subprogram. Those test routines have special wrappers for tested functions
18392 that have composition of pre- and postcondition of the subprogram with
18393 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18394 either count for Nominal mode or do not count for Robustness mode).
18395
18396 The third example demonstrates how this works:
18397
18398 @smallexample
18399 cd <install_prefix>/share/examples/gnattest/contracts
18400 gnattest --harness-dir=driver -Pcontracts.gpr
18401 @end smallexample
18402
18403 Putting actual checks within the range of the contract does not cause any
18404 error reports. For example, for the test routine which corresponds to
18405 test case 1:
18406
18407 @smallexample @c ada
18408 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18409 @end smallexample
18410
18411 and for the test routine corresponding to test case 2:
18412
18413 @smallexample @c ada
18414 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18415 @end smallexample
18416
18417 are acceptable:
18418
18419 @smallexample
18420 cd driver
18421 gprbuild -Ptest_driver
18422 test_runner
18423 @end smallexample
18424
18425 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18426 a precondition violation for test case one. Also, by using any otherwise
18427 correct but positive pair of numbers in the second test routine, you can also
18428 get a precondition violation. Postconditions are checked and reported
18429 the same way.
18430
18431 @node Additional Tests
18432 @section Additional Tests
18433
18434 @noindent
18435 @command{gnattest} can add user-written tests to the main suite of the test
18436 driver. @command{gnattest} traverses the given packages and searches for test
18437 routines. All procedures with a single in out parameter of a type which is
18438 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18439 specifications are added to the suites and are then executed by the test driver.
18440 (Set_Up and Tear_Down are filtered out.)
18441
18442 An example illustrates two ways of creating test harnesses for user-written
18443 tests. Directory additional_tests contains an AUnit-based test driver written
18444 by hand.
18445
18446 @smallexample
18447 <install_prefix>/share/examples/gnattest/additional_tests/
18448 @end smallexample
18449
18450 To create a test driver for already-written tests, use the --harness-only
18451 option:
18452
18453 @smallexample
18454 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18455   --harness-only
18456 gnatmake -Pharness_only/test_driver.gpr
18457 harness_only/test_runner
18458 @end smallexample
18459
18460 Additional tests can also be executed together with generated tests:
18461
18462 @smallexample
18463 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18464   --harness-dir=mixing
18465 gnatmake -Pmixing/test_driver.gpr
18466 mixing/test_runner
18467 @end smallexample
18468
18469 @node Current Limitations
18470 @section Current Limitations
18471
18472 @noindent
18473
18474 The tool currently does not support following features:
18475
18476 @itemize @bullet
18477 @item generic tests for generic packages and package instantiations
18478 @item tests for protected subprograms and entries
18479 @item aspects Precondition, Postcondition, and Test_Case
18480 @item generating test packages for code that is not conformant with ada 2005
18481
18482 @end itemize
18483
18484 @c *********************************
18485 @node Generating Ada Bindings for C and C++ headers
18486 @chapter Generating Ada Bindings for C and C++ headers
18487 @findex binding
18488
18489 @noindent
18490 GNAT now comes with a binding generator for C and C++ headers which is
18491 intended to do 95% of the tedious work of generating Ada specs from C
18492 or C++ header files.
18493
18494 Note that this capability is not intended to generate 100% correct Ada specs,
18495 and will is some cases require manual adjustments, although it can often
18496 be used out of the box in practice.
18497
18498 Some of the known limitations include:
18499
18500 @itemize @bullet
18501 @item only very simple character constant macros are translated into Ada
18502 constants. Function macros (macros with arguments) are partially translated
18503 as comments, to be completed manually if needed.
18504 @item some extensions (e.g. vector types) are not supported
18505 @item pointers to pointers or complex structures are mapped to System.Address
18506 @item identifiers with identical name (except casing) will generate compilation
18507       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18508 @end itemize
18509
18510 The code generated is using the Ada 2005 syntax, which makes it
18511 easier to interface with other languages than previous versions of Ada.
18512
18513 @menu
18514 * Running the binding generator::
18515 * Generating bindings for C++ headers::
18516 * Switches::
18517 @end menu
18518
18519 @node Running the binding generator
18520 @section Running the binding generator
18521
18522 @noindent
18523 The binding generator is part of the @command{gcc} compiler and can be
18524 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18525 spec files for the header files specified on the command line, and all
18526 header files needed by these files transitively. For example:
18527
18528 @smallexample
18529 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18530 $ gcc -c -gnat05 *.ads
18531 @end smallexample
18532
18533 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18534 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18535 correspond to the files @file{/usr/include/time.h},
18536 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18537 mode these Ada specs.
18538
18539 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18540 and will attempt to generate corresponding Ada comments.
18541
18542 If you want to generate a single Ada file and not the transitive closure, you
18543 can use instead the @option{-fdump-ada-spec-slim} switch.
18544
18545 Note that we recommend when possible to use the @command{g++} driver to
18546 generate bindings, even for most C headers, since this will in general
18547 generate better Ada specs. For generating bindings for C++ headers, it is
18548 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18549 is equivalent in this case. If @command{g++} cannot work on your C headers
18550 because of incompatibilities between C and C++, then you can fallback to
18551 @command{gcc} instead.
18552
18553 For an example of better bindings generated from the C++ front-end,
18554 the name of the parameters (when available) are actually ignored by the C
18555 front-end. Consider the following C header:
18556
18557 @smallexample
18558 extern void foo (int variable);
18559 @end smallexample
18560
18561 with the C front-end, @code{variable} is ignored, and the above is handled as:
18562
18563 @smallexample
18564 extern void foo (int);
18565 @end smallexample
18566
18567 generating a generic:
18568
18569 @smallexample
18570 procedure foo (param1 : int);
18571 @end smallexample
18572
18573 with the C++ front-end, the name is available, and we generate:
18574
18575 @smallexample
18576 procedure foo (variable : int);
18577 @end smallexample
18578
18579 In some cases, the generated bindings will be more complete or more meaningful
18580 when defining some macros, which you can do via the @option{-D} switch. This
18581 is for example the case with @file{Xlib.h} under GNU/Linux:
18582
18583 @smallexample
18584 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18585 @end smallexample
18586
18587 The above will generate more complete bindings than a straight call without
18588 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18589
18590 In other cases, it is not possible to parse a header file in a stand-alone
18591 manner, because other include files need to be included first. In this
18592 case, the solution is to create a small header file including the needed
18593 @code{#include} and possible @code{#define} directives. For example, to
18594 generate Ada bindings for @file{readline/readline.h}, you need to first
18595 include @file{stdio.h}, so you can create a file with the following two
18596 lines in e.g. @file{readline1.h}:
18597
18598 @smallexample
18599 #include <stdio.h>
18600 #include <readline/readline.h>
18601 @end smallexample
18602
18603 and then generate Ada bindings from this file:
18604
18605 @smallexample
18606 $ g++ -c -fdump-ada-spec readline1.h
18607 @end smallexample
18608
18609 @node Generating bindings for C++ headers
18610 @section Generating bindings for C++ headers
18611
18612 @noindent
18613 Generating bindings for C++ headers is done using the same options, always
18614 with the @command{g++} compiler.
18615
18616 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18617 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18618 multiple inheritance of abstract classes will be mapped to Ada interfaces
18619 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18620 information on interfacing to C++).
18621
18622 For example, given the following C++ header file:
18623
18624 @smallexample
18625 @group
18626 @cartouche
18627 class Carnivore @{
18628 public:
18629    virtual int Number_Of_Teeth () = 0;
18630 @};
18631
18632 class Domestic @{
18633 public:
18634    virtual void Set_Owner (char* Name) = 0;
18635 @};
18636
18637 class Animal @{
18638 public:
18639   int Age_Count;
18640   virtual void Set_Age (int New_Age);
18641 @};
18642
18643 class Dog : Animal, Carnivore, Domestic @{
18644  public:
18645   int  Tooth_Count;
18646   char *Owner;
18647
18648   virtual int  Number_Of_Teeth ();
18649   virtual void Set_Owner (char* Name);
18650
18651   Dog();
18652 @};
18653 @end cartouche
18654 @end group
18655 @end smallexample
18656
18657 The corresponding Ada code is generated:
18658
18659 @smallexample @c ada
18660 @group
18661 @cartouche
18662   package Class_Carnivore is
18663     type Carnivore is limited interface;
18664     pragma Import (CPP, Carnivore);
18665
18666     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18667   end;
18668   use Class_Carnivore;
18669
18670   package Class_Domestic is
18671     type Domestic is limited interface;
18672     pragma Import (CPP, Domestic);
18673
18674     procedure Set_Owner
18675       (this : access Domestic;
18676        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18677   end;
18678   use Class_Domestic;
18679
18680   package Class_Animal is
18681     type Animal is tagged limited record
18682       Age_Count : aliased int;
18683     end record;
18684     pragma Import (CPP, Animal);
18685
18686     procedure Set_Age (this : access Animal; New_Age : int);
18687     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18688   end;
18689   use Class_Animal;
18690
18691   package Class_Dog is
18692     type Dog is new Animal and Carnivore and Domestic with record
18693       Tooth_Count : aliased int;
18694       Owner : Interfaces.C.Strings.chars_ptr;
18695     end record;
18696     pragma Import (CPP, Dog);
18697
18698     function Number_Of_Teeth (this : access Dog) return int;
18699     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18700
18701     procedure Set_Owner
18702       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18703     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18704
18705     function New_Dog return Dog;
18706     pragma CPP_Constructor (New_Dog);
18707     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18708   end;
18709   use Class_Dog;
18710 @end cartouche
18711 @end group
18712 @end smallexample
18713
18714 @node Switches
18715 @section Switches
18716
18717 @table @option
18718 @item -fdump-ada-spec
18719 @cindex @option{-fdump-ada-spec} (@command{gcc})
18720 Generate Ada spec files for the given header files transitively (including
18721 all header files that these headers depend upon).
18722
18723 @item -fdump-ada-spec-slim
18724 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18725 Generate Ada spec files for the header files specified on the command line
18726 only.
18727
18728 @item -C
18729 @cindex @option{-C} (@command{gcc})
18730 Extract comments from headers and generate Ada comments in the Ada spec files.
18731 @end table
18732
18733 @node Other Utility Programs
18734 @chapter Other Utility Programs
18735
18736 @noindent
18737 This chapter discusses some other utility programs available in the Ada
18738 environment.
18739
18740 @menu
18741 * Using Other Utility Programs with GNAT::
18742 * The External Symbol Naming Scheme of GNAT::
18743 * Converting Ada Files to html with gnathtml::
18744 * Installing gnathtml::
18745 @ifset vms
18746 * LSE::
18747 * Profiling::
18748 @end ifset
18749 @end menu
18750
18751 @node Using Other Utility Programs with GNAT
18752 @section Using Other Utility Programs with GNAT
18753
18754 @noindent
18755 The object files generated by GNAT are in standard system format and in
18756 particular the debugging information uses this format. This means
18757 programs generated by GNAT can be used with existing utilities that
18758 depend on these formats.
18759
18760 @ifclear vms
18761 In general, any utility program that works with C will also often work with
18762 Ada programs generated by GNAT. This includes software utilities such as
18763 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18764 as Purify.
18765 @end ifclear
18766
18767 @node The External Symbol Naming Scheme of GNAT
18768 @section The External Symbol Naming Scheme of GNAT
18769
18770 @noindent
18771 In order to interpret the output from GNAT, when using tools that are
18772 originally intended for use with other languages, it is useful to
18773 understand the conventions used to generate link names from the Ada
18774 entity names.
18775
18776 All link names are in all lowercase letters. With the exception of library
18777 procedure names, the mechanism used is simply to use the full expanded
18778 Ada name with dots replaced by double underscores. For example, suppose
18779 we have the following package spec:
18780
18781 @smallexample @c ada
18782 @group
18783 @cartouche
18784 package QRS is
18785    MN : Integer;
18786 end QRS;
18787 @end cartouche
18788 @end group
18789 @end smallexample
18790
18791 @noindent
18792 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18793 the corresponding link name is @code{qrs__mn}.
18794 @findex Export
18795 Of course if a @code{pragma Export} is used this may be overridden:
18796
18797 @smallexample @c ada
18798 @group
18799 @cartouche
18800 package Exports is
18801    Var1 : Integer;
18802    pragma Export (Var1, C, External_Name => "var1_name");
18803    Var2 : Integer;
18804    pragma Export (Var2, C, Link_Name => "var2_link_name");
18805 end Exports;
18806 @end cartouche
18807 @end group
18808 @end smallexample
18809
18810 @noindent
18811 In this case, the link name for @var{Var1} is whatever link name the
18812 C compiler would assign for the C function @var{var1_name}. This typically
18813 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18814 system conventions, but other possibilities exist. The link name for
18815 @var{Var2} is @var{var2_link_name}, and this is not operating system
18816 dependent.
18817
18818 @findex _main
18819 One exception occurs for library level procedures. A potential ambiguity
18820 arises between the required name @code{_main} for the C main program,
18821 and the name we would otherwise assign to an Ada library level procedure
18822 called @code{Main} (which might well not be the main program).
18823
18824 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18825 names. So if we have a library level procedure such as
18826
18827 @smallexample @c ada
18828 @group
18829 @cartouche
18830 procedure Hello (S : String);
18831 @end cartouche
18832 @end group
18833 @end smallexample
18834
18835 @noindent
18836 the external name of this procedure will be @var{_ada_hello}.
18837
18838
18839 @node Converting Ada Files to html with gnathtml
18840 @section Converting Ada Files to HTML with @code{gnathtml}
18841
18842 @noindent
18843 This @code{Perl} script allows Ada source files to be browsed using
18844 standard Web browsers. For installation procedure, see the section
18845 @xref{Installing gnathtml}.
18846
18847 Ada reserved keywords are highlighted in a bold font and Ada comments in
18848 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18849 switch to suppress the generation of cross-referencing information, user
18850 defined variables and types will appear in a different color; you will
18851 be able to click on any identifier and go to its declaration.
18852
18853 The command line is as follow:
18854 @smallexample
18855 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18856 @c Expanding @ovar macro inline (explanation in macro def comments)
18857 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18858 @end smallexample
18859
18860 @noindent
18861 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18862 an html file for every ada file, and a global file called @file{index.htm}.
18863 This file is an index of every identifier defined in the files.
18864
18865 The available ^switches^options^ are the following ones:
18866
18867 @table @option
18868 @item -83
18869 @cindex @option{-83} (@code{gnathtml})
18870 Only the Ada 83 subset of keywords will be highlighted.
18871
18872 @item -cc @var{color}
18873 @cindex @option{-cc} (@code{gnathtml})
18874 This option allows you to change the color used for comments. The default
18875 value is green. The color argument can be any name accepted by html.
18876
18877 @item -d
18878 @cindex @option{-d} (@code{gnathtml})
18879 If the Ada files depend on some other files (for instance through
18880 @code{with} clauses, the latter files will also be converted to html.
18881 Only the files in the user project will be converted to html, not the files
18882 in the run-time library itself.
18883
18884 @item -D
18885 @cindex @option{-D} (@code{gnathtml})
18886 This command is the same as @option{-d} above, but @command{gnathtml} will
18887 also look for files in the run-time library, and generate html files for them.
18888
18889 @item -ext @var{extension}
18890 @cindex @option{-ext} (@code{gnathtml})
18891 This option allows you to change the extension of the generated HTML files.
18892 If you do not specify an extension, it will default to @file{htm}.
18893
18894 @item -f
18895 @cindex @option{-f} (@code{gnathtml})
18896 By default, gnathtml will generate html links only for global entities
18897 ('with'ed units, global variables and types,@dots{}).  If you specify
18898 @option{-f} on the command line, then links will be generated for local
18899 entities too.
18900
18901 @item -l @var{number}
18902 @cindex @option{-l} (@code{gnathtml})
18903 If this ^switch^option^ is provided and @var{number} is not 0, then
18904 @code{gnathtml} will number the html files every @var{number} line.
18905
18906 @item -I @var{dir}
18907 @cindex @option{-I} (@code{gnathtml})
18908 Specify a directory to search for library files (@file{.ALI} files) and
18909 source files. You can provide several -I switches on the command line,
18910 and the directories will be parsed in the order of the command line.
18911
18912 @item -o @var{dir}
18913 @cindex @option{-o} (@code{gnathtml})
18914 Specify the output directory for html files. By default, gnathtml will
18915 saved the generated html files in a subdirectory named @file{html/}.
18916
18917 @item -p @var{file}
18918 @cindex @option{-p} (@code{gnathtml})
18919 If you are using Emacs and the most recent Emacs Ada mode, which provides
18920 a full Integrated Development Environment for compiling, checking,
18921 running and debugging applications, you may use @file{.gpr} files
18922 to give the directories where Emacs can find sources and object files.
18923
18924 Using this ^switch^option^, you can tell gnathtml to use these files.
18925 This allows you to get an html version of your application, even if it
18926 is spread over multiple directories.
18927
18928 @item -sc @var{color}
18929 @cindex @option{-sc} (@code{gnathtml})
18930 This ^switch^option^ allows you to change the color used for symbol
18931 definitions.
18932 The default value is red. The color argument can be any name accepted by html.
18933
18934 @item -t @var{file}
18935 @cindex @option{-t} (@code{gnathtml})
18936 This ^switch^option^ provides the name of a file. This file contains a list of
18937 file names to be converted, and the effect is exactly as though they had
18938 appeared explicitly on the command line. This
18939 is the recommended way to work around the command line length limit on some
18940 systems.
18941
18942 @end table
18943
18944 @node Installing gnathtml
18945 @section Installing @code{gnathtml}
18946
18947 @noindent
18948 @code{Perl} needs to be installed on your machine to run this script.
18949 @code{Perl} is freely available for almost every architecture and
18950 Operating System via the Internet.
18951
18952 On Unix systems, you  may want to modify  the  first line of  the script
18953 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18954 is. The syntax of this line is:
18955 @smallexample
18956 #!full_path_name_to_perl
18957 @end smallexample
18958
18959 @noindent
18960 Alternatively, you may run the script using the following command line:
18961
18962 @smallexample
18963 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18964 @c Expanding @ovar macro inline (explanation in macro def comments)
18965 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18966 @end smallexample
18967
18968 @ifset vms
18969 @node LSE
18970 @section LSE
18971 @findex LSE
18972
18973 @noindent
18974 The GNAT distribution provides an Ada 95 template for the HP Language
18975 Sensitive Editor (LSE), a component of DECset. In order to
18976 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18977
18978 @node Profiling
18979 @section Profiling
18980 @findex PCA
18981
18982 @noindent
18983 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18984 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18985 the collection phase with the /DEBUG qualifier.
18986
18987 @smallexample
18988 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18989 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18990 $ RUN/DEBUG <PROGRAM_NAME>
18991 @end smallexample
18992 @noindent
18993 @end ifset
18994
18995 @ifclear vms
18996 @c ******************************
18997 @node Code Coverage and Profiling
18998 @chapter Code Coverage and Profiling
18999 @cindex Code Coverage
19000 @cindex Profiling
19001
19002 @noindent
19003 This chapter describes how to use @code{gcov} - coverage testing tool - and
19004 @code{gprof} - profiler tool - on your Ada programs.
19005
19006 @menu
19007 * Code Coverage of Ada Programs using gcov::
19008 * Profiling an Ada Program using gprof::
19009 @end menu
19010
19011 @node Code Coverage of Ada Programs using gcov
19012 @section Code Coverage of Ada Programs using gcov
19013 @cindex gcov
19014 @cindex -fprofile-arcs
19015 @cindex -ftest-coverage
19016 @cindex -coverage
19017 @cindex Code Coverage
19018
19019 @noindent
19020 @code{gcov} is a test coverage program: it analyzes the execution of a given
19021 program on selected tests, to help you determine the portions of the program
19022 that are still untested.
19023
19024 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
19025 User's Guide. You can refer to this documentation for a more complete
19026 description.
19027
19028 This chapter provides a quick startup guide, and
19029 details some Gnat-specific features.
19030
19031 @menu
19032 * Quick startup guide::
19033 * Gnat specifics::
19034 @end menu
19035
19036 @node Quick startup guide
19037 @subsection Quick startup guide
19038
19039 In order to perform coverage analysis of a program using @code{gcov}, 3
19040 steps are needed:
19041
19042 @itemize @bullet
19043 @item
19044 Code instrumentation during the compilation process
19045 @item
19046 Execution of the instrumented program
19047 @item
19048 Execution of the @code{gcov} tool to generate the result.
19049 @end itemize
19050
19051 The code instrumentation needed by gcov is created at the object level:
19052 The source code is not modified in any way, because the instrumentation code is
19053 inserted by gcc during the compilation process. To compile your code with code
19054 coverage activated, you need to recompile your whole project using the
19055 switches
19056 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
19057 @code{-fprofile-arcs}.
19058
19059 @smallexample
19060 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
19061    -largs -fprofile-arcs
19062 @end smallexample
19063
19064 This compilation process will create @file{.gcno} files together with
19065 the usual object files.
19066
19067 Once the program is compiled with coverage instrumentation, you can
19068 run it as many times as needed - on portions of a test suite for
19069 example. The first execution will produce @file{.gcda} files at the
19070 same location as the @file{.gcno} files.  The following executions
19071 will update those files, so that a cumulative result of the covered
19072 portions of the program is generated.
19073
19074 Finally, you need to call the @code{gcov} tool. The different options of
19075 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
19076
19077 This will create annotated source files with a @file{.gcov} extension:
19078 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
19079
19080 @node Gnat specifics
19081 @subsection Gnat specifics
19082
19083 Because Ada semantics, portions of the source code may be shared among
19084 several object files. This is the case for example when generics are
19085 involved, when inlining is active  or when declarations generate  initialisation
19086 calls. In order to take
19087 into account this shared code, you need to call @code{gcov} on all
19088 source files of the tested program at once.
19089
19090 The list of source files might exceed the system's maximum command line
19091 length. In order to bypass this limitation, a new mechanism has been
19092 implemented in @code{gcov}: you can now list all your project's files into a
19093 text file, and provide this file to gcov as a parameter,  preceded by a @@
19094 (e.g. @samp{gcov @@mysrclist.txt}).
19095
19096 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
19097 not supported as there can be unresolved symbols during the final link.
19098
19099 @node Profiling an Ada Program using gprof
19100 @section Profiling an Ada Program using gprof
19101 @cindex gprof
19102 @cindex -pg
19103 @cindex Profiling
19104
19105 @noindent
19106 This section is not meant to be an exhaustive documentation of @code{gprof}.
19107 Full documentation for it can be found in the GNU Profiler User's Guide
19108 documentation that is part of this GNAT distribution.
19109
19110 Profiling a program helps determine the parts of a program that are executed
19111 most often, and are therefore the most time-consuming.
19112
19113 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19114 better handle Ada programs and multitasking.
19115 It is currently supported on the following platforms
19116 @itemize @bullet
19117 @item
19118 linux x86/x86_64
19119 @item
19120 solaris sparc/sparc64/x86
19121 @item
19122 windows x86
19123 @end itemize
19124
19125 @noindent
19126 In order to profile a program using @code{gprof}, 3 steps are needed:
19127
19128 @itemize @bullet
19129 @item
19130 Code instrumentation, requiring a full recompilation of the project with the
19131 proper switches.
19132 @item
19133 Execution of the program under the analysis conditions, i.e. with the desired
19134 input.
19135 @item
19136 Analysis of the results using the @code{gprof} tool.
19137 @end itemize
19138
19139 @noindent
19140 The following sections detail the different steps, and indicate how
19141 to interpret the results:
19142 @menu
19143 * Compilation for profiling::
19144 * Program execution::
19145 * Running gprof::
19146 * Interpretation of profiling results::
19147 @end menu
19148
19149 @node Compilation for profiling
19150 @subsection Compilation for profiling
19151 @cindex -pg
19152 @cindex Profiling
19153
19154 In order to profile a program the first step is to tell the compiler
19155 to generate the necessary profiling information. The compiler switch to be used
19156 is @code{-pg}, which must be added to other compilation switches. This
19157 switch needs to be specified both during compilation and link stages, and can
19158 be specified once when using gnatmake:
19159
19160 @smallexample
19161 gnatmake -f -pg -P my_project
19162 @end smallexample
19163
19164 @noindent
19165 Note that only the objects that were compiled with the @samp{-pg} switch will
19166 be profiled; if you need to profile your whole project, use the @samp{-f}
19167 gnatmake switch to force full recompilation.
19168
19169 @node Program execution
19170 @subsection Program execution
19171
19172 @noindent
19173 Once the program has been compiled for profiling, you can run it as usual.
19174
19175 The only constraint imposed by profiling is that the program must terminate
19176 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19177 properly analyzed.
19178
19179 Once the program completes execution, a data file called @file{gmon.out} is
19180 generated in the directory where the program was launched from. If this file
19181 already exists, it will be overwritten.
19182
19183 @node Running gprof
19184 @subsection Running gprof
19185
19186 @noindent
19187 The @code{gprof} tool is called as follow:
19188
19189 @smallexample
19190 gprof my_prog gmon.out
19191 @end smallexample
19192
19193 @noindent
19194 or simpler:
19195
19196 @smallexample
19197 gprof my_prog
19198 @end smallexample
19199
19200 @noindent
19201 The complete form of the gprof command line is the following:
19202
19203 @smallexample
19204 gprof [^switches^options^] [executable [data-file]]
19205 @end smallexample
19206
19207 @noindent
19208 @code{gprof} supports numerous ^switch^options^. The order of these
19209 ^switch^options^ does not matter. The full list of options can be found in
19210 the GNU Profiler User's Guide documentation that comes with this documentation.
19211
19212 The following is the subset of those switches that is most relevant:
19213
19214 @table @option
19215
19216 @item --demangle[=@var{style}]
19217 @itemx --no-demangle
19218 @cindex @option{--demangle} (@code{gprof})
19219 These options control whether symbol names should be demangled when
19220 printing output.  The default is to demangle C++ symbols.  The
19221 @code{--no-demangle} option may be used to turn off demangling. Different
19222 compilers have different mangling styles.  The optional demangling style
19223 argument can be used to choose an appropriate demangling style for your
19224 compiler, in particular Ada symbols generated by GNAT can be demangled using
19225 @code{--demangle=gnat}.
19226
19227 @item -e @var{function_name}
19228 @cindex @option{-e} (@code{gprof})
19229 The @samp{-e @var{function}} option tells @code{gprof} not to print
19230 information about the function @var{function_name} (and its
19231 children@dots{}) in the call graph.  The function will still be listed
19232 as a child of any functions that call it, but its index number will be
19233 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19234 given; only one @var{function_name} may be indicated with each @samp{-e}
19235 option.
19236
19237 @item -E @var{function_name}
19238 @cindex @option{-E} (@code{gprof})
19239 The @code{-E @var{function}} option works like the @code{-e} option, but
19240 execution time spent in the function (and children who were not called from
19241 anywhere else), will not be used to compute the percentages-of-time for
19242 the call graph.  More than one @samp{-E} option may be given; only one
19243 @var{function_name} may be indicated with each @samp{-E} option.
19244
19245 @item -f @var{function_name}
19246 @cindex @option{-f} (@code{gprof})
19247 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19248 call graph to the function @var{function_name} and its children (and
19249 their children@dots{}).  More than one @samp{-f} option may be given;
19250 only one @var{function_name} may be indicated with each @samp{-f}
19251 option.
19252
19253 @item -F @var{function_name}
19254 @cindex @option{-F} (@code{gprof})
19255 The @samp{-F @var{function}} option works like the @code{-f} option, but
19256 only time spent in the function and its children (and their
19257 children@dots{}) will be used to determine total-time and
19258 percentages-of-time for the call graph.  More than one @samp{-F} option
19259 may be given; only one @var{function_name} may be indicated with each
19260 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19261
19262 @end table
19263
19264 @node Interpretation of profiling results
19265 @subsection Interpretation of profiling results
19266
19267 @noindent
19268
19269 The results of the profiling analysis are represented by two arrays: the
19270 'flat profile' and the 'call graph'. Full documentation of those outputs
19271 can be found in the GNU Profiler User's Guide.
19272
19273 The flat profile shows the time spent in each function of the program, and how
19274 many time it has been called. This allows you to locate easily the most
19275 time-consuming functions.
19276
19277 The call graph shows, for each subprogram, the subprograms that call it,
19278 and the subprograms that it calls. It also provides an estimate of the time
19279 spent in each of those callers/called subprograms.
19280 @end ifclear
19281
19282 @c ******************************
19283 @node Running and Debugging Ada Programs
19284 @chapter Running and Debugging Ada Programs
19285 @cindex Debugging
19286
19287 @noindent
19288 This chapter discusses how to debug Ada programs.
19289 @ifset vms
19290 It applies to GNAT on the Alpha OpenVMS platform;
19291 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19292 since HP has implemented Ada support in the OpenVMS debugger on I64.
19293 @end ifset
19294
19295 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19296
19297 @enumerate
19298 @item
19299 The illegality may be a violation of the static semantics of Ada. In
19300 that case GNAT diagnoses the constructs in the program that are illegal.
19301 It is then a straightforward matter for the user to modify those parts of
19302 the program.
19303
19304 @item
19305 The illegality may be a violation of the dynamic semantics of Ada. In
19306 that case the program compiles and executes, but may generate incorrect
19307 results, or may terminate abnormally with some exception.
19308
19309 @item
19310 When presented with a program that contains convoluted errors, GNAT
19311 itself may terminate abnormally without providing full diagnostics on
19312 the incorrect user program.
19313 @end enumerate
19314
19315 @menu
19316 * The GNAT Debugger GDB::
19317 * Running GDB::
19318 * Introduction to GDB Commands::
19319 * Using Ada Expressions::
19320 * Calling User-Defined Subprograms::
19321 * Using the Next Command in a Function::
19322 * Ada Exceptions::
19323 * Ada Tasks::
19324 * Debugging Generic Units::
19325 * Remote Debugging using gdbserver::
19326 * GNAT Abnormal Termination or Failure to Terminate::
19327 * Naming Conventions for GNAT Source Files::
19328 * Getting Internal Debugging Information::
19329 * Stack Traceback::
19330 @end menu
19331
19332 @cindex Debugger
19333 @findex gdb
19334
19335 @node The GNAT Debugger GDB
19336 @section The GNAT Debugger GDB
19337
19338 @noindent
19339 @code{GDB} is a general purpose, platform-independent debugger that
19340 can be used to debug mixed-language programs compiled with @command{gcc},
19341 and in particular is capable of debugging Ada programs compiled with
19342 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19343 complex Ada data structures.
19344
19345 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19346 @ifset vms
19347 located in the GNU:[DOCS] directory,
19348 @end ifset
19349 for full details on the usage of @code{GDB}, including a section on
19350 its usage on programs. This manual should be consulted for full
19351 details. The section that follows is a brief introduction to the
19352 philosophy and use of @code{GDB}.
19353
19354 When GNAT programs are compiled, the compiler optionally writes debugging
19355 information into the generated object file, including information on
19356 line numbers, and on declared types and variables. This information is
19357 separate from the generated code. It makes the object files considerably
19358 larger, but it does not add to the size of the actual executable that
19359 will be loaded into memory, and has no impact on run-time performance. The
19360 generation of debug information is triggered by the use of the
19361 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19362 used to carry out the compilations. It is important to emphasize that
19363 the use of these options does not change the generated code.
19364
19365 The debugging information is written in standard system formats that
19366 are used by many tools, including debuggers and profilers. The format
19367 of the information is typically designed to describe C types and
19368 semantics, but GNAT implements a translation scheme which allows full
19369 details about Ada types and variables to be encoded into these
19370 standard C formats. Details of this encoding scheme may be found in
19371 the file exp_dbug.ads in the GNAT source distribution. However, the
19372 details of this encoding are, in general, of no interest to a user,
19373 since @code{GDB} automatically performs the necessary decoding.
19374
19375 When a program is bound and linked, the debugging information is
19376 collected from the object files, and stored in the executable image of
19377 the program. Again, this process significantly increases the size of
19378 the generated executable file, but it does not increase the size of
19379 the executable program itself. Furthermore, if this program is run in
19380 the normal manner, it runs exactly as if the debug information were
19381 not present, and takes no more actual memory.
19382
19383 However, if the program is run under control of @code{GDB}, the
19384 debugger is activated.  The image of the program is loaded, at which
19385 point it is ready to run.  If a run command is given, then the program
19386 will run exactly as it would have if @code{GDB} were not present. This
19387 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19388 entirely non-intrusive until a breakpoint is encountered.  If no
19389 breakpoint is ever hit, the program will run exactly as it would if no
19390 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19391 the debugging information and can respond to user commands to inspect
19392 variables, and more generally to report on the state of execution.
19393
19394 @c **************
19395 @node Running GDB
19396 @section Running GDB
19397
19398 @noindent
19399 This section describes how to initiate the debugger.
19400 @c The above sentence is really just filler, but it was otherwise
19401 @c clumsy to get the first paragraph nonindented given the conditional
19402 @c nature of the description
19403
19404 @ifclear vms
19405 The debugger can be launched from a @code{GPS} menu or
19406 directly from the command line. The description below covers the latter use.
19407 All the commands shown can be used in the @code{GPS} debug console window,
19408 but there are usually more GUI-based ways to achieve the same effect.
19409 @end ifclear
19410
19411 The command to run @code{GDB} is
19412
19413 @smallexample
19414 $ ^gdb program^GDB PROGRAM^
19415 @end smallexample
19416
19417 @noindent
19418 where @code{^program^PROGRAM^} is the name of the executable file. This
19419 activates the debugger and results in a prompt for debugger commands.
19420 The simplest command is simply @code{run}, which causes the program to run
19421 exactly as if the debugger were not present. The following section
19422 describes some of the additional commands that can be given to @code{GDB}.
19423
19424 @c *******************************
19425 @node Introduction to GDB Commands
19426 @section Introduction to GDB Commands
19427
19428 @noindent
19429 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19430 Debugging with GDB, gdb, Debugging with GDB},
19431 @ifset vms
19432 located in the GNU:[DOCS] directory,
19433 @end ifset
19434 for extensive documentation on the use
19435 of these commands, together with examples of their use. Furthermore,
19436 the command @command{help} invoked from within GDB activates a simple help
19437 facility which summarizes the available commands and their options.
19438 In this section we summarize a few of the most commonly
19439 used commands to give an idea of what @code{GDB} is about. You should create
19440 a simple program with debugging information and experiment with the use of
19441 these @code{GDB} commands on the program as you read through the
19442 following section.
19443
19444 @table @code
19445 @item set args @var{arguments}
19446 The @var{arguments} list above is a list of arguments to be passed to
19447 the program on a subsequent run command, just as though the arguments
19448 had been entered on a normal invocation of the program. The @code{set args}
19449 command is not needed if the program does not require arguments.
19450
19451 @item run
19452 The @code{run} command causes execution of the program to start from
19453 the beginning. If the program is already running, that is to say if
19454 you are currently positioned at a breakpoint, then a prompt will ask
19455 for confirmation that you want to abandon the current execution and
19456 restart.
19457
19458 @item breakpoint @var{location}
19459 The breakpoint command sets a breakpoint, that is to say a point at which
19460 execution will halt and @code{GDB} will await further
19461 commands. @var{location} is
19462 either a line number within a file, given in the format @code{file:linenumber},
19463 or it is the name of a subprogram. If you request that a breakpoint be set on
19464 a subprogram that is overloaded, a prompt will ask you to specify on which of
19465 those subprograms you want to breakpoint. You can also
19466 specify that all of them should be breakpointed. If the program is run
19467 and execution encounters the breakpoint, then the program
19468 stops and @code{GDB} signals that the breakpoint was encountered by
19469 printing the line of code before which the program is halted.
19470
19471 @item catch exception @var{name}
19472 This command causes the program execution to stop whenever exception
19473 @var{name} is raised.  If @var{name} is omitted, then the execution is
19474 suspended when any exception is raised.
19475
19476 @item print @var{expression}
19477 This will print the value of the given expression. Most simple
19478 Ada expression formats are properly handled by @code{GDB}, so the expression
19479 can contain function calls, variables, operators, and attribute references.
19480
19481 @item continue
19482 Continues execution following a breakpoint, until the next breakpoint or the
19483 termination of the program.
19484
19485 @item step
19486 Executes a single line after a breakpoint. If the next statement
19487 is a subprogram call, execution continues into (the first statement of)
19488 the called subprogram.
19489
19490 @item next
19491 Executes a single line. If this line is a subprogram call, executes and
19492 returns from the call.
19493
19494 @item list
19495 Lists a few lines around the current source location. In practice, it
19496 is usually more convenient to have a separate edit window open with the
19497 relevant source file displayed. Successive applications of this command
19498 print subsequent lines. The command can be given an argument which is a
19499 line number, in which case it displays a few lines around the specified one.
19500
19501 @item backtrace
19502 Displays a backtrace of the call chain. This command is typically
19503 used after a breakpoint has occurred, to examine the sequence of calls that
19504 leads to the current breakpoint. The display includes one line for each
19505 activation record (frame) corresponding to an active subprogram.
19506
19507 @item up
19508 At a breakpoint, @code{GDB} can display the values of variables local
19509 to the current frame. The command @code{up} can be used to
19510 examine the contents of other active frames, by moving the focus up
19511 the stack, that is to say from callee to caller, one frame at a time.
19512
19513 @item down
19514 Moves the focus of @code{GDB} down from the frame currently being
19515 examined to the frame of its callee (the reverse of the previous command),
19516
19517 @item frame @var{n}
19518 Inspect the frame with the given number. The value 0 denotes the frame
19519 of the current breakpoint, that is to say the top of the call stack.
19520
19521 @end table
19522
19523 @noindent
19524 The above list is a very short introduction to the commands that
19525 @code{GDB} provides. Important additional capabilities, including conditional
19526 breakpoints, the ability to execute command sequences on a breakpoint,
19527 the ability to debug at the machine instruction level and many other
19528 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19529 Debugging with GDB}.  Note that most commands can be abbreviated
19530 (for example, c for continue, bt for backtrace).
19531
19532 @node Using Ada Expressions
19533 @section Using Ada Expressions
19534 @cindex Ada expressions
19535
19536 @noindent
19537 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19538 extensions. The philosophy behind the design of this subset is
19539
19540 @itemize @bullet
19541 @item
19542 That @code{GDB} should provide basic literals and access to operations for
19543 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19544 leaving more sophisticated computations to subprograms written into the
19545 program (which therefore may be called from @code{GDB}).
19546
19547 @item
19548 That type safety and strict adherence to Ada language restrictions
19549 are not particularly important to the @code{GDB} user.
19550
19551 @item
19552 That brevity is important to the @code{GDB} user.
19553 @end itemize
19554
19555 @noindent
19556 Thus, for brevity, the debugger acts as if there were
19557 implicit @code{with} and @code{use} clauses in effect for all user-written
19558 packages, thus making it unnecessary to fully qualify most names with
19559 their packages, regardless of context. Where this causes ambiguity,
19560 @code{GDB} asks the user's intent.
19561
19562 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19563 GDB, gdb, Debugging with GDB}.
19564
19565 @node Calling User-Defined Subprograms
19566 @section Calling User-Defined Subprograms
19567
19568 @noindent
19569 An important capability of @code{GDB} is the ability to call user-defined
19570 subprograms while debugging. This is achieved simply by entering
19571 a subprogram call statement in the form:
19572
19573 @smallexample
19574 call subprogram-name (parameters)
19575 @end smallexample
19576
19577 @noindent
19578 The keyword @code{call} can be omitted in the normal case where the
19579 @code{subprogram-name} does not coincide with any of the predefined
19580 @code{GDB} commands.
19581
19582 The effect is to invoke the given subprogram, passing it the
19583 list of parameters that is supplied. The parameters can be expressions and
19584 can include variables from the program being debugged. The
19585 subprogram must be defined
19586 at the library level within your program, and @code{GDB} will call the
19587 subprogram within the environment of your program execution (which
19588 means that the subprogram is free to access or even modify variables
19589 within your program).
19590
19591 The most important use of this facility is in allowing the inclusion of
19592 debugging routines that are tailored to particular data structures
19593 in your program. Such debugging routines can be written to provide a suitably
19594 high-level description of an abstract type, rather than a low-level dump
19595 of its physical layout. After all, the standard
19596 @code{GDB print} command only knows the physical layout of your
19597 types, not their abstract meaning. Debugging routines can provide information
19598 at the desired semantic level and are thus enormously useful.
19599
19600 For example, when debugging GNAT itself, it is crucial to have access to
19601 the contents of the tree nodes used to represent the program internally.
19602 But tree nodes are represented simply by an integer value (which in turn
19603 is an index into a table of nodes).
19604 Using the @code{print} command on a tree node would simply print this integer
19605 value, which is not very useful. But the PN routine (defined in file
19606 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19607 a useful high level representation of the tree node, which includes the
19608 syntactic category of the node, its position in the source, the integers
19609 that denote descendant nodes and parent node, as well as varied
19610 semantic information. To study this example in more detail, you might want to
19611 look at the body of the PN procedure in the stated file.
19612
19613 @node Using the Next Command in a Function
19614 @section Using the Next Command in a Function
19615
19616 @noindent
19617 When you use the @code{next} command in a function, the current source
19618 location will advance to the next statement as usual. A special case
19619 arises in the case of a @code{return} statement.
19620
19621 Part of the code for a return statement is the ``epilog'' of the function.
19622 This is the code that returns to the caller. There is only one copy of
19623 this epilog code, and it is typically associated with the last return
19624 statement in the function if there is more than one return. In some
19625 implementations, this epilog is associated with the first statement
19626 of the function.
19627
19628 The result is that if you use the @code{next} command from a return
19629 statement that is not the last return statement of the function you
19630 may see a strange apparent jump to the last return statement or to
19631 the start of the function. You should simply ignore this odd jump.
19632 The value returned is always that from the first return statement
19633 that was stepped through.
19634
19635 @node Ada Exceptions
19636 @section Stopping when Ada Exceptions are Raised
19637 @cindex Exceptions
19638
19639 @noindent
19640 You can set catchpoints that stop the program execution when your program
19641 raises selected exceptions.
19642
19643 @table @code
19644 @item catch exception
19645 Set a catchpoint that stops execution whenever (any task in the) program
19646 raises any exception.
19647
19648 @item catch exception @var{name}
19649 Set a catchpoint that stops execution whenever (any task in the) program
19650 raises the exception @var{name}.
19651
19652 @item catch exception unhandled
19653 Set a catchpoint that stops executing whenever (any task in the) program
19654 raises an exception for which there is no handler.
19655
19656 @item info exceptions
19657 @itemx info exceptions @var{regexp}
19658 The @code{info exceptions} command permits the user to examine all defined
19659 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19660 argument, prints out only those exceptions whose name matches @var{regexp}.
19661 @end table
19662
19663 @node Ada Tasks
19664 @section Ada Tasks
19665 @cindex Tasks
19666
19667 @noindent
19668 @code{GDB} allows the following task-related commands:
19669
19670 @table @code
19671 @item info tasks
19672 This command shows a list of current Ada tasks, as in the following example:
19673
19674 @smallexample
19675 @iftex
19676 @leftskip=0cm
19677 @end iftex
19678 (gdb) info tasks
19679   ID       TID P-ID   Thread Pri State                 Name
19680    1   8088000   0   807e000  15 Child Activation Wait main_task
19681    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19682    3   809a800   1   80a4800  15 Child Activation Wait a
19683 *  4   80ae800   3   80b8000  15 Running               c
19684 @end smallexample
19685
19686 @noindent
19687 In this listing, the asterisk before the first task indicates it to be the
19688 currently running task. The first column lists the task ID that is used
19689 to refer to tasks in the following commands.
19690
19691 @item break @var{linespec} task @var{taskid}
19692 @itemx break @var{linespec} task @var{taskid} if @dots{}
19693 @cindex Breakpoints and tasks
19694 These commands are like the @code{break @dots{} thread @dots{}}.
19695 @var{linespec} specifies source lines.
19696
19697 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19698 to specify that you only want @code{GDB} to stop the program when a
19699 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19700 numeric task identifiers assigned by @code{GDB}, shown in the first
19701 column of the @samp{info tasks} display.
19702
19703 If you do not specify @samp{task @var{taskid}} when you set a
19704 breakpoint, the breakpoint applies to @emph{all} tasks of your
19705 program.
19706
19707 You can use the @code{task} qualifier on conditional breakpoints as
19708 well; in this case, place @samp{task @var{taskid}} before the
19709 breakpoint condition (before the @code{if}).
19710
19711 @item task @var{taskno}
19712 @cindex Task switching
19713
19714 This command allows to switch to the task referred by @var{taskno}. In
19715 particular, This allows to browse the backtrace of the specified
19716 task. It is advised to switch back to the original task before
19717 continuing execution otherwise the scheduling of the program may be
19718 perturbed.
19719 @end table
19720
19721 @noindent
19722 For more detailed information on the tasking support,
19723 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19724
19725 @node Debugging Generic Units
19726 @section Debugging Generic Units
19727 @cindex Debugging Generic Units
19728 @cindex Generics
19729
19730 @noindent
19731 GNAT always uses code expansion for generic instantiation. This means that
19732 each time an instantiation occurs, a complete copy of the original code is
19733 made, with appropriate substitutions of formals by actuals.
19734
19735 It is not possible to refer to the original generic entities in
19736 @code{GDB}, but it is always possible to debug a particular instance of
19737 a generic, by using the appropriate expanded names. For example, if we have
19738
19739 @smallexample @c ada
19740 @group
19741 @cartouche
19742 procedure g is
19743
19744    generic package k is
19745       procedure kp (v1 : in out integer);
19746    end k;
19747
19748    package body k is
19749       procedure kp (v1 : in out integer) is
19750       begin
19751          v1 := v1 + 1;
19752       end kp;
19753    end k;
19754
19755    package k1 is new k;
19756    package k2 is new k;
19757
19758    var : integer := 1;
19759
19760 begin
19761    k1.kp (var);
19762    k2.kp (var);
19763    k1.kp (var);
19764    k2.kp (var);
19765 end;
19766 @end cartouche
19767 @end group
19768 @end smallexample
19769
19770 @noindent
19771 Then to break on a call to procedure kp in the k2 instance, simply
19772 use the command:
19773
19774 @smallexample
19775 (gdb) break g.k2.kp
19776 @end smallexample
19777
19778 @noindent
19779 When the breakpoint occurs, you can step through the code of the
19780 instance in the normal manner and examine the values of local variables, as for
19781 other units.
19782
19783 @node Remote Debugging using gdbserver
19784 @section Remote Debugging using gdbserver
19785 @cindex Remote Debugging using gdbserver
19786
19787 @noindent
19788 On platforms where gdbserver is supported, it is possible to use this tool
19789 to debug your application remotely.  This can be useful in situations
19790 where the program needs to be run on a target host that is different
19791 from the host used for development, particularly when the target has
19792 a limited amount of resources (either CPU and/or memory).
19793
19794 To do so, start your program using gdbserver on the target machine.
19795 gdbserver then automatically suspends the execution of your program
19796 at its entry point, waiting for a debugger to connect to it.  The
19797 following commands starts an application and tells gdbserver to
19798 wait for a connection with the debugger on localhost port 4444.
19799
19800 @smallexample
19801 $ gdbserver localhost:4444 program
19802 Process program created; pid = 5685
19803 Listening on port 4444
19804 @end smallexample
19805
19806 Once gdbserver has started listening, we can tell the debugger to establish
19807 a connection with this gdbserver, and then start the same debugging session
19808 as if the program was being debugged on the same host, directly under
19809 the control of GDB.
19810
19811 @smallexample
19812 $ gdb program
19813 (gdb) target remote targethost:4444
19814 Remote debugging using targethost:4444
19815 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19816 (gdb) b foo.adb:3
19817 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19818 (gdb) continue
19819 Continuing.
19820
19821 Breakpoint 1, foo () at foo.adb:4
19822 4       end foo;
19823 @end smallexample
19824
19825 It is also possible to use gdbserver to attach to an already running
19826 program, in which case the execution of that program is simply suspended
19827 until the connection between the debugger and gdbserver is established.
19828
19829 For more information on how to use gdbserver, @ref{Top, Server, Using
19830 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
19831 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19832
19833 @node GNAT Abnormal Termination or Failure to Terminate
19834 @section GNAT Abnormal Termination or Failure to Terminate
19835 @cindex GNAT Abnormal Termination or Failure to Terminate
19836
19837 @noindent
19838 When presented with programs that contain serious errors in syntax
19839 or semantics,
19840 GNAT may on rare occasions  experience problems in operation, such
19841 as aborting with a
19842 segmentation fault or illegal memory access, raising an internal
19843 exception, terminating abnormally, or failing to terminate at all.
19844 In such cases, you can activate
19845 various features of GNAT that can help you pinpoint the construct in your
19846 program that is the likely source of the problem.
19847
19848 The following strategies are presented in increasing order of
19849 difficulty, corresponding to your experience in using GNAT and your
19850 familiarity with compiler internals.
19851
19852 @enumerate
19853 @item
19854 Run @command{gcc} with the @option{-gnatf}. This first
19855 switch causes all errors on a given line to be reported. In its absence,
19856 only the first error on a line is displayed.
19857
19858 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19859 are encountered, rather than after compilation is terminated. If GNAT
19860 terminates prematurely or goes into an infinite loop, the last error
19861 message displayed may help to pinpoint the culprit.
19862
19863 @item
19864 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19865 mode, @command{gcc} produces ongoing information about the progress of the
19866 compilation and provides the name of each procedure as code is
19867 generated. This switch allows you to find which Ada procedure was being
19868 compiled when it encountered a code generation problem.
19869
19870 @item
19871 @cindex @option{-gnatdc} switch
19872 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19873 switch that does for the front-end what @option{^-v^VERBOSE^} does
19874 for the back end. The system prints the name of each unit,
19875 either a compilation unit or nested unit, as it is being analyzed.
19876 @item
19877 Finally, you can start
19878 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19879 front-end of GNAT, and can be run independently (normally it is just
19880 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19881 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19882 @code{where} command is the first line of attack; the variable
19883 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19884 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19885 which the execution stopped, and @code{input_file name} indicates the name of
19886 the source file.
19887 @end enumerate
19888
19889 @node Naming Conventions for GNAT Source Files
19890 @section Naming Conventions for GNAT Source Files
19891
19892 @noindent
19893 In order to examine the workings of the GNAT system, the following
19894 brief description of its organization may be helpful:
19895
19896 @itemize @bullet
19897 @item
19898 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19899
19900 @item
19901 All files prefixed with @file{^par^PAR^} are components of the parser. The
19902 numbers correspond to chapters of the Ada Reference Manual. For example,
19903 parsing of select statements can be found in @file{par-ch9.adb}.
19904
19905 @item
19906 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19907 numbers correspond to chapters of the Ada standard. For example, all
19908 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19909 addition, some features of the language require sufficient special processing
19910 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19911 dynamic dispatching, etc.
19912
19913 @item
19914 All files prefixed with @file{^exp^EXP^} perform normalization and
19915 expansion of the intermediate representation (abstract syntax tree, or AST).
19916 these files use the same numbering scheme as the parser and semantics files.
19917 For example, the construction of record initialization procedures is done in
19918 @file{exp_ch3.adb}.
19919
19920 @item
19921 The files prefixed with @file{^bind^BIND^} implement the binder, which
19922 verifies the consistency of the compilation, determines an order of
19923 elaboration, and generates the bind file.
19924
19925 @item
19926 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19927 data structures used by the front-end.
19928
19929 @item
19930 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19931 the abstract syntax tree as produced by the parser.
19932
19933 @item
19934 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19935 all entities, computed during semantic analysis.
19936
19937 @item
19938 Library management issues are dealt with in files with prefix
19939 @file{^lib^LIB^}.
19940
19941 @item
19942 @findex Ada
19943 @cindex Annex A
19944 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19945 defined in Annex A.
19946
19947 @item
19948 @findex Interfaces
19949 @cindex Annex B
19950 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19951 defined in Annex B.
19952
19953 @item
19954 @findex System
19955 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19956 both language-defined children and GNAT run-time routines.
19957
19958 @item
19959 @findex GNAT
19960 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19961 general-purpose packages, fully documented in their specs. All
19962 the other @file{.c} files are modifications of common @command{gcc} files.
19963 @end itemize
19964
19965 @node Getting Internal Debugging Information
19966 @section Getting Internal Debugging Information
19967
19968 @noindent
19969 Most compilers have internal debugging switches and modes. GNAT
19970 does also, except GNAT internal debugging switches and modes are not
19971 secret. A summary and full description of all the compiler and binder
19972 debug flags are in the file @file{debug.adb}. You must obtain the
19973 sources of the compiler to see the full detailed effects of these flags.
19974
19975 The switches that print the source of the program (reconstructed from
19976 the internal tree) are of general interest for user programs, as are the
19977 options to print
19978 the full internal tree, and the entity table (the symbol table
19979 information). The reconstructed source provides a readable version of the
19980 program after the front-end has completed analysis and  expansion,
19981 and is useful when studying the performance of specific constructs.
19982 For example, constraint checks are indicated, complex aggregates
19983 are replaced with loops and assignments, and tasking primitives
19984 are replaced with run-time calls.
19985
19986 @node Stack Traceback
19987 @section Stack Traceback
19988 @cindex traceback
19989 @cindex stack traceback
19990 @cindex stack unwinding
19991
19992 @noindent
19993 Traceback is a mechanism to display the sequence of subprogram calls that
19994 leads to a specified execution point in a program. Often (but not always)
19995 the execution point is an instruction at which an exception has been raised.
19996 This mechanism is also known as @i{stack unwinding} because it obtains
19997 its information by scanning the run-time stack and recovering the activation
19998 records of all active subprograms. Stack unwinding is one of the most
19999 important tools for program debugging.
20000
20001 The first entry stored in traceback corresponds to the deepest calling level,
20002 that is to say the subprogram currently executing the instruction
20003 from which we want to obtain the traceback.
20004
20005 Note that there is no runtime performance penalty when stack traceback
20006 is enabled, and no exception is raised during program execution.
20007
20008 @menu
20009 * Non-Symbolic Traceback::
20010 * Symbolic Traceback::
20011 @end menu
20012
20013 @node Non-Symbolic Traceback
20014 @subsection Non-Symbolic Traceback
20015 @cindex traceback, non-symbolic
20016
20017 @noindent
20018 Note: this feature is not supported on all platforms. See
20019 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20020 platforms.
20021
20022 @menu
20023 * Tracebacks From an Unhandled Exception::
20024 * Tracebacks From Exception Occurrences (non-symbolic)::
20025 * Tracebacks From Anywhere in a Program (non-symbolic)::
20026 @end menu
20027
20028 @node Tracebacks From an Unhandled Exception
20029 @subsubsection Tracebacks From an Unhandled Exception
20030
20031 @noindent
20032 A runtime non-symbolic traceback is a list of addresses of call instructions.
20033 To enable this feature you must use the @option{-E}
20034 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20035 of exception information. You can retrieve this information using the
20036 @code{addr2line} tool.
20037
20038 Here is a simple example:
20039
20040 @smallexample @c ada
20041 @cartouche
20042 procedure STB is
20043
20044    procedure P1 is
20045    begin
20046       raise Constraint_Error;
20047    end P1;
20048
20049    procedure P2 is
20050    begin
20051       P1;
20052    end P2;
20053
20054 begin
20055    P2;
20056 end STB;
20057 @end cartouche
20058 @end smallexample
20059
20060 @smallexample
20061 $ gnatmake stb -bargs -E
20062 $ stb
20063
20064 Execution terminated by unhandled exception
20065 Exception name: CONSTRAINT_ERROR
20066 Message: stb.adb:5
20067 Call stack traceback locations:
20068 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20069 @end smallexample
20070
20071 @noindent
20072 As we see the traceback lists a sequence of addresses for the unhandled
20073 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20074 guess that this exception come from procedure P1. To translate these
20075 addresses into the source lines where the calls appear, the
20076 @code{addr2line} tool, described below, is invaluable. The use of this tool
20077 requires the program to be compiled with debug information.
20078
20079 @smallexample
20080 $ gnatmake -g stb -bargs -E
20081 $ stb
20082
20083 Execution terminated by unhandled exception
20084 Exception name: CONSTRAINT_ERROR
20085 Message: stb.adb:5
20086 Call stack traceback locations:
20087 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20088
20089 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20090    0x4011f1 0x77e892a4
20091
20092 00401373 at d:/stb/stb.adb:5
20093 0040138B at d:/stb/stb.adb:10
20094 0040139C at d:/stb/stb.adb:14
20095 00401335 at d:/stb/b~stb.adb:104
20096 004011C4 at /build/@dots{}/crt1.c:200
20097 004011F1 at /build/@dots{}/crt1.c:222
20098 77E892A4 in ?? at ??:0
20099 @end smallexample
20100
20101 @noindent
20102 The @code{addr2line} tool has several other useful options:
20103
20104 @table @code
20105 @item --functions
20106 to get the function name corresponding to any location
20107
20108 @item --demangle=gnat
20109 to use the gnat decoding mode for the function names. Note that
20110 for binutils version 2.9.x the option is simply @option{--demangle}.
20111 @end table
20112
20113 @smallexample
20114 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20115    0x40139c 0x401335 0x4011c4 0x4011f1
20116
20117 00401373 in stb.p1 at d:/stb/stb.adb:5
20118 0040138B in stb.p2 at d:/stb/stb.adb:10
20119 0040139C in stb at d:/stb/stb.adb:14
20120 00401335 in main at d:/stb/b~stb.adb:104
20121 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
20122 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
20123 @end smallexample
20124
20125 @noindent
20126 From this traceback we can see that the exception was raised in
20127 @file{stb.adb} at line 5, which was reached from a procedure call in
20128 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20129 which contains the call to the main program.
20130 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20131 and the output will vary from platform to platform.
20132
20133 It is also possible to use @code{GDB} with these traceback addresses to debug
20134 the program. For example, we can break at a given code location, as reported
20135 in the stack traceback:
20136
20137 @smallexample
20138 $ gdb -nw stb
20139 @ifclear vms
20140 @noindent
20141 Furthermore, this feature is not implemented inside Windows DLL. Only
20142 the non-symbolic traceback is reported in this case.
20143 @end ifclear
20144
20145 (gdb) break *0x401373
20146 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20147 @end smallexample
20148
20149 @noindent
20150 It is important to note that the stack traceback addresses
20151 do not change when debug information is included. This is particularly useful
20152 because it makes it possible to release software without debug information (to
20153 minimize object size), get a field report that includes a stack traceback
20154 whenever an internal bug occurs, and then be able to retrieve the sequence
20155 of calls with the same program compiled with debug information.
20156
20157 @node Tracebacks From Exception Occurrences (non-symbolic)
20158 @subsubsection Tracebacks From Exception Occurrences
20159
20160 @noindent
20161 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20162 The stack traceback is attached to the exception information string, and can
20163 be retrieved in an exception handler within the Ada program, by means of the
20164 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20165
20166 @smallexample @c ada
20167 with Ada.Text_IO;
20168 with Ada.Exceptions;
20169
20170 procedure STB is
20171
20172    use Ada;
20173    use Ada.Exceptions;
20174
20175    procedure P1 is
20176       K : Positive := 1;
20177    begin
20178       K := K - 1;
20179    exception
20180       when E : others =>
20181          Text_IO.Put_Line (Exception_Information (E));
20182    end P1;
20183
20184    procedure P2 is
20185    begin
20186       P1;
20187    end P2;
20188
20189 begin
20190    P2;
20191 end STB;
20192 @end smallexample
20193
20194 @noindent
20195 This program will output:
20196
20197 @smallexample
20198 $ stb
20199
20200 Exception name: CONSTRAINT_ERROR
20201 Message: stb.adb:12
20202 Call stack traceback locations:
20203 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20204 @end smallexample
20205
20206 @node Tracebacks From Anywhere in a Program (non-symbolic)
20207 @subsubsection Tracebacks From Anywhere in a Program
20208
20209 @noindent
20210 It is also possible to retrieve a stack traceback from anywhere in a
20211 program. For this you need to
20212 use the @code{GNAT.Traceback} API. This package includes a procedure called
20213 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20214 display procedures described below. It is not necessary to use the
20215 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20216 is invoked explicitly.
20217
20218 @noindent
20219 In the following example we compute a traceback at a specific location in
20220 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20221 convert addresses to strings:
20222
20223 @smallexample @c ada
20224 with Ada.Text_IO;
20225 with GNAT.Traceback;
20226 with GNAT.Debug_Utilities;
20227
20228 procedure STB is
20229
20230    use Ada;
20231    use GNAT;
20232    use GNAT.Traceback;
20233
20234    procedure P1 is
20235       TB  : Tracebacks_Array (1 .. 10);
20236       --  We are asking for a maximum of 10 stack frames.
20237       Len : Natural;
20238       --  Len will receive the actual number of stack frames returned.
20239    begin
20240       Call_Chain (TB, Len);
20241
20242       Text_IO.Put ("In STB.P1 : ");
20243
20244       for K in 1 .. Len loop
20245          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20246          Text_IO.Put (' ');
20247       end loop;
20248
20249       Text_IO.New_Line;
20250    end P1;
20251
20252    procedure P2 is
20253    begin
20254       P1;
20255    end P2;
20256
20257 begin
20258    P2;
20259 end STB;
20260 @end smallexample
20261
20262 @smallexample
20263 $ gnatmake -g stb
20264 $ stb
20265
20266 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20267 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20268 @end smallexample
20269
20270 @noindent
20271 You can then get further information by invoking the @code{addr2line}
20272 tool as described earlier (note that the hexadecimal addresses
20273 need to be specified in C format, with a leading ``0x'').
20274
20275 @node Symbolic Traceback
20276 @subsection Symbolic Traceback
20277 @cindex traceback, symbolic
20278
20279 @noindent
20280 A symbolic traceback is a stack traceback in which procedure names are
20281 associated with each code location.
20282
20283 @noindent
20284 Note that this feature is not supported on all platforms. See
20285 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20286 list of currently supported platforms.
20287
20288 @noindent
20289 Note that the symbolic traceback requires that the program be compiled
20290 with debug information. If it is not compiled with debug information
20291 only the non-symbolic information will be valid.
20292
20293 @menu
20294 * Tracebacks From Exception Occurrences (symbolic)::
20295 * Tracebacks From Anywhere in a Program (symbolic)::
20296 @end menu
20297
20298 @node Tracebacks From Exception Occurrences (symbolic)
20299 @subsubsection Tracebacks From Exception Occurrences
20300
20301 @smallexample @c ada
20302 with Ada.Text_IO;
20303 with GNAT.Traceback.Symbolic;
20304
20305 procedure STB is
20306
20307    procedure P1 is
20308    begin
20309       raise Constraint_Error;
20310    end P1;
20311
20312    procedure P2 is
20313    begin
20314       P1;
20315    end P2;
20316
20317    procedure P3 is
20318    begin
20319       P2;
20320    end P3;
20321
20322 begin
20323    P3;
20324 exception
20325    when E : others =>
20326       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20327 end STB;
20328 @end smallexample
20329
20330 @smallexample
20331 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20332 $ stb
20333
20334 0040149F in stb.p1 at stb.adb:8
20335 004014B7 in stb.p2 at stb.adb:13
20336 004014CF in stb.p3 at stb.adb:18
20337 004015DD in ada.stb at stb.adb:22
20338 00401461 in main at b~stb.adb:168
20339 004011C4 in __mingw_CRTStartup at crt1.c:200
20340 004011F1 in mainCRTStartup at crt1.c:222
20341 77E892A4 in ?? at ??:0
20342 @end smallexample
20343
20344 @noindent
20345 In the above example the ``.\'' syntax in the @command{gnatmake} command
20346 is currently required by @command{addr2line} for files that are in
20347 the current working directory.
20348 Moreover, the exact sequence of linker options may vary from platform
20349 to platform.
20350 The above @option{-largs} section is for Windows platforms. By contrast,
20351 under Unix there is no need for the @option{-largs} section.
20352 Differences across platforms are due to details of linker implementation.
20353
20354 @node Tracebacks From Anywhere in a Program (symbolic)
20355 @subsubsection Tracebacks From Anywhere in a Program
20356
20357 @noindent
20358 It is possible to get a symbolic stack traceback
20359 from anywhere in a program, just as for non-symbolic tracebacks.
20360 The first step is to obtain a non-symbolic
20361 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20362 information. Here is an example:
20363
20364 @smallexample @c ada
20365 with Ada.Text_IO;
20366 with GNAT.Traceback;
20367 with GNAT.Traceback.Symbolic;
20368
20369 procedure STB is
20370
20371    use Ada;
20372    use GNAT.Traceback;
20373    use GNAT.Traceback.Symbolic;
20374
20375    procedure P1 is
20376       TB  : Tracebacks_Array (1 .. 10);
20377       --  We are asking for a maximum of 10 stack frames.
20378       Len : Natural;
20379       --  Len will receive the actual number of stack frames returned.
20380    begin
20381       Call_Chain (TB, Len);
20382       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20383    end P1;
20384
20385    procedure P2 is
20386    begin
20387       P1;
20388    end P2;
20389
20390 begin
20391    P2;
20392 end STB;
20393 @end smallexample
20394
20395 @c ******************************
20396 @ifset vms
20397 @node Compatibility with HP Ada
20398 @chapter Compatibility with HP Ada
20399 @cindex Compatibility
20400
20401 @noindent
20402 @cindex DEC Ada
20403 @cindex HP Ada
20404 @cindex Compatibility between GNAT and HP Ada
20405 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20406 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20407 GNAT is highly compatible
20408 with HP Ada, and it should generally be straightforward to port code
20409 from the HP Ada environment to GNAT. However, there are a few language
20410 and implementation differences of which the user must be aware. These
20411 differences are discussed in this chapter. In
20412 addition, the operating environment and command structure for the
20413 compiler are different, and these differences are also discussed.
20414
20415 For further details on these and other compatibility issues,
20416 see Appendix E of the HP publication
20417 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20418
20419 Except where otherwise indicated, the description of GNAT for OpenVMS
20420 applies to both the Alpha and I64 platforms.
20421
20422 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20423 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20424
20425 The discussion in this chapter addresses specifically the implementation
20426 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20427 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20428 GNAT always follows the Alpha implementation.
20429
20430 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20431 attributes are recognized, although only a subset of them can sensibly
20432 be implemented.  The description of pragmas in
20433 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20434 indicates whether or not they are applicable to non-VMS systems.
20435
20436 @menu
20437 * Ada Language Compatibility::
20438 * Differences in the Definition of Package System::
20439 * Language-Related Features::
20440 * The Package STANDARD::
20441 * The Package SYSTEM::
20442 * Tasking and Task-Related Features::
20443 * Pragmas and Pragma-Related Features::
20444 * Library of Predefined Units::
20445 * Bindings::
20446 * Main Program Definition::
20447 * Implementation-Defined Attributes::
20448 * Compiler and Run-Time Interfacing::
20449 * Program Compilation and Library Management::
20450 * Input-Output::
20451 * Implementation Limits::
20452 * Tools and Utilities::
20453 @end menu
20454
20455 @node Ada Language Compatibility
20456 @section Ada Language Compatibility
20457
20458 @noindent
20459 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20460 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20461 with Ada 83, and therefore Ada 83 programs will compile
20462 and run under GNAT with
20463 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20464 provides details on specific incompatibilities.
20465
20466 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20467 as well as the pragma @code{ADA_83}, to force the compiler to
20468 operate in Ada 83 mode. This mode does not guarantee complete
20469 conformance to Ada 83, but in practice is sufficient to
20470 eliminate most sources of incompatibilities.
20471 In particular, it eliminates the recognition of the
20472 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20473 in Ada 83 programs is legal, and handles the cases of packages
20474 with optional bodies, and generics that instantiate unconstrained
20475 types without the use of @code{(<>)}.
20476
20477 @node Differences in the Definition of Package System
20478 @section Differences in the Definition of Package @code{System}
20479
20480 @noindent
20481 An Ada compiler is allowed to add
20482 implementation-dependent declarations to package @code{System}.
20483 In normal mode,
20484 GNAT does not take advantage of this permission, and the version of
20485 @code{System} provided by GNAT exactly matches that defined in the Ada
20486 Reference Manual.
20487
20488 However, HP Ada adds an extensive set of declarations to package
20489 @code{System},
20490 as fully documented in the HP Ada manuals. To minimize changes required
20491 for programs that make use of these extensions, GNAT provides the pragma
20492 @code{Extend_System} for extending the definition of package System. By using:
20493 @cindex pragma @code{Extend_System}
20494 @cindex @code{Extend_System} pragma
20495
20496 @smallexample @c ada
20497 @group
20498 @cartouche
20499 pragma Extend_System (Aux_DEC);
20500 @end cartouche
20501 @end group
20502 @end smallexample
20503
20504 @noindent
20505 the set of definitions in @code{System} is extended to include those in
20506 package @code{System.Aux_DEC}.
20507 @cindex @code{System.Aux_DEC} package
20508 @cindex @code{Aux_DEC} package (child of @code{System})
20509 These definitions are incorporated directly into package @code{System},
20510 as though they had been declared there. For a
20511 list of the declarations added, see the spec of this package,
20512 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20513 @cindex @file{s-auxdec.ads} file
20514 The pragma @code{Extend_System} is a configuration pragma, which means that
20515 it can be placed in the file @file{gnat.adc}, so that it will automatically
20516 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20517 for further details.
20518
20519 An alternative approach that avoids the use of the non-standard
20520 @code{Extend_System} pragma is to add a context clause to the unit that
20521 references these facilities:
20522
20523 @smallexample @c ada
20524 @cartouche
20525 with System.Aux_DEC;
20526 use  System.Aux_DEC;
20527 @end cartouche
20528 @end smallexample
20529
20530 @noindent
20531 The effect is not quite semantically identical to incorporating
20532 the declarations directly into package @code{System},
20533 but most programs will not notice a difference
20534 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20535 to reference the entities directly in package @code{System}.
20536 For units containing such references,
20537 the prefixes must either be removed, or the pragma @code{Extend_System}
20538 must be used.
20539
20540 @node Language-Related Features
20541 @section Language-Related Features
20542
20543 @noindent
20544 The following sections highlight differences in types,
20545 representations of types, operations, alignment, and
20546 related topics.
20547
20548 @menu
20549 * Integer Types and Representations::
20550 * Floating-Point Types and Representations::
20551 * Pragmas Float_Representation and Long_Float::
20552 * Fixed-Point Types and Representations::
20553 * Record and Array Component Alignment::
20554 * Address Clauses::
20555 * Other Representation Clauses::
20556 @end menu
20557
20558 @node Integer Types and Representations
20559 @subsection Integer Types and Representations
20560
20561 @noindent
20562 The set of predefined integer types is identical in HP Ada and GNAT.
20563 Furthermore the representation of these integer types is also identical,
20564 including the capability of size clauses forcing biased representation.
20565
20566 In addition,
20567 HP Ada for OpenVMS Alpha systems has defined the
20568 following additional integer types in package @code{System}:
20569
20570 @itemize @bullet
20571
20572 @item
20573 @code{INTEGER_8}
20574
20575 @item
20576 @code{INTEGER_16}
20577
20578 @item
20579 @code{INTEGER_32}
20580
20581 @item
20582 @code{INTEGER_64}
20583
20584 @item
20585 @code{LARGEST_INTEGER}
20586 @end itemize
20587
20588 @noindent
20589 In GNAT, the first four of these types may be obtained from the
20590 standard Ada package @code{Interfaces}.
20591 Alternatively, by use of the pragma @code{Extend_System}, identical
20592 declarations can be referenced directly in package @code{System}.
20593 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20594
20595 @node Floating-Point Types and Representations
20596 @subsection Floating-Point Types and Representations
20597 @cindex Floating-Point types
20598
20599 @noindent
20600 The set of predefined floating-point types is identical in HP Ada and GNAT.
20601 Furthermore the representation of these floating-point
20602 types is also identical. One important difference is that the default
20603 representation for HP Ada is @code{VAX_Float}, but the default representation
20604 for GNAT is IEEE.
20605
20606 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20607 pragma @code{Float_Representation} as described in the HP Ada
20608 documentation.
20609 For example, the declarations:
20610
20611 @smallexample @c ada
20612 @cartouche
20613 type F_Float is digits 6;
20614 pragma Float_Representation (VAX_Float, F_Float);
20615 @end cartouche
20616 @end smallexample
20617
20618 @noindent
20619 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20620 format.
20621 This set of declarations actually appears in @code{System.Aux_DEC},
20622 which contains
20623 the full set of additional floating-point declarations provided in
20624 the HP Ada version of package @code{System}.
20625 This and similar declarations may be accessed in a user program
20626 by using pragma @code{Extend_System}. The use of this
20627 pragma, and the related pragma @code{Long_Float} is described in further
20628 detail in the following section.
20629
20630 @node Pragmas Float_Representation and Long_Float
20631 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20632
20633 @noindent
20634 HP Ada provides the pragma @code{Float_Representation}, which
20635 acts as a program library switch to allow control over
20636 the internal representation chosen for the predefined
20637 floating-point types declared in the package @code{Standard}.
20638 The format of this pragma is as follows:
20639
20640 @smallexample @c ada
20641 @cartouche
20642 pragma Float_Representation(VAX_Float | IEEE_Float);
20643 @end cartouche
20644 @end smallexample
20645
20646 @noindent
20647 This pragma controls the representation of floating-point
20648 types as follows:
20649
20650 @itemize @bullet
20651 @item
20652 @code{VAX_Float} specifies that floating-point
20653 types are represented by default with the VAX system hardware types
20654 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20655 Note that the @code{H-floating}
20656 type was available only on VAX systems, and is not available
20657 in either HP Ada or GNAT.
20658
20659 @item
20660 @code{IEEE_Float} specifies that floating-point
20661 types are represented by default with the IEEE single and
20662 double floating-point types.
20663 @end itemize
20664
20665 @noindent
20666 GNAT provides an identical implementation of the pragma
20667 @code{Float_Representation}, except that it functions as a
20668 configuration pragma. Note that the
20669 notion of configuration pragma corresponds closely to the
20670 HP Ada notion of a program library switch.
20671
20672 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20673 which is different
20674 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20675 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20676 advisable to change the format of numbers passed to standard library
20677 routines, and if necessary explicit type conversions may be needed.
20678
20679 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20680 efficient, and (given that it conforms to an international standard)
20681 potentially more portable.
20682 The situation in which @code{VAX_Float} may be useful is in interfacing
20683 to existing code and data that expect the use of @code{VAX_Float}.
20684 In such a situation use the predefined @code{VAX_Float}
20685 types in package @code{System}, as extended by
20686 @code{Extend_System}. For example, use @code{System.F_Float}
20687 to specify the 32-bit @code{F-Float} format.
20688
20689 @noindent
20690 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20691 to allow control over the internal representation chosen
20692 for the predefined type @code{Long_Float} and for floating-point
20693 type declarations with digits specified in the range 7 .. 15.
20694 The format of this pragma is as follows:
20695
20696 @smallexample @c ada
20697 @cartouche
20698 pragma Long_Float (D_FLOAT | G_FLOAT);
20699 @end cartouche
20700 @end smallexample
20701
20702 @node Fixed-Point Types and Representations
20703 @subsection Fixed-Point Types and Representations
20704
20705 @noindent
20706 On HP Ada for OpenVMS Alpha systems, rounding is
20707 away from zero for both positive and negative numbers.
20708 Therefore, @code{+0.5} rounds to @code{1},
20709 and @code{-0.5} rounds to @code{-1}.
20710
20711 On GNAT the results of operations
20712 on fixed-point types are in accordance with the Ada
20713 rules. In particular, results of operations on decimal
20714 fixed-point types are truncated.
20715
20716 @node Record and Array Component Alignment
20717 @subsection Record and Array Component Alignment
20718
20719 @noindent
20720 On HP Ada for OpenVMS Alpha, all non-composite components
20721 are aligned on natural boundaries. For example, 1-byte
20722 components are aligned on byte boundaries, 2-byte
20723 components on 2-byte boundaries, 4-byte components on 4-byte
20724 byte boundaries, and so on. The OpenVMS Alpha hardware
20725 runs more efficiently with naturally aligned data.
20726
20727 On GNAT, alignment rules are compatible
20728 with HP Ada for OpenVMS Alpha.
20729
20730 @node Address Clauses
20731 @subsection Address Clauses
20732
20733 @noindent
20734 In HP Ada and GNAT, address clauses are supported for
20735 objects and imported subprograms.
20736 The predefined type @code{System.Address} is a private type
20737 in both compilers on Alpha OpenVMS, with the same representation
20738 (it is simply a machine pointer). Addition, subtraction, and comparison
20739 operations are available in the standard Ada package
20740 @code{System.Storage_Elements}, or in package @code{System}
20741 if it is extended to include @code{System.Aux_DEC} using a
20742 pragma @code{Extend_System} as previously described.
20743
20744 Note that code that @code{with}'s both this extended package @code{System}
20745 and the package @code{System.Storage_Elements} should not @code{use}
20746 both packages, or ambiguities will result. In general it is better
20747 not to mix these two sets of facilities. The Ada package was
20748 designed specifically to provide the kind of features that HP Ada
20749 adds directly to package @code{System}.
20750
20751 The type @code{System.Address} is a 64-bit integer type in GNAT for
20752 I64 OpenVMS.  For more information,
20753 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20754
20755 GNAT is compatible with HP Ada in its handling of address
20756 clauses, except for some limitations in
20757 the form of address clauses for composite objects with
20758 initialization. Such address clauses are easily replaced
20759 by the use of an explicitly-defined constant as described
20760 in the Ada Reference Manual (13.1(22)). For example, the sequence
20761 of declarations:
20762
20763 @smallexample @c ada
20764 @cartouche
20765 X, Y : Integer := Init_Func;
20766 Q : String (X .. Y) := "abc";
20767 @dots{}
20768 for Q'Address use Compute_Address;
20769 @end cartouche
20770 @end smallexample
20771
20772 @noindent
20773 will be rejected by GNAT, since the address cannot be computed at the time
20774 that @code{Q} is declared. To achieve the intended effect, write instead:
20775
20776 @smallexample @c ada
20777 @group
20778 @cartouche
20779 X, Y : Integer := Init_Func;
20780 Q_Address : constant Address := Compute_Address;
20781 Q : String (X .. Y) := "abc";
20782 @dots{}
20783 for Q'Address use Q_Address;
20784 @end cartouche
20785 @end group
20786 @end smallexample
20787
20788 @noindent
20789 which will be accepted by GNAT (and other Ada compilers), and is also
20790 compatible with Ada 83. A fuller description of the restrictions
20791 on address specifications is found in @ref{Top, GNAT Reference Manual,
20792 About This Guide, gnat_rm, GNAT Reference Manual}.
20793
20794 @node Other Representation Clauses
20795 @subsection Other Representation Clauses
20796
20797 @noindent
20798 GNAT implements in a compatible manner all the representation
20799 clauses supported by HP Ada. In addition, GNAT
20800 implements the representation clause forms that were introduced in Ada 95,
20801 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20802
20803 @node The Package STANDARD
20804 @section The Package @code{STANDARD}
20805
20806 @noindent
20807 The package @code{STANDARD}, as implemented by HP Ada, is fully
20808 described in the @cite{Ada Reference Manual} and in the
20809 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20810 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20811
20812 In addition, HP Ada supports the Latin-1 character set in
20813 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20814 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20815 the type @code{WIDE_CHARACTER}.
20816
20817 The floating-point types supported by GNAT are those
20818 supported by HP Ada, but the defaults are different, and are controlled by
20819 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20820
20821 @node The Package SYSTEM
20822 @section The Package @code{SYSTEM}
20823
20824 @noindent
20825 HP Ada provides a specific version of the package
20826 @code{SYSTEM} for each platform on which the language is implemented.
20827 For the complete spec of the package @code{SYSTEM}, see
20828 Appendix F of the @cite{HP Ada Language Reference Manual}.
20829
20830 On HP Ada, the package @code{SYSTEM} includes the following conversion
20831 functions:
20832 @itemize @bullet
20833 @item @code{TO_ADDRESS(INTEGER)}
20834
20835 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20836
20837 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20838
20839 @item @code{TO_INTEGER(ADDRESS)}
20840
20841 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20842
20843 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20844 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20845 @end itemize
20846
20847 @noindent
20848 By default, GNAT supplies a version of @code{SYSTEM} that matches
20849 the definition given in the @cite{Ada Reference Manual}.
20850 This
20851 is a subset of the HP system definitions, which is as
20852 close as possible to the original definitions. The only difference
20853 is that the definition of @code{SYSTEM_NAME} is different:
20854
20855 @smallexample @c ada
20856 @cartouche
20857 type Name is (SYSTEM_NAME_GNAT);
20858 System_Name : constant Name := SYSTEM_NAME_GNAT;
20859 @end cartouche
20860 @end smallexample
20861
20862 @noindent
20863 Also, GNAT adds the Ada declarations for
20864 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20865
20866 However, the use of the following pragma causes GNAT
20867 to extend the definition of package @code{SYSTEM} so that it
20868 encompasses the full set of HP-specific extensions,
20869 including the functions listed above:
20870
20871 @smallexample @c ada
20872 @cartouche
20873 pragma Extend_System (Aux_DEC);
20874 @end cartouche
20875 @end smallexample
20876
20877 @noindent
20878 The pragma @code{Extend_System} is a configuration pragma that
20879 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20880 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20881
20882 HP Ada does not allow the recompilation of the package
20883 @code{SYSTEM}. Instead HP Ada provides several pragmas
20884 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20885 to modify values in the package @code{SYSTEM}.
20886 On OpenVMS Alpha systems, the pragma
20887 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20888 its single argument.
20889
20890 GNAT does permit the recompilation of package @code{SYSTEM} using
20891 the special switch @option{-gnatg}, and this switch can be used if
20892 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20893 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20894 or @code{MEMORY_SIZE} by any other means.
20895
20896 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20897 enumeration literal @code{SYSTEM_NAME_GNAT}.
20898
20899 The definitions provided by the use of
20900
20901 @smallexample @c ada
20902 pragma Extend_System (AUX_Dec);
20903 @end smallexample
20904
20905 @noindent
20906 are virtually identical to those provided by the HP Ada 83 package
20907 @code{SYSTEM}. One important difference is that the name of the
20908 @code{TO_ADDRESS}
20909 function for type @code{UNSIGNED_LONGWORD} is changed to
20910 @code{TO_ADDRESS_LONG}.
20911 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20912 discussion of why this change was necessary.
20913
20914 @noindent
20915 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20916 is in fact
20917 an extension to Ada 83 not strictly compatible with the reference manual.
20918 GNAT, in order to be exactly compatible with the standard,
20919 does not provide this capability. In HP Ada 83, the
20920 point of this definition is to deal with a call like:
20921
20922 @smallexample @c ada
20923 TO_ADDRESS (16#12777#);
20924 @end smallexample
20925
20926 @noindent
20927 Normally, according to Ada 83 semantics, one would expect this to be
20928 ambiguous, since it matches both the @code{INTEGER} and
20929 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20930 However, in HP Ada 83, there is no ambiguity, since the
20931 definition using @i{universal_integer} takes precedence.
20932
20933 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20934 it is
20935 not possible to be 100% compatible. Since there are many programs using
20936 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20937 GNAT was
20938 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20939 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20940
20941 @smallexample @c ada
20942 function To_Address (X : Integer) return Address;
20943 pragma Pure_Function (To_Address);
20944
20945 function To_Address_Long (X : Unsigned_Longword) return Address;
20946 pragma Pure_Function (To_Address_Long);
20947 @end smallexample
20948
20949 @noindent
20950 This means that programs using @code{TO_ADDRESS} for
20951 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20952
20953 @node Tasking and Task-Related Features
20954 @section Tasking and Task-Related Features
20955
20956 @noindent
20957 This section compares the treatment of tasking in GNAT
20958 and in HP Ada for OpenVMS Alpha.
20959 The GNAT description applies to both Alpha and I64 OpenVMS.
20960 For detailed information on tasking in
20961 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20962 relevant run-time reference manual.
20963
20964 @menu
20965 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20966 * Assigning Task IDs::
20967 * Task IDs and Delays::
20968 * Task-Related Pragmas::
20969 * Scheduling and Task Priority::
20970 * The Task Stack::
20971 * External Interrupts::
20972 @end menu
20973
20974 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20975 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20976
20977 @noindent
20978 On OpenVMS Alpha systems, each Ada task (except a passive
20979 task) is implemented as a single stream of execution
20980 that is created and managed by the kernel. On these
20981 systems, HP Ada tasking support is based on DECthreads,
20982 an implementation of the POSIX standard for threads.
20983
20984 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20985 code that calls DECthreads routines can be used together.
20986 The interaction between Ada tasks and DECthreads routines
20987 can have some benefits. For example when on OpenVMS Alpha,
20988 HP Ada can call C code that is already threaded.
20989
20990 GNAT uses the facilities of DECthreads,
20991 and Ada tasks are mapped to threads.
20992
20993 @node Assigning Task IDs
20994 @subsection Assigning Task IDs
20995
20996 @noindent
20997 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20998 the environment task that executes the main program. On
20999 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21000 that have been created but are not yet activated.
21001
21002 On OpenVMS Alpha systems, task IDs are assigned at
21003 activation. On GNAT systems, task IDs are also assigned at
21004 task creation but do not have the same form or values as
21005 task ID values in HP Ada. There is no null task, and the
21006 environment task does not have a specific task ID value.
21007
21008 @node Task IDs and Delays
21009 @subsection Task IDs and Delays
21010
21011 @noindent
21012 On OpenVMS Alpha systems, tasking delays are implemented
21013 using Timer System Services. The Task ID is used for the
21014 identification of the timer request (the @code{REQIDT} parameter).
21015 If Timers are used in the application take care not to use
21016 @code{0} for the identification, because cancelling such a timer
21017 will cancel all timers and may lead to unpredictable results.
21018
21019 @node Task-Related Pragmas
21020 @subsection Task-Related Pragmas
21021
21022 @noindent
21023 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21024 specification of the size of the guard area for a task
21025 stack. (The guard area forms an area of memory that has no
21026 read or write access and thus helps in the detection of
21027 stack overflow.) On OpenVMS Alpha systems, if the pragma
21028 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21029 area is created. In the absence of a pragma @code{TASK_STORAGE},
21030 a default guard area is created.
21031
21032 GNAT supplies the following task-related pragmas:
21033
21034 @itemize @bullet
21035 @item  @code{TASK_INFO}
21036
21037 This pragma appears within a task definition and
21038 applies to the task in which it appears. The argument
21039 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21040
21041 @item  @code{TASK_STORAGE}
21042
21043 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
21044 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21045 @code{SUPPRESS}, and @code{VOLATILE}.
21046 @end itemize
21047 @node Scheduling and Task Priority
21048 @subsection Scheduling and Task Priority
21049
21050 @noindent
21051 HP Ada implements the Ada language requirement that
21052 when two tasks are eligible for execution and they have
21053 different priorities, the lower priority task does not
21054 execute while the higher priority task is waiting. The HP
21055 Ada Run-Time Library keeps a task running until either the
21056 task is suspended or a higher priority task becomes ready.
21057
21058 On OpenVMS Alpha systems, the default strategy is round-
21059 robin with preemption. Tasks of equal priority take turns
21060 at the processor. A task is run for a certain period of
21061 time and then placed at the tail of the ready queue for
21062 its priority level.
21063
21064 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21065 which can be used to enable or disable round-robin
21066 scheduling of tasks with the same priority.
21067 See the relevant HP Ada run-time reference manual for
21068 information on using the pragmas to control HP Ada task
21069 scheduling.
21070
21071 GNAT follows the scheduling rules of Annex D (Real-Time
21072 Annex) of the @cite{Ada Reference Manual}. In general, this
21073 scheduling strategy is fully compatible with HP Ada
21074 although it provides some additional constraints (as
21075 fully documented in Annex D).
21076 GNAT implements time slicing control in a manner compatible with
21077 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21078 are identical to the HP Ada 83 pragma of the same name.
21079 Note that it is not possible to mix GNAT tasking and
21080 HP Ada 83 tasking in the same program, since the two run-time
21081 libraries are not compatible.
21082
21083 @node The Task Stack
21084 @subsection The Task Stack
21085
21086 @noindent
21087 In HP Ada, a task stack is allocated each time a
21088 non-passive task is activated. As soon as the task is
21089 terminated, the storage for the task stack is deallocated.
21090 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21091 a default stack size is used. Also, regardless of the size
21092 specified, some additional space is allocated for task
21093 management purposes. On OpenVMS Alpha systems, at least
21094 one page is allocated.
21095
21096 GNAT handles task stacks in a similar manner. In accordance with
21097 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
21098 an alternative method for controlling the task stack size.
21099 The specification of the attribute @code{T'STORAGE_SIZE} is also
21100 supported in a manner compatible with HP Ada.
21101
21102 @node External Interrupts
21103 @subsection External Interrupts
21104
21105 @noindent
21106 On HP Ada, external interrupts can be associated with task entries.
21107 GNAT is compatible with HP Ada in its handling of external interrupts.
21108
21109 @node Pragmas and Pragma-Related Features
21110 @section Pragmas and Pragma-Related Features
21111
21112 @noindent
21113 Both HP Ada and GNAT supply all language-defined pragmas
21114 as specified by the Ada 83 standard. GNAT also supplies all
21115 language-defined pragmas introduced by Ada 95 and Ada 2005.
21116 In addition, GNAT implements the implementation-defined pragmas
21117 from HP Ada 83.
21118
21119 @itemize @bullet
21120 @item  @code{AST_ENTRY}
21121
21122 @item  @code{COMMON_OBJECT}
21123
21124 @item  @code{COMPONENT_ALIGNMENT}
21125
21126 @item  @code{EXPORT_EXCEPTION}
21127
21128 @item  @code{EXPORT_FUNCTION}
21129
21130 @item  @code{EXPORT_OBJECT}
21131
21132 @item  @code{EXPORT_PROCEDURE}
21133
21134 @item  @code{EXPORT_VALUED_PROCEDURE}
21135
21136 @item  @code{FLOAT_REPRESENTATION}
21137
21138 @item  @code{IDENT}
21139
21140 @item  @code{IMPORT_EXCEPTION}
21141
21142 @item  @code{IMPORT_FUNCTION}
21143
21144 @item  @code{IMPORT_OBJECT}
21145
21146 @item  @code{IMPORT_PROCEDURE}
21147
21148 @item  @code{IMPORT_VALUED_PROCEDURE}
21149
21150 @item  @code{INLINE_GENERIC}
21151
21152 @item  @code{INTERFACE_NAME}
21153
21154 @item  @code{LONG_FLOAT}
21155
21156 @item  @code{MAIN_STORAGE}
21157
21158 @item  @code{PASSIVE}
21159
21160 @item  @code{PSECT_OBJECT}
21161
21162 @item  @code{SHARE_GENERIC}
21163
21164 @item  @code{SUPPRESS_ALL}
21165
21166 @item  @code{TASK_STORAGE}
21167
21168 @item  @code{TIME_SLICE}
21169
21170 @item  @code{TITLE}
21171 @end itemize
21172
21173 @noindent
21174 These pragmas are all fully implemented, with the exception of @code{TITLE},
21175 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21176 recognized, but which have no
21177 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21178 use of Ada protected objects. In GNAT, all generics are inlined.
21179
21180 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21181 a separate subprogram specification which must appear before the
21182 subprogram body.
21183
21184 GNAT also supplies a number of implementation-defined pragmas including the
21185 following:
21186
21187 @itemize @bullet
21188 @item  @code{ABORT_DEFER}
21189
21190 @item  @code{ADA_83}
21191
21192 @item  @code{ADA_95}
21193
21194 @item  @code{ADA_05}
21195
21196 @item  @code{Ada_2005}
21197
21198 @item  @code{Ada_12}
21199
21200 @item  @code{Ada_2012}
21201
21202 @item  @code{ANNOTATE}
21203
21204 @item  @code{ASSERT}
21205
21206 @item  @code{C_PASS_BY_COPY}
21207
21208 @item  @code{CPP_CLASS}
21209
21210 @item  @code{CPP_CONSTRUCTOR}
21211
21212 @item  @code{CPP_DESTRUCTOR}
21213
21214 @item  @code{DEBUG}
21215
21216 @item  @code{EXTEND_SYSTEM}
21217
21218 @item  @code{LINKER_ALIAS}
21219
21220 @item  @code{LINKER_SECTION}
21221
21222 @item  @code{MACHINE_ATTRIBUTE}
21223
21224 @item  @code{NO_RETURN}
21225
21226 @item  @code{PURE_FUNCTION}
21227
21228 @item  @code{SOURCE_FILE_NAME}
21229
21230 @item  @code{SOURCE_REFERENCE}
21231
21232 @item  @code{TASK_INFO}
21233
21234 @item  @code{UNCHECKED_UNION}
21235
21236 @item  @code{UNIMPLEMENTED_UNIT}
21237
21238 @item  @code{UNIVERSAL_DATA}
21239
21240 @item  @code{UNSUPPRESS}
21241
21242 @item  @code{WARNINGS}
21243
21244 @item  @code{WEAK_EXTERNAL}
21245 @end itemize
21246
21247 @noindent
21248 For full details on these and other GNAT implementation-defined pragmas,
21249 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21250 Manual}.
21251
21252 @menu
21253 * Restrictions on the Pragma INLINE::
21254 * Restrictions on the Pragma INTERFACE::
21255 * Restrictions on the Pragma SYSTEM_NAME::
21256 @end menu
21257
21258 @node Restrictions on the Pragma INLINE
21259 @subsection Restrictions on Pragma @code{INLINE}
21260
21261 @noindent
21262 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21263 @itemize @bullet
21264 @item  Parameters cannot have a task type.
21265
21266 @item  Function results cannot be task types, unconstrained
21267 array types, or unconstrained types with discriminants.
21268
21269 @item  Bodies cannot declare the following:
21270 @itemize @bullet
21271 @item  Subprogram body or stub (imported subprogram is allowed)
21272
21273 @item  Tasks
21274
21275 @item  Generic declarations
21276
21277 @item  Instantiations
21278
21279 @item  Exceptions
21280
21281 @item  Access types (types derived from access types allowed)
21282
21283 @item  Array or record types
21284
21285 @item  Dependent tasks
21286
21287 @item  Direct recursive calls of subprogram or containing
21288 subprogram, directly or via a renaming
21289
21290 @end itemize
21291 @end itemize
21292
21293 @noindent
21294 In GNAT, the only restriction on pragma @code{INLINE} is that the
21295 body must occur before the call if both are in the same
21296 unit, and the size must be appropriately small. There are
21297 no other specific restrictions which cause subprograms to
21298 be incapable of being inlined.
21299
21300 @node  Restrictions on the Pragma INTERFACE
21301 @subsection  Restrictions on Pragma @code{INTERFACE}
21302
21303 @noindent
21304 The following restrictions on pragma @code{INTERFACE}
21305 are enforced by both HP Ada and GNAT:
21306 @itemize @bullet
21307 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21308 Default is the default on OpenVMS Alpha systems.
21309
21310 @item  Parameter passing: Language specifies default
21311 mechanisms but can be overridden with an @code{EXPORT} pragma.
21312
21313 @itemize @bullet
21314 @item  Ada: Use internal Ada rules.
21315
21316 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21317 record or task type. Result cannot be a string, an
21318 array, or a record.
21319
21320 @item  Fortran: Parameters cannot have a task type. Result cannot
21321 be a string, an array, or a record.
21322 @end itemize
21323 @end itemize
21324
21325 @noindent
21326 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21327 record parameters for all languages.
21328
21329 @node  Restrictions on the Pragma SYSTEM_NAME
21330 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21331
21332 @noindent
21333 For HP Ada for OpenVMS Alpha, the enumeration literal
21334 for the type @code{NAME} is @code{OPENVMS_AXP}.
21335 In GNAT, the enumeration
21336 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21337
21338 @node  Library of Predefined Units
21339 @section  Library of Predefined Units
21340
21341 @noindent
21342 A library of predefined units is provided as part of the
21343 HP Ada and GNAT implementations. HP Ada does not provide
21344 the package @code{MACHINE_CODE} but instead recommends importing
21345 assembler code.
21346
21347 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21348 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21349 version.
21350 The HP Ada Predefined Library units are modified to remove post-Ada 83
21351 incompatibilities and to make them interoperable with GNAT
21352 (@pxref{Changes to DECLIB}, for details).
21353 The units are located in the @file{DECLIB} directory.
21354
21355 The GNAT RTL is contained in
21356 the @file{ADALIB} directory, and
21357 the default search path is set up to find @code{DECLIB} units in preference
21358 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21359 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21360
21361 @menu
21362 * Changes to DECLIB::
21363 @end menu
21364
21365 @node Changes to DECLIB
21366 @subsection Changes to @code{DECLIB}
21367
21368 @noindent
21369 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21370 compatibility are minor and include the following:
21371
21372 @itemize @bullet
21373 @item  Adjusting the location of pragmas and record representation
21374 clauses to obey Ada 95 (and thus Ada 2005) rules
21375
21376 @item  Adding the proper notation to generic formal parameters
21377 that take unconstrained types in instantiation
21378
21379 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21380 that have package bodies not otherwise allowed
21381
21382 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21383 ``@code{PROTECTD}''.
21384 Currently these are found only in the @code{STARLET} package spec.
21385
21386 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21387 where the address size is constrained to 32 bits.
21388 @end itemize
21389
21390 @noindent
21391 None of the above changes is visible to users.
21392
21393 @node Bindings
21394 @section Bindings
21395
21396 @noindent
21397 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21398 @itemize @bullet
21399
21400 @item  Command Language Interpreter (CLI interface)
21401
21402 @item  DECtalk Run-Time Library (DTK interface)
21403
21404 @item  Librarian utility routines (LBR interface)
21405
21406 @item  General Purpose Run-Time Library (LIB interface)
21407
21408 @item  Math Run-Time Library (MTH interface)
21409
21410 @item  National Character Set Run-Time Library (NCS interface)
21411
21412 @item  Compiled Code Support Run-Time Library (OTS interface)
21413
21414 @item  Parallel Processing Run-Time Library (PPL interface)
21415
21416 @item  Screen Management Run-Time Library (SMG interface)
21417
21418 @item  Sort Run-Time Library (SOR interface)
21419
21420 @item  String Run-Time Library (STR interface)
21421
21422 @item STARLET System Library
21423 @findex Starlet
21424
21425 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21426
21427 @item  X Windows Toolkit (XT interface)
21428
21429 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21430 @end itemize
21431
21432 @noindent
21433 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21434 directory, on both the Alpha and I64 OpenVMS platforms.
21435
21436 The X components of DECLIB compatibility package are located in a separate
21437 library, called XDECGNAT, which is not linked with by default; this library
21438 must be explicitly linked with any application that makes use of any X facilities,
21439 with a command similar to
21440
21441 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21442
21443 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21444 in the
21445 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21446 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21447 @code{Xt}, and @code{X_Lib}
21448 causing the default X/Motif sharable image libraries to be linked in. This
21449 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21450 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21451
21452 It may be necessary to edit these options files to update or correct the
21453 library names if, for example, the newer X/Motif bindings from
21454 @file{ADA$EXAMPLES}
21455 had been (previous to installing GNAT) copied and renamed to supersede the
21456 default @file{ADA$PREDEFINED} versions.
21457
21458 @menu
21459 * Shared Libraries and Options Files::
21460 * Interfaces to C::
21461 @end menu
21462
21463 @node Shared Libraries and Options Files
21464 @subsection Shared Libraries and Options Files
21465
21466 @noindent
21467 When using the HP Ada
21468 predefined X and Motif bindings, the linking with their sharable images is
21469 done automatically by @command{GNAT LINK}.
21470 When using other X and Motif bindings, you need
21471 to add the corresponding sharable images to the command line for
21472 @code{GNAT LINK}. When linking with shared libraries, or with
21473 @file{.OPT} files, you must
21474 also add them to the command line for @command{GNAT LINK}.
21475
21476 A shared library to be used with GNAT is built in the same way as other
21477 libraries under VMS. The VMS Link command can be used in standard fashion.
21478
21479 @node Interfaces to C
21480 @subsection Interfaces to C
21481
21482 @noindent
21483 HP Ada
21484 provides the following Ada types and operations:
21485
21486 @itemize @bullet
21487 @item C types package (@code{C_TYPES})
21488
21489 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21490
21491 @item Other_types (@code{SHORT_INT})
21492 @end itemize
21493
21494 @noindent
21495 Interfacing to C with GNAT, you can use the above approach
21496 described for HP Ada or the facilities of Annex B of
21497 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21498 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21499 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21500
21501 The @option{-gnatF} qualifier forces default and explicit
21502 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21503 to be uppercased for compatibility with the default behavior
21504 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21505
21506 @node Main Program Definition
21507 @section Main Program Definition
21508
21509 @noindent
21510 The following section discusses differences in the
21511 definition of main programs on HP Ada and GNAT.
21512 On HP Ada, main programs are defined to meet the
21513 following conditions:
21514 @itemize @bullet
21515 @item  Procedure with no formal parameters (returns @code{0} upon
21516 normal completion)
21517
21518 @item  Procedure with no formal parameters (returns @code{42} when
21519 an unhandled exception is raised)
21520
21521 @item  Function with no formal parameters whose returned value
21522 is of a discrete type
21523
21524 @item  Procedure with one @code{out} formal of a discrete type for
21525 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21526
21527 @end itemize
21528
21529 @noindent
21530 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21531 a main function or main procedure returns a discrete
21532 value whose size is less than 64 bits (32 on VAX systems),
21533 the value is zero- or sign-extended as appropriate.
21534 On GNAT, main programs are defined as follows:
21535 @itemize @bullet
21536 @item  Must be a non-generic, parameterless subprogram that
21537 is either a procedure or function returning an Ada
21538 @code{STANDARD.INTEGER} (the predefined type)
21539
21540 @item  Cannot be a generic subprogram or an instantiation of a
21541 generic subprogram
21542 @end itemize
21543
21544 @node Implementation-Defined Attributes
21545 @section Implementation-Defined Attributes
21546
21547 @noindent
21548 GNAT provides all HP Ada implementation-defined
21549 attributes.
21550
21551 @node Compiler and Run-Time Interfacing
21552 @section Compiler and Run-Time Interfacing
21553
21554 @noindent
21555 HP Ada provides the following qualifiers to pass options to the linker
21556 (ACS LINK):
21557 @itemize @bullet
21558 @item  @option{/WAIT} and @option{/SUBMIT}
21559
21560 @item  @option{/COMMAND}
21561
21562 @item  @option{/@r{[}NO@r{]}MAP}
21563
21564 @item  @option{/OUTPUT=@var{file-spec}}
21565
21566 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21567 @end itemize
21568
21569 @noindent
21570 To pass options to the linker, GNAT provides the following
21571 switches:
21572
21573 @itemize @bullet
21574 @item   @option{/EXECUTABLE=@var{exec-name}}
21575
21576 @item   @option{/VERBOSE}
21577
21578 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21579 @end itemize
21580
21581 @noindent
21582 For more information on these switches, see
21583 @ref{Switches for gnatlink}.
21584 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21585 to control optimization. HP Ada also supplies the
21586 following pragmas:
21587 @itemize @bullet
21588 @item  @code{OPTIMIZE}
21589
21590 @item  @code{INLINE}
21591
21592 @item  @code{INLINE_GENERIC}
21593
21594 @item  @code{SUPPRESS_ALL}
21595
21596 @item  @code{PASSIVE}
21597 @end itemize
21598
21599 @noindent
21600 In GNAT, optimization is controlled strictly by command
21601 line parameters, as described in the corresponding section of this guide.
21602 The HP pragmas for control of optimization are
21603 recognized but ignored.
21604
21605 Note that in GNAT, the default is optimization off, whereas in HP Ada
21606 the default is that optimization is turned on.
21607
21608 @node Program Compilation and Library Management
21609 @section Program Compilation and Library Management
21610
21611 @noindent
21612 HP Ada and GNAT provide a comparable set of commands to
21613 build programs. HP Ada also provides a program library,
21614 which is a concept that does not exist on GNAT. Instead,
21615 GNAT provides directories of sources that are compiled as
21616 needed.
21617
21618 The following table summarizes
21619 the HP Ada commands and provides
21620 equivalent GNAT commands. In this table, some GNAT
21621 equivalents reflect the fact that GNAT does not use the
21622 concept of a program library. Instead, it uses a model
21623 in which collections of source and object files are used
21624 in a manner consistent with other languages like C and
21625 Fortran. Therefore, standard system file commands are used
21626 to manipulate these elements. Those GNAT commands are marked with
21627 an asterisk.
21628 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21629
21630 @need 1500
21631 @multitable @columnfractions .35 .65
21632
21633 @item @emph{HP Ada Command}
21634 @tab @emph{GNAT Equivalent / Description}
21635
21636 @item @command{ADA}
21637 @tab @command{GNAT COMPILE}@*
21638 Invokes the compiler to compile one or more Ada source files.
21639
21640 @item @command{ACS ATTACH}@*
21641 @tab [No equivalent]@*
21642 Switches control of terminal from current process running the program
21643 library manager.
21644
21645 @item @command{ACS CHECK}
21646 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21647 Forms the execution closure of one
21648 or more compiled units and checks completeness and currency.
21649
21650 @item @command{ACS COMPILE}
21651 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21652 Forms the execution closure of one or
21653 more specified units, checks completeness and currency,
21654 identifies units that have revised source files, compiles same,
21655 and recompiles units that are or will become obsolete.
21656 Also completes incomplete generic instantiations.
21657
21658 @item @command{ACS COPY FOREIGN}
21659 @tab Copy (*)@*
21660 Copies a foreign object file into the program library as a
21661 library unit body.
21662
21663 @item @command{ACS COPY UNIT}
21664 @tab Copy (*)@*
21665 Copies a compiled unit from one program library to another.
21666
21667 @item @command{ACS CREATE LIBRARY}
21668 @tab Create /directory (*)@*
21669 Creates a program library.
21670
21671 @item @command{ACS CREATE SUBLIBRARY}
21672 @tab Create /directory (*)@*
21673 Creates a program sublibrary.
21674
21675 @item @command{ACS DELETE LIBRARY}
21676 @tab @*
21677 Deletes a program library and its contents.
21678
21679 @item @command{ACS DELETE SUBLIBRARY}
21680 @tab @*
21681 Deletes a program sublibrary and its contents.
21682
21683 @item @command{ACS DELETE UNIT}
21684 @tab Delete file (*)@*
21685 On OpenVMS systems, deletes one or more compiled units from
21686 the current program library.
21687
21688 @item @command{ACS DIRECTORY}
21689 @tab Directory (*)@*
21690 On OpenVMS systems, lists units contained in the current
21691 program library.
21692
21693 @item @command{ACS ENTER FOREIGN}
21694 @tab Copy (*)@*
21695 Allows the import of a foreign body as an Ada library
21696 spec and enters a reference to a pointer.
21697
21698 @item @command{ACS ENTER UNIT}
21699 @tab Copy (*)@*
21700 Enters a reference (pointer) from the current program library to
21701 a unit compiled into another program library.
21702
21703 @item @command{ACS EXIT}
21704 @tab [No equivalent]@*
21705 Exits from the program library manager.
21706
21707 @item @command{ACS EXPORT}
21708 @tab Copy (*)@*
21709 Creates an object file that contains system-specific object code
21710 for one or more units. With GNAT, object files can simply be copied
21711 into the desired directory.
21712
21713 @item @command{ACS EXTRACT SOURCE}
21714 @tab Copy (*)@*
21715 Allows access to the copied source file for each Ada compilation unit
21716
21717 @item @command{ACS HELP}
21718 @tab @command{HELP GNAT}@*
21719 Provides online help.
21720
21721 @item @command{ACS LINK}
21722 @tab @command{GNAT LINK}@*
21723 Links an object file containing Ada units into an executable file.
21724
21725 @item @command{ACS LOAD}
21726 @tab Copy (*)@*
21727 Loads (partially compiles) Ada units into the program library.
21728 Allows loading a program from a collection of files into a library
21729 without knowing the relationship among units.
21730
21731 @item @command{ACS MERGE}
21732 @tab Copy (*)@*
21733 Merges into the current program library, one or more units from
21734 another library where they were modified.
21735
21736 @item @command{ACS RECOMPILE}
21737 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21738 Recompiles from   external or copied source files any obsolete
21739 unit in the closure. Also, completes any incomplete generic
21740 instantiations.
21741
21742 @item @command{ACS REENTER}
21743 @tab @command{GNAT MAKE}@*
21744 Reenters current references to units compiled after last entered
21745 with the @command{ACS ENTER UNIT} command.
21746
21747 @item @command{ACS SET LIBRARY}
21748 @tab Set default (*)@*
21749 Defines a program library to be the compilation context as well
21750 as the target library for compiler output and commands in general.
21751
21752 @item @command{ACS SET PRAGMA}
21753 @tab Edit @file{gnat.adc} (*)@*
21754 Redefines specified  values of the library characteristics
21755 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21756 and @code{Float_Representation}.
21757
21758 @item @command{ACS SET SOURCE}
21759 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21760 Defines the source file search list for the @command{ACS COMPILE} command.
21761
21762 @item @command{ACS SHOW LIBRARY}
21763 @tab Directory (*)@*
21764 Lists information about one or more program libraries.
21765
21766 @item @command{ACS SHOW PROGRAM}
21767 @tab [No equivalent]@*
21768 Lists information about the execution closure of one or
21769 more units in the program library.
21770
21771 @item @command{ACS SHOW SOURCE}
21772 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21773 Shows the source file search used when compiling units.
21774
21775 @item @command{ACS SHOW VERSION}
21776 @tab Compile with @option{VERBOSE} option
21777 Displays the version number of the compiler and program library
21778 manager used.
21779
21780 @item @command{ACS SPAWN}
21781 @tab [No equivalent]@*
21782 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21783 command).
21784
21785 @item @command{ACS VERIFY}
21786 @tab [No equivalent]@*
21787 Performs a series of consistency checks on a program library to
21788 determine whether the library structure and library files are in
21789 valid form.
21790 @end multitable
21791
21792 @noindent
21793
21794 @node Input-Output
21795 @section Input-Output
21796
21797 @noindent
21798 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21799 Management Services (RMS) to perform operations on
21800 external files.
21801
21802 @noindent
21803 HP Ada and GNAT predefine an identical set of input-
21804 output packages. To make the use of the
21805 generic @code{TEXT_IO} operations more convenient, HP Ada
21806 provides predefined library packages that instantiate the
21807 integer and floating-point operations for the predefined
21808 integer and floating-point types as shown in the following table.
21809
21810 @multitable @columnfractions .45 .55
21811 @item @emph{Package Name} @tab Instantiation
21812
21813 @item @code{INTEGER_TEXT_IO}
21814 @tab @code{INTEGER_IO(INTEGER)}
21815
21816 @item @code{SHORT_INTEGER_TEXT_IO}
21817 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21818
21819 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21820 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21821
21822 @item @code{FLOAT_TEXT_IO}
21823 @tab @code{FLOAT_IO(FLOAT)}
21824
21825 @item @code{LONG_FLOAT_TEXT_IO}
21826 @tab @code{FLOAT_IO(LONG_FLOAT)}
21827 @end multitable
21828
21829 @noindent
21830 The HP Ada predefined packages and their operations
21831 are implemented using OpenVMS Alpha files and input-output
21832 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21833 Familiarity with the following is recommended:
21834 @itemize @bullet
21835 @item  RMS file organizations and access methods
21836
21837 @item  OpenVMS file specifications and directories
21838
21839 @item  OpenVMS File Definition Language (FDL)
21840 @end itemize
21841
21842 @noindent
21843 GNAT provides I/O facilities that are completely
21844 compatible with HP Ada. The distribution includes the
21845 standard HP Ada versions of all I/O packages, operating
21846 in a manner compatible with HP Ada. In particular, the
21847 following packages are by default the HP Ada (Ada 83)
21848 versions of these packages rather than the renamings
21849 suggested in Annex J of the Ada Reference Manual:
21850 @itemize @bullet
21851 @item  @code{TEXT_IO}
21852
21853 @item  @code{SEQUENTIAL_IO}
21854
21855 @item  @code{DIRECT_IO}
21856 @end itemize
21857
21858 @noindent
21859 The use of the standard child package syntax (for
21860 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21861 packages.
21862 GNAT provides HP-compatible predefined instantiations
21863 of the @code{TEXT_IO} packages, and also
21864 provides the standard predefined instantiations required
21865 by the @cite{Ada Reference Manual}.
21866
21867 For further information on how GNAT interfaces to the file
21868 system or how I/O is implemented in programs written in
21869 mixed languages, see @ref{Implementation of the Standard I/O,,,
21870 gnat_rm, GNAT Reference Manual}.
21871 This chapter covers the following:
21872 @itemize @bullet
21873 @item  Standard I/O packages
21874
21875 @item  @code{FORM} strings
21876
21877 @item  @code{ADA.DIRECT_IO}
21878
21879 @item  @code{ADA.SEQUENTIAL_IO}
21880
21881 @item  @code{ADA.TEXT_IO}
21882
21883 @item  Stream pointer positioning
21884
21885 @item  Reading and writing non-regular files
21886
21887 @item  @code{GET_IMMEDIATE}
21888
21889 @item  Treating @code{TEXT_IO} files as streams
21890
21891 @item  Shared files
21892
21893 @item  Open modes
21894 @end itemize
21895
21896 @node Implementation Limits
21897 @section Implementation Limits
21898
21899 @noindent
21900 The following table lists implementation limits for HP Ada
21901 and GNAT systems.
21902 @multitable @columnfractions .60 .20 .20
21903 @sp 1
21904 @item  @emph{Compilation Parameter}
21905 @tab   @emph{HP Ada}
21906 @tab   @emph{GNAT}
21907 @sp 1
21908
21909 @item  In a subprogram or entry  declaration, maximum number of
21910 formal parameters that are of an unconstrained record type
21911 @tab   32
21912 @tab   No set limit
21913 @sp 1
21914
21915 @item  Maximum identifier length (number of characters)
21916 @tab   255
21917 @tab   32766
21918 @sp 1
21919
21920 @item  Maximum number of characters in a source line
21921 @tab   255
21922 @tab   32766
21923 @sp 1
21924
21925 @item  Maximum collection size   (number of bytes)
21926 @tab   2**31-1
21927 @tab   2**31-1
21928 @sp 1
21929
21930 @item  Maximum number of discriminants for a record type
21931 @tab   245
21932 @tab   No set limit
21933 @sp 1
21934
21935 @item  Maximum number of formal parameters in an entry or
21936 subprogram declaration
21937 @tab   246
21938 @tab    No set limit
21939 @sp 1
21940
21941 @item  Maximum number of dimensions in an array type
21942 @tab   255
21943 @tab   No set limit
21944 @sp 1
21945
21946 @item  Maximum number of library  units and subunits in a compilation.
21947 @tab   4095
21948 @tab   No set limit
21949 @sp 1
21950
21951 @item  Maximum number of library units and subunits in an execution.
21952 @tab   16383
21953 @tab   No set limit
21954 @sp 1
21955
21956 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21957 or @code{PSECT_OBJECT}
21958 @tab   32757
21959 @tab   No set limit
21960 @sp 1
21961
21962 @item  Maximum number of enumeration literals in an enumeration type
21963 definition
21964 @tab   65535
21965 @tab   No set limit
21966 @sp 1
21967
21968 @item  Maximum number of lines in a source file
21969 @tab   65534
21970 @tab   No set limit
21971 @sp 1
21972
21973 @item  Maximum number of bits in any object
21974 @tab   2**31-1
21975 @tab   2**31-1
21976 @sp 1
21977
21978 @item  Maximum size of the static portion of a stack frame (approximate)
21979 @tab   2**31-1
21980 @tab   2**31-1
21981 @end multitable
21982
21983 @node Tools and Utilities
21984 @section Tools and Utilities
21985
21986 @noindent
21987 The following table lists some of the OpenVMS development tools
21988 available for HP Ada, and the corresponding tools for
21989 use with @value{EDITION} on Alpha and I64 platforms.
21990 Aside from the debugger, all the OpenVMS tools identified are part
21991 of the DECset package.
21992
21993 @iftex
21994 @c Specify table in TeX since Texinfo does a poor job
21995 @tex
21996 \smallskip
21997 \smallskip
21998 \settabs\+Language-Sensitive Editor\quad
21999    &Product with HP Ada\quad
22000    &\cr
22001 \+\it Tool
22002    &\it Product with HP Ada
22003    & \it Product with @value{EDITION}\cr
22004 \smallskip
22005 \+Code Management System
22006    &HP CMS
22007    & HP CMS\cr
22008 \smallskip
22009 \+Language-Sensitive Editor
22010    &HP LSE
22011    & emacs or HP LSE (Alpha)\cr
22012 \+
22013    &
22014    & HP LSE (I64)\cr
22015 \smallskip
22016 \+Debugger
22017    &OpenVMS Debug
22018    & gdb (Alpha),\cr
22019 \+
22020    &
22021    & OpenVMS Debug (I64)\cr
22022 \smallskip
22023 \+Source Code Analyzer /
22024    &HP SCA
22025    & GNAT XREF\cr
22026 \+Cross Referencer
22027    &
22028    &\cr
22029 \smallskip
22030 \+Test Manager
22031    &HP Digital Test
22032    & HP DTM\cr
22033 \+
22034    &Manager (DTM)
22035    &\cr
22036 \smallskip
22037 \+Performance and
22038    & HP PCA
22039    & HP PCA\cr
22040 \+Coverage Analyzer
22041    &
22042    &\cr
22043 \smallskip
22044 \+Module Management
22045    & HP MMS
22046    & Not applicable\cr
22047 \+ System
22048    &
22049    &\cr
22050 \smallskip
22051 \smallskip
22052 @end tex
22053 @end iftex
22054
22055 @ifnottex
22056 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22057 @c the TeX version above for the printed version
22058 @flushleft
22059 @c @multitable @columnfractions .3 .4 .4
22060 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
22061 @item @i{Tool}
22062 @tab @i{Tool with HP Ada}
22063 @tab @i{Tool with @value{EDITION}}
22064 @item Code Management@*System
22065 @tab HP CMS
22066 @tab HP CMS
22067 @item Language-Sensitive@*Editor
22068 @tab HP LSE
22069 @tab emacs or HP LSE (Alpha)
22070 @item
22071 @tab
22072 @tab HP LSE (I64)
22073 @item Debugger
22074 @tab OpenVMS Debug
22075 @tab gdb (Alpha),
22076 @item
22077 @tab
22078 @tab OpenVMS Debug (I64)
22079 @item Source Code Analyzer /@*Cross Referencer
22080 @tab HP SCA
22081 @tab GNAT XREF
22082 @item Test Manager
22083 @tab HP Digital Test@*Manager (DTM)
22084 @tab HP DTM
22085 @item Performance and@*Coverage Analyzer
22086 @tab HP PCA
22087 @tab HP PCA
22088 @item Module Management@*System
22089 @tab HP MMS
22090 @tab Not applicable
22091 @end multitable
22092 @end flushleft
22093 @end ifnottex
22094
22095 @end ifset
22096
22097 @c **************************************
22098 @node Platform-Specific Information for the Run-Time Libraries
22099 @appendix Platform-Specific Information for the Run-Time Libraries
22100 @cindex Tasking and threads libraries
22101 @cindex Threads libraries and tasking
22102 @cindex Run-time libraries (platform-specific information)
22103
22104 @noindent
22105 The GNAT run-time implementation may vary with respect to both the
22106 underlying threads library and the exception handling scheme.
22107 For threads support, one or more of the following are supplied:
22108 @itemize @bullet
22109 @item @b{native threads library}, a binding to the thread package from
22110 the underlying operating system
22111
22112 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22113 POSIX thread package
22114 @end itemize
22115
22116 @noindent
22117 For exception handling, either or both of two models are supplied:
22118 @itemize @bullet
22119 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22120 Most programs should experience a substantial speed improvement by
22121 being compiled with a ZCX run-time.
22122 This is especially true for
22123 tasking applications or applications with many exception handlers.}
22124 @cindex Zero-Cost Exceptions
22125 @cindex ZCX (Zero-Cost Exceptions)
22126 which uses binder-generated tables that
22127 are interrogated at run time to locate a handler
22128
22129 @item @b{setjmp / longjmp} (``SJLJ''),
22130 @cindex setjmp/longjmp Exception Model
22131 @cindex SJLJ (setjmp/longjmp Exception Model)
22132 which uses dynamically-set data to establish
22133 the set of handlers
22134 @end itemize
22135
22136 @noindent
22137 This appendix summarizes which combinations of threads and exception support
22138 are supplied on various GNAT platforms.
22139 It then shows how to select a particular library either
22140 permanently or temporarily,
22141 explains the properties of (and tradeoffs among) the various threads
22142 libraries, and provides some additional
22143 information about several specific platforms.
22144
22145 @menu
22146 * Summary of Run-Time Configurations::
22147 * Specifying a Run-Time Library::
22148 * Choosing the Scheduling Policy::
22149 * Solaris-Specific Considerations::
22150 * Linux-Specific Considerations::
22151 * AIX-Specific Considerations::
22152 * Irix-Specific Considerations::
22153 * RTX-Specific Considerations::
22154 * HP-UX-Specific Considerations::
22155 @end menu
22156
22157 @node Summary of Run-Time Configurations
22158 @section Summary of Run-Time Configurations
22159
22160 @multitable @columnfractions .30 .70
22161 @item @b{alpha-openvms}
22162 @item @code{@ @ }@i{rts-native (default)}
22163 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22164 @item @code{@ @ @ @ }Exceptions @tab ZCX
22165 @*
22166 @item @b{alpha-tru64}
22167 @item @code{@ @ }@i{rts-native (default)}
22168 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22169 @item @code{@ @ @ @ }Exceptions @tab ZCX
22170 @*
22171 @item @code{@ @ }@i{rts-sjlj}
22172 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22173 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22174 @*
22175 @item @b{ia64-hp_linux}
22176 @item @code{@ @ }@i{rts-native (default)}
22177 @item @code{@ @ @ @ }Tasking    @tab pthread library
22178 @item @code{@ @ @ @ }Exceptions @tab ZCX
22179 @*
22180 @item @b{ia64-hpux}
22181 @item @code{@ @ }@i{rts-native (default)}
22182 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22183 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22184 @*
22185 @item @b{ia64-openvms}
22186 @item @code{@ @ }@i{rts-native (default)}
22187 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22188 @item @code{@ @ @ @ }Exceptions @tab ZCX
22189 @*
22190 @item @b{ia64-sgi_linux}
22191 @item @code{@ @ }@i{rts-native (default)}
22192 @item @code{@ @ @ @ }Tasking    @tab pthread library
22193 @item @code{@ @ @ @ }Exceptions @tab ZCX
22194 @*
22195 @item @b{mips-irix}
22196 @item @code{@ @ }@i{rts-native (default)}
22197 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22198 @item @code{@ @ @ @ }Exceptions @tab ZCX
22199 @*
22200 @item @b{pa-hpux}
22201 @item @code{@ @ }@i{rts-native (default)}
22202 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22203 @item @code{@ @ @ @ }Exceptions @tab ZCX
22204 @*
22205 @item @code{@ @ }@i{rts-sjlj}
22206 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22207 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22208 @*
22209 @item @b{ppc-aix}
22210 @item @code{@ @ }@i{rts-native (default)}
22211 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22212 @item @code{@ @ @ @ }Exceptions @tab ZCX
22213 @*
22214 @item @code{@ @ }@i{rts-sjlj}
22215 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22216 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22217 @*
22218 @item @b{ppc-darwin}
22219 @item @code{@ @ }@i{rts-native (default)}
22220 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22221 @item @code{@ @ @ @ }Exceptions @tab ZCX
22222 @*
22223 @item @b{sparc-solaris}  @tab
22224 @item @code{@ @ }@i{rts-native (default)}
22225 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22226 @item @code{@ @ @ @ }Exceptions @tab ZCX
22227 @*
22228 @item @code{@ @ }@i{rts-pthread}
22229 @item @code{@ @ @ @ }Tasking    @tab pthread library
22230 @item @code{@ @ @ @ }Exceptions @tab ZCX
22231 @*
22232 @item @code{@ @ }@i{rts-sjlj}
22233 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22234 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22235 @*
22236 @item @b{sparc64-solaris}  @tab
22237 @item @code{@ @ }@i{rts-native (default)}
22238 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22239 @item @code{@ @ @ @ }Exceptions @tab ZCX
22240 @*
22241 @item @b{x86-linux}
22242 @item @code{@ @ }@i{rts-native (default)}
22243 @item @code{@ @ @ @ }Tasking    @tab pthread library
22244 @item @code{@ @ @ @ }Exceptions @tab ZCX
22245 @*
22246 @item @code{@ @ }@i{rts-sjlj}
22247 @item @code{@ @ @ @ }Tasking    @tab pthread library
22248 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22249 @*
22250 @item @b{x86-lynx}
22251 @item @code{@ @ }@i{rts-native (default)}
22252 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22253 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22254 @*
22255 @item @b{x86-solaris}
22256 @item @code{@ @ }@i{rts-native (default)}
22257 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22258 @item @code{@ @ @ @ }Exceptions @tab ZCX
22259 @*
22260 @item @code{@ @ }@i{rts-sjlj}
22261 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22262 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22263 @*
22264 @item @b{x86-windows}
22265 @item @code{@ @ }@i{rts-native (default)}
22266 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22267 @item @code{@ @ @ @ }Exceptions @tab ZCX
22268 @*
22269 @item @code{@ @ }@i{rts-sjlj}
22270 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22271 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22272 @*
22273 @item @b{x86-windows-rtx}
22274 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22275 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22276 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22277 @*
22278 @item @code{@ @ }@i{rts-rtx-w32}
22279 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22280 @item @code{@ @ @ @ }Exceptions @tab ZCX
22281 @*
22282 @item @b{x86_64-linux}
22283 @item @code{@ @ }@i{rts-native (default)}
22284 @item @code{@ @ @ @ }Tasking    @tab pthread library
22285 @item @code{@ @ @ @ }Exceptions @tab ZCX
22286 @*
22287 @item @code{@ @ }@i{rts-sjlj}
22288 @item @code{@ @ @ @ }Tasking    @tab pthread library
22289 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22290 @*
22291 @end multitable
22292
22293 @node Specifying a Run-Time Library
22294 @section Specifying a Run-Time Library
22295
22296 @noindent
22297 The @file{adainclude} subdirectory containing the sources of the GNAT
22298 run-time library, and the @file{adalib} subdirectory containing the
22299 @file{ALI} files and the static and/or shared GNAT library, are located
22300 in the gcc target-dependent area:
22301
22302 @smallexample
22303 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22304 @end smallexample
22305
22306 @noindent
22307 As indicated above, on some platforms several run-time libraries are supplied.
22308 These libraries are installed in the target dependent area and
22309 contain a complete source and binary subdirectory. The detailed description
22310 below explains the differences between the different libraries in terms of
22311 their thread support.
22312
22313 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22314 This default run time is selected by the means of soft links.
22315 For example on x86-linux:
22316
22317 @smallexample
22318 @group
22319  $(target-dir)
22320      |
22321      +--- adainclude----------+
22322      |                        |
22323      +--- adalib-----------+  |
22324      |                     |  |
22325      +--- rts-native       |  |
22326      |    |                |  |
22327      |    +--- adainclude <---+
22328      |    |                |
22329      |    +--- adalib <----+
22330      |
22331      +--- rts-sjlj
22332           |
22333           +--- adainclude
22334           |
22335           +--- adalib
22336 @end group
22337 @end smallexample
22338
22339 @noindent
22340 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22341 these soft links can be modified with the following commands:
22342
22343 @smallexample
22344 $ cd $target
22345 $ rm -f adainclude adalib
22346 $ ln -s rts-sjlj/adainclude adainclude
22347 $ ln -s rts-sjlj/adalib adalib
22348 @end smallexample
22349
22350 @noindent
22351 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22352 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22353 @file{$target/ada_object_path}.
22354
22355 Selecting another run-time library temporarily can be
22356 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22357 @cindex @option{--RTS} option
22358
22359 @node Choosing the Scheduling Policy
22360 @section Choosing the Scheduling Policy
22361
22362 @noindent
22363 When using a POSIX threads implementation, you have a choice of several
22364 scheduling policies: @code{SCHED_FIFO},
22365 @cindex @code{SCHED_FIFO} scheduling policy
22366 @code{SCHED_RR}
22367 @cindex @code{SCHED_RR} scheduling policy
22368 and @code{SCHED_OTHER}.
22369 @cindex @code{SCHED_OTHER} scheduling policy
22370 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22371 or @code{SCHED_RR} requires special (e.g., root) privileges.
22372
22373 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22374 @code{SCHED_FIFO},
22375 @cindex @code{SCHED_FIFO} scheduling policy
22376 you can use one of the following:
22377
22378 @itemize @bullet
22379 @item
22380 @code{pragma Time_Slice (0.0)}
22381 @cindex pragma Time_Slice
22382 @item
22383 the corresponding binder option @option{-T0}
22384 @cindex @option{-T0} option
22385 @item
22386 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22387 @cindex pragma Task_Dispatching_Policy
22388 @end itemize
22389
22390 @noindent
22391 To specify @code{SCHED_RR},
22392 @cindex @code{SCHED_RR} scheduling policy
22393 you should use @code{pragma Time_Slice} with a
22394 value greater than @code{0.0}, or else use the corresponding @option{-T}
22395 binder option.
22396
22397 @node Solaris-Specific Considerations
22398 @section Solaris-Specific Considerations
22399 @cindex Solaris Sparc threads libraries
22400
22401 @noindent
22402 This section addresses some topics related to the various threads libraries
22403 on Sparc Solaris.
22404
22405 @menu
22406 * Solaris Threads Issues::
22407 @end menu
22408
22409 @node Solaris Threads Issues
22410 @subsection Solaris Threads Issues
22411
22412 @noindent
22413 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22414 library based on POSIX threads --- @emph{rts-pthread}.
22415 @cindex rts-pthread threads library
22416 This run-time library has the advantage of being mostly shared across all
22417 POSIX-compliant thread implementations, and it also provides under
22418 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22419 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22420 and @code{PTHREAD_PRIO_PROTECT}
22421 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22422 semantics that can be selected using the predefined pragma
22423 @code{Locking_Policy}
22424 @cindex pragma Locking_Policy (under rts-pthread)
22425 with respectively
22426 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22427 @cindex @code{Inheritance_Locking} (under rts-pthread)
22428 @cindex @code{Ceiling_Locking} (under rts-pthread)
22429
22430 As explained above, the native run-time library is based on the Solaris thread
22431 library (@code{libthread}) and is the default library.
22432
22433 When the Solaris threads library is used (this is the default), programs
22434 compiled with GNAT can automatically take advantage of
22435 and can thus execute on multiple processors.
22436 The user can alternatively specify a processor on which the program should run
22437 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22438 is made by
22439 setting the environment variable @env{GNAT_PROCESSOR}
22440 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22441 to one of the following:
22442
22443 @table @code
22444 @item -2
22445 Use the default configuration (run the program on all
22446 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22447 unset
22448
22449 @item -1
22450 Let the run-time implementation choose one processor and run the program on
22451 that processor
22452
22453 @item 0 .. Last_Proc
22454 Run the program on the specified processor.
22455 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22456 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22457 @end table
22458
22459 @node Linux-Specific Considerations
22460 @section Linux-Specific Considerations
22461 @cindex Linux threads libraries
22462
22463 @noindent
22464 On GNU/Linux without NPTL support (usually system with GNU C Library
22465 older than 2.3), the signal model is not POSIX compliant, which means
22466 that to send a signal to the process, you need to send the signal to all
22467 threads, e.g.@: by using @code{killpg()}.
22468
22469 @node AIX-Specific Considerations
22470 @section AIX-Specific Considerations
22471 @cindex AIX resolver library
22472
22473 @noindent
22474 On AIX, the resolver library initializes some internal structure on
22475 the first call to @code{get*by*} functions, which are used to implement
22476 @code{GNAT.Sockets.Get_Host_By_Name} and
22477 @code{GNAT.Sockets.Get_Host_By_Address}.
22478 If such initialization occurs within an Ada task, and the stack size for
22479 the task is the default size, a stack overflow may occur.
22480
22481 To avoid this overflow, the user should either ensure that the first call
22482 to @code{GNAT.Sockets.Get_Host_By_Name} or
22483 @code{GNAT.Sockets.Get_Host_By_Addrss}
22484 occurs in the environment task, or use @code{pragma Storage_Size} to
22485 specify a sufficiently large size for the stack of the task that contains
22486 this call.
22487
22488 @node Irix-Specific Considerations
22489 @section Irix-Specific Considerations
22490 @cindex Irix libraries
22491
22492 @noindent
22493 The GCC support libraries coming with the Irix compiler have moved to
22494 their canonical place with respect to the general Irix ABI related
22495 conventions. Running applications built with the default shared GNAT
22496 run-time now requires the LD_LIBRARY_PATH environment variable to
22497 include this location. A possible way to achieve this is to issue the
22498 following command line on a bash prompt:
22499
22500 @smallexample
22501 @group
22502 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22503 @end group
22504 @end smallexample
22505
22506 @node RTX-Specific Considerations
22507 @section RTX-Specific Considerations
22508 @cindex RTX libraries
22509
22510 @noindent
22511 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22512 API. Applications can be built to work in two different modes:
22513
22514 @itemize @bullet
22515 @item
22516 Windows executables that run in Ring 3 to utilize memory protection
22517 (@emph{rts-rtx-w32}).
22518
22519 @item
22520 Real-time subsystem (RTSS) executables that run in Ring 0, where
22521 performance can be optimized with RTSS applications taking precedent
22522 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22523 the Microsoft linker to handle RTSS libraries.
22524
22525 @end itemize
22526
22527 @node HP-UX-Specific Considerations
22528 @section HP-UX-Specific Considerations
22529 @cindex HP-UX Scheduling
22530
22531 @noindent
22532 On HP-UX, appropriate privileges are required to change the scheduling
22533 parameters of a task. The calling process must have appropriate
22534 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22535 successfully change the scheduling parameters.
22536
22537 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22538 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22539 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22540
22541 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22542 one of the following:
22543
22544 @itemize @bullet
22545 @item
22546 @code{pragma Time_Slice (0.0)}
22547 @cindex pragma Time_Slice
22548 @item
22549 the corresponding binder option @option{-T0}
22550 @cindex @option{-T0} option
22551 @item
22552 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22553 @cindex pragma Task_Dispatching_Policy
22554 @end itemize
22555
22556 @noindent
22557 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22558 you should use @code{pragma Time_Slice} with a
22559 value greater than @code{0.0}, or use the corresponding @option{-T}
22560 binder option, or set the @code{pragma Task_Dispatching_Policy
22561 (Round_Robin_Within_Priorities)}.
22562
22563 @c *******************************
22564 @node Example of Binder Output File
22565 @appendix Example of Binder Output File
22566
22567 @noindent
22568 This Appendix displays the source code for @command{gnatbind}'s output
22569 file generated for a simple ``Hello World'' program.
22570 Comments have been added for clarification purposes.
22571
22572 @smallexample @c adanocomment
22573 @iftex
22574 @leftskip=0cm
22575 @end iftex
22576 --  The package is called Ada_Main unless this name is actually used
22577 --  as a unit name in the partition, in which case some other unique
22578 --  name is used.
22579
22580 with System;
22581 package ada_main is
22582
22583    Elab_Final_Code : Integer;
22584    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22585
22586    --  The main program saves the parameters (argument count,
22587    --  argument values, environment pointer) in global variables
22588    --  for later access by other units including
22589    --  Ada.Command_Line.
22590
22591    gnat_argc : Integer;
22592    gnat_argv : System.Address;
22593    gnat_envp : System.Address;
22594
22595    --  The actual variables are stored in a library routine. This
22596    --  is useful for some shared library situations, where there
22597    --  are problems if variables are not in the library.
22598
22599    pragma Import (C, gnat_argc);
22600    pragma Import (C, gnat_argv);
22601    pragma Import (C, gnat_envp);
22602
22603    --  The exit status is similarly an external location
22604
22605    gnat_exit_status : Integer;
22606    pragma Import (C, gnat_exit_status);
22607
22608    GNAT_Version : constant String :=
22609                     "GNAT Version: 6.0.0w (20061115)";
22610    pragma Export (C, GNAT_Version, "__gnat_version");
22611
22612    --  This is the generated adafinal routine that performs
22613    --  finalization at the end of execution. In the case where
22614    --  Ada is the main program, this main program makes a call
22615    --  to adafinal at program termination.
22616
22617    procedure adafinal;
22618    pragma Export (C, adafinal, "adafinal");
22619
22620    --  This is the generated adainit routine that performs
22621    --  initialization at the start of execution. In the case
22622    --  where Ada is the main program, this main program makes
22623    --  a call to adainit at program startup.
22624
22625    procedure adainit;
22626    pragma Export (C, adainit, "adainit");
22627
22628    --  This routine is called at the start of execution. It is
22629    --  a dummy routine that is used by the debugger to breakpoint
22630    --  at the start of execution.
22631
22632    procedure Break_Start;
22633    pragma Import (C, Break_Start, "__gnat_break_start");
22634
22635    --  This is the actual generated main program (it would be
22636    --  suppressed if the no main program switch were used). As
22637    --  required by standard system conventions, this program has
22638    --  the external name main.
22639
22640    function main
22641      (argc : Integer;
22642       argv : System.Address;
22643       envp : System.Address)
22644       return Integer;
22645    pragma Export (C, main, "main");
22646
22647    --  The following set of constants give the version
22648    --  identification values for every unit in the bound
22649    --  partition. This identification is computed from all
22650    --  dependent semantic units, and corresponds to the
22651    --  string that would be returned by use of the
22652    --  Body_Version or Version attributes.
22653
22654    type Version_32 is mod 2 ** 32;
22655    u00001 : constant Version_32 := 16#7880BEB3#;
22656    u00002 : constant Version_32 := 16#0D24CBD0#;
22657    u00003 : constant Version_32 := 16#3283DBEB#;
22658    u00004 : constant Version_32 := 16#2359F9ED#;
22659    u00005 : constant Version_32 := 16#664FB847#;
22660    u00006 : constant Version_32 := 16#68E803DF#;
22661    u00007 : constant Version_32 := 16#5572E604#;
22662    u00008 : constant Version_32 := 16#46B173D8#;
22663    u00009 : constant Version_32 := 16#156A40CF#;
22664    u00010 : constant Version_32 := 16#033DABE0#;
22665    u00011 : constant Version_32 := 16#6AB38FEA#;
22666    u00012 : constant Version_32 := 16#22B6217D#;
22667    u00013 : constant Version_32 := 16#68A22947#;
22668    u00014 : constant Version_32 := 16#18CC4A56#;
22669    u00015 : constant Version_32 := 16#08258E1B#;
22670    u00016 : constant Version_32 := 16#367D5222#;
22671    u00017 : constant Version_32 := 16#20C9ECA4#;
22672    u00018 : constant Version_32 := 16#50D32CB6#;
22673    u00019 : constant Version_32 := 16#39A8BB77#;
22674    u00020 : constant Version_32 := 16#5CF8FA2B#;
22675    u00021 : constant Version_32 := 16#2F1EB794#;
22676    u00022 : constant Version_32 := 16#31AB6444#;
22677    u00023 : constant Version_32 := 16#1574B6E9#;
22678    u00024 : constant Version_32 := 16#5109C189#;
22679    u00025 : constant Version_32 := 16#56D770CD#;
22680    u00026 : constant Version_32 := 16#02F9DE3D#;
22681    u00027 : constant Version_32 := 16#08AB6B2C#;
22682    u00028 : constant Version_32 := 16#3FA37670#;
22683    u00029 : constant Version_32 := 16#476457A0#;
22684    u00030 : constant Version_32 := 16#731E1B6E#;
22685    u00031 : constant Version_32 := 16#23C2E789#;
22686    u00032 : constant Version_32 := 16#0F1BD6A1#;
22687    u00033 : constant Version_32 := 16#7C25DE96#;
22688    u00034 : constant Version_32 := 16#39ADFFA2#;
22689    u00035 : constant Version_32 := 16#571DE3E7#;
22690    u00036 : constant Version_32 := 16#5EB646AB#;
22691    u00037 : constant Version_32 := 16#4249379B#;
22692    u00038 : constant Version_32 := 16#0357E00A#;
22693    u00039 : constant Version_32 := 16#3784FB72#;
22694    u00040 : constant Version_32 := 16#2E723019#;
22695    u00041 : constant Version_32 := 16#623358EA#;
22696    u00042 : constant Version_32 := 16#107F9465#;
22697    u00043 : constant Version_32 := 16#6843F68A#;
22698    u00044 : constant Version_32 := 16#63305874#;
22699    u00045 : constant Version_32 := 16#31E56CE1#;
22700    u00046 : constant Version_32 := 16#02917970#;
22701    u00047 : constant Version_32 := 16#6CCBA70E#;
22702    u00048 : constant Version_32 := 16#41CD4204#;
22703    u00049 : constant Version_32 := 16#572E3F58#;
22704    u00050 : constant Version_32 := 16#20729FF5#;
22705    u00051 : constant Version_32 := 16#1D4F93E8#;
22706    u00052 : constant Version_32 := 16#30B2EC3D#;
22707    u00053 : constant Version_32 := 16#34054F96#;
22708    u00054 : constant Version_32 := 16#5A199860#;
22709    u00055 : constant Version_32 := 16#0E7F912B#;
22710    u00056 : constant Version_32 := 16#5760634A#;
22711    u00057 : constant Version_32 := 16#5D851835#;
22712
22713    --  The following Export pragmas export the version numbers
22714    --  with symbolic names ending in B (for body) or S
22715    --  (for spec) so that they can be located in a link. The
22716    --  information provided here is sufficient to track down
22717    --  the exact versions of units used in a given build.
22718
22719    pragma Export (C, u00001, "helloB");
22720    pragma Export (C, u00002, "system__standard_libraryB");
22721    pragma Export (C, u00003, "system__standard_libraryS");
22722    pragma Export (C, u00004, "adaS");
22723    pragma Export (C, u00005, "ada__text_ioB");
22724    pragma Export (C, u00006, "ada__text_ioS");
22725    pragma Export (C, u00007, "ada__exceptionsB");
22726    pragma Export (C, u00008, "ada__exceptionsS");
22727    pragma Export (C, u00009, "gnatS");
22728    pragma Export (C, u00010, "gnat__heap_sort_aB");
22729    pragma Export (C, u00011, "gnat__heap_sort_aS");
22730    pragma Export (C, u00012, "systemS");
22731    pragma Export (C, u00013, "system__exception_tableB");
22732    pragma Export (C, u00014, "system__exception_tableS");
22733    pragma Export (C, u00015, "gnat__htableB");
22734    pragma Export (C, u00016, "gnat__htableS");
22735    pragma Export (C, u00017, "system__exceptionsS");
22736    pragma Export (C, u00018, "system__machine_state_operationsB");
22737    pragma Export (C, u00019, "system__machine_state_operationsS");
22738    pragma Export (C, u00020, "system__machine_codeS");
22739    pragma Export (C, u00021, "system__storage_elementsB");
22740    pragma Export (C, u00022, "system__storage_elementsS");
22741    pragma Export (C, u00023, "system__secondary_stackB");
22742    pragma Export (C, u00024, "system__secondary_stackS");
22743    pragma Export (C, u00025, "system__parametersB");
22744    pragma Export (C, u00026, "system__parametersS");
22745    pragma Export (C, u00027, "system__soft_linksB");
22746    pragma Export (C, u00028, "system__soft_linksS");
22747    pragma Export (C, u00029, "system__stack_checkingB");
22748    pragma Export (C, u00030, "system__stack_checkingS");
22749    pragma Export (C, u00031, "system__tracebackB");
22750    pragma Export (C, u00032, "system__tracebackS");
22751    pragma Export (C, u00033, "ada__streamsS");
22752    pragma Export (C, u00034, "ada__tagsB");
22753    pragma Export (C, u00035, "ada__tagsS");
22754    pragma Export (C, u00036, "system__string_opsB");
22755    pragma Export (C, u00037, "system__string_opsS");
22756    pragma Export (C, u00038, "interfacesS");
22757    pragma Export (C, u00039, "interfaces__c_streamsB");
22758    pragma Export (C, u00040, "interfaces__c_streamsS");
22759    pragma Export (C, u00041, "system__file_ioB");
22760    pragma Export (C, u00042, "system__file_ioS");
22761    pragma Export (C, u00043, "ada__finalizationB");
22762    pragma Export (C, u00044, "ada__finalizationS");
22763    pragma Export (C, u00045, "system__finalization_rootB");
22764    pragma Export (C, u00046, "system__finalization_rootS");
22765    pragma Export (C, u00047, "system__finalization_implementationB");
22766    pragma Export (C, u00048, "system__finalization_implementationS");
22767    pragma Export (C, u00049, "system__string_ops_concat_3B");
22768    pragma Export (C, u00050, "system__string_ops_concat_3S");
22769    pragma Export (C, u00051, "system__stream_attributesB");
22770    pragma Export (C, u00052, "system__stream_attributesS");
22771    pragma Export (C, u00053, "ada__io_exceptionsS");
22772    pragma Export (C, u00054, "system__unsigned_typesS");
22773    pragma Export (C, u00055, "system__file_control_blockS");
22774    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22775    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22776
22777    -- BEGIN ELABORATION ORDER
22778    -- ada (spec)
22779    -- gnat (spec)
22780    -- gnat.heap_sort_a (spec)
22781    -- gnat.heap_sort_a (body)
22782    -- gnat.htable (spec)
22783    -- gnat.htable (body)
22784    -- interfaces (spec)
22785    -- system (spec)
22786    -- system.machine_code (spec)
22787    -- system.parameters (spec)
22788    -- system.parameters (body)
22789    -- interfaces.c_streams (spec)
22790    -- interfaces.c_streams (body)
22791    -- system.standard_library (spec)
22792    -- ada.exceptions (spec)
22793    -- system.exception_table (spec)
22794    -- system.exception_table (body)
22795    -- ada.io_exceptions (spec)
22796    -- system.exceptions (spec)
22797    -- system.storage_elements (spec)
22798    -- system.storage_elements (body)
22799    -- system.machine_state_operations (spec)
22800    -- system.machine_state_operations (body)
22801    -- system.secondary_stack (spec)
22802    -- system.stack_checking (spec)
22803    -- system.soft_links (spec)
22804    -- system.soft_links (body)
22805    -- system.stack_checking (body)
22806    -- system.secondary_stack (body)
22807    -- system.standard_library (body)
22808    -- system.string_ops (spec)
22809    -- system.string_ops (body)
22810    -- ada.tags (spec)
22811    -- ada.tags (body)
22812    -- ada.streams (spec)
22813    -- system.finalization_root (spec)
22814    -- system.finalization_root (body)
22815    -- system.string_ops_concat_3 (spec)
22816    -- system.string_ops_concat_3 (body)
22817    -- system.traceback (spec)
22818    -- system.traceback (body)
22819    -- ada.exceptions (body)
22820    -- system.unsigned_types (spec)
22821    -- system.stream_attributes (spec)
22822    -- system.stream_attributes (body)
22823    -- system.finalization_implementation (spec)
22824    -- system.finalization_implementation (body)
22825    -- ada.finalization (spec)
22826    -- ada.finalization (body)
22827    -- ada.finalization.list_controller (spec)
22828    -- ada.finalization.list_controller (body)
22829    -- system.file_control_block (spec)
22830    -- system.file_io (spec)
22831    -- system.file_io (body)
22832    -- ada.text_io (spec)
22833    -- ada.text_io (body)
22834    -- hello (body)
22835    -- END ELABORATION ORDER
22836
22837 end ada_main;
22838
22839 --  The following source file name pragmas allow the generated file
22840 --  names to be unique for different main programs. They are needed
22841 --  since the package name will always be Ada_Main.
22842
22843 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22844 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22845
22846 --  Generated package body for Ada_Main starts here
22847
22848 package body ada_main is
22849
22850    --  The actual finalization is performed by calling the
22851    --  library routine in System.Standard_Library.Adafinal
22852
22853    procedure Do_Finalize;
22854    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22855
22856    -------------
22857    -- adainit --
22858    -------------
22859
22860 @findex adainit
22861    procedure adainit is
22862
22863       --  These booleans are set to True once the associated unit has
22864       --  been elaborated. It is also used to avoid elaborating the
22865       --  same unit twice.
22866
22867       E040 : Boolean;
22868       pragma Import (Ada, E040, "interfaces__c_streams_E");
22869
22870       E008 : Boolean;
22871       pragma Import (Ada, E008, "ada__exceptions_E");
22872
22873       E014 : Boolean;
22874       pragma Import (Ada, E014, "system__exception_table_E");
22875
22876       E053 : Boolean;
22877       pragma Import (Ada, E053, "ada__io_exceptions_E");
22878
22879       E017 : Boolean;
22880       pragma Import (Ada, E017, "system__exceptions_E");
22881
22882       E024 : Boolean;
22883       pragma Import (Ada, E024, "system__secondary_stack_E");
22884
22885       E030 : Boolean;
22886       pragma Import (Ada, E030, "system__stack_checking_E");
22887
22888       E028 : Boolean;
22889       pragma Import (Ada, E028, "system__soft_links_E");
22890
22891       E035 : Boolean;
22892       pragma Import (Ada, E035, "ada__tags_E");
22893
22894       E033 : Boolean;
22895       pragma Import (Ada, E033, "ada__streams_E");
22896
22897       E046 : Boolean;
22898       pragma Import (Ada, E046, "system__finalization_root_E");
22899
22900       E048 : Boolean;
22901       pragma Import (Ada, E048, "system__finalization_implementation_E");
22902
22903       E044 : Boolean;
22904       pragma Import (Ada, E044, "ada__finalization_E");
22905
22906       E057 : Boolean;
22907       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22908
22909       E055 : Boolean;
22910       pragma Import (Ada, E055, "system__file_control_block_E");
22911
22912       E042 : Boolean;
22913       pragma Import (Ada, E042, "system__file_io_E");
22914
22915       E006 : Boolean;
22916       pragma Import (Ada, E006, "ada__text_io_E");
22917
22918       --  Set_Globals is a library routine that stores away the
22919       --  value of the indicated set of global values in global
22920       --  variables within the library.
22921
22922       procedure Set_Globals
22923         (Main_Priority            : Integer;
22924          Time_Slice_Value         : Integer;
22925          WC_Encoding              : Character;
22926          Locking_Policy           : Character;
22927          Queuing_Policy           : Character;
22928          Task_Dispatching_Policy  : Character;
22929          Adafinal                 : System.Address;
22930          Unreserve_All_Interrupts : Integer;
22931          Exception_Tracebacks     : Integer);
22932 @findex __gnat_set_globals
22933       pragma Import (C, Set_Globals, "__gnat_set_globals");
22934
22935       --  SDP_Table_Build is a library routine used to build the
22936       --  exception tables. See unit Ada.Exceptions in files
22937       --  a-except.ads/adb for full details of how zero cost
22938       --  exception handling works. This procedure, the call to
22939       --  it, and the two following tables are all omitted if the
22940       --  build is in longjmp/setjmp exception mode.
22941
22942 @findex SDP_Table_Build
22943 @findex Zero Cost Exceptions
22944       procedure SDP_Table_Build
22945         (SDP_Addresses   : System.Address;
22946          SDP_Count       : Natural;
22947          Elab_Addresses  : System.Address;
22948          Elab_Addr_Count : Natural);
22949       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22950
22951       --  Table of Unit_Exception_Table addresses. Used for zero
22952       --  cost exception handling to build the top level table.
22953
22954       ST : aliased constant array (1 .. 23) of System.Address := (
22955         Hello'UET_Address,
22956         Ada.Text_Io'UET_Address,
22957         Ada.Exceptions'UET_Address,
22958         Gnat.Heap_Sort_A'UET_Address,
22959         System.Exception_Table'UET_Address,
22960         System.Machine_State_Operations'UET_Address,
22961         System.Secondary_Stack'UET_Address,
22962         System.Parameters'UET_Address,
22963         System.Soft_Links'UET_Address,
22964         System.Stack_Checking'UET_Address,
22965         System.Traceback'UET_Address,
22966         Ada.Streams'UET_Address,
22967         Ada.Tags'UET_Address,
22968         System.String_Ops'UET_Address,
22969         Interfaces.C_Streams'UET_Address,
22970         System.File_Io'UET_Address,
22971         Ada.Finalization'UET_Address,
22972         System.Finalization_Root'UET_Address,
22973         System.Finalization_Implementation'UET_Address,
22974         System.String_Ops_Concat_3'UET_Address,
22975         System.Stream_Attributes'UET_Address,
22976         System.File_Control_Block'UET_Address,
22977         Ada.Finalization.List_Controller'UET_Address);
22978
22979       --  Table of addresses of elaboration routines. Used for
22980       --  zero cost exception handling to make sure these
22981       --  addresses are included in the top level procedure
22982       --  address table.
22983
22984       EA : aliased constant array (1 .. 23) of System.Address := (
22985         adainit'Code_Address,
22986         Do_Finalize'Code_Address,
22987         Ada.Exceptions'Elab_Spec'Address,
22988         System.Exceptions'Elab_Spec'Address,
22989         Interfaces.C_Streams'Elab_Spec'Address,
22990         System.Exception_Table'Elab_Body'Address,
22991         Ada.Io_Exceptions'Elab_Spec'Address,
22992         System.Stack_Checking'Elab_Spec'Address,
22993         System.Soft_Links'Elab_Body'Address,
22994         System.Secondary_Stack'Elab_Body'Address,
22995         Ada.Tags'Elab_Spec'Address,
22996         Ada.Tags'Elab_Body'Address,
22997         Ada.Streams'Elab_Spec'Address,
22998         System.Finalization_Root'Elab_Spec'Address,
22999         Ada.Exceptions'Elab_Body'Address,
23000         System.Finalization_Implementation'Elab_Spec'Address,
23001         System.Finalization_Implementation'Elab_Body'Address,
23002         Ada.Finalization'Elab_Spec'Address,
23003         Ada.Finalization.List_Controller'Elab_Spec'Address,
23004         System.File_Control_Block'Elab_Spec'Address,
23005         System.File_Io'Elab_Body'Address,
23006         Ada.Text_Io'Elab_Spec'Address,
23007         Ada.Text_Io'Elab_Body'Address);
23008
23009    --  Start of processing for adainit
23010
23011    begin
23012
23013       --  Call SDP_Table_Build to build the top level procedure
23014       --  table for zero cost exception handling (omitted in
23015       --  longjmp/setjmp mode).
23016
23017       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23018
23019       --  Call Set_Globals to record various information for
23020       --  this partition.  The values are derived by the binder
23021       --  from information stored in the ali files by the compiler.
23022
23023 @findex __gnat_set_globals
23024       Set_Globals
23025         (Main_Priority            => -1,
23026          --  Priority of main program, -1 if no pragma Priority used
23027
23028          Time_Slice_Value         => -1,
23029          --  Time slice from Time_Slice pragma, -1 if none used
23030
23031          WC_Encoding              => 'b',
23032          --  Wide_Character encoding used, default is brackets
23033
23034          Locking_Policy           => ' ',
23035          --  Locking_Policy used, default of space means not
23036          --  specified, otherwise it is the first character of
23037          --  the policy name.
23038
23039          Queuing_Policy           => ' ',
23040          --  Queuing_Policy used, default of space means not
23041          --  specified, otherwise it is the first character of
23042          --  the policy name.
23043
23044          Task_Dispatching_Policy  => ' ',
23045          --  Task_Dispatching_Policy used, default of space means
23046          --  not specified, otherwise first character of the
23047          --  policy name.
23048
23049          Adafinal                 => System.Null_Address,
23050          --  Address of Adafinal routine, not used anymore
23051
23052          Unreserve_All_Interrupts => 0,
23053          --  Set true if pragma Unreserve_All_Interrupts was used
23054
23055          Exception_Tracebacks     => 0);
23056          --  Indicates if exception tracebacks are enabled
23057
23058       Elab_Final_Code := 1;
23059
23060       --  Now we have the elaboration calls for all units in the partition.
23061       --  The Elab_Spec and Elab_Body attributes generate references to the
23062       --  implicit elaboration procedures generated by the compiler for
23063       --  each unit that requires elaboration.
23064
23065       if not E040 then
23066          Interfaces.C_Streams'Elab_Spec;
23067       end if;
23068       E040 := True;
23069       if not E008 then
23070          Ada.Exceptions'Elab_Spec;
23071       end if;
23072       if not E014 then
23073          System.Exception_Table'Elab_Body;
23074          E014 := True;
23075       end if;
23076       if not E053 then
23077          Ada.Io_Exceptions'Elab_Spec;
23078          E053 := True;
23079       end if;
23080       if not E017 then
23081          System.Exceptions'Elab_Spec;
23082          E017 := True;
23083       end if;
23084       if not E030 then
23085          System.Stack_Checking'Elab_Spec;
23086       end if;
23087       if not E028 then
23088          System.Soft_Links'Elab_Body;
23089          E028 := True;
23090       end if;
23091       E030 := True;
23092       if not E024 then
23093          System.Secondary_Stack'Elab_Body;
23094          E024 := True;
23095       end if;
23096       if not E035 then
23097          Ada.Tags'Elab_Spec;
23098       end if;
23099       if not E035 then
23100          Ada.Tags'Elab_Body;
23101          E035 := True;
23102       end if;
23103       if not E033 then
23104          Ada.Streams'Elab_Spec;
23105          E033 := True;
23106       end if;
23107       if not E046 then
23108          System.Finalization_Root'Elab_Spec;
23109       end if;
23110       E046 := True;
23111       if not E008 then
23112          Ada.Exceptions'Elab_Body;
23113          E008 := True;
23114       end if;
23115       if not E048 then
23116          System.Finalization_Implementation'Elab_Spec;
23117       end if;
23118       if not E048 then
23119          System.Finalization_Implementation'Elab_Body;
23120          E048 := True;
23121       end if;
23122       if not E044 then
23123          Ada.Finalization'Elab_Spec;
23124       end if;
23125       E044 := True;
23126       if not E057 then
23127          Ada.Finalization.List_Controller'Elab_Spec;
23128       end if;
23129       E057 := True;
23130       if not E055 then
23131          System.File_Control_Block'Elab_Spec;
23132          E055 := True;
23133       end if;
23134       if not E042 then
23135          System.File_Io'Elab_Body;
23136          E042 := True;
23137       end if;
23138       if not E006 then
23139          Ada.Text_Io'Elab_Spec;
23140       end if;
23141       if not E006 then
23142          Ada.Text_Io'Elab_Body;
23143          E006 := True;
23144       end if;
23145
23146       Elab_Final_Code := 0;
23147    end adainit;
23148
23149    --------------
23150    -- adafinal --
23151    --------------
23152
23153 @findex adafinal
23154    procedure adafinal is
23155    begin
23156       Do_Finalize;
23157    end adafinal;
23158
23159    ----------
23160    -- main --
23161    ----------
23162
23163    --  main is actually a function, as in the ANSI C standard,
23164    --  defined to return the exit status. The three parameters
23165    --  are the argument count, argument values and environment
23166    --  pointer.
23167
23168 @findex Main Program
23169    function main
23170      (argc : Integer;
23171       argv : System.Address;
23172       envp : System.Address)
23173       return Integer
23174    is
23175       --  The initialize routine performs low level system
23176       --  initialization using a standard library routine which
23177       --  sets up signal handling and performs any other
23178       --  required setup. The routine can be found in file
23179       --  a-init.c.
23180
23181 @findex __gnat_initialize
23182       procedure initialize;
23183       pragma Import (C, initialize, "__gnat_initialize");
23184
23185       --  The finalize routine performs low level system
23186       --  finalization using a standard library routine. The
23187       --  routine is found in file a-final.c and in the standard
23188       --  distribution is a dummy routine that does nothing, so
23189       --  really this is a hook for special user finalization.
23190
23191 @findex __gnat_finalize
23192       procedure finalize;
23193       pragma Import (C, finalize, "__gnat_finalize");
23194
23195       --  We get to the main program of the partition by using
23196       --  pragma Import because if we try to with the unit and
23197       --  call it Ada style, then not only do we waste time
23198       --  recompiling it, but also, we don't really know the right
23199       --  switches (e.g.@: identifier character set) to be used
23200       --  to compile it.
23201
23202       procedure Ada_Main_Program;
23203       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23204
23205    --  Start of processing for main
23206
23207    begin
23208       --  Save global variables
23209
23210       gnat_argc := argc;
23211       gnat_argv := argv;
23212       gnat_envp := envp;
23213
23214       --  Call low level system initialization
23215
23216       Initialize;
23217
23218       --  Call our generated Ada initialization routine
23219
23220       adainit;
23221
23222       --  This is the point at which we want the debugger to get
23223       --  control
23224
23225       Break_Start;
23226
23227       --  Now we call the main program of the partition
23228
23229       Ada_Main_Program;
23230
23231       --  Perform Ada finalization
23232
23233       adafinal;
23234
23235       --  Perform low level system finalization
23236
23237       Finalize;
23238
23239       --  Return the proper exit status
23240       return (gnat_exit_status);
23241    end;
23242
23243 --  This section is entirely comments, so it has no effect on the
23244 --  compilation of the Ada_Main package. It provides the list of
23245 --  object files and linker options, as well as some standard
23246 --  libraries needed for the link. The gnatlink utility parses
23247 --  this b~hello.adb file to read these comment lines to generate
23248 --  the appropriate command line arguments for the call to the
23249 --  system linker. The BEGIN/END lines are used for sentinels for
23250 --  this parsing operation.
23251
23252 --  The exact file names will of course depend on the environment,
23253 --  host/target and location of files on the host system.
23254
23255 @findex Object file list
23256 -- BEGIN Object file/option list
23257    --   ./hello.o
23258    --   -L./
23259    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23260    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23261 -- END Object file/option list
23262
23263 end ada_main;
23264 @end smallexample
23265
23266 @noindent
23267 The Ada code in the above example is exactly what is generated by the
23268 binder. We have added comments to more clearly indicate the function
23269 of each part of the generated @code{Ada_Main} package.
23270
23271 The code is standard Ada in all respects, and can be processed by any
23272 tools that handle Ada. In particular, it is possible to use the debugger
23273 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23274 suppose that for reasons that you do not understand, your program is crashing
23275 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23276 you can place a breakpoint on the call:
23277
23278 @smallexample @c ada
23279 Ada.Text_Io'Elab_Body;
23280 @end smallexample
23281
23282 @noindent
23283 and trace the elaboration routine for this package to find out where
23284 the problem might be (more usually of course you would be debugging
23285 elaboration code in your own application).
23286
23287 @node Elaboration Order Handling in GNAT
23288 @appendix Elaboration Order Handling in GNAT
23289 @cindex Order of elaboration
23290 @cindex Elaboration control
23291
23292 @menu
23293 * Elaboration Code::
23294 * Checking the Elaboration Order::
23295 * Controlling the Elaboration Order::
23296 * Controlling Elaboration in GNAT - Internal Calls::
23297 * Controlling Elaboration in GNAT - External Calls::
23298 * Default Behavior in GNAT - Ensuring Safety::
23299 * Treatment of Pragma Elaborate::
23300 * Elaboration Issues for Library Tasks::
23301 * Mixing Elaboration Models::
23302 * What to Do If the Default Elaboration Behavior Fails::
23303 * Elaboration for Access-to-Subprogram Values::
23304 * Summary of Procedures for Elaboration Control::
23305 * Other Elaboration Order Considerations::
23306 @end menu
23307
23308 @noindent
23309 This chapter describes the handling of elaboration code in Ada and
23310 in GNAT, and discusses how the order of elaboration of program units can
23311 be controlled in GNAT, either automatically or with explicit programming
23312 features.
23313
23314 @node Elaboration Code
23315 @section Elaboration Code
23316
23317 @noindent
23318 Ada provides rather general mechanisms for executing code at elaboration
23319 time, that is to say before the main program starts executing. Such code arises
23320 in three contexts:
23321
23322 @table @asis
23323 @item Initializers for variables.
23324 Variables declared at the library level, in package specs or bodies, can
23325 require initialization that is performed at elaboration time, as in:
23326 @smallexample @c ada
23327 @cartouche
23328 Sqrt_Half : Float := Sqrt (0.5);
23329 @end cartouche
23330 @end smallexample
23331
23332 @item Package initialization code
23333 Code in a @code{BEGIN-END} section at the outer level of a package body is
23334 executed as part of the package body elaboration code.
23335
23336 @item Library level task allocators
23337 Tasks that are declared using task allocators at the library level
23338 start executing immediately and hence can execute at elaboration time.
23339 @end table
23340
23341 @noindent
23342 Subprogram calls are possible in any of these contexts, which means that
23343 any arbitrary part of the program may be executed as part of the elaboration
23344 code. It is even possible to write a program which does all its work at
23345 elaboration time, with a null main program, although stylistically this
23346 would usually be considered an inappropriate way to structure
23347 a program.
23348
23349 An important concern arises in the context of elaboration code:
23350 we have to be sure that it is executed in an appropriate order. What we
23351 have is a series of elaboration code sections, potentially one section
23352 for each unit in the program. It is important that these execute
23353 in the correct order. Correctness here means that, taking the above
23354 example of the declaration of @code{Sqrt_Half},
23355 if some other piece of
23356 elaboration code references @code{Sqrt_Half},
23357 then it must run after the
23358 section of elaboration code that contains the declaration of
23359 @code{Sqrt_Half}.
23360
23361 There would never be any order of elaboration problem if we made a rule
23362 that whenever you @code{with} a unit, you must elaborate both the spec and body
23363 of that unit before elaborating the unit doing the @code{with}'ing:
23364
23365 @smallexample @c ada
23366 @group
23367 @cartouche
23368 with Unit_1;
23369 package Unit_2 is @dots{}
23370 @end cartouche
23371 @end group
23372 @end smallexample
23373
23374 @noindent
23375 would require that both the body and spec of @code{Unit_1} be elaborated
23376 before the spec of @code{Unit_2}. However, a rule like that would be far too
23377 restrictive. In particular, it would make it impossible to have routines
23378 in separate packages that were mutually recursive.
23379
23380 You might think that a clever enough compiler could look at the actual
23381 elaboration code and determine an appropriate correct order of elaboration,
23382 but in the general case, this is not possible. Consider the following
23383 example.
23384
23385 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23386 that references
23387 the variable @code{Sqrt_1}, which is declared in the elaboration code
23388 of the body of @code{Unit_1}:
23389
23390 @smallexample @c ada
23391 @cartouche
23392 Sqrt_1 : Float := Sqrt (0.1);
23393 @end cartouche
23394 @end smallexample
23395
23396 @noindent
23397 The elaboration code of the body of @code{Unit_1} also contains:
23398
23399 @smallexample @c ada
23400 @group
23401 @cartouche
23402 if expression_1 = 1 then
23403    Q := Unit_2.Func_2;
23404 end if;
23405 @end cartouche
23406 @end group
23407 @end smallexample
23408
23409 @noindent
23410 @code{Unit_2} is exactly parallel,
23411 it has a procedure @code{Func_2} that references
23412 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23413 the body @code{Unit_2}:
23414
23415 @smallexample @c ada
23416 @cartouche
23417 Sqrt_2 : Float := Sqrt (0.1);
23418 @end cartouche
23419 @end smallexample
23420
23421 @noindent
23422 The elaboration code of the body of @code{Unit_2} also contains:
23423
23424 @smallexample @c ada
23425 @group
23426 @cartouche
23427 if expression_2 = 2 then
23428    Q := Unit_1.Func_1;
23429 end if;
23430 @end cartouche
23431 @end group
23432 @end smallexample
23433
23434 @noindent
23435 Now the question is, which of the following orders of elaboration is
23436 acceptable:
23437
23438 @smallexample
23439 @group
23440 Spec of Unit_1
23441 Spec of Unit_2
23442 Body of Unit_1
23443 Body of Unit_2
23444 @end group
23445 @end smallexample
23446
23447 @noindent
23448 or
23449
23450 @smallexample
23451 @group
23452 Spec of Unit_2
23453 Spec of Unit_1
23454 Body of Unit_2
23455 Body of Unit_1
23456 @end group
23457 @end smallexample
23458
23459 @noindent
23460 If you carefully analyze the flow here, you will see that you cannot tell
23461 at compile time the answer to this question.
23462 If @code{expression_1} is not equal to 1,
23463 and @code{expression_2} is not equal to 2,
23464 then either order is acceptable, because neither of the function calls is
23465 executed. If both tests evaluate to true, then neither order is acceptable
23466 and in fact there is no correct order.
23467
23468 If one of the two expressions is true, and the other is false, then one
23469 of the above orders is correct, and the other is incorrect. For example,
23470 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23471 then the call to @code{Func_1}
23472 will occur, but not the call to @code{Func_2.}
23473 This means that it is essential
23474 to elaborate the body of @code{Unit_1} before
23475 the body of @code{Unit_2}, so the first
23476 order of elaboration is correct and the second is wrong.
23477
23478 By making @code{expression_1} and @code{expression_2}
23479 depend on input data, or perhaps
23480 the time of day, we can make it impossible for the compiler or binder
23481 to figure out which of these expressions will be true, and hence it
23482 is impossible to guarantee a safe order of elaboration at run time.
23483
23484 @node Checking the Elaboration Order
23485 @section Checking the Elaboration Order
23486
23487 @noindent
23488 In some languages that involve the same kind of elaboration problems,
23489 e.g.@: Java and C++, the programmer is expected to worry about these
23490 ordering problems himself, and it is common to
23491 write a program in which an incorrect elaboration order  gives
23492 surprising results, because it references variables before they
23493 are initialized.
23494 Ada is designed to be a safe language, and a programmer-beware approach is
23495 clearly not sufficient. Consequently, the language provides three lines
23496 of defense:
23497
23498 @table @asis
23499 @item Standard rules
23500 Some standard rules restrict the possible choice of elaboration
23501 order. In particular, if you @code{with} a unit, then its spec is always
23502 elaborated before the unit doing the @code{with}. Similarly, a parent
23503 spec is always elaborated before the child spec, and finally
23504 a spec is always elaborated before its corresponding body.
23505
23506 @item Dynamic elaboration checks
23507 @cindex Elaboration checks
23508 @cindex Checks, elaboration
23509 Dynamic checks are made at run time, so that if some entity is accessed
23510 before it is elaborated (typically  by means of a subprogram call)
23511 then the exception (@code{Program_Error}) is raised.
23512
23513 @item Elaboration control
23514 Facilities are provided for the programmer to specify the desired order
23515 of elaboration.
23516 @end table
23517
23518 Let's look at these facilities in more detail. First, the rules for
23519 dynamic checking. One possible rule would be simply to say that the
23520 exception is raised if you access a variable which has not yet been
23521 elaborated. The trouble with this approach is that it could require
23522 expensive checks on every variable reference. Instead Ada has two
23523 rules which are a little more restrictive, but easier to check, and
23524 easier to state:
23525
23526 @table @asis
23527 @item Restrictions on calls
23528 A subprogram can only be called at elaboration time if its body
23529 has been elaborated. The rules for elaboration given above guarantee
23530 that the spec of the subprogram has been elaborated before the
23531 call, but not the body. If this rule is violated, then the
23532 exception @code{Program_Error} is raised.
23533
23534 @item Restrictions on instantiations
23535 A generic unit can only be instantiated if the body of the generic
23536 unit has been elaborated. Again, the rules for elaboration given above
23537 guarantee that the spec of the generic unit has been elaborated
23538 before the instantiation, but not the body. If this rule is
23539 violated, then the exception @code{Program_Error} is raised.
23540 @end table
23541
23542 @noindent
23543 The idea is that if the body has been elaborated, then any variables
23544 it references must have been elaborated; by checking for the body being
23545 elaborated we guarantee that none of its references causes any
23546 trouble. As we noted above, this is a little too restrictive, because a
23547 subprogram that has no non-local references in its body may in fact be safe
23548 to call. However, it really would be unsafe to rely on this, because
23549 it would mean that the caller was aware of details of the implementation
23550 in the body. This goes against the basic tenets of Ada.
23551
23552 A plausible implementation can be described as follows.
23553 A Boolean variable is associated with each subprogram
23554 and each generic unit. This variable is initialized to False, and is set to
23555 True at the point body is elaborated. Every call or instantiation checks the
23556 variable, and raises @code{Program_Error} if the variable is False.
23557
23558 Note that one might think that it would be good enough to have one Boolean
23559 variable for each package, but that would not deal with cases of trying
23560 to call a body in the same package as the call
23561 that has not been elaborated yet.
23562 Of course a compiler may be able to do enough analysis to optimize away
23563 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23564 does such optimizations, but still the easiest conceptual model is to
23565 think of there being one variable per subprogram.
23566
23567 @node Controlling the Elaboration Order
23568 @section Controlling the Elaboration Order
23569
23570 @noindent
23571 In the previous section we discussed the rules in Ada which ensure
23572 that @code{Program_Error} is raised if an incorrect elaboration order is
23573 chosen. This prevents erroneous executions, but we need mechanisms to
23574 specify a correct execution and avoid the exception altogether.
23575 To achieve this, Ada provides a number of features for controlling
23576 the order of elaboration. We discuss these features in this section.
23577
23578 First, there are several ways of indicating to the compiler that a given
23579 unit has no elaboration problems:
23580
23581 @table @asis
23582 @item packages that do not require a body
23583 A library package that does not require a body does not permit
23584 a body (this rule was introduced in Ada 95).
23585 Thus if we have a such a package, as in:
23586
23587 @smallexample @c ada
23588 @group
23589 @cartouche
23590 package Definitions is
23591    generic
23592       type m is new integer;
23593    package Subp is
23594       type a is array (1 .. 10) of m;
23595       type b is array (1 .. 20) of m;
23596    end Subp;
23597 end Definitions;
23598 @end cartouche
23599 @end group
23600 @end smallexample
23601
23602 @noindent
23603 A package that @code{with}'s @code{Definitions} may safely instantiate
23604 @code{Definitions.Subp} because the compiler can determine that there
23605 definitely is no package body to worry about in this case
23606
23607 @item pragma Pure
23608 @cindex pragma Pure
23609 @findex Pure
23610 Places sufficient restrictions on a unit to guarantee that
23611 no call to any subprogram in the unit can result in an
23612 elaboration problem. This means that the compiler does not need
23613 to worry about the point of elaboration of such units, and in
23614 particular, does not need to check any calls to any subprograms
23615 in this unit.
23616
23617 @item pragma Preelaborate
23618 @findex Preelaborate
23619 @cindex pragma Preelaborate
23620 This pragma places slightly less stringent restrictions on a unit than
23621 does pragma Pure,
23622 but these restrictions are still sufficient to ensure that there
23623 are no elaboration problems with any calls to the unit.
23624
23625 @item pragma Elaborate_Body
23626 @findex Elaborate_Body
23627 @cindex pragma Elaborate_Body
23628 This pragma requires that the body of a unit be elaborated immediately
23629 after its spec. Suppose a unit @code{A} has such a pragma,
23630 and unit @code{B} does
23631 a @code{with} of unit @code{A}. Recall that the standard rules require
23632 the spec of unit @code{A}
23633 to be elaborated before the @code{with}'ing unit; given the pragma in
23634 @code{A}, we also know that the body of @code{A}
23635 will be elaborated before @code{B}, so
23636 that calls to @code{A} are safe and do not need a check.
23637 @end table
23638
23639 @noindent
23640 Note that,
23641 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23642 the use of
23643 @code{Elaborate_Body} does not guarantee that the program is
23644 free of elaboration problems, because it may not be possible
23645 to satisfy the requested elaboration order.
23646 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23647 If a programmer
23648 marks @code{Unit_1} as @code{Elaborate_Body},
23649 and not @code{Unit_2,} then the order of
23650 elaboration will be:
23651
23652 @smallexample
23653 @group
23654 Spec of Unit_2
23655 Spec of Unit_1
23656 Body of Unit_1
23657 Body of Unit_2
23658 @end group
23659 @end smallexample
23660
23661 @noindent
23662 Now that means that the call to @code{Func_1} in @code{Unit_2}
23663 need not be checked,
23664 it must be safe. But the call to @code{Func_2} in
23665 @code{Unit_1} may still fail if
23666 @code{Expression_1} is equal to 1,
23667 and the programmer must still take
23668 responsibility for this not being the case.
23669
23670 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23671 eliminated, except for calls entirely within a body, which are
23672 in any case fully under programmer control. However, using the pragma
23673 everywhere is not always possible.
23674 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23675 we marked both of them as having pragma @code{Elaborate_Body}, then
23676 clearly there would be no possible elaboration order.
23677
23678 The above pragmas allow a server to guarantee safe use by clients, and
23679 clearly this is the preferable approach. Consequently a good rule
23680 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23681 and if this is not possible,
23682 mark them as @code{Elaborate_Body} if possible.
23683 As we have seen, there are situations where neither of these
23684 three pragmas can be used.
23685 So we also provide methods for clients to control the
23686 order of elaboration of the servers on which they depend:
23687
23688 @table @asis
23689 @item pragma Elaborate (unit)
23690 @findex Elaborate
23691 @cindex pragma Elaborate
23692 This pragma is placed in the context clause, after a @code{with} clause,
23693 and it requires that the body of the named unit be elaborated before
23694 the unit in which the pragma occurs. The idea is to use this pragma
23695 if the current unit calls at elaboration time, directly or indirectly,
23696 some subprogram in the named unit.
23697
23698 @item pragma Elaborate_All (unit)
23699 @findex Elaborate_All
23700 @cindex pragma Elaborate_All
23701 This is a stronger version of the Elaborate pragma. Consider the
23702 following example:
23703
23704 @smallexample
23705 Unit A @code{with}'s unit B and calls B.Func in elab code
23706 Unit B @code{with}'s unit C, and B.Func calls C.Func
23707 @end smallexample
23708
23709 @noindent
23710 Now if we put a pragma @code{Elaborate (B)}
23711 in unit @code{A}, this ensures that the
23712 body of @code{B} is elaborated before the call, but not the
23713 body of @code{C}, so
23714 the call to @code{C.Func} could still cause @code{Program_Error} to
23715 be raised.
23716
23717 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23718 not only that the body of the named unit be elaborated before the
23719 unit doing the @code{with}, but also the bodies of all units that the
23720 named unit uses, following @code{with} links transitively. For example,
23721 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23722 then it requires
23723 not only that the body of @code{B} be elaborated before @code{A},
23724 but also the
23725 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23726 @end table
23727
23728 @noindent
23729 We are now in a position to give a usage rule in Ada for avoiding
23730 elaboration problems, at least if dynamic dispatching and access to
23731 subprogram values are not used. We will handle these cases separately
23732 later.
23733
23734 The rule is simple. If a unit has elaboration code that can directly or
23735 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23736 a generic package in a @code{with}'ed unit,
23737 then if the @code{with}'ed unit does not have
23738 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23739 a pragma @code{Elaborate_All}
23740 for the @code{with}'ed unit. By following this rule a client is
23741 assured that calls can be made without risk of an exception.
23742
23743 For generic subprogram instantiations, the rule can be relaxed to
23744 require only a pragma @code{Elaborate} since elaborating the body
23745 of a subprogram cannot cause any transitive elaboration (we are
23746 not calling the subprogram in this case, just elaborating its
23747 declaration).
23748
23749 If this rule is not followed, then a program may be in one of four
23750 states:
23751
23752 @table @asis
23753 @item No order exists
23754 No order of elaboration exists which follows the rules, taking into
23755 account any @code{Elaborate}, @code{Elaborate_All},
23756 or @code{Elaborate_Body} pragmas. In
23757 this case, an Ada compiler must diagnose the situation at bind
23758 time, and refuse to build an executable program.
23759
23760 @item One or more orders exist, all incorrect
23761 One or more acceptable elaboration orders exist, and all of them
23762 generate an elaboration order problem. In this case, the binder
23763 can build an executable program, but @code{Program_Error} will be raised
23764 when the program is run.
23765
23766 @item Several orders exist, some right, some incorrect
23767 One or more acceptable elaboration orders exists, and some of them
23768 work, and some do not. The programmer has not controlled
23769 the order of elaboration, so the binder may or may not pick one of
23770 the correct orders, and the program may or may not raise an
23771 exception when it is run. This is the worst case, because it means
23772 that the program may fail when moved to another compiler, or even
23773 another version of the same compiler.
23774
23775 @item One or more orders exists, all correct
23776 One ore more acceptable elaboration orders exist, and all of them
23777 work. In this case the program runs successfully. This state of
23778 affairs can be guaranteed by following the rule we gave above, but
23779 may be true even if the rule is not followed.
23780 @end table
23781
23782 @noindent
23783 Note that one additional advantage of following our rules on the use
23784 of @code{Elaborate} and @code{Elaborate_All}
23785 is that the program continues to stay in the ideal (all orders OK) state
23786 even if maintenance
23787 changes some bodies of some units. Conversely, if a program that does
23788 not follow this rule happens to be safe at some point, this state of affairs
23789 may deteriorate silently as a result of maintenance changes.
23790
23791 You may have noticed that the above discussion did not mention
23792 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23793 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23794 code in the body makes calls to some other unit, so it is still necessary
23795 to use @code{Elaborate_All} on such units.
23796
23797 @node Controlling Elaboration in GNAT - Internal Calls
23798 @section Controlling Elaboration in GNAT - Internal Calls
23799
23800 @noindent
23801 In the case of internal calls, i.e., calls within a single package, the
23802 programmer has full control over the order of elaboration, and it is up
23803 to the programmer to elaborate declarations in an appropriate order. For
23804 example writing:
23805
23806 @smallexample @c ada
23807 @group
23808 @cartouche
23809 function One return Float;
23810
23811 Q : Float := One;
23812
23813 function One return Float is
23814 begin
23815      return 1.0;
23816 end One;
23817 @end cartouche
23818 @end group
23819 @end smallexample
23820
23821 @noindent
23822 will obviously raise @code{Program_Error} at run time, because function
23823 One will be called before its body is elaborated. In this case GNAT will
23824 generate a warning that the call will raise @code{Program_Error}:
23825
23826 @smallexample
23827 @group
23828 @cartouche
23829  1. procedure y is
23830  2.    function One return Float;
23831  3.
23832  4.    Q : Float := One;
23833                     |
23834     >>> warning: cannot call "One" before body is elaborated
23835     >>> warning: Program_Error will be raised at run time
23836
23837  5.
23838  6.    function One return Float is
23839  7.    begin
23840  8.         return 1.0;
23841  9.    end One;
23842 10.
23843 11. begin
23844 12.    null;
23845 13. end;
23846 @end cartouche
23847 @end group
23848 @end smallexample
23849
23850 @noindent
23851 Note that in this particular case, it is likely that the call is safe, because
23852 the function @code{One} does not access any global variables.
23853 Nevertheless in Ada, we do not want the validity of the check to depend on
23854 the contents of the body (think about the separate compilation case), so this
23855 is still wrong, as we discussed in the previous sections.
23856
23857 The error is easily corrected by rearranging the declarations so that the
23858 body of @code{One} appears before the declaration containing the call
23859 (note that in Ada 95 and Ada 2005,
23860 declarations can appear in any order, so there is no restriction that
23861 would prevent this reordering, and if we write:
23862
23863 @smallexample @c ada
23864 @group
23865 @cartouche
23866 function One return Float;
23867
23868 function One return Float is
23869 begin
23870      return 1.0;
23871 end One;
23872
23873 Q : Float := One;
23874 @end cartouche
23875 @end group
23876 @end smallexample
23877
23878 @noindent
23879 then all is well, no warning is generated, and no
23880 @code{Program_Error} exception
23881 will be raised.
23882 Things are more complicated when a chain of subprograms is executed:
23883
23884 @smallexample @c ada
23885 @group
23886 @cartouche
23887 function A return Integer;
23888 function B return Integer;
23889 function C return Integer;
23890
23891 function B return Integer is begin return A; end;
23892 function C return Integer is begin return B; end;
23893
23894 X : Integer := C;
23895
23896 function A return Integer is begin return 1; end;
23897 @end cartouche
23898 @end group
23899 @end smallexample
23900
23901 @noindent
23902 Now the call to @code{C}
23903 at elaboration time in the declaration of @code{X} is correct, because
23904 the body of @code{C} is already elaborated,
23905 and the call to @code{B} within the body of
23906 @code{C} is correct, but the call
23907 to @code{A} within the body of @code{B} is incorrect, because the body
23908 of @code{A} has not been elaborated, so @code{Program_Error}
23909 will be raised on the call to @code{A}.
23910 In this case GNAT will generate a
23911 warning that @code{Program_Error} may be
23912 raised at the point of the call. Let's look at the warning:
23913
23914 @smallexample
23915 @group
23916 @cartouche
23917  1. procedure x is
23918  2.    function A return Integer;
23919  3.    function B return Integer;
23920  4.    function C return Integer;
23921  5.
23922  6.    function B return Integer is begin return A; end;
23923                                                     |
23924     >>> warning: call to "A" before body is elaborated may
23925                  raise Program_Error
23926     >>> warning: "B" called at line 7
23927     >>> warning: "C" called at line 9
23928
23929  7.    function C return Integer is begin return B; end;
23930  8.
23931  9.    X : Integer := C;
23932 10.
23933 11.    function A return Integer is begin return 1; end;
23934 12.
23935 13. begin
23936 14.    null;
23937 15. end;
23938 @end cartouche
23939 @end group
23940 @end smallexample
23941
23942 @noindent
23943 Note that the message here says ``may raise'', instead of the direct case,
23944 where the message says ``will be raised''. That's because whether
23945 @code{A} is
23946 actually called depends in general on run-time flow of control.
23947 For example, if the body of @code{B} said
23948
23949 @smallexample @c ada
23950 @group
23951 @cartouche
23952 function B return Integer is
23953 begin
23954    if some-condition-depending-on-input-data then
23955       return A;
23956    else
23957       return 1;
23958    end if;
23959 end B;
23960 @end cartouche
23961 @end group
23962 @end smallexample
23963
23964 @noindent
23965 then we could not know until run time whether the incorrect call to A would
23966 actually occur, so @code{Program_Error} might
23967 or might not be raised. It is possible for a compiler to
23968 do a better job of analyzing bodies, to
23969 determine whether or not @code{Program_Error}
23970 might be raised, but it certainly
23971 couldn't do a perfect job (that would require solving the halting problem
23972 and is provably impossible), and because this is a warning anyway, it does
23973 not seem worth the effort to do the analysis. Cases in which it
23974 would be relevant are rare.
23975
23976 In practice, warnings of either of the forms given
23977 above will usually correspond to
23978 real errors, and should be examined carefully and eliminated.
23979 In the rare case where a warning is bogus, it can be suppressed by any of
23980 the following methods:
23981
23982 @itemize @bullet
23983 @item
23984 Compile with the @option{-gnatws} switch set
23985
23986 @item
23987 Suppress @code{Elaboration_Check} for the called subprogram
23988
23989 @item
23990 Use pragma @code{Warnings_Off} to turn warnings off for the call
23991 @end itemize
23992
23993 @noindent
23994 For the internal elaboration check case,
23995 GNAT by default generates the
23996 necessary run-time checks to ensure
23997 that @code{Program_Error} is raised if any
23998 call fails an elaboration check. Of course this can only happen if a
23999 warning has been issued as described above. The use of pragma
24000 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24001 some of these checks, meaning that it may be possible (but is not
24002 guaranteed) for a program to be able to call a subprogram whose body
24003 is not yet elaborated, without raising a @code{Program_Error} exception.
24004
24005 @node Controlling Elaboration in GNAT - External Calls
24006 @section Controlling Elaboration in GNAT - External Calls
24007
24008 @noindent
24009 The previous section discussed the case in which the execution of a
24010 particular thread of elaboration code occurred entirely within a
24011 single unit. This is the easy case to handle, because a programmer
24012 has direct and total control over the order of elaboration, and
24013 furthermore, checks need only be generated in cases which are rare
24014 and which the compiler can easily detect.
24015 The situation is more complex when separate compilation is taken into account.
24016 Consider the following:
24017
24018 @smallexample @c ada
24019 @cartouche
24020 @group
24021 package Math is
24022    function Sqrt (Arg : Float) return Float;
24023 end Math;
24024
24025 package body Math is
24026    function Sqrt (Arg : Float) return Float is
24027    begin
24028          @dots{}
24029    end Sqrt;
24030 end Math;
24031 @end group
24032 @group
24033 with Math;
24034 package Stuff is
24035    X : Float := Math.Sqrt (0.5);
24036 end Stuff;
24037
24038 with Stuff;
24039 procedure Main is
24040 begin
24041    @dots{}
24042 end Main;
24043 @end group
24044 @end cartouche
24045 @end smallexample
24046
24047 @noindent
24048 where @code{Main} is the main program. When this program is executed, the
24049 elaboration code must first be executed, and one of the jobs of the
24050 binder is to determine the order in which the units of a program are
24051 to be elaborated. In this case we have four units: the spec and body
24052 of @code{Math},
24053 the spec of @code{Stuff} and the body of @code{Main}).
24054 In what order should the four separate sections of elaboration code
24055 be executed?
24056
24057 There are some restrictions in the order of elaboration that the binder
24058 can choose. In particular, if unit U has a @code{with}
24059 for a package @code{X}, then you
24060 are assured that the spec of @code{X}
24061 is elaborated before U , but you are
24062 not assured that the body of @code{X}
24063 is elaborated before U.
24064 This means that in the above case, the binder is allowed to choose the
24065 order:
24066
24067 @smallexample
24068 spec of Math
24069 spec of Stuff
24070 body of Math
24071 body of Main
24072 @end smallexample
24073
24074 @noindent
24075 but that's not good, because now the call to @code{Math.Sqrt}
24076 that happens during
24077 the elaboration of the @code{Stuff}
24078 spec happens before the body of @code{Math.Sqrt} is
24079 elaborated, and hence causes @code{Program_Error} exception to be raised.
24080 At first glance, one might say that the binder is misbehaving, because
24081 obviously you want to elaborate the body of something you @code{with}
24082 first, but
24083 that is not a general rule that can be followed in all cases. Consider
24084
24085 @smallexample @c ada
24086 @group
24087 @cartouche
24088 package X is @dots{}
24089
24090 package Y is @dots{}
24091
24092 with X;
24093 package body Y is @dots{}
24094
24095 with Y;
24096 package body X is @dots{}
24097 @end cartouche
24098 @end group
24099 @end smallexample
24100
24101 @noindent
24102 This is a common arrangement, and, apart from the order of elaboration
24103 problems that might arise in connection with elaboration code, this works fine.
24104 A rule that says that you must first elaborate the body of anything you
24105 @code{with} cannot work in this case:
24106 the body of @code{X} @code{with}'s @code{Y},
24107 which means you would have to
24108 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24109 which means
24110 you have to elaborate the body of @code{X} first, but @dots{} and we have a
24111 loop that cannot be broken.
24112
24113 It is true that the binder can in many cases guess an order of elaboration
24114 that is unlikely to cause a @code{Program_Error}
24115 exception to be raised, and it tries to do so (in the
24116 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24117 by default
24118 elaborate the body of @code{Math} right after its spec, so all will be well).
24119
24120 However, a program that blindly relies on the binder to be helpful can
24121 get into trouble, as we discussed in the previous sections, so
24122 GNAT
24123 provides a number of facilities for assisting the programmer in
24124 developing programs that are robust with respect to elaboration order.
24125
24126 @node Default Behavior in GNAT - Ensuring Safety
24127 @section Default Behavior in GNAT - Ensuring Safety
24128
24129 @noindent
24130 The default behavior in GNAT ensures elaboration safety. In its
24131 default mode GNAT implements the
24132 rule we previously described as the right approach. Let's restate it:
24133
24134 @itemize
24135 @item
24136 @emph{If a unit has elaboration code that can directly or indirectly make a
24137 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24138 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24139 does not have pragma @code{Pure} or
24140 @code{Preelaborate}, then the client should have an
24141 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24142
24143 @emph{In the case of instantiating a generic subprogram, it is always
24144 sufficient to have only an @code{Elaborate} pragma for the
24145 @code{with}'ed unit.}
24146 @end itemize
24147
24148 @noindent
24149 By following this rule a client is assured that calls and instantiations
24150 can be made without risk of an exception.
24151
24152 In this mode GNAT traces all calls that are potentially made from
24153 elaboration code, and puts in any missing implicit @code{Elaborate}
24154 and @code{Elaborate_All} pragmas.
24155 The advantage of this approach is that no elaboration problems
24156 are possible if the binder can find an elaboration order that is
24157 consistent with these implicit @code{Elaborate} and
24158 @code{Elaborate_All} pragmas. The
24159 disadvantage of this approach is that no such order may exist.
24160
24161 If the binder does not generate any diagnostics, then it means that it has
24162 found an elaboration order that is guaranteed to be safe. However, the binder
24163 may still be relying on implicitly generated @code{Elaborate} and
24164 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24165 guaranteed.
24166
24167 If it is important to guarantee portability, then the compilations should
24168 use the
24169 @option{-gnatwl}
24170 (warn on elaboration problems) switch. This will cause warning messages
24171 to be generated indicating the missing @code{Elaborate} and
24172 @code{Elaborate_All} pragmas.
24173 Consider the following source program:
24174
24175 @smallexample @c ada
24176 @group
24177 @cartouche
24178 with k;
24179 package j is
24180   m : integer := k.r;
24181 end;
24182 @end cartouche
24183 @end group
24184 @end smallexample
24185
24186 @noindent
24187 where it is clear that there
24188 should be a pragma @code{Elaborate_All}
24189 for unit @code{k}. An implicit pragma will be generated, and it is
24190 likely that the binder will be able to honor it. However, if you want
24191 to port this program to some other Ada compiler than GNAT.
24192 it is safer to include the pragma explicitly in the source. If this
24193 unit is compiled with the
24194 @option{-gnatwl}
24195 switch, then the compiler outputs a warning:
24196
24197 @smallexample
24198 @group
24199 @cartouche
24200 1. with k;
24201 2. package j is
24202 3.   m : integer := k.r;
24203                      |
24204    >>> warning: call to "r" may raise Program_Error
24205    >>> warning: missing pragma Elaborate_All for "k"
24206
24207 4. end;
24208 @end cartouche
24209 @end group
24210 @end smallexample
24211
24212 @noindent
24213 and these warnings can be used as a guide for supplying manually
24214 the missing pragmas. It is usually a bad idea to use this warning
24215 option during development. That's because it will warn you when
24216 you need to put in a pragma, but cannot warn you when it is time
24217 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24218 unnecessary dependencies and even false circularities.
24219
24220 This default mode is more restrictive than the Ada Reference
24221 Manual, and it is possible to construct programs which will compile
24222 using the dynamic model described there, but will run into a
24223 circularity using the safer static model we have described.
24224
24225 Of course any Ada compiler must be able to operate in a mode
24226 consistent with the requirements of the Ada Reference Manual,
24227 and in particular must have the capability of implementing the
24228 standard dynamic model of elaboration with run-time checks.
24229
24230 In GNAT, this standard mode can be achieved either by the use of
24231 the @option{-gnatE} switch on the compiler (@command{gcc} or
24232 @command{gnatmake}) command, or by the use of the configuration pragma:
24233
24234 @smallexample @c ada
24235 pragma Elaboration_Checks (DYNAMIC);
24236 @end smallexample
24237
24238 @noindent
24239 Either approach will cause the unit affected to be compiled using the
24240 standard dynamic run-time elaboration checks described in the Ada
24241 Reference Manual. The static model is generally preferable, since it
24242 is clearly safer to rely on compile and link time checks rather than
24243 run-time checks. However, in the case of legacy code, it may be
24244 difficult to meet the requirements of the static model. This
24245 issue is further discussed in
24246 @ref{What to Do If the Default Elaboration Behavior Fails}.
24247
24248 Note that the static model provides a strict subset of the allowed
24249 behavior and programs of the Ada Reference Manual, so if you do
24250 adhere to the static model and no circularities exist,
24251 then you are assured that your program will
24252 work using the dynamic model, providing that you remove any
24253 pragma Elaborate statements from the source.
24254
24255 @node Treatment of Pragma Elaborate
24256 @section Treatment of Pragma Elaborate
24257 @cindex Pragma Elaborate
24258
24259 @noindent
24260 The use of @code{pragma Elaborate}
24261 should generally be avoided in Ada 95 and Ada 2005 programs,
24262 since there is no guarantee that transitive calls
24263 will be properly handled. Indeed at one point, this pragma was placed
24264 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24265
24266 Now that's a bit restrictive. In practice, the case in which
24267 @code{pragma Elaborate} is useful is when the caller knows that there
24268 are no transitive calls, or that the called unit contains all necessary
24269 transitive @code{pragma Elaborate} statements, and legacy code often
24270 contains such uses.
24271
24272 Strictly speaking the static mode in GNAT should ignore such pragmas,
24273 since there is no assurance at compile time that the necessary safety
24274 conditions are met. In practice, this would cause GNAT to be incompatible
24275 with correctly written Ada 83 code that had all necessary
24276 @code{pragma Elaborate} statements in place. Consequently, we made the
24277 decision that GNAT in its default mode will believe that if it encounters
24278 a @code{pragma Elaborate} then the programmer knows what they are doing,
24279 and it will trust that no elaboration errors can occur.
24280
24281 The result of this decision is two-fold. First to be safe using the
24282 static mode, you should remove all @code{pragma Elaborate} statements.
24283 Second, when fixing circularities in existing code, you can selectively
24284 use @code{pragma Elaborate} statements to convince the static mode of
24285 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24286 statement.
24287
24288 When using the static mode with @option{-gnatwl}, any use of
24289 @code{pragma Elaborate} will generate a warning about possible
24290 problems.
24291
24292 @node Elaboration Issues for Library Tasks
24293 @section Elaboration Issues for Library Tasks
24294 @cindex Library tasks, elaboration issues
24295 @cindex Elaboration of library tasks
24296
24297 @noindent
24298 In this section we examine special elaboration issues that arise for
24299 programs that declare library level tasks.
24300
24301 Generally the model of execution of an Ada program is that all units are
24302 elaborated, and then execution of the program starts. However, the
24303 declaration of library tasks definitely does not fit this model. The
24304 reason for this is that library tasks start as soon as they are declared
24305 (more precisely, as soon as the statement part of the enclosing package
24306 body is reached), that is to say before elaboration
24307 of the program is complete. This means that if such a task calls a
24308 subprogram, or an entry in another task, the callee may or may not be
24309 elaborated yet, and in the standard
24310 Reference Manual model of dynamic elaboration checks, you can even
24311 get timing dependent Program_Error exceptions, since there can be
24312 a race between the elaboration code and the task code.
24313
24314 The static model of elaboration in GNAT seeks to avoid all such
24315 dynamic behavior, by being conservative, and the conservative
24316 approach in this particular case is to assume that all the code
24317 in a task body is potentially executed at elaboration time if
24318 a task is declared at the library level.
24319
24320 This can definitely result in unexpected circularities. Consider
24321 the following example
24322
24323 @smallexample @c ada
24324 package Decls is
24325   task Lib_Task is
24326      entry Start;
24327   end Lib_Task;
24328
24329   type My_Int is new Integer;
24330
24331   function Ident (M : My_Int) return My_Int;
24332 end Decls;
24333
24334 with Utils;
24335 package body Decls is
24336   task body Lib_Task is
24337   begin
24338      accept Start;
24339      Utils.Put_Val (2);
24340   end Lib_Task;
24341
24342   function Ident (M : My_Int) return My_Int is
24343   begin
24344      return M;
24345   end Ident;
24346 end Decls;
24347
24348 with Decls;
24349 package Utils is
24350   procedure Put_Val (Arg : Decls.My_Int);
24351 end Utils;
24352
24353 with Text_IO;
24354 package body Utils is
24355   procedure Put_Val (Arg : Decls.My_Int) is
24356   begin
24357      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24358   end Put_Val;
24359 end Utils;
24360
24361 with Decls;
24362 procedure Main is
24363 begin
24364    Decls.Lib_Task.Start;
24365 end;
24366 @end smallexample
24367
24368 @noindent
24369 If the above example is compiled in the default static elaboration
24370 mode, then a circularity occurs. The circularity comes from the call
24371 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24372 this call occurs in elaboration code, we need an implicit pragma
24373 @code{Elaborate_All} for @code{Utils}. This means that not only must
24374 the spec and body of @code{Utils} be elaborated before the body
24375 of @code{Decls}, but also the spec and body of any unit that is
24376 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24377 the body of @code{Decls}. This is the transitive implication of
24378 pragma @code{Elaborate_All} and it makes sense, because in general
24379 the body of @code{Put_Val} might have a call to something in a
24380 @code{with'ed} unit.
24381
24382 In this case, the body of Utils (actually its spec) @code{with's}
24383 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24384 must be elaborated before itself, in case there is a call from the
24385 body of @code{Utils}.
24386
24387 Here is the exact chain of events we are worrying about:
24388
24389 @enumerate
24390 @item
24391 In the body of @code{Decls} a call is made from within the body of a library
24392 task to a subprogram in the package @code{Utils}. Since this call may
24393 occur at elaboration time (given that the task is activated at elaboration
24394 time), we have to assume the worst, i.e., that the
24395 call does happen at elaboration time.
24396
24397 @item
24398 This means that the body and spec of @code{Util} must be elaborated before
24399 the body of @code{Decls} so that this call does not cause an access before
24400 elaboration.
24401
24402 @item
24403 Within the body of @code{Util}, specifically within the body of
24404 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24405 by this package.
24406
24407 @item
24408 One such @code{with}'ed package is package @code{Decls}, so there
24409 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24410 In fact there is such a call in this example, but we would have to
24411 assume that there was such a call even if it were not there, since
24412 we are not supposed to write the body of @code{Decls} knowing what
24413 is in the body of @code{Utils}; certainly in the case of the
24414 static elaboration model, the compiler does not know what is in
24415 other bodies and must assume the worst.
24416
24417 @item
24418 This means that the spec and body of @code{Decls} must also be
24419 elaborated before we elaborate the unit containing the call, but
24420 that unit is @code{Decls}! This means that the body of @code{Decls}
24421 must be elaborated before itself, and that's a circularity.
24422 @end enumerate
24423
24424 @noindent
24425 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24426 the body of @code{Decls} you will get a true Ada Reference Manual
24427 circularity that makes the program illegal.
24428
24429 In practice, we have found that problems with the static model of
24430 elaboration in existing code often arise from library tasks, so
24431 we must address this particular situation.
24432
24433 Note that if we compile and run the program above, using the dynamic model of
24434 elaboration (that is to say use the @option{-gnatE} switch),
24435 then it compiles, binds,
24436 links, and runs, printing the expected result of 2. Therefore in some sense
24437 the circularity here is only apparent, and we need to capture
24438 the properties of this program that  distinguish it from other library-level
24439 tasks that have real elaboration problems.
24440
24441 We have four possible answers to this question:
24442
24443 @itemize @bullet
24444
24445 @item
24446 Use the dynamic model of elaboration.
24447
24448 If we use the @option{-gnatE} switch, then as noted above, the program works.
24449 Why is this? If we examine the task body, it is apparent that the task cannot
24450 proceed past the
24451 @code{accept} statement until after elaboration has been completed, because
24452 the corresponding entry call comes from the main program, not earlier.
24453 This is why the dynamic model works here. But that's really giving
24454 up on a precise analysis, and we prefer to take this approach only if we cannot
24455 solve the
24456 problem in any other manner. So let us examine two ways to reorganize
24457 the program to avoid the potential elaboration problem.
24458
24459 @item
24460 Split library tasks into separate packages.
24461
24462 Write separate packages, so that library tasks are isolated from
24463 other declarations as much as possible. Let us look at a variation on
24464 the above program.
24465
24466 @smallexample @c ada
24467 package Decls1 is
24468   task Lib_Task is
24469      entry Start;
24470   end Lib_Task;
24471 end Decls1;
24472
24473 with Utils;
24474 package body Decls1 is
24475   task body Lib_Task is
24476   begin
24477      accept Start;
24478      Utils.Put_Val (2);
24479   end Lib_Task;
24480 end Decls1;
24481
24482 package Decls2 is
24483   type My_Int is new Integer;
24484   function Ident (M : My_Int) return My_Int;
24485 end Decls2;
24486
24487 with Utils;
24488 package body Decls2 is
24489   function Ident (M : My_Int) return My_Int is
24490   begin
24491      return M;
24492   end Ident;
24493 end Decls2;
24494
24495 with Decls2;
24496 package Utils is
24497   procedure Put_Val (Arg : Decls2.My_Int);
24498 end Utils;
24499
24500 with Text_IO;
24501 package body Utils is
24502   procedure Put_Val (Arg : Decls2.My_Int) is
24503   begin
24504      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24505   end Put_Val;
24506 end Utils;
24507
24508 with Decls1;
24509 procedure Main is
24510 begin
24511    Decls1.Lib_Task.Start;
24512 end;
24513 @end smallexample
24514
24515 @noindent
24516 All we have done is to split @code{Decls} into two packages, one
24517 containing the library task, and one containing everything else. Now
24518 there is no cycle, and the program compiles, binds, links and executes
24519 using the default static model of elaboration.
24520
24521 @item
24522 Declare separate task types.
24523
24524 A significant part of the problem arises because of the use of the
24525 single task declaration form. This means that the elaboration of
24526 the task type, and the elaboration of the task itself (i.e.@: the
24527 creation of the task) happen at the same time. A good rule
24528 of style in Ada is to always create explicit task types. By
24529 following the additional step of placing task objects in separate
24530 packages from the task type declaration, many elaboration problems
24531 are avoided. Here is another modified example of the example program:
24532
24533 @smallexample @c ada
24534 package Decls is
24535   task type Lib_Task_Type is
24536      entry Start;
24537   end Lib_Task_Type;
24538
24539   type My_Int is new Integer;
24540
24541   function Ident (M : My_Int) return My_Int;
24542 end Decls;
24543
24544 with Utils;
24545 package body Decls is
24546   task body Lib_Task_Type is
24547   begin
24548      accept Start;
24549      Utils.Put_Val (2);
24550   end Lib_Task_Type;
24551
24552   function Ident (M : My_Int) return My_Int is
24553   begin
24554      return M;
24555   end Ident;
24556 end Decls;
24557
24558 with Decls;
24559 package Utils is
24560   procedure Put_Val (Arg : Decls.My_Int);
24561 end Utils;
24562
24563 with Text_IO;
24564 package body Utils is
24565   procedure Put_Val (Arg : Decls.My_Int) is
24566   begin
24567      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24568   end Put_Val;
24569 end Utils;
24570
24571 with Decls;
24572 package Declst is
24573    Lib_Task : Decls.Lib_Task_Type;
24574 end Declst;
24575
24576 with Declst;
24577 procedure Main is
24578 begin
24579    Declst.Lib_Task.Start;
24580 end;
24581 @end smallexample
24582
24583 @noindent
24584 What we have done here is to replace the @code{task} declaration in
24585 package @code{Decls} with a @code{task type} declaration. Then we
24586 introduce a separate package @code{Declst} to contain the actual
24587 task object. This separates the elaboration issues for
24588 the @code{task type}
24589 declaration, which causes no trouble, from the elaboration issues
24590 of the task object, which is also unproblematic, since it is now independent
24591 of the elaboration of  @code{Utils}.
24592 This separation of concerns also corresponds to
24593 a generally sound engineering principle of separating declarations
24594 from instances. This version of the program also compiles, binds, links,
24595 and executes, generating the expected output.
24596
24597 @item
24598 Use No_Entry_Calls_In_Elaboration_Code restriction.
24599 @cindex No_Entry_Calls_In_Elaboration_Code
24600
24601 The previous two approaches described how a program can be restructured
24602 to avoid the special problems caused by library task bodies. in practice,
24603 however, such restructuring may be difficult to apply to existing legacy code,
24604 so we must consider solutions that do not require massive rewriting.
24605
24606 Let us consider more carefully why our original sample program works
24607 under the dynamic model of elaboration. The reason is that the code
24608 in the task body blocks immediately on the @code{accept}
24609 statement. Now of course there is nothing to prohibit elaboration
24610 code from making entry calls (for example from another library level task),
24611 so we cannot tell in isolation that
24612 the task will not execute the accept statement  during elaboration.
24613
24614 However, in practice it is very unusual to see elaboration code
24615 make any entry calls, and the pattern of tasks starting
24616 at elaboration time and then immediately blocking on @code{accept} or
24617 @code{select} statements is very common. What this means is that
24618 the compiler is being too pessimistic when it analyzes the
24619 whole package body as though it might be executed at elaboration
24620 time.
24621
24622 If we know that the elaboration code contains no entry calls, (a very safe
24623 assumption most of the time, that could almost be made the default
24624 behavior), then we can compile all units of the program under control
24625 of the following configuration pragma:
24626
24627 @smallexample
24628 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24629 @end smallexample
24630
24631 @noindent
24632 This pragma can be placed in the @file{gnat.adc} file in the usual
24633 manner. If we take our original unmodified program and compile it
24634 in the presence of a @file{gnat.adc} containing the above pragma,
24635 then once again, we can compile, bind, link, and execute, obtaining
24636 the expected result. In the presence of this pragma, the compiler does
24637 not trace calls in a task body, that appear after the first @code{accept}
24638 or @code{select} statement, and therefore does not report a potential
24639 circularity in the original program.
24640
24641 The compiler will check to the extent it can that the above
24642 restriction is not violated, but it is not always possible to do a
24643 complete check at compile time, so it is important to use this
24644 pragma only if the stated restriction is in fact met, that is to say
24645 no task receives an entry call before elaboration of all units is completed.
24646
24647 @end itemize
24648
24649 @node Mixing Elaboration Models
24650 @section Mixing Elaboration Models
24651 @noindent
24652 So far, we have assumed that the entire program is either compiled
24653 using the dynamic model or static model, ensuring consistency. It
24654 is possible to mix the two models, but rules have to be followed
24655 if this mixing is done to ensure that elaboration checks are not
24656 omitted.
24657
24658 The basic rule is that @emph{a unit compiled with the static model cannot
24659 be @code{with'ed} by a unit compiled with the dynamic model}. The
24660 reason for this is that in the static model, a unit assumes that
24661 its clients guarantee to use (the equivalent of) pragma
24662 @code{Elaborate_All} so that no elaboration checks are required
24663 in inner subprograms, and this assumption is violated if the
24664 client is compiled with dynamic checks.
24665
24666 The precise rule is as follows. A unit that is compiled with dynamic
24667 checks can only @code{with} a unit that meets at least one of the
24668 following criteria:
24669
24670 @itemize @bullet
24671
24672 @item
24673 The @code{with'ed} unit is itself compiled with dynamic elaboration
24674 checks (that is with the @option{-gnatE} switch.
24675
24676 @item
24677 The @code{with'ed} unit is an internal GNAT implementation unit from
24678 the System, Interfaces, Ada, or GNAT hierarchies.
24679
24680 @item
24681 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24682
24683 @item
24684 The @code{with'ing} unit (that is the client) has an explicit pragma
24685 @code{Elaborate_All} for the @code{with'ed} unit.
24686
24687 @end itemize
24688
24689 @noindent
24690 If this rule is violated, that is if a unit with dynamic elaboration
24691 checks @code{with's} a unit that does not meet one of the above four
24692 criteria, then the binder (@code{gnatbind}) will issue a warning
24693 similar to that in the following example:
24694
24695 @smallexample
24696 warning: "x.ads" has dynamic elaboration checks and with's
24697 warning:   "y.ads" which has static elaboration checks
24698 @end smallexample
24699
24700 @noindent
24701 These warnings indicate that the rule has been violated, and that as a result
24702 elaboration checks may be missed in the resulting executable file.
24703 This warning may be suppressed using the @option{-ws} binder switch
24704 in the usual manner.
24705
24706 One useful application of this mixing rule is in the case of a subsystem
24707 which does not itself @code{with} units from the remainder of the
24708 application. In this case, the entire subsystem can be compiled with
24709 dynamic checks to resolve a circularity in the subsystem, while
24710 allowing the main application that uses this subsystem to be compiled
24711 using the more reliable default static model.
24712
24713 @node What to Do If the Default Elaboration Behavior Fails
24714 @section What to Do If the Default Elaboration Behavior Fails
24715
24716 @noindent
24717 If the binder cannot find an acceptable order, it outputs detailed
24718 diagnostics. For example:
24719 @smallexample
24720 @group
24721 @iftex
24722 @leftskip=0cm
24723 @end iftex
24724 error: elaboration circularity detected
24725 info:   "proc (body)" must be elaborated before "pack (body)"
24726 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24727 info:     recompile "pack (body)" with -gnatwl
24728 info:                             for full details
24729 info:       "proc (body)"
24730 info:         is needed by its spec:
24731 info:       "proc (spec)"
24732 info:         which is withed by:
24733 info:       "pack (body)"
24734 info:  "pack (body)" must be elaborated before "proc (body)"
24735 info:     reason: pragma Elaborate in unit "proc (body)"
24736 @end group
24737
24738 @end smallexample
24739
24740 @noindent
24741 In this case we have a cycle that the binder cannot break. On the one
24742 hand, there is an explicit pragma Elaborate in @code{proc} for
24743 @code{pack}. This means that the body of @code{pack} must be elaborated
24744 before the body of @code{proc}. On the other hand, there is elaboration
24745 code in @code{pack} that calls a subprogram in @code{proc}. This means
24746 that for maximum safety, there should really be a pragma
24747 Elaborate_All in @code{pack} for @code{proc} which would require that
24748 the body of @code{proc} be elaborated before the body of
24749 @code{pack}. Clearly both requirements cannot be satisfied.
24750 Faced with a circularity of this kind, you have three different options.
24751
24752 @table @asis
24753 @item Fix the program
24754 The most desirable option from the point of view of long-term maintenance
24755 is to rearrange the program so that the elaboration problems are avoided.
24756 One useful technique is to place the elaboration code into separate
24757 child packages. Another is to move some of the initialization code to
24758 explicitly called subprograms, where the program controls the order
24759 of initialization explicitly. Although this is the most desirable option,
24760 it may be impractical and involve too much modification, especially in
24761 the case of complex legacy code.
24762
24763 @item Perform dynamic checks
24764 If the compilations are done using the
24765 @option{-gnatE}
24766 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24767 manner. Dynamic checks are generated for all calls that could possibly result
24768 in raising an exception. With this switch, the compiler does not generate
24769 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24770 exactly as specified in the @cite{Ada Reference Manual}.
24771 The binder will generate
24772 an executable program that may or may not raise @code{Program_Error}, and then
24773 it is the programmer's job to ensure that it does not raise an exception. Note
24774 that it is important to compile all units with the switch, it cannot be used
24775 selectively.
24776
24777 @item Suppress checks
24778 The drawback of dynamic checks is that they generate a
24779 significant overhead at run time, both in space and time. If you
24780 are absolutely sure that your program cannot raise any elaboration
24781 exceptions, and you still want to use the dynamic elaboration model,
24782 then you can use the configuration pragma
24783 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24784 example this pragma could be placed in the @file{gnat.adc} file.
24785
24786 @item Suppress checks selectively
24787 When you know that certain calls or instantiations in elaboration code cannot
24788 possibly lead to an elaboration error, and the binder nevertheless complains
24789 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24790 elaboration circularities, it is possible to remove those warnings locally and
24791 obtain a program that will bind. Clearly this can be unsafe, and it is the
24792 responsibility of the programmer to make sure that the resulting program has no
24793 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24794 used with different granularity to suppress warnings and break elaboration
24795 circularities:
24796
24797 @itemize @bullet
24798 @item
24799 Place the pragma that names the called subprogram in the declarative part
24800 that contains the call.
24801
24802 @item
24803 Place the pragma in the declarative part, without naming an entity. This
24804 disables warnings on all calls in the corresponding  declarative region.
24805
24806 @item
24807 Place the pragma in the package spec that declares the called subprogram,
24808 and name the subprogram. This disables warnings on all elaboration calls to
24809 that subprogram.
24810
24811 @item
24812 Place the pragma in the package spec that declares the called subprogram,
24813 without naming any entity. This disables warnings on all elaboration calls to
24814 all subprograms declared in this spec.
24815
24816 @item Use Pragma Elaborate
24817 As previously described in section @xref{Treatment of Pragma Elaborate},
24818 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24819 that no elaboration checks are required on calls to the designated unit.
24820 There may be cases in which the caller knows that no transitive calls
24821 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24822 case where @code{pragma Elaborate_All} would cause a circularity.
24823 @end itemize
24824
24825 @noindent
24826 These five cases are listed in order of decreasing safety, and therefore
24827 require increasing programmer care in their application. Consider the
24828 following program:
24829
24830 @smallexample @c adanocomment
24831 package Pack1 is
24832   function F1 return Integer;
24833   X1 : Integer;
24834 end Pack1;
24835
24836 package Pack2 is
24837   function F2 return Integer;
24838   function Pure (x : integer) return integer;
24839   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24840   --  pragma Suppress (Elaboration_Check);              -- (4)
24841 end Pack2;
24842
24843 with Pack2;
24844 package body Pack1 is
24845   function F1 return Integer is
24846   begin
24847     return 100;
24848   end F1;
24849   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24850 begin
24851   declare
24852     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24853     --  pragma Suppress(Elaboration_Check);             -- (2)
24854   begin
24855     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24856   end;
24857 end Pack1;
24858
24859 with Pack1;
24860 package body Pack2 is
24861   function F2 return Integer is
24862   begin
24863      return Pack1.F1;
24864   end F2;
24865   function Pure (x : integer) return integer is
24866   begin
24867      return x ** 3 - 3 * x;
24868   end;
24869 end Pack2;
24870
24871 with Pack1, Ada.Text_IO;
24872 procedure Proc3 is
24873 begin
24874   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24875 end Proc3;
24876 @end smallexample
24877 In the absence of any pragmas, an attempt to bind this program produces
24878 the following diagnostics:
24879 @smallexample
24880 @group
24881 @iftex
24882 @leftskip=.5cm
24883 @end iftex
24884 error: elaboration circularity detected
24885 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24886 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24887 info:       recompile "pack1 (body)" with -gnatwl for full details
24888 info:          "pack1 (body)"
24889 info:             must be elaborated along with its spec:
24890 info:          "pack1 (spec)"
24891 info:             which is withed by:
24892 info:          "pack2 (body)"
24893 info:             which must be elaborated along with its spec:
24894 info:          "pack2 (spec)"
24895 info:             which is withed by:
24896 info:          "pack1 (body)"
24897 @end group
24898 @end smallexample
24899 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24900 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24901 F2 is safe, even though F2 calls F1, because the call appears after the
24902 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24903 remove the warning on the call. It is also possible to use pragma (2)
24904 because there are no other potentially unsafe calls in the block.
24905
24906 @noindent
24907 The call to @code{Pure} is safe because this function does not depend on the
24908 state of @code{Pack2}. Therefore any call to this function is safe, and it
24909 is correct to place pragma (3) in the corresponding package spec.
24910
24911 @noindent
24912 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24913 warnings on all calls to functions declared therein. Note that this is not
24914 necessarily safe, and requires more detailed examination of the subprogram
24915 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24916 be already elaborated.
24917 @end table
24918
24919 @noindent
24920 It is hard to generalize on which of these four approaches should be
24921 taken. Obviously if it is possible to fix the program so that the default
24922 treatment works, this is preferable, but this may not always be practical.
24923 It is certainly simple enough to use
24924 @option{-gnatE}
24925 but the danger in this case is that, even if the GNAT binder
24926 finds a correct elaboration order, it may not always do so,
24927 and certainly a binder from another Ada compiler might not. A
24928 combination of testing and analysis (for which the warnings generated
24929 with the
24930 @option{-gnatwl}
24931 switch can be useful) must be used to ensure that the program is free
24932 of errors. One switch that is useful in this testing is the
24933 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24934 switch for
24935 @code{gnatbind}.
24936 Normally the binder tries to find an order that has the best chance
24937 of avoiding elaboration problems. However, if this switch is used, the binder
24938 plays a devil's advocate role, and tries to choose the order that
24939 has the best chance of failing. If your program works even with this
24940 switch, then it has a better chance of being error free, but this is still
24941 not a guarantee.
24942
24943 For an example of this approach in action, consider the C-tests (executable
24944 tests) from the ACVC suite. If these are compiled and run with the default
24945 treatment, then all but one of them succeed without generating any error
24946 diagnostics from the binder. However, there is one test that fails, and
24947 this is not surprising, because the whole point of this test is to ensure
24948 that the compiler can handle cases where it is impossible to determine
24949 a correct order statically, and it checks that an exception is indeed
24950 raised at run time.
24951
24952 This one test must be compiled and run using the
24953 @option{-gnatE}
24954 switch, and then it passes. Alternatively, the entire suite can
24955 be run using this switch. It is never wrong to run with the dynamic
24956 elaboration switch if your code is correct, and we assume that the
24957 C-tests are indeed correct (it is less efficient, but efficiency is
24958 not a factor in running the ACVC tests.)
24959
24960 @node Elaboration for Access-to-Subprogram Values
24961 @section Elaboration for Access-to-Subprogram Values
24962 @cindex Access-to-subprogram
24963
24964 @noindent
24965 Access-to-subprogram types (introduced in Ada 95) complicate
24966 the handling of elaboration. The trouble is that it becomes
24967 impossible to tell at compile time which procedure
24968 is being called. This means that it is not possible for the binder
24969 to analyze the elaboration requirements in this case.
24970
24971 If at the point at which the access value is created
24972 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24973 the body of the subprogram is
24974 known to have been elaborated, then the access value is safe, and its use
24975 does not require a check. This may be achieved by appropriate arrangement
24976 of the order of declarations if the subprogram is in the current unit,
24977 or, if the subprogram is in another unit, by using pragma
24978 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24979 on the referenced unit.
24980
24981 If the referenced body is not known to have been elaborated at the point
24982 the access value is created, then any use of the access value must do a
24983 dynamic check, and this dynamic check will fail and raise a
24984 @code{Program_Error} exception if the body has not been elaborated yet.
24985 GNAT will generate the necessary checks, and in addition, if the
24986 @option{-gnatwl}
24987 switch is set, will generate warnings that such checks are required.
24988
24989 The use of dynamic dispatching for tagged types similarly generates
24990 a requirement for dynamic checks, and premature calls to any primitive
24991 operation of a tagged type before the body of the operation has been
24992 elaborated, will result in the raising of @code{Program_Error}.
24993
24994 @node Summary of Procedures for Elaboration Control
24995 @section Summary of Procedures for Elaboration Control
24996 @cindex Elaboration control
24997
24998 @noindent
24999 First, compile your program with the default options, using none of
25000 the special elaboration control switches. If the binder successfully
25001 binds your program, then you can be confident that, apart from issues
25002 raised by the use of access-to-subprogram types and dynamic dispatching,
25003 the program is free of elaboration errors. If it is important that the
25004 program be portable, then use the
25005 @option{-gnatwl}
25006 switch to generate warnings about missing @code{Elaborate} or
25007 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25008
25009 If the program fails to bind using the default static elaboration
25010 handling, then you can fix the program to eliminate the binder
25011 message, or recompile the entire program with the
25012 @option{-gnatE} switch to generate dynamic elaboration checks,
25013 and, if you are sure there really are no elaboration problems,
25014 use a global pragma @code{Suppress (Elaboration_Check)}.
25015
25016 @node Other Elaboration Order Considerations
25017 @section Other Elaboration Order Considerations
25018 @noindent
25019 This section has been entirely concerned with the issue of finding a valid
25020 elaboration order, as defined by the Ada Reference Manual. In a case
25021 where several elaboration orders are valid, the task is to find one
25022 of the possible valid elaboration orders (and the static model in GNAT
25023 will ensure that this is achieved).
25024
25025 The purpose of the elaboration rules in the Ada Reference Manual is to
25026 make sure that no entity is accessed before it has been elaborated. For
25027 a subprogram, this means that the spec and body must have been elaborated
25028 before the subprogram is called. For an object, this means that the object
25029 must have been elaborated before its value is read or written. A violation
25030 of either of these two requirements is an access before elaboration order,
25031 and this section has been all about avoiding such errors.
25032
25033 In the case where more than one order of elaboration is possible, in the
25034 sense that access before elaboration errors are avoided, then any one of
25035 the orders is ``correct'' in the sense that it meets the requirements of
25036 the Ada Reference Manual, and no such error occurs.
25037
25038 However, it may be the case for a given program, that there are
25039 constraints on the order of elaboration that come not from consideration
25040 of avoiding elaboration errors, but rather from extra-lingual logic
25041 requirements. Consider this example:
25042
25043 @smallexample @c ada
25044 with Init_Constants;
25045 package Constants is
25046    X : Integer := 0;
25047    Y : Integer := 0;
25048 end Constants;
25049
25050 package Init_Constants is
25051    procedure P; -- require a body
25052 end Init_Constants;
25053
25054 with Constants;
25055 package body Init_Constants is
25056    procedure P is begin null; end;
25057 begin
25058    Constants.X := 3;
25059    Constants.Y := 4;
25060 end Init_Constants;
25061
25062 with Constants;
25063 package Calc is
25064    Z : Integer := Constants.X + Constants.Y;
25065 end Calc;
25066
25067 with Calc;
25068 with Text_IO; use Text_IO;
25069 procedure Main is
25070 begin
25071    Put_Line (Calc.Z'Img);
25072 end Main;
25073 @end smallexample
25074
25075 @noindent
25076 In this example, there is more than one valid order of elaboration. For
25077 example both the following are correct orders:
25078
25079 @smallexample
25080 Init_Constants spec
25081 Constants spec
25082 Calc spec
25083 Init_Constants body
25084 Main body
25085
25086   and
25087
25088 Init_Constants spec
25089 Init_Constants body
25090 Constants spec
25091 Calc spec
25092 Main body
25093 @end smallexample
25094
25095 @noindent
25096 There is no language rule to prefer one or the other, both are correct
25097 from an order of elaboration point of view. But the programmatic effects
25098 of the two orders are very different. In the first, the elaboration routine
25099 of @code{Calc} initializes @code{Z} to zero, and then the main program
25100 runs with this value of zero. But in the second order, the elaboration
25101 routine of @code{Calc} runs after the body of Init_Constants has set
25102 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25103 runs.
25104
25105 One could perhaps by applying pretty clever non-artificial intelligence
25106 to the situation guess that it is more likely that the second order of
25107 elaboration is the one desired, but there is no formal linguistic reason
25108 to prefer one over the other. In fact in this particular case, GNAT will
25109 prefer the second order, because of the rule that bodies are elaborated
25110 as soon as possible, but it's just luck that this is what was wanted
25111 (if indeed the second order was preferred).
25112
25113 If the program cares about the order of elaboration routines in a case like
25114 this, it is important to specify the order required. In this particular
25115 case, that could have been achieved by adding to the spec of Calc:
25116
25117 @smallexample @c ada
25118 pragma Elaborate_All (Constants);
25119 @end smallexample
25120
25121 @noindent
25122 which requires that the body (if any) and spec of @code{Constants},
25123 as well as the body and spec of any unit @code{with}'ed by
25124 @code{Constants} be elaborated before @code{Calc} is elaborated.
25125
25126 Clearly no automatic method can always guess which alternative you require,
25127 and if you are working with legacy code that had constraints of this kind
25128 which were not properly specified by adding @code{Elaborate} or
25129 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25130 compilers can choose different orders.
25131
25132 However, GNAT does attempt to diagnose the common situation where there
25133 are uninitialized variables in the visible part of a package spec, and the
25134 corresponding package body has an elaboration block that directly or
25135 indirectly initialized one or more of these variables. This is the situation
25136 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
25137 a warning that suggests this addition if it detects this situation.
25138
25139 The @code{gnatbind}
25140 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25141 out problems. This switch causes bodies to be elaborated as late as possible
25142 instead of as early as possible. In the example above, it would have forced
25143 the choice of the first elaboration order. If you get different results
25144 when using this switch, and particularly if one set of results is right,
25145 and one is wrong as far as you are concerned, it shows that you have some
25146 missing @code{Elaborate} pragmas. For the example above, we have the
25147 following output:
25148
25149 @smallexample
25150 gnatmake -f -q main
25151 main
25152  7
25153 gnatmake -f -q main -bargs -p
25154 main
25155  0
25156 @end smallexample
25157
25158 @noindent
25159 It is of course quite unlikely that both these results are correct, so
25160 it is up to you in a case like this to investigate the source of the
25161 difference, by looking at the two elaboration orders that are chosen,
25162 and figuring out which is correct, and then adding the necessary
25163 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25164
25165
25166
25167 @c *******************************
25168 @node Conditional Compilation
25169 @appendix Conditional Compilation
25170 @c *******************************
25171 @cindex Conditional compilation
25172
25173 @noindent
25174 It is often necessary to arrange for a single source program
25175 to serve multiple purposes, where it is compiled in different
25176 ways to achieve these different goals. Some examples of the
25177 need for this feature are
25178
25179 @itemize @bullet
25180 @item  Adapting a program to a different hardware environment
25181 @item  Adapting a program to a different target architecture
25182 @item  Turning debugging features on and off
25183 @item  Arranging for a program to compile with different compilers
25184 @end itemize
25185
25186 @noindent
25187 In C, or C++, the typical approach would be to use the preprocessor
25188 that is defined as part of the language. The Ada language does not
25189 contain such a feature. This is not an oversight, but rather a very
25190 deliberate design decision, based on the experience that overuse of
25191 the preprocessing features in C and C++ can result in programs that
25192 are extremely difficult to maintain. For example, if we have ten
25193 switches that can be on or off, this means that there are a thousand
25194 separate programs, any one of which might not even be syntactically
25195 correct, and even if syntactically correct, the resulting program
25196 might not work correctly. Testing all combinations can quickly become
25197 impossible.
25198
25199 Nevertheless, the need to tailor programs certainly exists, and in
25200 this Appendix we will discuss how this can
25201 be achieved using Ada in general, and GNAT in particular.
25202
25203 @menu
25204 * Use of Boolean Constants::
25205 * Debugging - A Special Case::
25206 * Conditionalizing Declarations::
25207 * Use of Alternative Implementations::
25208 * Preprocessing::
25209 @end menu
25210
25211 @node Use of Boolean Constants
25212 @section Use of Boolean Constants
25213
25214 @noindent
25215 In the case where the difference is simply which code
25216 sequence is executed, the cleanest solution is to use Boolean
25217 constants to control which code is executed.
25218
25219 @smallexample @c ada
25220 @group
25221 FP_Initialize_Required : constant Boolean := True;
25222 @dots{}
25223 if FP_Initialize_Required then
25224 @dots{}
25225 end if;
25226 @end group
25227 @end smallexample
25228
25229 @noindent
25230 Not only will the code inside the @code{if} statement not be executed if
25231 the constant Boolean is @code{False}, but it will also be completely
25232 deleted from the program.
25233 However, the code is only deleted after the @code{if} statement
25234 has been checked for syntactic and semantic correctness.
25235 (In contrast, with preprocessors the code is deleted before the
25236 compiler ever gets to see it, so it is not checked until the switch
25237 is turned on.)
25238 @cindex Preprocessors (contrasted with conditional compilation)
25239
25240 Typically the Boolean constants will be in a separate package,
25241 something like:
25242
25243 @smallexample @c ada
25244 @group
25245 package Config is
25246    FP_Initialize_Required : constant Boolean := True;
25247    Reset_Available        : constant Boolean := False;
25248    @dots{}
25249 end Config;
25250 @end group
25251 @end smallexample
25252
25253 @noindent
25254 The @code{Config} package exists in multiple forms for the various targets,
25255 with an appropriate script selecting the version of @code{Config} needed.
25256 Then any other unit requiring conditional compilation can do a @code{with}
25257 of @code{Config} to make the constants visible.
25258
25259
25260 @node Debugging - A Special Case
25261 @section Debugging - A Special Case
25262
25263 @noindent
25264 A common use of conditional code is to execute statements (for example
25265 dynamic checks, or output of intermediate results) under control of a
25266 debug switch, so that the debugging behavior can be turned on and off.
25267 This can be done using a Boolean constant to control whether the code
25268 is active:
25269
25270 @smallexample @c ada
25271 @group
25272 if Debugging then
25273    Put_Line ("got to the first stage!");
25274 end if;
25275 @end group
25276 @end smallexample
25277
25278 @noindent
25279 or
25280
25281 @smallexample @c ada
25282 @group
25283 if Debugging and then Temperature > 999.0 then
25284    raise Temperature_Crazy;
25285 end if;
25286 @end group
25287 @end smallexample
25288
25289 @noindent
25290 Since this is a common case, there are special features to deal with
25291 this in a convenient manner. For the case of tests, Ada 2005 has added
25292 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25293 @cindex pragma @code{Assert}
25294 on the @code{Assert} pragma that has always been available in GNAT, so this
25295 feature may be used with GNAT even if you are not using Ada 2005 features.
25296 The use of pragma @code{Assert} is described in
25297 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25298 example, the last test could be written:
25299
25300 @smallexample @c ada
25301 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25302 @end smallexample
25303
25304 @noindent
25305 or simply
25306
25307 @smallexample @c ada
25308 pragma Assert (Temperature <= 999.0);
25309 @end smallexample
25310
25311 @noindent
25312 In both cases, if assertions are active and the temperature is excessive,
25313 the exception @code{Assert_Failure} will be raised, with the given string in
25314 the first case or a string indicating the location of the pragma in the second
25315 case used as the exception message.
25316
25317 You can turn assertions on and off by using the @code{Assertion_Policy}
25318 pragma.
25319 @cindex pragma @code{Assertion_Policy}
25320 This is an Ada 2005 pragma which is implemented in all modes by
25321 GNAT, but only in the latest versions of GNAT which include Ada 2005
25322 capability. Alternatively, you can use the @option{-gnata} switch
25323 @cindex @option{-gnata} switch
25324 to enable assertions from the command line (this is recognized by all versions
25325 of GNAT).
25326
25327 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25328 @code{Debug} can be used:
25329 @cindex pragma @code{Debug}
25330
25331 @smallexample @c ada
25332 pragma Debug (Put_Line ("got to the first stage!"));
25333 @end smallexample
25334
25335 @noindent
25336 If debug pragmas are enabled, the argument, which must be of the form of
25337 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25338 Only one call can be present, but of course a special debugging procedure
25339 containing any code you like can be included in the program and then
25340 called in a pragma @code{Debug} argument as needed.
25341
25342 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25343 construct is that pragma @code{Debug} can appear in declarative contexts,
25344 such as at the very beginning of a procedure, before local declarations have
25345 been elaborated.
25346
25347 Debug pragmas are enabled using either the @option{-gnata} switch that also
25348 controls assertions, or with a separate Debug_Policy pragma.
25349 @cindex pragma @code{Debug_Policy}
25350 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25351 in Ada 95 and Ada 83 programs as well), and is analogous to
25352 pragma @code{Assertion_Policy} to control assertions.
25353
25354 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25355 and thus they can appear in @file{gnat.adc} if you are not using a
25356 project file, or in the file designated to contain configuration pragmas
25357 in a project file.
25358 They then apply to all subsequent compilations. In practice the use of
25359 the @option{-gnata} switch is often the most convenient method of controlling
25360 the status of these pragmas.
25361
25362 Note that a pragma is not a statement, so in contexts where a statement
25363 sequence is required, you can't just write a pragma on its own. You have
25364 to add a @code{null} statement.
25365
25366 @smallexample @c ada
25367 @group
25368 if @dots{} then
25369    @dots{} -- some statements
25370 else
25371    pragma Assert (Num_Cases < 10);
25372    null;
25373 end if;
25374 @end group
25375 @end smallexample
25376
25377
25378 @node Conditionalizing Declarations
25379 @section Conditionalizing Declarations
25380
25381 @noindent
25382 In some cases, it may be necessary to conditionalize declarations to meet
25383 different requirements. For example we might want a bit string whose length
25384 is set to meet some hardware message requirement.
25385
25386 In some cases, it may be possible to do this using declare blocks controlled
25387 by conditional constants:
25388
25389 @smallexample @c ada
25390 @group
25391 if Small_Machine then
25392    declare
25393       X : Bit_String (1 .. 10);
25394    begin
25395       @dots{}
25396    end;
25397 else
25398    declare
25399       X : Large_Bit_String (1 .. 1000);
25400    begin
25401       @dots{}
25402    end;
25403 end if;
25404 @end group
25405 @end smallexample
25406
25407 @noindent
25408 Note that in this approach, both declarations are analyzed by the
25409 compiler so this can only be used where both declarations are legal,
25410 even though one of them will not be used.
25411
25412 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25413 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25414 that are parameterized by these constants. For example
25415
25416 @smallexample @c ada
25417 @group
25418 for Rec use
25419   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25420 end record;
25421 @end group
25422 @end smallexample
25423
25424 @noindent
25425 If @code{Bits_Per_Word} is set to 32, this generates either
25426
25427 @smallexample @c ada
25428 @group
25429 for Rec use
25430   Field1 at 0 range 0 .. 32;
25431 end record;
25432 @end group
25433 @end smallexample
25434
25435 @noindent
25436 for the big endian case, or
25437
25438 @smallexample @c ada
25439 @group
25440 for Rec use record
25441   Field1 at 0 range 10 .. 32;
25442 end record;
25443 @end group
25444 @end smallexample
25445
25446 @noindent
25447 for the little endian case. Since a powerful subset of Ada expression
25448 notation is usable for creating static constants, clever use of this
25449 feature can often solve quite difficult problems in conditionalizing
25450 compilation (note incidentally that in Ada 95, the little endian
25451 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25452 need to define this one yourself).
25453
25454
25455 @node Use of Alternative Implementations
25456 @section Use of Alternative Implementations
25457
25458 @noindent
25459 In some cases, none of the approaches described above are adequate. This
25460 can occur for example if the set of declarations required is radically
25461 different for two different configurations.
25462
25463 In this situation, the official Ada way of dealing with conditionalizing
25464 such code is to write separate units for the different cases. As long as
25465 this does not result in excessive duplication of code, this can be done
25466 without creating maintenance problems. The approach is to share common
25467 code as far as possible, and then isolate the code and declarations
25468 that are different. Subunits are often a convenient method for breaking
25469 out a piece of a unit that is to be conditionalized, with separate files
25470 for different versions of the subunit for different targets, where the
25471 build script selects the right one to give to the compiler.
25472 @cindex Subunits (and conditional compilation)
25473
25474 As an example, consider a situation where a new feature in Ada 2005
25475 allows something to be done in a really nice way. But your code must be able
25476 to compile with an Ada 95 compiler. Conceptually you want to say:
25477
25478 @smallexample @c ada
25479 @group
25480 if Ada_2005 then
25481    @dots{} neat Ada 2005 code
25482 else
25483    @dots{} not quite as neat Ada 95 code
25484 end if;
25485 @end group
25486 @end smallexample
25487
25488 @noindent
25489 where @code{Ada_2005} is a Boolean constant.
25490
25491 But this won't work when @code{Ada_2005} is set to @code{False},
25492 since the @code{then} clause will be illegal for an Ada 95 compiler.
25493 (Recall that although such unreachable code would eventually be deleted
25494 by the compiler, it still needs to be legal.  If it uses features
25495 introduced in Ada 2005, it will be illegal in Ada 95.)
25496
25497 So instead we write
25498
25499 @smallexample @c ada
25500 procedure Insert is separate;
25501 @end smallexample
25502
25503 @noindent
25504 Then we have two files for the subunit @code{Insert}, with the two sets of
25505 code.
25506 If the package containing this is called @code{File_Queries}, then we might
25507 have two files
25508
25509 @itemize @bullet
25510 @item    @file{file_queries-insert-2005.adb}
25511 @item    @file{file_queries-insert-95.adb}
25512 @end itemize
25513
25514 @noindent
25515 and the build script renames the appropriate file to
25516
25517 @smallexample
25518 file_queries-insert.adb
25519 @end smallexample
25520
25521 @noindent
25522 and then carries out the compilation.
25523
25524 This can also be done with project files' naming schemes. For example:
25525
25526 @smallexample @c project
25527 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25528 @end smallexample
25529
25530 @noindent
25531 Note also that with project files it is desirable to use a different extension
25532 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25533 conflict may arise through another commonly used feature: to declare as part
25534 of the project a set of directories containing all the sources obeying the
25535 default naming scheme.
25536
25537 The use of alternative units is certainly feasible in all situations,
25538 and for example the Ada part of the GNAT run-time is conditionalized
25539 based on the target architecture using this approach. As a specific example,
25540 consider the implementation of the AST feature in VMS. There is one
25541 spec:
25542
25543 @smallexample
25544 s-asthan.ads
25545 @end smallexample
25546
25547 @noindent
25548 which is the same for all architectures, and three bodies:
25549
25550 @table @file
25551 @item    s-asthan.adb
25552 used for all non-VMS operating systems
25553 @item    s-asthan-vms-alpha.adb
25554 used for VMS on the Alpha
25555 @item    s-asthan-vms-ia64.adb
25556 used for VMS on the ia64
25557 @end table
25558
25559 @noindent
25560 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25561 this operating system feature is not available, and the two remaining
25562 versions interface with the corresponding versions of VMS to provide
25563 VMS-compatible AST handling. The GNAT build script knows the architecture
25564 and operating system, and automatically selects the right version,
25565 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25566
25567 Another style for arranging alternative implementations is through Ada's
25568 access-to-subprogram facility.
25569 In case some functionality is to be conditionally included,
25570 you can declare an access-to-procedure variable @code{Ref} that is initialized
25571 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25572 when appropriate.
25573 In some library package, set @code{Ref} to @code{Proc'Access} for some
25574 procedure @code{Proc} that performs the relevant processing.
25575 The initialization only occurs if the library package is included in the
25576 program.
25577 The same idea can also be implemented using tagged types and dispatching
25578 calls.
25579
25580
25581 @node Preprocessing
25582 @section Preprocessing
25583 @cindex Preprocessing
25584
25585 @noindent
25586 Although it is quite possible to conditionalize code without the use of
25587 C-style preprocessing, as described earlier in this section, it is
25588 nevertheless convenient in some cases to use the C approach. Moreover,
25589 older Ada compilers have often provided some preprocessing capability,
25590 so legacy code may depend on this approach, even though it is not
25591 standard.
25592
25593 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25594 extent on the various preprocessors that have been used
25595 with legacy code on other compilers, to enable easier transition).
25596
25597 The preprocessor may be used in two separate modes. It can be used quite
25598 separately from the compiler, to generate a separate output source file
25599 that is then fed to the compiler as a separate step. This is the
25600 @code{gnatprep} utility, whose use is fully described in
25601 @ref{Preprocessing Using gnatprep}.
25602 @cindex @code{gnatprep}
25603
25604 The preprocessing language allows such constructs as
25605
25606 @smallexample
25607 @group
25608 #if DEBUG or PRIORITY > 4 then
25609    bunch of declarations
25610 #else
25611    completely different bunch of declarations
25612 #end if;
25613 @end group
25614 @end smallexample
25615
25616 @noindent
25617 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25618 defined either on the command line or in a separate file.
25619
25620 The other way of running the preprocessor is even closer to the C style and
25621 often more convenient. In this approach the preprocessing is integrated into
25622 the compilation process. The compiler is fed the preprocessor input which
25623 includes @code{#if} lines etc, and then the compiler carries out the
25624 preprocessing internally and processes the resulting output.
25625 For more details on this approach, see @ref{Integrated Preprocessing}.
25626
25627
25628 @c *******************************
25629 @node Inline Assembler
25630 @appendix Inline Assembler
25631 @c *******************************
25632
25633 @noindent
25634 If you need to write low-level software that interacts directly
25635 with the hardware, Ada provides two ways to incorporate assembly
25636 language code into your program.  First, you can import and invoke
25637 external routines written in assembly language, an Ada feature fully
25638 supported by GNAT@.  However, for small sections of code it may be simpler
25639 or more efficient to include assembly language statements directly
25640 in your Ada source program, using the facilities of the implementation-defined
25641 package @code{System.Machine_Code}, which incorporates the gcc
25642 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25643 including the following:
25644
25645 @itemize @bullet
25646 @item No need to use non-Ada tools
25647 @item Consistent interface over different targets
25648 @item Automatic usage of the proper calling conventions
25649 @item Access to Ada constants and variables
25650 @item Definition of intrinsic routines
25651 @item Possibility of inlining a subprogram comprising assembler code
25652 @item Code optimizer can take Inline Assembler code into account
25653 @end itemize
25654
25655 This chapter presents a series of examples to show you how to use
25656 the Inline Assembler.  Although it focuses on the Intel x86,
25657 the general approach applies also to other processors.
25658 It is assumed that you are familiar with Ada
25659 and with assembly language programming.
25660
25661 @menu
25662 * Basic Assembler Syntax::
25663 * A Simple Example of Inline Assembler::
25664 * Output Variables in Inline Assembler::
25665 * Input Variables in Inline Assembler::
25666 * Inlining Inline Assembler Code::
25667 * Other Asm Functionality::
25668 @end menu
25669
25670 @c ---------------------------------------------------------------------------
25671 @node Basic Assembler Syntax
25672 @section Basic Assembler Syntax
25673
25674 @noindent
25675 The assembler used by GNAT and gcc is based not on the Intel assembly
25676 language, but rather on a language that descends from the AT&T Unix
25677 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25678 The following table summarizes the main features of @emph{as} syntax
25679 and points out the differences from the Intel conventions.
25680 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25681 pre-processor) documentation for further information.
25682
25683 @table @asis
25684 @item Register names
25685 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25686 @*
25687 Intel: No extra punctuation; for example @code{eax}
25688
25689 @item Immediate operand
25690 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25691 @*
25692 Intel: No extra punctuation; for example @code{4}
25693
25694 @item Address
25695 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25696 @*
25697 Intel: No extra punctuation; for example @code{loc}
25698
25699 @item Memory contents
25700 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25701 @*
25702 Intel: Square brackets; for example @code{[loc]}
25703
25704 @item Register contents
25705 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25706 @*
25707 Intel: Square brackets; for example @code{[eax]}
25708
25709 @item Hexadecimal numbers
25710 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25711 @*
25712 Intel: Trailing ``h''; for example @code{A0h}
25713
25714 @item Operand size
25715 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25716 a 16-bit word
25717 @*
25718 Intel: Implicit, deduced by assembler; for example @code{mov}
25719
25720 @item Instruction repetition
25721 gcc / @emph{as}: Split into two lines; for example
25722 @*
25723 @code{rep}
25724 @*
25725 @code{stosl}
25726 @*
25727 Intel: Keep on one line; for example @code{rep stosl}
25728
25729 @item Order of operands
25730 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25731 @*
25732 Intel: Destination first; for example @code{mov eax, 4}
25733 @end table
25734
25735 @c ---------------------------------------------------------------------------
25736 @node A Simple Example of Inline Assembler
25737 @section A Simple Example of Inline Assembler
25738
25739 @noindent
25740 The following example will generate a single assembly language statement,
25741 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25742 the example will be useful in illustrating the basics of
25743 the Inline Assembler facility.
25744
25745 @smallexample @c ada
25746 @group
25747 with System.Machine_Code; use System.Machine_Code;
25748 procedure Nothing is
25749 begin
25750    Asm ("nop");
25751 end Nothing;
25752 @end group
25753 @end smallexample
25754
25755 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25756 here it takes one parameter, a @emph{template string} that must be a static
25757 expression and that will form the generated instruction.
25758 @code{Asm} may be regarded as a compile-time procedure that parses
25759 the template string and additional parameters (none here),
25760 from which it generates a sequence of assembly language instructions.
25761
25762 The examples in this chapter will illustrate several of the forms
25763 for invoking @code{Asm}; a complete specification of the syntax
25764 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25765 Manual}.
25766
25767 Under the standard GNAT conventions, the @code{Nothing} procedure
25768 should be in a file named @file{nothing.adb}.
25769 You can build the executable in the usual way:
25770 @smallexample
25771 gnatmake nothing
25772 @end smallexample
25773 However, the interesting aspect of this example is not its run-time behavior
25774 but rather the generated assembly code.
25775 To see this output, invoke the compiler as follows:
25776 @smallexample
25777    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25778 @end smallexample
25779 where the options are:
25780
25781 @table @code
25782 @item -c
25783 compile only (no bind or link)
25784 @item -S
25785 generate assembler listing
25786 @item -fomit-frame-pointer
25787 do not set up separate stack frames
25788 @item -gnatp
25789 do not add runtime checks
25790 @end table
25791
25792 This gives a human-readable assembler version of the code. The resulting
25793 file will have the same name as the Ada source file, but with a @code{.s}
25794 extension. In our example, the file @file{nothing.s} has the following
25795 contents:
25796
25797 @smallexample
25798 @group
25799 .file "nothing.adb"
25800 gcc2_compiled.:
25801 ___gnu_compiled_ada:
25802 .text
25803    .align 4
25804 .globl __ada_nothing
25805 __ada_nothing:
25806 #APP
25807    nop
25808 #NO_APP
25809    jmp L1
25810    .align 2,0x90
25811 L1:
25812    ret
25813 @end group
25814 @end smallexample
25815
25816 The assembly code you included is clearly indicated by
25817 the compiler, between the @code{#APP} and @code{#NO_APP}
25818 delimiters. The character before the 'APP' and 'NOAPP'
25819 can differ on different targets. For example, GNU/Linux uses '#APP' while
25820 on NT you will see '/APP'.
25821
25822 If you make a mistake in your assembler code (such as using the
25823 wrong size modifier, or using a wrong operand for the instruction) GNAT
25824 will report this error in a temporary file, which will be deleted when
25825 the compilation is finished.  Generating an assembler file will help
25826 in such cases, since you can assemble this file separately using the
25827 @emph{as} assembler that comes with gcc.
25828
25829 Assembling the file using the command
25830
25831 @smallexample
25832 as @file{nothing.s}
25833 @end smallexample
25834 @noindent
25835 will give you error messages whose lines correspond to the assembler
25836 input file, so you can easily find and correct any mistakes you made.
25837 If there are no errors, @emph{as} will generate an object file
25838 @file{nothing.out}.
25839
25840 @c ---------------------------------------------------------------------------
25841 @node Output Variables in Inline Assembler
25842 @section Output Variables in Inline Assembler
25843
25844 @noindent
25845 The examples in this section, showing how to access the processor flags,
25846 illustrate how to specify the destination operands for assembly language
25847 statements.
25848
25849 @smallexample @c ada
25850 @group
25851 with Interfaces; use Interfaces;
25852 with Ada.Text_IO; use Ada.Text_IO;
25853 with System.Machine_Code; use System.Machine_Code;
25854 procedure Get_Flags is
25855    Flags : Unsigned_32;
25856    use ASCII;
25857 begin
25858    Asm ("pushfl"          & LF & HT & -- push flags on stack
25859         "popl %%eax"      & LF & HT & -- load eax with flags
25860         "movl %%eax, %0",             -- store flags in variable
25861         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25862    Put_Line ("Flags register:" & Flags'Img);
25863 end Get_Flags;
25864 @end group
25865 @end smallexample
25866
25867 In order to have a nicely aligned assembly listing, we have separated
25868 multiple assembler statements in the Asm template string with linefeed
25869 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25870 The resulting section of the assembly output file is:
25871
25872 @smallexample
25873 @group
25874 #APP
25875    pushfl
25876    popl %eax
25877    movl %eax, -40(%ebp)
25878 #NO_APP
25879 @end group
25880 @end smallexample
25881
25882 It would have been legal to write the Asm invocation as:
25883
25884 @smallexample
25885 Asm ("pushfl popl %%eax movl %%eax, %0")
25886 @end smallexample
25887
25888 but in the generated assembler file, this would come out as:
25889
25890 @smallexample
25891 #APP
25892    pushfl popl %eax movl %eax, -40(%ebp)
25893 #NO_APP
25894 @end smallexample
25895
25896 which is not so convenient for the human reader.
25897
25898 We use Ada comments
25899 at the end of each line to explain what the assembler instructions
25900 actually do.  This is a useful convention.
25901
25902 When writing Inline Assembler instructions, you need to precede each register
25903 and variable name with a percent sign.  Since the assembler already requires
25904 a percent sign at the beginning of a register name, you need two consecutive
25905 percent signs for such names in the Asm template string, thus @code{%%eax}.
25906 In the generated assembly code, one of the percent signs will be stripped off.
25907
25908 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25909 variables: operands you later define using @code{Input} or @code{Output}
25910 parameters to @code{Asm}.
25911 An output variable is illustrated in
25912 the third statement in the Asm template string:
25913 @smallexample
25914 movl %%eax, %0
25915 @end smallexample
25916 The intent is to store the contents of the eax register in a variable that can
25917 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25918 necessarily work, since the compiler might optimize by using a register
25919 to hold Flags, and the expansion of the @code{movl} instruction would not be
25920 aware of this optimization.  The solution is not to store the result directly
25921 but rather to advise the compiler to choose the correct operand form;
25922 that is the purpose of the @code{%0} output variable.
25923
25924 Information about the output variable is supplied in the @code{Outputs}
25925 parameter to @code{Asm}:
25926 @smallexample
25927 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25928 @end smallexample
25929
25930 The output is defined by the @code{Asm_Output} attribute of the target type;
25931 the general format is
25932 @smallexample
25933 Type'Asm_Output (constraint_string, variable_name)
25934 @end smallexample
25935
25936 The constraint string directs the compiler how
25937 to store/access the associated variable.  In the example
25938 @smallexample
25939 Unsigned_32'Asm_Output ("=m", Flags);
25940 @end smallexample
25941 the @code{"m"} (memory) constraint tells the compiler that the variable
25942 @code{Flags} should be stored in a memory variable, thus preventing
25943 the optimizer from keeping it in a register.  In contrast,
25944 @smallexample
25945 Unsigned_32'Asm_Output ("=r", Flags);
25946 @end smallexample
25947 uses the @code{"r"} (register) constraint, telling the compiler to
25948 store the variable in a register.
25949
25950 If the constraint is preceded by the equal character (@strong{=}), it tells
25951 the compiler that the variable will be used to store data into it.
25952
25953 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25954 allowing the optimizer to choose whatever it deems best.
25955
25956 There are a fairly large number of constraints, but the ones that are
25957 most useful (for the Intel x86 processor) are the following:
25958
25959 @table @code
25960 @item =
25961 output constraint
25962 @item g
25963 global (i.e.@: can be stored anywhere)
25964 @item m
25965 in memory
25966 @item I
25967 a constant
25968 @item a
25969 use eax
25970 @item b
25971 use ebx
25972 @item c
25973 use ecx
25974 @item d
25975 use edx
25976 @item S
25977 use esi
25978 @item D
25979 use edi
25980 @item r
25981 use one of eax, ebx, ecx or edx
25982 @item q
25983 use one of eax, ebx, ecx, edx, esi or edi
25984 @end table
25985
25986 The full set of constraints is described in the gcc and @emph{as}
25987 documentation; note that it is possible to combine certain constraints
25988 in one constraint string.
25989
25990 You specify the association of an output variable with an assembler operand
25991 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25992 integer.  Thus in
25993 @smallexample @c ada
25994 @group
25995 Asm ("pushfl"          & LF & HT & -- push flags on stack
25996      "popl %%eax"      & LF & HT & -- load eax with flags
25997      "movl %%eax, %0",             -- store flags in variable
25998      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25999 @end group
26000 @end smallexample
26001 @noindent
26002 @code{%0} will be replaced in the expanded code by the appropriate operand,
26003 whatever
26004 the compiler decided for the @code{Flags} variable.
26005
26006 In general, you may have any number of output variables:
26007 @itemize @bullet
26008 @item
26009 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
26010 @item
26011 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
26012 of @code{Asm_Output} attributes
26013 @end itemize
26014
26015 For example:
26016 @smallexample @c ada
26017 @group
26018 Asm ("movl %%eax, %0" & LF & HT &
26019      "movl %%ebx, %1" & LF & HT &
26020      "movl %%ecx, %2",
26021      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
26022                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
26023                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
26024 @end group
26025 @end smallexample
26026 @noindent
26027 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
26028 in the Ada program.
26029
26030 As a variation on the @code{Get_Flags} example, we can use the constraints
26031 string to direct the compiler to store the eax register into the @code{Flags}
26032 variable, instead of including the store instruction explicitly in the
26033 @code{Asm} template string:
26034
26035 @smallexample @c ada
26036 @group
26037 with Interfaces; use Interfaces;
26038 with Ada.Text_IO; use Ada.Text_IO;
26039 with System.Machine_Code; use System.Machine_Code;
26040 procedure Get_Flags_2 is
26041    Flags : Unsigned_32;
26042    use ASCII;
26043 begin
26044    Asm ("pushfl"      & LF & HT & -- push flags on stack
26045         "popl %%eax",             -- save flags in eax
26046         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
26047    Put_Line ("Flags register:" & Flags'Img);
26048 end Get_Flags_2;
26049 @end group
26050 @end smallexample
26051
26052 @noindent
26053 The @code{"a"} constraint tells the compiler that the @code{Flags}
26054 variable will come from the eax register. Here is the resulting code:
26055
26056 @smallexample
26057 @group
26058 #APP
26059    pushfl
26060    popl %eax
26061 #NO_APP
26062    movl %eax,-40(%ebp)
26063 @end group
26064 @end smallexample
26065
26066 @noindent
26067 The compiler generated the store of eax into Flags after
26068 expanding the assembler code.
26069
26070 Actually, there was no need to pop the flags into the eax register;
26071 more simply, we could just pop the flags directly into the program variable:
26072
26073 @smallexample @c ada
26074 @group
26075 with Interfaces; use Interfaces;
26076 with Ada.Text_IO; use Ada.Text_IO;
26077 with System.Machine_Code; use System.Machine_Code;
26078 procedure Get_Flags_3 is
26079    Flags : Unsigned_32;
26080    use ASCII;
26081 begin
26082    Asm ("pushfl"  & LF & HT & -- push flags on stack
26083         "pop %0",             -- save flags in Flags
26084         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
26085    Put_Line ("Flags register:" & Flags'Img);
26086 end Get_Flags_3;
26087 @end group
26088 @end smallexample
26089
26090 @c ---------------------------------------------------------------------------
26091 @node Input Variables in Inline Assembler
26092 @section Input Variables in Inline Assembler
26093
26094 @noindent
26095 The example in this section illustrates how to specify the source operands
26096 for assembly language statements.
26097 The program simply increments its input value by 1:
26098
26099 @smallexample @c ada
26100 @group
26101 with Interfaces; use Interfaces;
26102 with Ada.Text_IO; use Ada.Text_IO;
26103 with System.Machine_Code; use System.Machine_Code;
26104 procedure Increment is
26105
26106    function Incr (Value : Unsigned_32) return Unsigned_32 is
26107       Result : Unsigned_32;
26108    begin
26109       Asm ("incl %0",
26110            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26111            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26112       return Result;
26113    end Incr;
26114
26115    Value : Unsigned_32;
26116
26117 begin
26118    Value := 5;
26119    Put_Line ("Value before is" & Value'Img);
26120    Value := Incr (Value);
26121    Put_Line ("Value after is" & Value'Img);
26122 end Increment;
26123 @end group
26124 @end smallexample
26125
26126 The @code{Outputs} parameter to @code{Asm} specifies
26127 that the result will be in the eax register and that it is to be stored
26128 in the @code{Result} variable.
26129
26130 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
26131 but with an @code{Asm_Input} attribute.
26132 The @code{"="} constraint, indicating an output value, is not present.
26133
26134 You can have multiple input variables, in the same way that you can have more
26135 than one output variable.
26136
26137 The parameter count (%0, %1) etc, now starts at the first input
26138 statement, and continues with the output statements.
26139 When both parameters use the same variable, the
26140 compiler will treat them as the same %n operand, which is the case here.
26141
26142 Just as the @code{Outputs} parameter causes the register to be stored into the
26143 target variable after execution of the assembler statements, so does the
26144 @code{Inputs} parameter cause its variable to be loaded into the register
26145 before execution of the assembler statements.
26146
26147 Thus the effect of the @code{Asm} invocation is:
26148 @enumerate
26149 @item load the 32-bit value of @code{Value} into eax
26150 @item execute the @code{incl %eax} instruction
26151 @item store the contents of eax into the @code{Result} variable
26152 @end enumerate
26153
26154 The resulting assembler file (with @option{-O2} optimization) contains:
26155 @smallexample
26156 @group
26157 _increment__incr.1:
26158    subl $4,%esp
26159    movl 8(%esp),%eax
26160 #APP
26161    incl %eax
26162 #NO_APP
26163    movl %eax,%edx
26164    movl %ecx,(%esp)
26165    addl $4,%esp
26166    ret
26167 @end group
26168 @end smallexample
26169
26170 @c ---------------------------------------------------------------------------
26171 @node Inlining Inline Assembler Code
26172 @section Inlining Inline Assembler Code
26173
26174 @noindent
26175 For a short subprogram such as the @code{Incr} function in the previous
26176 section, the overhead of the call and return (creating / deleting the stack
26177 frame) can be significant, compared to the amount of code in the subprogram
26178 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
26179 which directs the compiler to expand invocations of the subprogram at the
26180 point(s) of call, instead of setting up a stack frame for out-of-line calls.
26181 Here is the resulting program:
26182
26183 @smallexample @c ada
26184 @group
26185 with Interfaces; use Interfaces;
26186 with Ada.Text_IO; use Ada.Text_IO;
26187 with System.Machine_Code; use System.Machine_Code;
26188 procedure Increment_2 is
26189
26190    function Incr (Value : Unsigned_32) return Unsigned_32 is
26191       Result : Unsigned_32;
26192    begin
26193       Asm ("incl %0",
26194            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26195            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26196       return Result;
26197    end Incr;
26198    pragma Inline (Increment);
26199
26200    Value : Unsigned_32;
26201
26202 begin
26203    Value := 5;
26204    Put_Line ("Value before is" & Value'Img);
26205    Value := Increment (Value);
26206    Put_Line ("Value after is" & Value'Img);
26207 end Increment_2;
26208 @end group
26209 @end smallexample
26210
26211 Compile the program with both optimization (@option{-O2}) and inlining
26212 (@option{-gnatn}) enabled.
26213
26214 The @code{Incr} function is still compiled as usual, but at the
26215 point in @code{Increment} where our function used to be called:
26216
26217 @smallexample
26218 @group
26219 pushl %edi
26220 call _increment__incr.1
26221 @end group
26222 @end smallexample
26223
26224 @noindent
26225 the code for the function body directly appears:
26226
26227 @smallexample
26228 @group
26229 movl %esi,%eax
26230 #APP
26231    incl %eax
26232 #NO_APP
26233    movl %eax,%edx
26234 @end group
26235 @end smallexample
26236
26237 @noindent
26238 thus saving the overhead of stack frame setup and an out-of-line call.
26239
26240 @c ---------------------------------------------------------------------------
26241 @node Other Asm Functionality
26242 @section Other @code{Asm} Functionality
26243
26244 @noindent
26245 This section describes two important parameters to the @code{Asm}
26246 procedure: @code{Clobber}, which identifies register usage;
26247 and @code{Volatile}, which inhibits unwanted optimizations.
26248
26249 @menu
26250 * The Clobber Parameter::
26251 * The Volatile Parameter::
26252 @end menu
26253
26254 @c ---------------------------------------------------------------------------
26255 @node The Clobber Parameter
26256 @subsection The @code{Clobber} Parameter
26257
26258 @noindent
26259 One of the dangers of intermixing assembly language and a compiled language
26260 such as Ada is that the compiler needs to be aware of which registers are
26261 being used by the assembly code.  In some cases, such as the earlier examples,
26262 the constraint string is sufficient to indicate register usage (e.g.,
26263 @code{"a"} for
26264 the eax register).  But more generally, the compiler needs an explicit
26265 identification of the registers that are used by the Inline Assembly
26266 statements.
26267
26268 Using a register that the compiler doesn't know about
26269 could be a side effect of an instruction (like @code{mull}
26270 storing its result in both eax and edx).
26271 It can also arise from explicit register usage in your
26272 assembly code; for example:
26273 @smallexample
26274 @group
26275 Asm ("movl %0, %%ebx" & LF & HT &
26276      "movl %%ebx, %1",
26277      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26278      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26279 @end group
26280 @end smallexample
26281 @noindent
26282 where the compiler (since it does not analyze the @code{Asm} template string)
26283 does not know you are using the ebx register.
26284
26285 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26286 to identify the registers that will be used by your assembly code:
26287
26288 @smallexample
26289 @group
26290 Asm ("movl %0, %%ebx" & LF & HT &
26291      "movl %%ebx, %1",
26292      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26293      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26294      Clobber => "ebx");
26295 @end group
26296 @end smallexample
26297
26298 The Clobber parameter is a static string expression specifying the
26299 register(s) you are using.  Note that register names are @emph{not} prefixed
26300 by a percent sign. Also, if more than one register is used then their names
26301 are separated by commas; e.g., @code{"eax, ebx"}
26302
26303 The @code{Clobber} parameter has several additional uses:
26304 @enumerate
26305 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26306 @item Use ``register'' name @code{memory} if you changed a memory location
26307 @end enumerate
26308
26309 @c ---------------------------------------------------------------------------
26310 @node The Volatile Parameter
26311 @subsection The @code{Volatile} Parameter
26312 @cindex Volatile parameter
26313
26314 @noindent
26315 Compiler optimizations in the presence of Inline Assembler may sometimes have
26316 unwanted effects.  For example, when an @code{Asm} invocation with an input
26317 variable is inside a loop, the compiler might move the loading of the input
26318 variable outside the loop, regarding it as a one-time initialization.
26319
26320 If this effect is not desired, you can disable such optimizations by setting
26321 the @code{Volatile} parameter to @code{True}; for example:
26322
26323 @smallexample @c ada
26324 @group
26325 Asm ("movl %0, %%ebx" & LF & HT &
26326      "movl %%ebx, %1",
26327      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26328      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26329      Clobber  => "ebx",
26330      Volatile => True);
26331 @end group
26332 @end smallexample
26333
26334 By default, @code{Volatile} is set to @code{False} unless there is no
26335 @code{Outputs} parameter.
26336
26337 Although setting @code{Volatile} to @code{True} prevents unwanted
26338 optimizations, it will also disable other optimizations that might be
26339 important for efficiency. In general, you should set @code{Volatile}
26340 to @code{True} only if the compiler's optimizations have created
26341 problems.
26342 @c END OF INLINE ASSEMBLER CHAPTER
26343 @c ===============================
26344
26345 @c ***********************************
26346 @c * Compatibility and Porting Guide *
26347 @c ***********************************
26348 @node Compatibility and Porting Guide
26349 @appendix Compatibility and Porting Guide
26350
26351 @noindent
26352 This chapter describes the compatibility issues that may arise between
26353 GNAT and other Ada compilation systems (including those for Ada 83),
26354 and shows how GNAT can expedite porting
26355 applications developed in other Ada environments.
26356
26357 @menu
26358 * Compatibility with Ada 83::
26359 * Compatibility between Ada 95 and Ada 2005::
26360 * Implementation-dependent characteristics::
26361 * Compatibility with Other Ada Systems::
26362 * Representation Clauses::
26363 @ifclear vms
26364 @c Brief section is only in non-VMS version
26365 @c Full chapter is in VMS version
26366 * Compatibility with HP Ada 83::
26367 @end ifclear
26368 @ifset vms
26369 * Transitioning to 64-Bit GNAT for OpenVMS::
26370 @end ifset
26371 @end menu
26372
26373 @node Compatibility with Ada 83
26374 @section Compatibility with Ada 83
26375 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26376
26377 @noindent
26378 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26379 particular, the design intention was that the difficulties associated
26380 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26381 that occur when moving from one Ada 83 system to another.
26382
26383 However, there are a number of points at which there are minor
26384 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26385 full details of these issues,
26386 and should be consulted for a complete treatment.
26387 In practice the
26388 following subsections treat the most likely issues to be encountered.
26389
26390 @menu
26391 * Legal Ada 83 programs that are illegal in Ada 95::
26392 * More deterministic semantics::
26393 * Changed semantics::
26394 * Other language compatibility issues::
26395 @end menu
26396
26397 @node Legal Ada 83 programs that are illegal in Ada 95
26398 @subsection Legal Ada 83 programs that are illegal in Ada 95
26399
26400 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26401 Ada 95 and thus also in Ada 2005:
26402
26403 @table @emph
26404 @item Character literals
26405 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26406 @code{Wide_Character} as a new predefined character type, some uses of
26407 character literals that were legal in Ada 83 are illegal in Ada 95.
26408 For example:
26409 @smallexample @c ada
26410    for Char in 'A' .. 'Z' loop @dots{} end loop;
26411 @end smallexample
26412
26413 @noindent
26414 The problem is that @code{'A'} and @code{'Z'} could be from either
26415 @code{Character} or @code{Wide_Character}.  The simplest correction
26416 is to make the type explicit; e.g.:
26417 @smallexample @c ada
26418    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26419 @end smallexample
26420
26421 @item New reserved words
26422 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26423 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26424 Existing Ada 83 code using any of these identifiers must be edited to
26425 use some alternative name.
26426
26427 @item Freezing rules
26428 The rules in Ada 95 are slightly different with regard to the point at
26429 which entities are frozen, and representation pragmas and clauses are
26430 not permitted past the freeze point.  This shows up most typically in
26431 the form of an error message complaining that a representation item
26432 appears too late, and the appropriate corrective action is to move
26433 the item nearer to the declaration of the entity to which it refers.
26434
26435 A particular case is that representation pragmas
26436 @ifset vms
26437 (including the
26438 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26439 @end ifset
26440 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26441 declaration must be introduced to which the pragma can be applied.
26442
26443 @item Optional bodies for library packages
26444 In Ada 83, a package that did not require a package body was nevertheless
26445 allowed to have one.  This lead to certain surprises in compiling large
26446 systems (situations in which the body could be unexpectedly ignored by the
26447 binder).  In Ada 95, if a package does not require a body then it is not
26448 permitted to have a body.  To fix this problem, simply remove a redundant
26449 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26450 into the spec that makes the body required.  One approach is to add a private
26451 part to the package declaration (if necessary), and define a parameterless
26452 procedure called @code{Requires_Body}, which must then be given a dummy
26453 procedure body in the package body, which then becomes required.
26454 Another approach (assuming that this does not introduce elaboration
26455 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26456 since one effect of this pragma is to require the presence of a package body.
26457
26458 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26459 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26460 @code{Constraint_Error}.
26461 This means that it is illegal to have separate exception handlers for
26462 the two exceptions.  The fix is simply to remove the handler for the
26463 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26464 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26465
26466 @item Indefinite subtypes in generics
26467 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26468 as the actual for a generic formal private type, but then the instantiation
26469 would be illegal if there were any instances of declarations of variables
26470 of this type in the generic body.  In Ada 95, to avoid this clear violation
26471 of the methodological principle known as the ``contract model'',
26472 the generic declaration explicitly indicates whether
26473 or not such instantiations are permitted.  If a generic formal parameter
26474 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26475 subtype name, then it can be instantiated with indefinite types, but no
26476 stand-alone variables can be declared of this type.  Any attempt to declare
26477 such a variable will result in an illegality at the time the generic is
26478 declared.  If the @code{(<>)} notation is not used, then it is illegal
26479 to instantiate the generic with an indefinite type.
26480 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26481 It will show up as a compile time error, and
26482 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26483 @end table
26484
26485 @node More deterministic semantics
26486 @subsection More deterministic semantics
26487
26488 @table @emph
26489 @item Conversions
26490 Conversions from real types to integer types round away from 0.  In Ada 83
26491 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26492 implementation freedom was intended to support unbiased rounding in
26493 statistical applications, but in practice it interfered with portability.
26494 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26495 is required.  Numeric code may be affected by this change in semantics.
26496 Note, though, that this issue is no worse than already existed in Ada 83
26497 when porting code from one vendor to another.
26498
26499 @item Tasking
26500 The Real-Time Annex introduces a set of policies that define the behavior of
26501 features that were implementation dependent in Ada 83, such as the order in
26502 which open select branches are executed.
26503 @end table
26504
26505 @node Changed semantics
26506 @subsection Changed semantics
26507
26508 @noindent
26509 The worst kind of incompatibility is one where a program that is legal in
26510 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26511 possible in Ada 83.  Fortunately this is extremely rare, but the one
26512 situation that you should be alert to is the change in the predefined type
26513 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26514
26515 @table @emph
26516 @item Range of type @code{Character}
26517 The range of @code{Standard.Character} is now the full 256 characters
26518 of Latin-1, whereas in most Ada 83 implementations it was restricted
26519 to 128 characters. Although some of the effects of
26520 this change will be manifest in compile-time rejection of legal
26521 Ada 83 programs it is possible for a working Ada 83 program to have
26522 a different effect in Ada 95, one that was not permitted in Ada 83.
26523 As an example, the expression
26524 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26525 delivers @code{255} as its value.
26526 In general, you should look at the logic of any
26527 character-processing Ada 83 program and see whether it needs to be adapted
26528 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26529 character handling package that may be relevant if code needs to be adapted
26530 to account for the additional Latin-1 elements.
26531 The desirable fix is to
26532 modify the program to accommodate the full character set, but in some cases
26533 it may be convenient to define a subtype or derived type of Character that
26534 covers only the restricted range.
26535 @cindex Latin-1
26536 @end table
26537
26538 @node Other language compatibility issues
26539 @subsection Other language compatibility issues
26540
26541 @table @emph
26542 @item @option{-gnat83} switch
26543 All implementations of GNAT provide a switch that causes GNAT to operate
26544 in Ada 83 mode.  In this mode, some but not all compatibility problems
26545 of the type described above are handled automatically.  For example, the
26546 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26547 as identifiers as in Ada 83.
26548 However,
26549 in practice, it is usually advisable to make the necessary modifications
26550 to the program to remove the need for using this switch.
26551 See @ref{Compiling Different Versions of Ada}.
26552
26553 @item Support for removed Ada 83 pragmas and attributes
26554 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26555 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26556 compilers are allowed, but not required, to implement these missing
26557 elements.  In contrast with some other compilers, GNAT implements all
26558 such pragmas and attributes, eliminating this compatibility concern.  These
26559 include @code{pragma Interface} and the floating point type attributes
26560 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26561 @end table
26562
26563
26564 @node Compatibility between Ada 95 and Ada 2005
26565 @section Compatibility between Ada 95 and Ada 2005
26566 @cindex Compatibility between Ada 95 and Ada 2005
26567
26568 @noindent
26569 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26570 a number of incompatibilities. Several are enumerated below;
26571 for a complete description please see the
26572 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26573 @cite{Rationale for Ada 2005}.
26574
26575 @table @emph
26576 @item New reserved words.
26577 The words @code{interface}, @code{overriding} and @code{synchronized} are
26578 reserved in Ada 2005.
26579 A pre-Ada 2005 program that uses any of these as an identifier will be
26580 illegal.
26581
26582 @item New declarations in predefined packages.
26583 A number of packages in the predefined environment contain new declarations:
26584 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26585 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26586 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26587 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26588 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26589 If an Ada 95 program does a @code{with} and @code{use} of any of these
26590 packages, the new declarations may cause name clashes.
26591
26592 @item Access parameters.
26593 A nondispatching subprogram with an access parameter cannot be renamed
26594 as a dispatching operation.  This was permitted in Ada 95.
26595
26596 @item Access types, discriminants, and constraints.
26597 Rule changes in this area have led to some incompatibilities; for example,
26598 constrained subtypes of some access types are not permitted in Ada 2005.
26599
26600 @item Aggregates for limited types.
26601 The allowance of aggregates for limited types in Ada 2005 raises the
26602 possibility of ambiguities in legal Ada 95 programs, since additional types
26603 now need to be considered in expression resolution.
26604
26605 @item Fixed-point multiplication and division.
26606 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26607 were legal in Ada 95 and invoked the predefined versions of these operations,
26608 are now ambiguous.
26609 The ambiguity may be resolved either by applying a type conversion to the
26610 expression, or by explicitly invoking the operation from package
26611 @code{Standard}.
26612
26613 @item Return-by-reference types.
26614 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26615 can declare a function returning a value from an anonymous access type.
26616 @end table
26617
26618
26619 @node Implementation-dependent characteristics
26620 @section Implementation-dependent characteristics
26621 @noindent
26622 Although the Ada language defines the semantics of each construct as
26623 precisely as practical, in some situations (for example for reasons of
26624 efficiency, or where the effect is heavily dependent on the host or target
26625 platform) the implementation is allowed some freedom.  In porting Ada 83
26626 code to GNAT, you need to be aware of whether / how the existing code
26627 exercised such implementation dependencies.  Such characteristics fall into
26628 several categories, and GNAT offers specific support in assisting the
26629 transition from certain Ada 83 compilers.
26630
26631 @menu
26632 * Implementation-defined pragmas::
26633 * Implementation-defined attributes::
26634 * Libraries::
26635 * Elaboration order::
26636 * Target-specific aspects::
26637 @end menu
26638
26639 @node Implementation-defined pragmas
26640 @subsection Implementation-defined pragmas
26641
26642 @noindent
26643 Ada compilers are allowed to supplement the language-defined pragmas, and
26644 these are a potential source of non-portability.  All GNAT-defined pragmas
26645 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26646 Reference Manual}, and these include several that are specifically
26647 intended to correspond to other vendors' Ada 83 pragmas.
26648 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26649 For compatibility with HP Ada 83, GNAT supplies the pragmas
26650 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26651 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26652 and @code{Volatile}.
26653 Other relevant pragmas include @code{External} and @code{Link_With}.
26654 Some vendor-specific
26655 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26656 recognized, thus
26657 avoiding compiler rejection of units that contain such pragmas; they are not
26658 relevant in a GNAT context and hence are not otherwise implemented.
26659
26660 @node Implementation-defined attributes
26661 @subsection Implementation-defined attributes
26662
26663 Analogous to pragmas, the set of attributes may be extended by an
26664 implementation.  All GNAT-defined attributes are described in
26665 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26666 Manual}, and these include several that are specifically intended
26667 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26668 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26669 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26670 @code{Type_Class}.
26671
26672 @node Libraries
26673 @subsection Libraries
26674 @noindent
26675 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26676 code uses vendor-specific libraries then there are several ways to manage
26677 this in Ada 95 or Ada 2005:
26678 @enumerate
26679 @item
26680 If the source code for the libraries (specs and bodies) are
26681 available, then the libraries can be migrated in the same way as the
26682 application.
26683 @item
26684 If the source code for the specs but not the bodies are
26685 available, then you can reimplement the bodies.
26686 @item
26687 Some features introduced by Ada 95 obviate the need for library support.  For
26688 example most Ada 83 vendors supplied a package for unsigned integers.  The
26689 Ada 95 modular type feature is the preferred way to handle this need, so
26690 instead of migrating or reimplementing the unsigned integer package it may
26691 be preferable to retrofit the application using modular types.
26692 @end enumerate
26693
26694 @node Elaboration order
26695 @subsection Elaboration order
26696 @noindent
26697 The implementation can choose any elaboration order consistent with the unit
26698 dependency relationship.  This freedom means that some orders can result in
26699 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26700 to invoke a subprogram its body has been elaborated, or to instantiate a
26701 generic before the generic body has been elaborated.  By default GNAT
26702 attempts to choose a safe order (one that will not encounter access before
26703 elaboration problems) by implicitly inserting @code{Elaborate} or
26704 @code{Elaborate_All} pragmas where
26705 needed.  However, this can lead to the creation of elaboration circularities
26706 and a resulting rejection of the program by gnatbind.  This issue is
26707 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26708 In brief, there are several
26709 ways to deal with this situation:
26710
26711 @itemize @bullet
26712 @item
26713 Modify the program to eliminate the circularities, e.g.@: by moving
26714 elaboration-time code into explicitly-invoked procedures
26715 @item
26716 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26717 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26718 @code{Elaborate_All}
26719 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26720 (by selectively suppressing elaboration checks via pragma
26721 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26722 @end itemize
26723
26724 @node Target-specific aspects
26725 @subsection Target-specific aspects
26726 @noindent
26727 Low-level applications need to deal with machine addresses, data
26728 representations, interfacing with assembler code, and similar issues.  If
26729 such an Ada 83 application is being ported to different target hardware (for
26730 example where the byte endianness has changed) then you will need to
26731 carefully examine the program logic; the porting effort will heavily depend
26732 on the robustness of the original design.  Moreover, Ada 95 (and thus
26733 Ada 2005) are sometimes
26734 incompatible with typical Ada 83 compiler practices regarding implicit
26735 packing, the meaning of the Size attribute, and the size of access values.
26736 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26737
26738 @node Compatibility with Other Ada Systems
26739 @section Compatibility with Other Ada Systems
26740
26741 @noindent
26742 If programs avoid the use of implementation dependent and
26743 implementation defined features, as documented in the @cite{Ada
26744 Reference Manual}, there should be a high degree of portability between
26745 GNAT and other Ada systems.  The following are specific items which
26746 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26747 compilers, but do not affect porting code to GNAT@.
26748 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26749 the following issues may or may not arise for Ada 2005 programs
26750 when other compilers appear.)
26751
26752 @table @emph
26753 @item Ada 83 Pragmas and Attributes
26754 Ada 95 compilers are allowed, but not required, to implement the missing
26755 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26756 GNAT implements all such pragmas and attributes, eliminating this as
26757 a compatibility concern, but some other Ada 95 compilers reject these
26758 pragmas and attributes.
26759
26760 @item Specialized Needs Annexes
26761 GNAT implements the full set of special needs annexes.  At the
26762 current time, it is the only Ada 95 compiler to do so.  This means that
26763 programs making use of these features may not be portable to other Ada
26764 95 compilation systems.
26765
26766 @item Representation Clauses
26767 Some other Ada 95 compilers implement only the minimal set of
26768 representation clauses required by the Ada 95 reference manual.  GNAT goes
26769 far beyond this minimal set, as described in the next section.
26770 @end table
26771
26772 @node Representation Clauses
26773 @section Representation Clauses
26774
26775 @noindent
26776 The Ada 83 reference manual was quite vague in describing both the minimal
26777 required implementation of representation clauses, and also their precise
26778 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26779 minimal set of capabilities required is still quite limited.
26780
26781 GNAT implements the full required set of capabilities in
26782 Ada 95 and Ada 2005, but also goes much further, and in particular
26783 an effort has been made to be compatible with existing Ada 83 usage to the
26784 greatest extent possible.
26785
26786 A few cases exist in which Ada 83 compiler behavior is incompatible with
26787 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26788 intentional or accidental dependence on specific implementation dependent
26789 characteristics of these Ada 83 compilers.  The following is a list of
26790 the cases most likely to arise in existing Ada 83 code.
26791
26792 @table @emph
26793 @item Implicit Packing
26794 Some Ada 83 compilers allowed a Size specification to cause implicit
26795 packing of an array or record.  This could cause expensive implicit
26796 conversions for change of representation in the presence of derived
26797 types, and the Ada design intends to avoid this possibility.
26798 Subsequent AI's were issued to make it clear that such implicit
26799 change of representation in response to a Size clause is inadvisable,
26800 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26801 Reference Manuals as implementation advice that is followed by GNAT@.
26802 The problem will show up as an error
26803 message rejecting the size clause.  The fix is simply to provide
26804 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26805 a Component_Size clause.
26806
26807 @item Meaning of Size Attribute
26808 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26809 the minimal number of bits required to hold values of the type.  For example,
26810 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26811 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26812 some 32 in this situation.  This problem will usually show up as a compile
26813 time error, but not always.  It is a good idea to check all uses of the
26814 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26815 Object_Size can provide a useful way of duplicating the behavior of
26816 some Ada 83 compiler systems.
26817
26818 @item Size of Access Types
26819 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26820 and that therefore it will be the same size as a System.Address value.  This
26821 assumption is true for GNAT in most cases with one exception.  For the case of
26822 a pointer to an unconstrained array type (where the bounds may vary from one
26823 value of the access type to another), the default is to use a ``fat pointer'',
26824 which is represented as two separate pointers, one to the bounds, and one to
26825 the array.  This representation has a number of advantages, including improved
26826 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26827 code which makes the assumption that, for example, pointers fit in 32 bits on
26828 a machine with 32-bit addressing.
26829
26830 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26831 access types in this case (where the designated type is an unconstrained array
26832 type).  These thin pointers are indeed the same size as a System.Address value.
26833 To specify a thin pointer, use a size clause for the type, for example:
26834
26835 @smallexample @c ada
26836 type X is access all String;
26837 for X'Size use Standard'Address_Size;
26838 @end smallexample
26839
26840 @noindent
26841 which will cause the type X to be represented using a single pointer.
26842 When using this representation, the bounds are right behind the array.
26843 This representation is slightly less efficient, and does not allow quite
26844 such flexibility in the use of foreign pointers or in using the
26845 Unrestricted_Access attribute to create pointers to non-aliased objects.
26846 But for any standard portable use of the access type it will work in
26847 a functionally correct manner and allow porting of existing code.
26848 Note that another way of forcing a thin pointer representation
26849 is to use a component size clause for the element size in an array,
26850 or a record representation clause for an access field in a record.
26851 @end table
26852
26853 @ifclear vms
26854 @c This brief section is only in the non-VMS version
26855 @c The complete chapter on HP Ada is in the VMS version
26856 @node Compatibility with HP Ada 83
26857 @section Compatibility with HP Ada 83
26858
26859 @noindent
26860 The VMS version of GNAT fully implements all the pragmas and attributes
26861 provided by HP Ada 83, as well as providing the standard HP Ada 83
26862 libraries, including Starlet.  In addition, data layouts and parameter
26863 passing conventions are highly compatible.  This means that porting
26864 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26865 most other porting efforts.  The following are some of the most
26866 significant differences between GNAT and HP Ada 83.
26867
26868 @table @emph
26869 @item Default floating-point representation
26870 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26871 it is VMS format.  GNAT does implement the necessary pragmas
26872 (Long_Float, Float_Representation) for changing this default.
26873
26874 @item System
26875 The package System in GNAT exactly corresponds to the definition in the
26876 Ada 95 reference manual, which means that it excludes many of the
26877 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26878 that contains the additional definitions, and a special pragma,
26879 Extend_System allows this package to be treated transparently as an
26880 extension of package System.
26881
26882 @item To_Address
26883 The definitions provided by Aux_DEC are exactly compatible with those
26884 in the HP Ada 83 version of System, with one exception.
26885 HP Ada provides the following declarations:
26886
26887 @smallexample @c ada
26888 TO_ADDRESS (INTEGER)
26889 TO_ADDRESS (UNSIGNED_LONGWORD)
26890 TO_ADDRESS (@i{universal_integer})
26891 @end smallexample
26892
26893 @noindent
26894 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26895 an extension to Ada 83 not strictly compatible with the reference manual.
26896 In GNAT, we are constrained to be exactly compatible with the standard,
26897 and this means we cannot provide this capability.  In HP Ada 83, the
26898 point of this definition is to deal with a call like:
26899
26900 @smallexample @c ada
26901 TO_ADDRESS (16#12777#);
26902 @end smallexample
26903
26904 @noindent
26905 Normally, according to the Ada 83 standard, one would expect this to be
26906 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26907 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26908 definition using @i{universal_integer} takes precedence.
26909
26910 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26911 is not possible to be 100% compatible.  Since there are many programs using
26912 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26913 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26914 declarations provided in the GNAT version of AUX_Dec are:
26915
26916 @smallexample @c ada
26917 function To_Address (X : Integer) return Address;
26918 pragma Pure_Function (To_Address);
26919
26920 function To_Address_Long (X : Unsigned_Longword)
26921  return Address;
26922 pragma Pure_Function (To_Address_Long);
26923 @end smallexample
26924
26925 @noindent
26926 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26927 change the name to TO_ADDRESS_LONG@.
26928
26929 @item Task_Id values
26930 The Task_Id values assigned will be different in the two systems, and GNAT
26931 does not provide a specified value for the Task_Id of the environment task,
26932 which in GNAT is treated like any other declared task.
26933 @end table
26934
26935 @noindent
26936 For full details on these and other less significant compatibility issues,
26937 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26938 Overview and Comparison on HP Platforms}.
26939
26940 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26941 attributes are recognized, although only a subset of them can sensibly
26942 be implemented.  The description of pragmas in @ref{Implementation
26943 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26944 indicates whether or not they are applicable to non-VMS systems.
26945 @end ifclear
26946
26947 @ifset vms
26948 @node Transitioning to 64-Bit GNAT for OpenVMS
26949 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26950
26951 @noindent
26952 This section is meant to assist users of pre-2006 @value{EDITION}
26953 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26954 the version of the GNAT technology supplied in 2006 and later for
26955 OpenVMS on both Alpha and I64.
26956
26957 @menu
26958 * Introduction to transitioning::
26959 * Migration of 32 bit code::
26960 * Taking advantage of 64 bit addressing::
26961 * Technical details::
26962 @end menu
26963
26964 @node Introduction to transitioning
26965 @subsection Introduction
26966
26967 @noindent
26968 64-bit @value{EDITION} for Open VMS has been designed to meet
26969 three main goals:
26970
26971 @enumerate
26972 @item
26973 Providing a full conforming implementation of Ada 95 and Ada 2005
26974
26975 @item
26976 Allowing maximum backward compatibility, thus easing migration of existing
26977 Ada source code
26978
26979 @item
26980 Supplying a path for exploiting the full 64-bit address range
26981 @end enumerate
26982
26983 @noindent
26984 Ada's strong typing semantics has made it
26985 impractical to have different 32-bit and 64-bit modes. As soon as
26986 one object could possibly be outside the 32-bit address space, this
26987 would make it necessary for the @code{System.Address} type to be 64 bits.
26988 In particular, this would cause inconsistencies if 32-bit code is
26989 called from 64-bit code that raises an exception.
26990
26991 This issue has been resolved by always using 64-bit addressing
26992 at the system level, but allowing for automatic conversions between
26993 32-bit and 64-bit addresses where required. Thus users who
26994 do not currently require 64-bit addressing capabilities, can
26995 recompile their code with only minimal changes (and indeed
26996 if the code is written in portable Ada, with no assumptions about
26997 the size of the @code{Address} type, then no changes at all are necessary).
26998 At the same time,
26999 this approach provides a simple, gradual upgrade path to future
27000 use of larger memories than available for 32-bit systems.
27001 Also, newly written applications or libraries will by default
27002 be fully compatible with future systems exploiting 64-bit
27003 addressing capabilities.
27004
27005 @ref{Migration of 32 bit code}, will focus on porting applications
27006 that do not require more than 2 GB of
27007 addressable memory. This code will be referred to as
27008 @emph{32-bit code}.
27009 For applications intending to exploit the full 64-bit address space,
27010 @ref{Taking advantage of 64 bit addressing},
27011 will consider further changes that may be required.
27012 Such code will be referred to below as @emph{64-bit code}.
27013
27014 @node Migration of 32 bit code
27015 @subsection Migration of 32-bit code
27016
27017 @menu
27018 * Address types::
27019 * Access types and 32/64-bit allocation::
27020 * Unchecked conversions::
27021 * Predefined constants::
27022 * Interfacing with C::
27023 * 32/64-bit descriptors::
27024 * Experience with source compatibility::
27025 @end menu
27026
27027 @node Address types
27028 @subsubsection Address types
27029
27030 @noindent
27031 To solve the problem of mixing 64-bit and 32-bit addressing,
27032 while maintaining maximum backward compatibility, the following
27033 approach has been taken:
27034
27035 @itemize @bullet
27036 @item
27037 @code{System.Address} always has a size of 64 bits
27038 @cindex @code{System.Address} size
27039 @cindex @code{Address} size
27040
27041 @item
27042 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
27043 @cindex @code{System.Short_Address} size
27044 @cindex @code{Short_Address} size
27045 @end itemize
27046
27047 @noindent
27048 Since @code{System.Short_Address} is a subtype of @code{System.Address},
27049 a @code{Short_Address}
27050 may be used where an @code{Address} is required, and vice versa, without
27051 needing explicit type conversions.
27052 By virtue of the Open VMS parameter passing conventions,
27053 even imported
27054 and exported subprograms that have 32-bit address parameters are
27055 compatible with those that have 64-bit address parameters.
27056 (See @ref{Making code 64 bit clean} for details.)
27057
27058 The areas that may need attention are those where record types have
27059 been defined that contain components of the type @code{System.Address}, and
27060 where objects of this type are passed to code expecting a record layout with
27061 32-bit addresses.
27062
27063 Different compilers on different platforms cannot be
27064 expected to represent the same type in the same way,
27065 since alignment constraints
27066 and other system-dependent properties affect the compiler's decision.
27067 For that reason, Ada code
27068 generally uses representation clauses to specify the expected
27069 layout where required.
27070
27071 If such a representation clause uses 32 bits for a component having
27072 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
27073 will detect that error and produce a specific diagnostic message.
27074 The developer should then determine whether the representation
27075 should be 64 bits or not and make either of two changes:
27076 change the size to 64 bits and leave the type as @code{System.Address}, or
27077 leave the size as 32 bits and change the type to @code{System.Short_Address}.
27078 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
27079 required in any code setting or accessing the field; the compiler will
27080 automatically perform any needed conversions between address
27081 formats.
27082
27083 @node Access types and 32/64-bit allocation
27084 @subsubsection Access types and 32/64-bit allocation
27085 @cindex 32-bit allocation
27086 @cindex 64-bit allocation
27087
27088 @noindent
27089 By default, objects designated by access values are always allocated in
27090 the 64-bit address space, and access values themselves are represented
27091 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
27092 is required (for example if the address of an allocated object is assigned
27093 to a @code{Short_Address} variable), then several alternatives are available:
27094
27095 @itemize @bullet
27096 @item
27097 A pool-specific access type (ie, an @w{Ada 83} access type, whose
27098 definition is @code{access T} versus @code{access all T} or
27099 @code{access constant T}), may be declared with a @code{'Size} representation
27100 clause that establishes the size as 32 bits.
27101 In such circumstances allocations for that type will
27102 be from the 32-bit heap.  Such a clause is not permitted
27103 for a general access type (declared with @code{access all} or
27104 @code{access constant}) as values of such types must be able to refer
27105 to any object of the designated type, including objects residing outside
27106 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
27107 type definitions, however, since general access types were introduced
27108 in @w{Ada 95}.
27109
27110 @item
27111 Switches for @command{GNAT BIND} control whether the internal GNAT
27112 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
27113 @cindex @code{__gnat_malloc}
27114 The switches are respectively @option{-H64} (the default) and
27115 @option{-H32}.
27116 @cindex @option{-H32} (@command{gnatbind})
27117 @cindex @option{-H64} (@command{gnatbind})
27118
27119 @item
27120 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
27121 @cindex @code{GNAT$NO_MALLOC_64} environment variable
27122 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
27123 If this variable is left
27124 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
27125 then the default (64-bit) allocation is used.
27126 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
27127 then 32-bit allocation is used.  The gnatbind qualifiers described above
27128 override this logical name.
27129
27130 @item
27131 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
27132 @cindex @option{-mno-malloc64} (^gcc^gcc^)
27133 at a low level to convert explicit calls to @code{malloc} and related
27134 functions from the C run-time library so that they perform allocations
27135 in the 32-bit heap.
27136 Since all internal allocations from GNAT use @code{__gnat_malloc},
27137 this switch is not required unless the program makes explicit calls on
27138 @code{malloc} (or related functions) from interfaced C code.
27139 @end itemize
27140
27141
27142 @node Unchecked conversions
27143 @subsubsection Unchecked conversions
27144
27145 @noindent
27146 In the case of an @code{Unchecked_Conversion} where the source type is a
27147 64-bit access type or the type @code{System.Address}, and the target
27148 type is a 32-bit type, the compiler will generate a warning.
27149 Even though the generated code will still perform the required
27150 conversions, it is highly recommended in these cases to use
27151 respectively a 32-bit access type or @code{System.Short_Address}
27152 as the source type.
27153
27154 @node Predefined constants
27155 @subsubsection Predefined constants
27156
27157 @noindent
27158 The following table shows the correspondence between pre-2006 versions of
27159 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
27160 (``New''):
27161
27162 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
27163 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
27164 @item   @code{System.Word_Size}          @tab 32      @tab 64
27165 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
27166 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
27167 @item   @code{System.Address_Size}       @tab 32      @tab 64
27168 @end multitable
27169
27170 @noindent
27171 If you need to refer to the specific
27172 memory size of a 32-bit implementation, instead of the
27173 actual memory size, use @code{System.Short_Memory_Size}
27174 rather than @code{System.Memory_Size}.
27175 Similarly, references to @code{System.Address_Size} may need
27176 to be replaced by @code{System.Short_Address'Size}.
27177 The program @command{gnatfind} may be useful for locating
27178 references to the above constants, so that you can verify that they
27179 are still correct.
27180
27181 @node Interfacing with C
27182 @subsubsection Interfacing with C
27183
27184 @noindent
27185 In order to minimize the impact of the transition to 64-bit addresses on
27186 legacy programs, some fundamental types in the @code{Interfaces.C}
27187 package hierarchy continue to be represented in 32 bits.
27188 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
27189 This eases integration with the default HP C layout choices, for example
27190 as found in the system routines in @code{DECC$SHR.EXE}.
27191 Because of this implementation choice, the type fully compatible with
27192 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27193 Depending on the context the compiler will issue a
27194 warning or an error when type @code{Address} is used, alerting the user to a
27195 potential problem. Otherwise 32-bit programs that use
27196 @code{Interfaces.C} should normally not require code modifications
27197
27198 The other issue arising with C interfacing concerns pragma @code{Convention}.
27199 For VMS 64-bit systems, there is an issue of the appropriate default size
27200 of C convention pointers in the absence of an explicit size clause. The HP
27201 C compiler can choose either 32 or 64 bits depending on compiler options.
27202 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27203 clause is given. This proves a better choice for porting 32-bit legacy
27204 applications. In order to have a 64-bit representation, it is necessary to
27205 specify a size representation clause. For example:
27206
27207 @smallexample @c ada
27208 type int_star is access Interfaces.C.int;
27209 pragma Convention(C, int_star);
27210 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
27211 @end smallexample
27212
27213 @node 32/64-bit descriptors
27214 @subsubsection 32/64-bit descriptors
27215
27216 @noindent
27217 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
27218 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27219 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27220 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27221 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27222
27223 If the configuration pragma @code{Short_Descriptors} is supplied, then
27224 all descriptors will be 32 bits.
27225 @cindex pragma @code{Short_Descriptors}
27226
27227 @node Experience with source compatibility
27228 @subsubsection Experience with source compatibility
27229
27230 @noindent
27231 The Security Server and STARLET on I64 provide an interesting ``test case''
27232 for source compatibility issues, since it is in such system code
27233 where assumptions about @code{Address} size might be expected to occur.
27234 Indeed, there were a small number of occasions in the Security Server
27235 file @file{jibdef.ads}
27236 where a representation clause for a record type specified
27237 32 bits for a component of type @code{Address}.
27238 All of these errors were detected by the compiler.
27239 The repair was obvious and immediate; to simply replace @code{Address} by
27240 @code{Short_Address}.
27241
27242 In the case of STARLET, there were several record types that should
27243 have had representation clauses but did not.  In these record types
27244 there was an implicit assumption that an @code{Address} value occupied
27245 32 bits.
27246 These compiled without error, but their usage resulted in run-time error
27247 returns from STARLET system calls.
27248 Future GNAT technology enhancements may include a tool that detects and flags
27249 these sorts of potential source code porting problems.
27250
27251 @c ****************************************
27252 @node Taking advantage of 64 bit addressing
27253 @subsection Taking advantage of 64-bit addressing
27254
27255 @menu
27256 * Making code 64 bit clean::
27257 * Allocating memory from the 64 bit storage pool::
27258 * Restrictions on use of 64 bit objects::
27259 * STARLET and other predefined libraries::
27260 @end menu
27261
27262 @node Making code 64 bit clean
27263 @subsubsection Making code 64-bit clean
27264
27265 @noindent
27266 In order to prevent problems that may occur when (parts of) a
27267 system start using memory outside the 32-bit address range,
27268 we recommend some additional guidelines:
27269
27270 @itemize @bullet
27271 @item
27272 For imported subprograms that take parameters of the
27273 type @code{System.Address}, ensure that these subprograms can
27274 indeed handle 64-bit addresses. If not, or when in doubt,
27275 change the subprogram declaration to specify
27276 @code{System.Short_Address} instead.
27277
27278 @item
27279 Resolve all warnings related to size mismatches in
27280 unchecked conversions. Failing to do so causes
27281 erroneous execution if the source object is outside
27282 the 32-bit address space.
27283
27284 @item
27285 (optional) Explicitly use the 32-bit storage pool
27286 for access types used in a 32-bit context, or use
27287 generic access types where possible
27288 (@pxref{Restrictions on use of 64 bit objects}).
27289 @end itemize
27290
27291 @noindent
27292 If these rules are followed, the compiler will automatically insert
27293 any necessary checks to ensure that no addresses or access values
27294 passed to 32-bit code ever refer to objects outside the 32-bit
27295 address range.
27296 Any attempt to do this will raise @code{Constraint_Error}.
27297
27298 @node Allocating memory from the 64 bit storage pool
27299 @subsubsection Allocating memory from the 64-bit storage pool
27300
27301 @noindent
27302 By default, all allocations -- for both pool-specific and general
27303 access types -- use the 64-bit storage pool.  To override
27304 this default, for an individual access type or globally, see
27305 @ref{Access types and 32/64-bit allocation}.
27306
27307 @node Restrictions on use of 64 bit objects
27308 @subsubsection Restrictions on use of 64-bit objects
27309
27310 @noindent
27311 Taking the address of an object allocated from a 64-bit storage pool,
27312 and then passing this address to a subprogram expecting
27313 @code{System.Short_Address},
27314 or assigning it to a variable of type @code{Short_Address}, will cause
27315 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27316 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27317 no exception is raised and execution
27318 will become erroneous.
27319
27320 @node STARLET and other predefined libraries
27321 @subsubsection STARLET and other predefined libraries
27322
27323 @noindent
27324 All code that comes as part of GNAT is 64-bit clean, but the
27325 restrictions given in @ref{Restrictions on use of 64 bit objects},
27326 still apply. Look at the package
27327 specs to see in which contexts objects allocated
27328 in 64-bit address space are acceptable.
27329
27330 @node Technical details
27331 @subsection Technical details
27332
27333 @noindent
27334 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27335 Ada standard with respect to the type of @code{System.Address}. Previous
27336 versions of @value{EDITION} have defined this type as private and implemented it as a
27337 modular type.
27338
27339 In order to allow defining @code{System.Short_Address} as a proper subtype,
27340 and to match the implicit sign extension in parameter passing,
27341 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27342 visible (i.e., non-private) integer type.
27343 Standard operations on the type, such as the binary operators ``+'', ``-'',
27344 etc., that take @code{Address} operands and return an @code{Address} result,
27345 have been hidden by declaring these
27346 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27347 ambiguities that would otherwise result from overloading.
27348 (Note that, although @code{Address} is a visible integer type,
27349 good programming practice dictates against exploiting the type's
27350 integer properties such as literals, since this will compromise
27351 code portability.)
27352
27353 Defining @code{Address} as a visible integer type helps achieve
27354 maximum compatibility for existing Ada code,
27355 without sacrificing the capabilities of the 64-bit architecture.
27356 @end ifset
27357
27358 @c ************************************************
27359 @ifset unw
27360 @node Microsoft Windows Topics
27361 @appendix Microsoft Windows Topics
27362 @cindex Windows NT
27363 @cindex Windows 95
27364 @cindex Windows 98
27365
27366 @noindent
27367 This chapter describes topics that are specific to the Microsoft Windows
27368 platforms (NT, 2000, and XP Professional).
27369
27370 @menu
27371 * Using GNAT on Windows::
27372 * Using a network installation of GNAT::
27373 * CONSOLE and WINDOWS subsystems::
27374 * Temporary Files::
27375 * Mixed-Language Programming on Windows::
27376 * Windows Calling Conventions::
27377 * Introduction to Dynamic Link Libraries (DLLs)::
27378 * Using DLLs with GNAT::
27379 * Building DLLs with GNAT Project files::
27380 * Building DLLs with GNAT::
27381 * Building DLLs with gnatdll::
27382 * GNAT and Windows Resources::
27383 * Debugging a DLL::
27384 * Setting Stack Size from gnatlink::
27385 * Setting Heap Size from gnatlink::
27386 @end menu
27387
27388 @node Using GNAT on Windows
27389 @section Using GNAT on Windows
27390
27391 @noindent
27392 One of the strengths of the GNAT technology is that its tool set
27393 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27394 @code{gdb} debugger, etc.) is used in the same way regardless of the
27395 platform.
27396
27397 On Windows this tool set is complemented by a number of Microsoft-specific
27398 tools that have been provided to facilitate interoperability with Windows
27399 when this is required. With these tools:
27400
27401 @itemize @bullet
27402
27403 @item
27404 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27405 subsystems.
27406
27407 @item
27408 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27409 relocatable and non-relocatable DLLs are supported).
27410
27411 @item
27412 You can build Ada DLLs for use in other applications. These applications
27413 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27414 relocatable and non-relocatable Ada DLLs are supported.
27415
27416 @item
27417 You can include Windows resources in your Ada application.
27418
27419 @item
27420 You can use or create COM/DCOM objects.
27421 @end itemize
27422
27423 @noindent
27424 Immediately below are listed all known general GNAT-for-Windows restrictions.
27425 Other restrictions about specific features like Windows Resources and DLLs
27426 are listed in separate sections below.
27427
27428 @itemize @bullet
27429
27430 @item
27431 It is not possible to use @code{GetLastError} and @code{SetLastError}
27432 when tasking, protected records, or exceptions are used. In these
27433 cases, in order to implement Ada semantics, the GNAT run-time system
27434 calls certain Win32 routines that set the last error variable to 0 upon
27435 success. It should be possible to use @code{GetLastError} and
27436 @code{SetLastError} when tasking, protected record, and exception
27437 features are not used, but it is not guaranteed to work.
27438
27439 @item
27440 It is not possible to link against Microsoft libraries except for
27441 import libraries. Interfacing must be done by the mean of DLLs.
27442
27443 @item
27444 When the compilation environment is located on FAT32 drives, users may
27445 experience recompilations of the source files that have not changed if
27446 Daylight Saving Time (DST) state has changed since the last time files
27447 were compiled. NTFS drives do not have this problem.
27448
27449 @item
27450 No components of the GNAT toolset use any entries in the Windows
27451 registry. The only entries that can be created are file associations and
27452 PATH settings, provided the user has chosen to create them at installation
27453 time, as well as some minimal book-keeping information needed to correctly
27454 uninstall or integrate different GNAT products.
27455 @end itemize
27456
27457 @node Using a network installation of GNAT
27458 @section Using a network installation of GNAT
27459
27460 @noindent
27461 Make sure the system on which GNAT is installed is accessible from the
27462 current machine, i.e., the install location is shared over the network.
27463 Shared resources are accessed on Windows by means of UNC paths, which
27464 have the format @code{\\server\sharename\path}
27465
27466 In order to use such a network installation, simply add the UNC path of the
27467 @file{bin} directory of your GNAT installation in front of your PATH. For
27468 example, if GNAT is installed in @file{\GNAT} directory of a share location
27469 called @file{c-drive} on a machine @file{LOKI}, the following command will
27470 make it available:
27471
27472 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27473
27474 Be aware that every compilation using the network installation results in the
27475 transfer of large amounts of data across the network and will likely cause
27476 serious performance penalty.
27477
27478 @node CONSOLE and WINDOWS subsystems
27479 @section CONSOLE and WINDOWS subsystems
27480 @cindex CONSOLE Subsystem
27481 @cindex WINDOWS Subsystem
27482 @cindex -mwindows
27483
27484 @noindent
27485 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27486 (which is the default subsystem) will always create a console when
27487 launching the application. This is not something desirable when the
27488 application has a Windows GUI. To get rid of this console the
27489 application must be using the @code{WINDOWS} subsystem. To do so
27490 the @option{-mwindows} linker option must be specified.
27491
27492 @smallexample
27493 $ gnatmake winprog -largs -mwindows
27494 @end smallexample
27495
27496 @node Temporary Files
27497 @section Temporary Files
27498 @cindex Temporary files
27499
27500 @noindent
27501 It is possible to control where temporary files gets created by setting
27502 the @env{TMP} environment variable. The file will be created:
27503
27504 @itemize
27505 @item Under the directory pointed to by the @env{TMP} environment variable if
27506 this directory exists.
27507
27508 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27509 set (or not pointing to a directory) and if this directory exists.
27510
27511 @item Under the current working directory otherwise.
27512 @end itemize
27513
27514 @noindent
27515 This allows you to determine exactly where the temporary
27516 file will be created. This is particularly useful in networked
27517 environments where you may not have write access to some
27518 directories.
27519
27520 @node Mixed-Language Programming on Windows
27521 @section Mixed-Language Programming on Windows
27522
27523 @noindent
27524 Developing pure Ada applications on Windows is no different than on
27525 other GNAT-supported platforms. However, when developing or porting an
27526 application that contains a mix of Ada and C/C++, the choice of your
27527 Windows C/C++ development environment conditions your overall
27528 interoperability strategy.
27529
27530 If you use @command{gcc} to compile the non-Ada part of your application,
27531 there are no Windows-specific restrictions that affect the overall
27532 interoperability with your Ada code. If you do want to use the
27533 Microsoft tools for your non-Ada code, you have two choices:
27534
27535 @enumerate
27536 @item
27537 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27538 application. In this case, use the Microsoft or whatever environment to
27539 build the DLL and use GNAT to build your executable
27540 (@pxref{Using DLLs with GNAT}).
27541
27542 @item
27543 Or you can encapsulate your Ada code in a DLL to be linked with the
27544 other part of your application. In this case, use GNAT to build the DLL
27545 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27546 or whatever environment to build your executable.
27547 @end enumerate
27548
27549 @node Windows Calling Conventions
27550 @section Windows Calling Conventions
27551 @findex Stdcall
27552 @findex APIENTRY
27553
27554 This section pertain only to Win32. On Win64 there is a single native
27555 calling convention. All convention specifiers are ignored on this
27556 platform.
27557
27558 @menu
27559 * C Calling Convention::
27560 * Stdcall Calling Convention::
27561 * Win32 Calling Convention::
27562 * DLL Calling Convention::
27563 @end menu
27564
27565 @noindent
27566 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27567 (callee), there are several ways to push @code{G}'s parameters on the
27568 stack and there are several possible scenarios to clean up the stack
27569 upon @code{G}'s return. A calling convention is an agreed upon software
27570 protocol whereby the responsibilities between the caller (@code{F}) and
27571 the callee (@code{G}) are clearly defined. Several calling conventions
27572 are available for Windows:
27573
27574 @itemize @bullet
27575 @item
27576 @code{C} (Microsoft defined)
27577
27578 @item
27579 @code{Stdcall} (Microsoft defined)
27580
27581 @item
27582 @code{Win32} (GNAT specific)
27583
27584 @item
27585 @code{DLL} (GNAT specific)
27586 @end itemize
27587
27588 @node C Calling Convention
27589 @subsection @code{C} Calling Convention
27590
27591 @noindent
27592 This is the default calling convention used when interfacing to C/C++
27593 routines compiled with either @command{gcc} or Microsoft Visual C++.
27594
27595 In the @code{C} calling convention subprogram parameters are pushed on the
27596 stack by the caller from right to left. The caller itself is in charge of
27597 cleaning up the stack after the call. In addition, the name of a routine
27598 with @code{C} calling convention is mangled by adding a leading underscore.
27599
27600 The name to use on the Ada side when importing (or exporting) a routine
27601 with @code{C} calling convention is the name of the routine. For
27602 instance the C function:
27603
27604 @smallexample
27605 int get_val (long);
27606 @end smallexample
27607
27608 @noindent
27609 should be imported from Ada as follows:
27610
27611 @smallexample @c ada
27612 @group
27613 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27614 pragma Import (C, Get_Val, External_Name => "get_val");
27615 @end group
27616 @end smallexample
27617
27618 @noindent
27619 Note that in this particular case the @code{External_Name} parameter could
27620 have been omitted since, when missing, this parameter is taken to be the
27621 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27622 is missing, as in the above example, this parameter is set to be the
27623 @code{External_Name} with a leading underscore.
27624
27625 When importing a variable defined in C, you should always use the @code{C}
27626 calling convention unless the object containing the variable is part of a
27627 DLL (in which case you should use the @code{Stdcall} calling
27628 convention, @pxref{Stdcall Calling Convention}).
27629
27630 @node Stdcall Calling Convention
27631 @subsection @code{Stdcall} Calling Convention
27632
27633 @noindent
27634 This convention, which was the calling convention used for Pascal
27635 programs, is used by Microsoft for all the routines in the Win32 API for
27636 efficiency reasons. It must be used to import any routine for which this
27637 convention was specified.
27638
27639 In the @code{Stdcall} calling convention subprogram parameters are pushed
27640 on the stack by the caller from right to left. The callee (and not the
27641 caller) is in charge of cleaning the stack on routine exit. In addition,
27642 the name of a routine with @code{Stdcall} calling convention is mangled by
27643 adding a leading underscore (as for the @code{C} calling convention) and a
27644 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27645 bytes) of the parameters passed to the routine.
27646
27647 The name to use on the Ada side when importing a C routine with a
27648 @code{Stdcall} calling convention is the name of the C routine. The leading
27649 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27650 the compiler. For instance the Win32 function:
27651
27652 @smallexample
27653 @b{APIENTRY} int get_val (long);
27654 @end smallexample
27655
27656 @noindent
27657 should be imported from Ada as follows:
27658
27659 @smallexample @c ada
27660 @group
27661 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27662 pragma Import (Stdcall, Get_Val);
27663 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27664 @end group
27665 @end smallexample
27666
27667 @noindent
27668 As for the @code{C} calling convention, when the @code{External_Name}
27669 parameter is missing, it is taken to be the name of the Ada entity in lower
27670 case. If instead of writing the above import pragma you write:
27671
27672 @smallexample @c ada
27673 @group
27674 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27675 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27676 @end group
27677 @end smallexample
27678
27679 @noindent
27680 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27681 of specifying the @code{External_Name} parameter you specify the
27682 @code{Link_Name} as in the following example:
27683
27684 @smallexample @c ada
27685 @group
27686 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27687 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27688 @end group
27689 @end smallexample
27690
27691 @noindent
27692 then the imported routine is @code{retrieve_val}, that is, there is no
27693 decoration at all. No leading underscore and no Stdcall suffix
27694 @code{@@}@code{@var{nn}}.
27695
27696 @noindent
27697 This is especially important as in some special cases a DLL's entry
27698 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27699 name generated for a call has it.
27700
27701 @noindent
27702 It is also possible to import variables defined in a DLL by using an
27703 import pragma for a variable. As an example, if a DLL contains a
27704 variable defined as:
27705
27706 @smallexample
27707 int my_var;
27708 @end smallexample
27709
27710 @noindent
27711 then, to access this variable from Ada you should write:
27712
27713 @smallexample @c ada
27714 @group
27715 My_Var : Interfaces.C.int;
27716 pragma Import (Stdcall, My_Var);
27717 @end group
27718 @end smallexample
27719
27720 @noindent
27721 Note that to ease building cross-platform bindings this convention
27722 will be handled as a @code{C} calling convention on non-Windows platforms.
27723
27724 @node Win32 Calling Convention
27725 @subsection @code{Win32} Calling Convention
27726
27727 @noindent
27728 This convention, which is GNAT-specific is fully equivalent to the
27729 @code{Stdcall} calling convention described above.
27730
27731 @node DLL Calling Convention
27732 @subsection @code{DLL} Calling Convention
27733
27734 @noindent
27735 This convention, which is GNAT-specific is fully equivalent to the
27736 @code{Stdcall} calling convention described above.
27737
27738 @node Introduction to Dynamic Link Libraries (DLLs)
27739 @section Introduction to Dynamic Link Libraries (DLLs)
27740 @findex DLL
27741
27742 @noindent
27743 A Dynamically Linked Library (DLL) is a library that can be shared by
27744 several applications running under Windows. A DLL can contain any number of
27745 routines and variables.
27746
27747 One advantage of DLLs is that you can change and enhance them without
27748 forcing all the applications that depend on them to be relinked or
27749 recompiled. However, you should be aware than all calls to DLL routines are
27750 slower since, as you will understand below, such calls are indirect.
27751
27752 To illustrate the remainder of this section, suppose that an application
27753 wants to use the services of a DLL @file{API.dll}. To use the services
27754 provided by @file{API.dll} you must statically link against the DLL or
27755 an import library which contains a jump table with an entry for each
27756 routine and variable exported by the DLL. In the Microsoft world this
27757 import library is called @file{API.lib}. When using GNAT this import
27758 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27759 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27760
27761 After you have linked your application with the DLL or the import library
27762 and you run your application, here is what happens:
27763
27764 @enumerate
27765 @item
27766 Your application is loaded into memory.
27767
27768 @item
27769 The DLL @file{API.dll} is mapped into the address space of your
27770 application. This means that:
27771
27772 @itemize @bullet
27773 @item
27774 The DLL will use the stack of the calling thread.
27775
27776 @item
27777 The DLL will use the virtual address space of the calling process.
27778
27779 @item
27780 The DLL will allocate memory from the virtual address space of the calling
27781 process.
27782
27783 @item
27784 Handles (pointers) can be safely exchanged between routines in the DLL
27785 routines and routines in the application using the DLL.
27786 @end itemize
27787
27788 @item
27789 The entries in the jump table (from the import library @file{libAPI.dll.a}
27790 or @file{API.lib} or automatically created when linking against a DLL)
27791 which is part of your application are initialized with the addresses
27792 of the routines and variables in @file{API.dll}.
27793
27794 @item
27795 If present in @file{API.dll}, routines @code{DllMain} or
27796 @code{DllMainCRTStartup} are invoked. These routines typically contain
27797 the initialization code needed for the well-being of the routines and
27798 variables exported by the DLL.
27799 @end enumerate
27800
27801 @noindent
27802 There is an additional point which is worth mentioning. In the Windows
27803 world there are two kind of DLLs: relocatable and non-relocatable
27804 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27805 in the target application address space. If the addresses of two
27806 non-relocatable DLLs overlap and these happen to be used by the same
27807 application, a conflict will occur and the application will run
27808 incorrectly. Hence, when possible, it is always preferable to use and
27809 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27810 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27811 User's Guide) removes the debugging symbols from the DLL but the DLL can
27812 still be relocated.
27813
27814 As a side note, an interesting difference between Microsoft DLLs and
27815 Unix shared libraries, is the fact that on most Unix systems all public
27816 routines are exported by default in a Unix shared library, while under
27817 Windows it is possible (but not required) to list exported routines in
27818 a definition file (@pxref{The Definition File}).
27819
27820 @node Using DLLs with GNAT
27821 @section Using DLLs with GNAT
27822
27823 @menu
27824 * Creating an Ada Spec for the DLL Services::
27825 * Creating an Import Library::
27826 @end menu
27827
27828 @noindent
27829 To use the services of a DLL, say @file{API.dll}, in your Ada application
27830 you must have:
27831
27832 @enumerate
27833 @item
27834 The Ada spec for the routines and/or variables you want to access in
27835 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27836 header files provided with the DLL.
27837
27838 @item
27839 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27840 mentioned an import library is a statically linked library containing the
27841 import table which will be filled at load time to point to the actual
27842 @file{API.dll} routines. Sometimes you don't have an import library for the
27843 DLL you want to use. The following sections will explain how to build
27844 one. Note that this is optional.
27845
27846 @item
27847 The actual DLL, @file{API.dll}.
27848 @end enumerate
27849
27850 @noindent
27851 Once you have all the above, to compile an Ada application that uses the
27852 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27853 you simply issue the command
27854
27855 @smallexample
27856 $ gnatmake my_ada_app -largs -lAPI
27857 @end smallexample
27858
27859 @noindent
27860 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27861 tells the GNAT linker to look for an import library. The linker will
27862 look for a library name in this specific order:
27863
27864 @enumerate
27865 @item @file{libAPI.dll.a}
27866 @item @file{API.dll.a}
27867 @item @file{libAPI.a}
27868 @item @file{API.lib}
27869 @item @file{libAPI.dll}
27870 @item @file{API.dll}
27871 @end enumerate
27872
27873 The first three are the GNU style import libraries. The third is the
27874 Microsoft style import libraries. The last two are the actual DLL names.
27875
27876 Note that if the Ada package spec for @file{API.dll} contains the
27877 following pragma
27878
27879 @smallexample @c ada
27880 pragma Linker_Options ("-lAPI");
27881 @end smallexample
27882
27883 @noindent
27884 you do not have to add @option{-largs -lAPI} at the end of the
27885 @command{gnatmake} command.
27886
27887 If any one of the items above is missing you will have to create it
27888 yourself. The following sections explain how to do so using as an
27889 example a fictitious DLL called @file{API.dll}.
27890
27891 @node Creating an Ada Spec for the DLL Services
27892 @subsection Creating an Ada Spec for the DLL Services
27893
27894 @noindent
27895 A DLL typically comes with a C/C++ header file which provides the
27896 definitions of the routines and variables exported by the DLL. The Ada
27897 equivalent of this header file is a package spec that contains definitions
27898 for the imported entities. If the DLL you intend to use does not come with
27899 an Ada spec you have to generate one such spec yourself. For example if
27900 the header file of @file{API.dll} is a file @file{api.h} containing the
27901 following two definitions:
27902
27903 @smallexample
27904 @group
27905 @cartouche
27906 int some_var;
27907 int get (char *);
27908 @end cartouche
27909 @end group
27910 @end smallexample
27911
27912 @noindent
27913 then the equivalent Ada spec could be:
27914
27915 @smallexample @c ada
27916 @group
27917 @cartouche
27918 with Interfaces.C.Strings;
27919 package API is
27920    use Interfaces;
27921
27922    Some_Var : C.int;
27923    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27924
27925 private
27926    pragma Import (C, Get);
27927    pragma Import (DLL, Some_Var);
27928 end API;
27929 @end cartouche
27930 @end group
27931 @end smallexample
27932
27933 @noindent
27934 Note that a variable is
27935 @strong{always imported with a DLL convention}. A function
27936 can have @code{C} or @code{Stdcall} convention.
27937 (@pxref{Windows Calling Conventions}).
27938
27939 @node Creating an Import Library
27940 @subsection Creating an Import Library
27941 @cindex Import library
27942
27943 @menu
27944 * The Definition File::
27945 * GNAT-Style Import Library::
27946 * Microsoft-Style Import Library::
27947 @end menu
27948
27949 @noindent
27950 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27951 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27952 with @file{API.dll} you can skip this section. You can also skip this
27953 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27954 as in this case it is possible to link directly against the
27955 DLL. Otherwise read on.
27956
27957 @node The Definition File
27958 @subsubsection The Definition File
27959 @cindex Definition file
27960 @findex .def
27961
27962 @noindent
27963 As previously mentioned, and unlike Unix systems, the list of symbols
27964 that are exported from a DLL must be provided explicitly in Windows.
27965 The main goal of a definition file is precisely that: list the symbols
27966 exported by a DLL. A definition file (usually a file with a @code{.def}
27967 suffix) has the following structure:
27968
27969 @smallexample
27970 @group
27971 @cartouche
27972 @r{[}LIBRARY @var{name}@r{]}
27973 @r{[}DESCRIPTION @var{string}@r{]}
27974 EXPORTS
27975    @var{symbol1}
27976    @var{symbol2}
27977    @dots{}
27978 @end cartouche
27979 @end group
27980 @end smallexample
27981
27982 @table @code
27983 @item LIBRARY @var{name}
27984 This section, which is optional, gives the name of the DLL.
27985
27986 @item DESCRIPTION @var{string}
27987 This section, which is optional, gives a description string that will be
27988 embedded in the import library.
27989
27990 @item EXPORTS
27991 This section gives the list of exported symbols (procedures, functions or
27992 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27993 section of @file{API.def} looks like:
27994
27995 @smallexample
27996 @group
27997 @cartouche
27998 EXPORTS
27999    some_var
28000    get
28001 @end cartouche
28002 @end group
28003 @end smallexample
28004 @end table
28005
28006 @noindent
28007 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
28008 (@pxref{Windows Calling Conventions}) for a Stdcall
28009 calling convention function in the exported symbols list.
28010
28011 @noindent
28012 There can actually be other sections in a definition file, but these
28013 sections are not relevant to the discussion at hand.
28014
28015 @node GNAT-Style Import Library
28016 @subsubsection GNAT-Style Import Library
28017
28018 @noindent
28019 To create a static import library from @file{API.dll} with the GNAT tools
28020 you should proceed as follows:
28021
28022 @enumerate
28023 @item
28024 Create the definition file @file{API.def} (@pxref{The Definition File}).
28025 For that use the @code{dll2def} tool as follows:
28026
28027 @smallexample
28028 $ dll2def API.dll > API.def
28029 @end smallexample
28030
28031 @noindent
28032 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
28033 to standard output the list of entry points in the DLL. Note that if
28034 some routines in the DLL have the @code{Stdcall} convention
28035 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
28036 suffix then you'll have to edit @file{api.def} to add it, and specify
28037 @option{-k} to @command{gnatdll} when creating the import library.
28038
28039 @noindent
28040 Here are some hints to find the right @code{@@}@var{nn} suffix.
28041
28042 @enumerate
28043 @item
28044 If you have the Microsoft import library (.lib), it is possible to get
28045 the right symbols by using Microsoft @code{dumpbin} tool (see the
28046 corresponding Microsoft documentation for further details).
28047
28048 @smallexample
28049 $ dumpbin /exports api.lib
28050 @end smallexample
28051
28052 @item
28053 If you have a message about a missing symbol at link time the compiler
28054 tells you what symbol is expected. You just have to go back to the
28055 definition file and add the right suffix.
28056 @end enumerate
28057
28058 @item
28059 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
28060 (@pxref{Using gnatdll}) as follows:
28061
28062 @smallexample
28063 $ gnatdll -e API.def -d API.dll
28064 @end smallexample
28065
28066 @noindent
28067 @code{gnatdll} takes as input a definition file @file{API.def} and the
28068 name of the DLL containing the services listed in the definition file
28069 @file{API.dll}. The name of the static import library generated is
28070 computed from the name of the definition file as follows: if the
28071 definition file name is @var{xyz}@code{.def}, the import library name will
28072 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
28073 @option{-e} could have been removed because the name of the definition
28074 file (before the ``@code{.def}'' suffix) is the same as the name of the
28075 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
28076 @end enumerate
28077
28078 @node Microsoft-Style Import Library
28079 @subsubsection Microsoft-Style Import Library
28080
28081 @noindent
28082 With GNAT you can either use a GNAT-style or Microsoft-style import
28083 library. A Microsoft import library is needed only if you plan to make an
28084 Ada DLL available to applications developed with Microsoft
28085 tools (@pxref{Mixed-Language Programming on Windows}).
28086
28087 To create a Microsoft-style import library for @file{API.dll} you
28088 should proceed as follows:
28089
28090 @enumerate
28091 @item
28092 Create the definition file @file{API.def} from the DLL. For this use either
28093 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
28094 tool (see the corresponding Microsoft documentation for further details).
28095
28096 @item
28097 Build the actual import library using Microsoft's @code{lib} utility:
28098
28099 @smallexample
28100 $ lib -machine:IX86 -def:API.def -out:API.lib
28101 @end smallexample
28102
28103 @noindent
28104 If you use the above command the definition file @file{API.def} must
28105 contain a line giving the name of the DLL:
28106
28107 @smallexample
28108 LIBRARY      "API"
28109 @end smallexample
28110
28111 @noindent
28112 See the Microsoft documentation for further details about the usage of
28113 @code{lib}.
28114 @end enumerate
28115
28116 @node Building DLLs with GNAT Project files
28117 @section Building DLLs with GNAT Project files
28118 @cindex DLLs, building
28119
28120 @noindent
28121 There is nothing specific to Windows in the build process.
28122 @pxref{Library Projects}.
28123
28124 @noindent
28125 Due to a system limitation, it is not possible under Windows to create threads
28126 when inside the @code{DllMain} routine which is used for auto-initialization
28127 of shared libraries, so it is not possible to have library level tasks in SALs.
28128
28129 @node Building DLLs with GNAT
28130 @section Building DLLs with GNAT
28131 @cindex DLLs, building
28132
28133 @noindent
28134 This section explain how to build DLLs using the GNAT built-in DLL
28135 support. With the following procedure it is straight forward to build
28136 and use DLLs with GNAT.
28137
28138 @enumerate
28139
28140 @item building object files
28141
28142 The first step is to build all objects files that are to be included
28143 into the DLL. This is done by using the standard @command{gnatmake} tool.
28144
28145 @item building the DLL
28146
28147 To build the DLL you must use @command{gcc}'s @option{-shared} and
28148 @option{-shared-libgcc} options. It is quite simple to use this method:
28149
28150 @smallexample
28151 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
28152 @end smallexample
28153
28154 It is important to note that in this case all symbols found in the
28155 object files are automatically exported. It is possible to restrict
28156 the set of symbols to export by passing to @command{gcc} a definition
28157 file, @pxref{The Definition File}. For example:
28158
28159 @smallexample
28160 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
28161 @end smallexample
28162
28163 If you use a definition file you must export the elaboration procedures
28164 for every package that required one. Elaboration procedures are named
28165 using the package name followed by "_E".
28166
28167 @item preparing DLL to be used
28168
28169 For the DLL to be used by client programs the bodies must be hidden
28170 from it and the .ali set with read-only attribute. This is very important
28171 otherwise GNAT will recompile all packages and will not actually use
28172 the code in the DLL. For example:
28173
28174 @smallexample
28175 $ mkdir apilib
28176 $ copy *.ads *.ali api.dll apilib
28177 $ attrib +R apilib\*.ali
28178 @end smallexample
28179
28180 @end enumerate
28181
28182 At this point it is possible to use the DLL by directly linking
28183 against it. Note that you must use the GNAT shared runtime when using
28184 GNAT shared libraries. This is achieved by using @option{-shared} binder's
28185 option.
28186
28187 @smallexample
28188 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
28189 @end smallexample
28190
28191 @node Building DLLs with gnatdll
28192 @section Building DLLs with gnatdll
28193 @cindex DLLs, building
28194
28195 @menu
28196 * Limitations When Using Ada DLLs from Ada::
28197 * Exporting Ada Entities::
28198 * Ada DLLs and Elaboration::
28199 * Ada DLLs and Finalization::
28200 * Creating a Spec for Ada DLLs::
28201 * Creating the Definition File::
28202 * Using gnatdll::
28203 @end menu
28204
28205 @noindent
28206 Note that it is preferred to use GNAT Project files
28207 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28208 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28209
28210 This section explains how to build DLLs containing Ada code using
28211 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28212 remainder of this section.
28213
28214 The steps required to build an Ada DLL that is to be used by Ada as well as
28215 non-Ada applications are as follows:
28216
28217 @enumerate
28218 @item
28219 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28220 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28221 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28222 skip this step if you plan to use the Ada DLL only from Ada applications.
28223
28224 @item
28225 Your Ada code must export an initialization routine which calls the routine
28226 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28227 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28228 routine exported by the Ada DLL must be invoked by the clients of the DLL
28229 to initialize the DLL.
28230
28231 @item
28232 When useful, the DLL should also export a finalization routine which calls
28233 routine @code{adafinal} generated by @command{gnatbind} to perform the
28234 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28235 The finalization routine exported by the Ada DLL must be invoked by the
28236 clients of the DLL when the DLL services are no further needed.
28237
28238 @item
28239 You must provide a spec for the services exported by the Ada DLL in each
28240 of the programming languages to which you plan to make the DLL available.
28241
28242 @item
28243 You must provide a definition file listing the exported entities
28244 (@pxref{The Definition File}).
28245
28246 @item
28247 Finally you must use @code{gnatdll} to produce the DLL and the import
28248 library (@pxref{Using gnatdll}).
28249 @end enumerate
28250
28251 @noindent
28252 Note that a relocatable DLL stripped using the @code{strip}
28253 binutils tool will not be relocatable anymore. To build a DLL without
28254 debug information pass @code{-largs -s} to @code{gnatdll}. This
28255 restriction does not apply to a DLL built using a Library Project.
28256 @pxref{Library Projects}.
28257
28258 @node Limitations When Using Ada DLLs from Ada
28259 @subsection Limitations When Using Ada DLLs from Ada
28260
28261 @noindent
28262 When using Ada DLLs from Ada applications there is a limitation users
28263 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28264 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28265 each Ada DLL includes the services of the GNAT run time that are necessary
28266 to the Ada code inside the DLL. As a result, when an Ada program uses an
28267 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28268 one in the main program.
28269
28270 It is therefore not possible to exchange GNAT run-time objects between the
28271 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28272 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28273 types, etc.
28274
28275 It is completely safe to exchange plain elementary, array or record types,
28276 Windows object handles, etc.
28277
28278 @node Exporting Ada Entities
28279 @subsection Exporting Ada Entities
28280 @cindex Export table
28281
28282 @noindent
28283 Building a DLL is a way to encapsulate a set of services usable from any
28284 application. As a result, the Ada entities exported by a DLL should be
28285 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28286 any Ada name mangling. As an example here is an Ada package
28287 @code{API}, spec and body, exporting two procedures, a function, and a
28288 variable:
28289
28290 @smallexample @c ada
28291 @group
28292 @cartouche
28293 with Interfaces.C; use Interfaces;
28294 package API is
28295    Count : C.int := 0;
28296    function Factorial (Val : C.int) return C.int;
28297
28298    procedure Initialize_API;
28299    procedure Finalize_API;
28300    --  Initialization & Finalization routines. More in the next section.
28301 private
28302    pragma Export (C, Initialize_API);
28303    pragma Export (C, Finalize_API);
28304    pragma Export (C, Count);
28305    pragma Export (C, Factorial);
28306 end API;
28307 @end cartouche
28308 @end group
28309 @end smallexample
28310
28311 @smallexample @c ada
28312 @group
28313 @cartouche
28314 package body API is
28315    function Factorial (Val : C.int) return C.int is
28316       Fact : C.int := 1;
28317    begin
28318       Count := Count + 1;
28319       for K in 1 .. Val loop
28320          Fact := Fact * K;
28321       end loop;
28322       return Fact;
28323    end Factorial;
28324
28325    procedure Initialize_API is
28326       procedure Adainit;
28327       pragma Import (C, Adainit);
28328    begin
28329       Adainit;
28330    end Initialize_API;
28331
28332    procedure Finalize_API is
28333       procedure Adafinal;
28334       pragma Import (C, Adafinal);
28335    begin
28336       Adafinal;
28337    end Finalize_API;
28338 end API;
28339 @end cartouche
28340 @end group
28341 @end smallexample
28342
28343 @noindent
28344 If the Ada DLL you are building will only be used by Ada applications
28345 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28346 convention. As an example, the previous package could be written as
28347 follows:
28348
28349 @smallexample @c ada
28350 @group
28351 @cartouche
28352 package API is
28353    Count : Integer := 0;
28354    function Factorial (Val : Integer) return Integer;
28355
28356    procedure Initialize_API;
28357    procedure Finalize_API;
28358    --  Initialization and Finalization routines.
28359 end API;
28360 @end cartouche
28361 @end group
28362 @end smallexample
28363
28364 @smallexample @c ada
28365 @group
28366 @cartouche
28367 package body API is
28368    function Factorial (Val : Integer) return Integer is
28369       Fact : Integer := 1;
28370    begin
28371       Count := Count + 1;
28372       for K in 1 .. Val loop
28373          Fact := Fact * K;
28374       end loop;
28375       return Fact;
28376    end Factorial;
28377
28378    @dots{}
28379    --  The remainder of this package body is unchanged.
28380 end API;
28381 @end cartouche
28382 @end group
28383 @end smallexample
28384
28385 @noindent
28386 Note that if you do not export the Ada entities with a @code{C} or
28387 @code{Stdcall} convention you will have to provide the mangled Ada names
28388 in the definition file of the Ada DLL
28389 (@pxref{Creating the Definition File}).
28390
28391 @node Ada DLLs and Elaboration
28392 @subsection Ada DLLs and Elaboration
28393 @cindex DLLs and elaboration
28394
28395 @noindent
28396 The DLL that you are building contains your Ada code as well as all the
28397 routines in the Ada library that are needed by it. The first thing a
28398 user of your DLL must do is elaborate the Ada code
28399 (@pxref{Elaboration Order Handling in GNAT}).
28400
28401 To achieve this you must export an initialization routine
28402 (@code{Initialize_API} in the previous example), which must be invoked
28403 before using any of the DLL services. This elaboration routine must call
28404 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28405 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28406 @code{Initialize_Api} for an example. Note that the GNAT binder is
28407 automatically invoked during the DLL build process by the @code{gnatdll}
28408 tool (@pxref{Using gnatdll}).
28409
28410 When a DLL is loaded, Windows systematically invokes a routine called
28411 @code{DllMain}. It would therefore be possible to call @code{adainit}
28412 directly from @code{DllMain} without having to provide an explicit
28413 initialization routine. Unfortunately, it is not possible to call
28414 @code{adainit} from the @code{DllMain} if your program has library level
28415 tasks because access to the @code{DllMain} entry point is serialized by
28416 the system (that is, only a single thread can execute ``through'' it at a
28417 time), which means that the GNAT run time will deadlock waiting for the
28418 newly created task to complete its initialization.
28419
28420 @node Ada DLLs and Finalization
28421 @subsection Ada DLLs and Finalization
28422 @cindex DLLs and finalization
28423
28424 @noindent
28425 When the services of an Ada DLL are no longer needed, the client code should
28426 invoke the DLL finalization routine, if available. The DLL finalization
28427 routine is in charge of releasing all resources acquired by the DLL. In the
28428 case of the Ada code contained in the DLL, this is achieved by calling
28429 routine @code{adafinal} generated by the GNAT binder
28430 (@pxref{Binding with Non-Ada Main Programs}).
28431 See the body of @code{Finalize_Api} for an
28432 example. As already pointed out the GNAT binder is automatically invoked
28433 during the DLL build process by the @code{gnatdll} tool
28434 (@pxref{Using gnatdll}).
28435
28436 @node Creating a Spec for Ada DLLs
28437 @subsection Creating a Spec for Ada DLLs
28438
28439 @noindent
28440 To use the services exported by the Ada DLL from another programming
28441 language (e.g.@: C), you have to translate the specs of the exported Ada
28442 entities in that language. For instance in the case of @code{API.dll},
28443 the corresponding C header file could look like:
28444
28445 @smallexample
28446 @group
28447 @cartouche
28448 extern int *_imp__count;
28449 #define count (*_imp__count)
28450 int factorial (int);
28451 @end cartouche
28452 @end group
28453 @end smallexample
28454
28455 @noindent
28456 It is important to understand that when building an Ada DLL to be used by
28457 other Ada applications, you need two different specs for the packages
28458 contained in the DLL: one for building the DLL and the other for using
28459 the DLL. This is because the @code{DLL} calling convention is needed to
28460 use a variable defined in a DLL, but when building the DLL, the variable
28461 must have either the @code{Ada} or @code{C} calling convention. As an
28462 example consider a DLL comprising the following package @code{API}:
28463
28464 @smallexample @c ada
28465 @group
28466 @cartouche
28467 package API is
28468    Count : Integer := 0;
28469    @dots{}
28470    --  Remainder of the package omitted.
28471 end API;
28472 @end cartouche
28473 @end group
28474 @end smallexample
28475
28476 @noindent
28477 After producing a DLL containing package @code{API}, the spec that
28478 must be used to import @code{API.Count} from Ada code outside of the
28479 DLL is:
28480
28481 @smallexample @c ada
28482 @group
28483 @cartouche
28484 package API is
28485    Count : Integer;
28486    pragma Import (DLL, Count);
28487 end API;
28488 @end cartouche
28489 @end group
28490 @end smallexample
28491
28492 @node Creating the Definition File
28493 @subsection Creating the Definition File
28494
28495 @noindent
28496 The definition file is the last file needed to build the DLL. It lists
28497 the exported symbols. As an example, the definition file for a DLL
28498 containing only package @code{API} (where all the entities are exported
28499 with a @code{C} calling convention) is:
28500
28501 @smallexample
28502 @group
28503 @cartouche
28504 EXPORTS
28505     count
28506     factorial
28507     finalize_api
28508     initialize_api
28509 @end cartouche
28510 @end group
28511 @end smallexample
28512
28513 @noindent
28514 If the @code{C} calling convention is missing from package @code{API},
28515 then the definition file contains the mangled Ada names of the above
28516 entities, which in this case are:
28517
28518 @smallexample
28519 @group
28520 @cartouche
28521 EXPORTS
28522     api__count
28523     api__factorial
28524     api__finalize_api
28525     api__initialize_api
28526 @end cartouche
28527 @end group
28528 @end smallexample
28529
28530 @node Using gnatdll
28531 @subsection Using @code{gnatdll}
28532 @findex gnatdll
28533
28534 @menu
28535 * gnatdll Example::
28536 * gnatdll behind the Scenes::
28537 * Using dlltool::
28538 @end menu
28539
28540 @noindent
28541 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28542 and non-Ada sources that make up your DLL have been compiled.
28543 @code{gnatdll} is actually in charge of two distinct tasks: build the
28544 static import library for the DLL and the actual DLL. The form of the
28545 @code{gnatdll} command is
28546
28547 @smallexample
28548 @cartouche
28549 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28550 @c Expanding @ovar macro inline (explanation in macro def comments)
28551 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28552 @end cartouche
28553 @end smallexample
28554
28555 @noindent
28556 where @var{list-of-files} is a list of ALI and object files. The object
28557 file list must be the exact list of objects corresponding to the non-Ada
28558 sources whose services are to be included in the DLL. The ALI file list
28559 must be the exact list of ALI files for the corresponding Ada sources
28560 whose services are to be included in the DLL. If @var{list-of-files} is
28561 missing, only the static import library is generated.
28562
28563 @noindent
28564 You may specify any of the following switches to @code{gnatdll}:
28565
28566 @table @code
28567 @c @item -a@ovar{address}
28568 @c Expanding @ovar macro inline (explanation in macro def comments)
28569 @item -a@r{[}@var{address}@r{]}
28570 @cindex @option{-a} (@code{gnatdll})
28571 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28572 specified the default address @var{0x11000000} will be used. By default,
28573 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28574 advise the reader to build relocatable DLL.
28575
28576 @item -b @var{address}
28577 @cindex @option{-b} (@code{gnatdll})
28578 Set the relocatable DLL base address. By default the address is
28579 @code{0x11000000}.
28580
28581 @item -bargs @var{opts}
28582 @cindex @option{-bargs} (@code{gnatdll})
28583 Binder options. Pass @var{opts} to the binder.
28584
28585 @item -d @var{dllfile}
28586 @cindex @option{-d} (@code{gnatdll})
28587 @var{dllfile} is the name of the DLL. This switch must be present for
28588 @code{gnatdll} to do anything. The name of the generated import library is
28589 obtained algorithmically from @var{dllfile} as shown in the following
28590 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28591 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28592 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28593 as shown in the following example:
28594 if @var{dllfile} is @code{xyz.dll}, the definition
28595 file used is @code{xyz.def}.
28596
28597 @item -e @var{deffile}
28598 @cindex @option{-e} (@code{gnatdll})
28599 @var{deffile} is the name of the definition file.
28600
28601 @item -g
28602 @cindex @option{-g} (@code{gnatdll})
28603 Generate debugging information. This information is stored in the object
28604 file and copied from there to the final DLL file by the linker,
28605 where it can be read by the debugger. You must use the
28606 @option{-g} switch if you plan on using the debugger or the symbolic
28607 stack traceback.
28608
28609 @item -h
28610 @cindex @option{-h} (@code{gnatdll})
28611 Help mode. Displays @code{gnatdll} switch usage information.
28612
28613 @item -Idir
28614 @cindex @option{-I} (@code{gnatdll})
28615 Direct @code{gnatdll} to search the @var{dir} directory for source and
28616 object files needed to build the DLL.
28617 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28618
28619 @item -k
28620 @cindex @option{-k} (@code{gnatdll})
28621 Removes the @code{@@}@var{nn} suffix from the import library's exported
28622 names, but keeps them for the link names. You must specify this
28623 option if you want to use a @code{Stdcall} function in a DLL for which
28624 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28625 of the Windows NT DLL for example. This option has no effect when
28626 @option{-n} option is specified.
28627
28628 @item -l @var{file}
28629 @cindex @option{-l} (@code{gnatdll})
28630 The list of ALI and object files used to build the DLL are listed in
28631 @var{file}, instead of being given in the command line. Each line in
28632 @var{file} contains the name of an ALI or object file.
28633
28634 @item -n
28635 @cindex @option{-n} (@code{gnatdll})
28636 No Import. Do not create the import library.
28637
28638 @item -q
28639 @cindex @option{-q} (@code{gnatdll})
28640 Quiet mode. Do not display unnecessary messages.
28641
28642 @item -v
28643 @cindex @option{-v} (@code{gnatdll})
28644 Verbose mode. Display extra information.
28645
28646 @item -largs @var{opts}
28647 @cindex @option{-largs} (@code{gnatdll})
28648 Linker options. Pass @var{opts} to the linker.
28649 @end table
28650
28651 @node gnatdll Example
28652 @subsubsection @code{gnatdll} Example
28653
28654 @noindent
28655 As an example the command to build a relocatable DLL from @file{api.adb}
28656 once @file{api.adb} has been compiled and @file{api.def} created is
28657
28658 @smallexample
28659 $ gnatdll -d api.dll api.ali
28660 @end smallexample
28661
28662 @noindent
28663 The above command creates two files: @file{libapi.dll.a} (the import
28664 library) and @file{api.dll} (the actual DLL). If you want to create
28665 only the DLL, just type:
28666
28667 @smallexample
28668 $ gnatdll -d api.dll -n api.ali
28669 @end smallexample
28670
28671 @noindent
28672 Alternatively if you want to create just the import library, type:
28673
28674 @smallexample
28675 $ gnatdll -d api.dll
28676 @end smallexample
28677
28678 @node gnatdll behind the Scenes
28679 @subsubsection @code{gnatdll} behind the Scenes
28680
28681 @noindent
28682 This section details the steps involved in creating a DLL. @code{gnatdll}
28683 does these steps for you. Unless you are interested in understanding what
28684 goes on behind the scenes, you should skip this section.
28685
28686 We use the previous example of a DLL containing the Ada package @code{API},
28687 to illustrate the steps necessary to build a DLL. The starting point is a
28688 set of objects that will make up the DLL and the corresponding ALI
28689 files. In the case of this example this means that @file{api.o} and
28690 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28691 the following:
28692
28693 @enumerate
28694 @item
28695 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28696 the information necessary to generate relocation information for the
28697 DLL.
28698
28699 @smallexample
28700 @group
28701 $ gnatbind -n api
28702 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28703 @end group
28704 @end smallexample
28705
28706 @noindent
28707 In addition to the base file, the @command{gnatlink} command generates an
28708 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28709 asks @command{gnatlink} to generate the routines @code{DllMain} and
28710 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28711 is loaded into memory.
28712
28713 @item
28714 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28715 export table (@file{api.exp}). The export table contains the relocation
28716 information in a form which can be used during the final link to ensure
28717 that the Windows loader is able to place the DLL anywhere in memory.
28718
28719 @smallexample
28720 @group
28721 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28722           --output-exp api.exp
28723 @end group
28724 @end smallexample
28725
28726 @item
28727 @code{gnatdll} builds the base file using the new export table. Note that
28728 @command{gnatbind} must be called once again since the binder generated file
28729 has been deleted during the previous call to @command{gnatlink}.
28730
28731 @smallexample
28732 @group
28733 $ gnatbind -n api
28734 $ gnatlink api -o api.jnk api.exp -mdll
28735       -Wl,--base-file,api.base
28736 @end group
28737 @end smallexample
28738
28739 @item
28740 @code{gnatdll} builds the new export table using the new base file and
28741 generates the DLL import library @file{libAPI.dll.a}.
28742
28743 @smallexample
28744 @group
28745 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28746           --output-exp api.exp --output-lib libAPI.a
28747 @end group
28748 @end smallexample
28749
28750 @item
28751 Finally @code{gnatdll} builds the relocatable DLL using the final export
28752 table.
28753
28754 @smallexample
28755 @group
28756 $ gnatbind -n api
28757 $ gnatlink api api.exp -o api.dll -mdll
28758 @end group
28759 @end smallexample
28760 @end enumerate
28761
28762 @node Using dlltool
28763 @subsubsection Using @code{dlltool}
28764
28765 @noindent
28766 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28767 DLLs and static import libraries. This section summarizes the most
28768 common @code{dlltool} switches. The form of the @code{dlltool} command
28769 is
28770
28771 @smallexample
28772 @c $ dlltool @ovar{switches}
28773 @c Expanding @ovar macro inline (explanation in macro def comments)
28774 $ dlltool @r{[}@var{switches}@r{]}
28775 @end smallexample
28776
28777 @noindent
28778 @code{dlltool} switches include:
28779
28780 @table @option
28781 @item --base-file @var{basefile}
28782 @cindex @option{--base-file} (@command{dlltool})
28783 Read the base file @var{basefile} generated by the linker. This switch
28784 is used to create a relocatable DLL.
28785
28786 @item --def @var{deffile}
28787 @cindex @option{--def} (@command{dlltool})
28788 Read the definition file.
28789
28790 @item --dllname @var{name}
28791 @cindex @option{--dllname} (@command{dlltool})
28792 Gives the name of the DLL. This switch is used to embed the name of the
28793 DLL in the static import library generated by @code{dlltool} with switch
28794 @option{--output-lib}.
28795
28796 @item -k
28797 @cindex @option{-k} (@command{dlltool})
28798 Kill @code{@@}@var{nn} from exported names
28799 (@pxref{Windows Calling Conventions}
28800 for a discussion about @code{Stdcall}-style symbols.
28801
28802 @item --help
28803 @cindex @option{--help} (@command{dlltool})
28804 Prints the @code{dlltool} switches with a concise description.
28805
28806 @item --output-exp @var{exportfile}
28807 @cindex @option{--output-exp} (@command{dlltool})
28808 Generate an export file @var{exportfile}. The export file contains the
28809 export table (list of symbols in the DLL) and is used to create the DLL.
28810
28811 @item --output-lib @var{libfile}
28812 @cindex @option{--output-lib} (@command{dlltool})
28813 Generate a static import library @var{libfile}.
28814
28815 @item -v
28816 @cindex @option{-v} (@command{dlltool})
28817 Verbose mode.
28818
28819 @item --as @var{assembler-name}
28820 @cindex @option{--as} (@command{dlltool})
28821 Use @var{assembler-name} as the assembler. The default is @code{as}.
28822 @end table
28823
28824 @node GNAT and Windows Resources
28825 @section GNAT and Windows Resources
28826 @cindex Resources, windows
28827
28828 @menu
28829 * Building Resources::
28830 * Compiling Resources::
28831 * Using Resources::
28832 @end menu
28833
28834 @noindent
28835 Resources are an easy way to add Windows specific objects to your
28836 application. The objects that can be added as resources include:
28837
28838 @itemize @bullet
28839 @item menus
28840
28841 @item accelerators
28842
28843 @item dialog boxes
28844
28845 @item string tables
28846
28847 @item bitmaps
28848
28849 @item cursors
28850
28851 @item icons
28852
28853 @item fonts
28854
28855 @item version information
28856 @end itemize
28857
28858 For example, a version information resource can be defined as follow and
28859 embedded into an executable or DLL:
28860
28861 A version information resource can be used to embed information into an
28862 executable or a DLL. These information can be viewed using the file properties
28863 from the Windows Explorer. Here is an example of a version information
28864 resource:
28865
28866 @smallexample
28867 @group
28868 1 VERSIONINFO
28869 FILEVERSION     1,0,0,0
28870 PRODUCTVERSION  1,0,0,0
28871 BEGIN
28872   BLOCK "StringFileInfo"
28873   BEGIN
28874     BLOCK "080904E4"
28875     BEGIN
28876       VALUE "CompanyName", "My Company Name"
28877       VALUE "FileDescription", "My application"
28878       VALUE "FileVersion", "1.0"
28879       VALUE "InternalName", "my_app"
28880       VALUE "LegalCopyright", "My Name"
28881       VALUE "OriginalFilename", "my_app.exe"
28882       VALUE "ProductName", "My App"
28883       VALUE "ProductVersion", "1.0"
28884     END
28885   END
28886
28887   BLOCK "VarFileInfo"
28888   BEGIN
28889     VALUE "Translation", 0x809, 1252
28890   END
28891 END
28892 @end group
28893 @end smallexample
28894
28895 The value @code{0809} (langID) is for the U.K English language and
28896 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28897 multilingual.
28898
28899 @noindent
28900 This section explains how to build, compile and use resources. Note that this
28901 section does not cover all resource objects, for a complete description see
28902 the corresponding Microsoft documentation.
28903
28904 @node Building Resources
28905 @subsection Building Resources
28906 @cindex Resources, building
28907
28908 @noindent
28909 A resource file is an ASCII file. By convention resource files have an
28910 @file{.rc} extension.
28911 The easiest way to build a resource file is to use Microsoft tools
28912 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28913 @code{dlgedit.exe} to build dialogs.
28914 It is always possible to build an @file{.rc} file yourself by writing a
28915 resource script.
28916
28917 It is not our objective to explain how to write a resource file. A
28918 complete description of the resource script language can be found in the
28919 Microsoft documentation.
28920
28921 @node Compiling Resources
28922 @subsection Compiling Resources
28923 @findex rc
28924 @findex windres
28925 @cindex Resources, compiling
28926
28927 @noindent
28928 This section describes how to build a GNAT-compatible (COFF) object file
28929 containing the resources. This is done using the Resource Compiler
28930 @code{windres} as follows:
28931
28932 @smallexample
28933 $ windres -i myres.rc -o myres.o
28934 @end smallexample
28935
28936 @noindent
28937 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28938 file. You can specify an alternate preprocessor (usually named
28939 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28940 parameter. A list of all possible options may be obtained by entering
28941 the command @code{windres} @option{--help}.
28942
28943 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28944 to produce a @file{.res} file (binary resource file). See the
28945 corresponding Microsoft documentation for further details. In this case
28946 you need to use @code{windres} to translate the @file{.res} file to a
28947 GNAT-compatible object file as follows:
28948
28949 @smallexample
28950 $ windres -i myres.res -o myres.o
28951 @end smallexample
28952
28953 @node Using Resources
28954 @subsection Using Resources
28955 @cindex Resources, using
28956
28957 @noindent
28958 To include the resource file in your program just add the
28959 GNAT-compatible object file for the resource(s) to the linker
28960 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28961 option:
28962
28963 @smallexample
28964 $ gnatmake myprog -largs myres.o
28965 @end smallexample
28966
28967 @node Debugging a DLL
28968 @section Debugging a DLL
28969 @cindex DLL debugging
28970
28971 @menu
28972 * Program and DLL Both Built with GCC/GNAT::
28973 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28974 @end menu
28975
28976 @noindent
28977 Debugging a DLL is similar to debugging a standard program. But
28978 we have to deal with two different executable parts: the DLL and the
28979 program that uses it. We have the following four possibilities:
28980
28981 @enumerate 1
28982 @item
28983 The program and the DLL are built with @code{GCC/GNAT}.
28984 @item
28985 The program is built with foreign tools and the DLL is built with
28986 @code{GCC/GNAT}.
28987 @item
28988 The program is built with @code{GCC/GNAT} and the DLL is built with
28989 foreign tools.
28990 @end enumerate
28991
28992 @noindent
28993 In this section we address only cases one and two above.
28994 There is no point in trying to debug
28995 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28996 information in it. To do so you must use a debugger compatible with the
28997 tools suite used to build the DLL.
28998
28999 @node Program and DLL Both Built with GCC/GNAT
29000 @subsection Program and DLL Both Built with GCC/GNAT
29001
29002 @noindent
29003 This is the simplest case. Both the DLL and the program have @code{GDB}
29004 compatible debugging information. It is then possible to break anywhere in
29005 the process. Let's suppose here that the main procedure is named
29006 @code{ada_main} and that in the DLL there is an entry point named
29007 @code{ada_dll}.
29008
29009 @noindent
29010 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
29011 program must have been built with the debugging information (see GNAT -g
29012 switch). Here are the step-by-step instructions for debugging it:
29013
29014 @enumerate 1
29015 @item Launch @code{GDB} on the main program.
29016
29017 @smallexample
29018 $ gdb -nw ada_main
29019 @end smallexample
29020
29021 @item Start the program and stop at the beginning of the main procedure
29022
29023 @smallexample
29024 (gdb) start
29025 @end smallexample
29026
29027 @noindent
29028 This step is required to be able to set a breakpoint inside the DLL. As long
29029 as the program is not run, the DLL is not loaded. This has the
29030 consequence that the DLL debugging information is also not loaded, so it is not
29031 possible to set a breakpoint in the DLL.
29032
29033 @item Set a breakpoint inside the DLL
29034
29035 @smallexample
29036 (gdb) break ada_dll
29037 (gdb) cont
29038 @end smallexample
29039
29040 @end enumerate
29041
29042 @noindent
29043 At this stage a breakpoint is set inside the DLL. From there on
29044 you can use the standard approach to debug the whole program
29045 (@pxref{Running and Debugging Ada Programs}).
29046
29047 @ignore
29048 @c This used to work, probably because the DLLs were non-relocatable
29049 @c keep this section around until the problem is sorted out.
29050
29051 To break on the @code{DllMain} routine it is not possible to follow
29052 the procedure above. At the time the program stop on @code{ada_main}
29053 the @code{DllMain} routine as already been called. Either you can use
29054 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
29055
29056 @enumerate 1
29057 @item Launch @code{GDB} on the main program.
29058
29059 @smallexample
29060 $ gdb ada_main
29061 @end smallexample
29062
29063 @item Load DLL symbols
29064
29065 @smallexample
29066 (gdb) add-sym api.dll
29067 @end smallexample
29068
29069 @item Set a breakpoint inside the DLL
29070
29071 @smallexample
29072 (gdb) break ada_dll.adb:45
29073 @end smallexample
29074
29075 Note that at this point it is not possible to break using the routine symbol
29076 directly as the program is not yet running. The solution is to break
29077 on the proper line (break in @file{ada_dll.adb} line 45).
29078
29079 @item Start the program
29080
29081 @smallexample
29082 (gdb) run
29083 @end smallexample
29084
29085 @end enumerate
29086 @end ignore
29087
29088 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
29089 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
29090
29091 @menu
29092 * Debugging the DLL Directly::
29093 * Attaching to a Running Process::
29094 @end menu
29095
29096 @noindent
29097 In this case things are slightly more complex because it is not possible to
29098 start the main program and then break at the beginning to load the DLL and the
29099 associated DLL debugging information. It is not possible to break at the
29100 beginning of the program because there is no @code{GDB} debugging information,
29101 and therefore there is no direct way of getting initial control. This
29102 section addresses this issue by describing some methods that can be used
29103 to break somewhere in the DLL to debug it.
29104
29105 @noindent
29106 First suppose that the main procedure is named @code{main} (this is for
29107 example some C code built with Microsoft Visual C) and that there is a
29108 DLL named @code{test.dll} containing an Ada entry point named
29109 @code{ada_dll}.
29110
29111 @noindent
29112 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
29113 been built with debugging information (see GNAT -g option).
29114
29115 @node Debugging the DLL Directly
29116 @subsubsection Debugging the DLL Directly
29117
29118 @enumerate 1
29119 @item
29120 Find out the executable starting address
29121
29122 @smallexample
29123 $ objdump --file-header main.exe
29124 @end smallexample
29125
29126 The starting address is reported on the last line. For example:
29127
29128 @smallexample
29129 main.exe:     file format pei-i386
29130 architecture: i386, flags 0x0000010a:
29131 EXEC_P, HAS_DEBUG, D_PAGED
29132 start address 0x00401010
29133 @end smallexample
29134
29135 @item
29136 Launch the debugger on the executable.
29137
29138 @smallexample
29139 $ gdb main.exe
29140 @end smallexample
29141
29142 @item
29143 Set a breakpoint at the starting address, and launch the program.
29144
29145 @smallexample
29146 $ (gdb) break *0x00401010
29147 $ (gdb) run
29148 @end smallexample
29149
29150 The program will stop at the given address.
29151
29152 @item
29153 Set a breakpoint on a DLL subroutine.
29154
29155 @smallexample
29156 (gdb) break ada_dll.adb:45
29157 @end smallexample
29158
29159 Or if you want to break using a symbol on the DLL, you need first to
29160 select the Ada language (language used by the DLL).
29161
29162 @smallexample
29163 (gdb) set language ada
29164 (gdb) break ada_dll
29165 @end smallexample
29166
29167 @item
29168 Continue the program.
29169
29170 @smallexample
29171 (gdb) cont
29172 @end smallexample
29173
29174 @noindent
29175 This will run the program until it reaches the breakpoint that has been
29176 set. From that point you can use the standard way to debug a program
29177 as described in (@pxref{Running and Debugging Ada Programs}).
29178
29179 @end enumerate
29180
29181 @noindent
29182 It is also possible to debug the DLL by attaching to a running process.
29183
29184 @node Attaching to a Running Process
29185 @subsubsection Attaching to a Running Process
29186 @cindex DLL debugging, attach to process
29187
29188 @noindent
29189 With @code{GDB} it is always possible to debug a running process by
29190 attaching to it. It is possible to debug a DLL this way. The limitation
29191 of this approach is that the DLL must run long enough to perform the
29192 attach operation. It may be useful for instance to insert a time wasting
29193 loop in the code of the DLL to meet this criterion.
29194
29195 @enumerate 1
29196
29197 @item Launch the main program @file{main.exe}.
29198
29199 @smallexample
29200 $ main
29201 @end smallexample
29202
29203 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29204 that the process PID for @file{main.exe} is 208.
29205
29206 @item Launch gdb.
29207
29208 @smallexample
29209 $ gdb
29210 @end smallexample
29211
29212 @item Attach to the running process to be debugged.
29213
29214 @smallexample
29215 (gdb) attach 208
29216 @end smallexample
29217
29218 @item Load the process debugging information.
29219
29220 @smallexample
29221 (gdb) symbol-file main.exe
29222 @end smallexample
29223
29224 @item Break somewhere in the DLL.
29225
29226 @smallexample
29227 (gdb) break ada_dll
29228 @end smallexample
29229
29230 @item Continue process execution.
29231
29232 @smallexample
29233 (gdb) cont
29234 @end smallexample
29235
29236 @end enumerate
29237
29238 @noindent
29239 This last step will resume the process execution, and stop at
29240 the breakpoint we have set. From there you can use the standard
29241 approach to debug a program as described in
29242 (@pxref{Running and Debugging Ada Programs}).
29243
29244 @node Setting Stack Size from gnatlink
29245 @section Setting Stack Size from @command{gnatlink}
29246
29247 @noindent
29248 It is possible to specify the program stack size at link time. On modern
29249 versions of Windows, starting with XP, this is mostly useful to set the size of
29250 the main stack (environment task). The other task stacks are set with pragma
29251 Storage_Size or with the @command{gnatbind -d} command.
29252
29253 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29254 reserve size of individual tasks, the link-time stack size applies to all
29255 tasks, and pragma Storage_Size has no effect.
29256 In particular, Stack Overflow checks are made against this
29257 link-time specified size.
29258
29259 This setting can be done with
29260 @command{gnatlink} using either:
29261
29262 @itemize @bullet
29263
29264 @item using @option{-Xlinker} linker option
29265
29266 @smallexample
29267 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29268 @end smallexample
29269
29270 This sets the stack reserve size to 0x10000 bytes and the stack commit
29271 size to 0x1000 bytes.
29272
29273 @item using @option{-Wl} linker option
29274
29275 @smallexample
29276 $ gnatlink hello -Wl,--stack=0x1000000
29277 @end smallexample
29278
29279 This sets the stack reserve size to 0x1000000 bytes. Note that with
29280 @option{-Wl} option it is not possible to set the stack commit size
29281 because the coma is a separator for this option.
29282
29283 @end itemize
29284
29285 @node Setting Heap Size from gnatlink
29286 @section Setting Heap Size from @command{gnatlink}
29287
29288 @noindent
29289 Under Windows systems, it is possible to specify the program heap size from
29290 @command{gnatlink} using either:
29291
29292 @itemize @bullet
29293
29294 @item using @option{-Xlinker} linker option
29295
29296 @smallexample
29297 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29298 @end smallexample
29299
29300 This sets the heap reserve size to 0x10000 bytes and the heap commit
29301 size to 0x1000 bytes.
29302
29303 @item using @option{-Wl} linker option
29304
29305 @smallexample
29306 $ gnatlink hello -Wl,--heap=0x1000000
29307 @end smallexample
29308
29309 This sets the heap reserve size to 0x1000000 bytes. Note that with
29310 @option{-Wl} option it is not possible to set the heap commit size
29311 because the coma is a separator for this option.
29312
29313 @end itemize
29314
29315 @end ifset
29316
29317 @c **********************************
29318 @c * GNU Free Documentation License *
29319 @c **********************************
29320 @include fdl.texi
29321 @c GNU Free Documentation License
29322
29323 @node Index,,GNU Free Documentation License, Top
29324 @unnumbered Index
29325
29326 @printindex cp
29327
29328 @contents
29329 @c Put table of contents at end, otherwise it precedes the "title page" in
29330 @c the .txt version
29331 @c Edit the pdf file to move the contents to the beginning, after the title
29332 @c page
29333
29334 @bye