OSDN Git Service

More improvements to sparc VIS vec_init code generation.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c           Copyright (C) 1992-2011, 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{-gnatwl} (elaboration warnings),
5096 @option{-gnatw.o} (warn on values set by out parameters ignored)
5097 and @option{-gnatwt} (tracking of deleted conditional code).
5098 All other optional warnings are turned on.
5099
5100 @item -gnatwA
5101 @emph{Suppress all optional errors.}
5102 @cindex @option{-gnatwA} (@command{gcc})
5103 This switch suppresses all optional warning messages, see remaining list
5104 in this section for details on optional warning messages that can be
5105 individually controlled.
5106
5107 @item -gnatw.a
5108 @emph{Activate warnings on failing assertions.}
5109 @cindex @option{-gnatw.a} (@command{gcc})
5110 @cindex Assert failures
5111 This switch activates warnings for assertions where the compiler can tell at
5112 compile time that the assertion will fail. Note that this warning is given
5113 even if assertions are disabled. The default is that such warnings are
5114 generated.
5115
5116 @item -gnatw.A
5117 @emph{Suppress warnings on failing assertions.}
5118 @cindex @option{-gnatw.A} (@command{gcc})
5119 @cindex Assert failures
5120 This switch suppresses warnings for assertions where the compiler can tell at
5121 compile time that the assertion will fail.
5122
5123 @item -gnatwb
5124 @emph{Activate warnings on bad fixed values.}
5125 @cindex @option{-gnatwb} (@command{gcc})
5126 @cindex Bad fixed values
5127 @cindex Fixed-point Small value
5128 @cindex Small value
5129 This switch activates warnings for static fixed-point expressions whose
5130 value is not an exact multiple of Small. Such values are implementation
5131 dependent, since an implementation is free to choose either of the multiples
5132 that surround the value. GNAT always chooses the closer one, but this is not
5133 required behavior, and it is better to specify a value that is an exact
5134 multiple, ensuring predictable execution. The default is that such warnings
5135 are not generated.
5136
5137 @item -gnatwB
5138 @emph{Suppress warnings on bad fixed values.}
5139 @cindex @option{-gnatwB} (@command{gcc})
5140 This switch suppresses warnings for static fixed-point expressions whose
5141 value is not an exact multiple of Small.
5142
5143 @item -gnatw.b
5144 @emph{Activate warnings on biased representation.}
5145 @cindex @option{-gnatw.b} (@command{gcc})
5146 @cindex Biased representation
5147 This switch activates warnings when a size clause, value size clause, component
5148 clause, or component size clause forces the use of biased representation for an
5149 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5150 to represent 10/11). The default is that such warnings are generated.
5151
5152 @item -gnatw.B
5153 @emph{Suppress warnings on biased representation.}
5154 @cindex @option{-gnatwB} (@command{gcc})
5155 This switch suppresses warnings for representation clauses that force the use
5156 of biased representation.
5157
5158 @item -gnatwc
5159 @emph{Activate warnings on conditionals.}
5160 @cindex @option{-gnatwc} (@command{gcc})
5161 @cindex Conditionals, constant
5162 This switch activates warnings for conditional expressions used in
5163 tests that are known to be True or False at compile time. The default
5164 is that such warnings are not generated.
5165 Note that this warning does
5166 not get issued for the use of boolean variables or constants whose
5167 values are known at compile time, since this is a standard technique
5168 for conditional compilation in Ada, and this would generate too many
5169 false positive warnings.
5170
5171 This warning option also activates a special test for comparisons using
5172 the operators ``>='' and`` <=''.
5173 If the compiler can tell that only the equality condition is possible,
5174 then it will warn that the ``>'' or ``<'' part of the test
5175 is useless and that the operator could be replaced by ``=''.
5176 An example would be comparing a @code{Natural} variable <= 0.
5177
5178 This warning option also generates warnings if
5179 one or both tests is optimized away in a membership test for integer
5180 values if the result can be determined at compile time. Range tests on
5181 enumeration types are not included, since it is common for such tests
5182 to include an end point.
5183
5184 This warning can also be turned on using @option{-gnatwa}.
5185
5186 @item -gnatwC
5187 @emph{Suppress warnings on conditionals.}
5188 @cindex @option{-gnatwC} (@command{gcc})
5189 This switch suppresses warnings for conditional expressions used in
5190 tests that are known to be True or False at compile time.
5191
5192 @item -gnatw.c
5193 @emph{Activate warnings on missing component clauses.}
5194 @cindex @option{-gnatw.c} (@command{gcc})
5195 @cindex Component clause, missing
5196 This switch activates warnings for record components where a record
5197 representation clause is present and has component clauses for the
5198 majority, but not all, of the components. A warning is given for each
5199 component for which no component clause is present.
5200
5201 This warning can also be turned on using @option{-gnatwa}.
5202
5203 @item -gnatw.C
5204 @emph{Suppress warnings on missing component clauses.}
5205 @cindex @option{-gnatwC} (@command{gcc})
5206 This switch suppresses warnings for record components that are
5207 missing a component clause in the situation described above.
5208
5209 @item -gnatwd
5210 @emph{Activate warnings on implicit dereferencing.}
5211 @cindex @option{-gnatwd} (@command{gcc})
5212 If this switch is set, then the use of a prefix of an access type
5213 in an indexed component, slice, or selected component without an
5214 explicit @code{.all} will generate a warning. With this warning
5215 enabled, access checks occur only at points where an explicit
5216 @code{.all} appears in the source code (assuming no warnings are
5217 generated as a result of this switch). The default is that such
5218 warnings are not generated.
5219 Note that @option{-gnatwa} does not affect the setting of
5220 this warning option.
5221
5222 @item -gnatwD
5223 @emph{Suppress warnings on implicit dereferencing.}
5224 @cindex @option{-gnatwD} (@command{gcc})
5225 @cindex Implicit dereferencing
5226 @cindex Dereferencing, implicit
5227 This switch suppresses warnings for implicit dereferences in
5228 indexed components, slices, and selected components.
5229
5230 @item -gnatwe
5231 @emph{Treat warnings and style checks as errors.}
5232 @cindex @option{-gnatwe} (@command{gcc})
5233 @cindex Warnings, treat as error
5234 This switch causes warning messages and style check messages to be
5235 treated as errors.
5236 The warning string still appears, but the warning messages are counted
5237 as errors, and prevent the generation of an object file. Note that this
5238 is the only -gnatw switch that affects the handling of style check messages.
5239
5240 @item -gnatw.e
5241 @emph{Activate every optional warning}
5242 @cindex @option{-gnatw.e} (@command{gcc})
5243 @cindex Warnings, activate every optional warning
5244 This switch activates all optional warnings, including those which
5245 are not activated by @code{-gnatwa}.
5246
5247 @item -gnatwf
5248 @emph{Activate warnings on unreferenced formals.}
5249 @cindex @option{-gnatwf} (@command{gcc})
5250 @cindex Formals, unreferenced
5251 This switch causes a warning to be generated if a formal parameter
5252 is not referenced in the body of the subprogram. This warning can
5253 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5254 default is that these warnings are not generated.
5255
5256 @item -gnatwF
5257 @emph{Suppress warnings on unreferenced formals.}
5258 @cindex @option{-gnatwF} (@command{gcc})
5259 This switch suppresses warnings for unreferenced formal
5260 parameters. Note that the
5261 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5262 effect of warning on unreferenced entities other than subprogram
5263 formals.
5264
5265 @item -gnatwg
5266 @emph{Activate warnings on unrecognized pragmas.}
5267 @cindex @option{-gnatwg} (@command{gcc})
5268 @cindex Pragmas, unrecognized
5269 This switch causes a warning to be generated if an unrecognized
5270 pragma is encountered. Apart from issuing this warning, the
5271 pragma is ignored and has no effect. This warning can
5272 also be turned on using @option{-gnatwa}. The default
5273 is that such warnings are issued (satisfying the Ada Reference
5274 Manual requirement that such warnings appear).
5275
5276 @item -gnatwG
5277 @emph{Suppress warnings on unrecognized pragmas.}
5278 @cindex @option{-gnatwG} (@command{gcc})
5279 This switch suppresses warnings for unrecognized pragmas.
5280
5281 @item -gnatwh
5282 @emph{Activate warnings on hiding.}
5283 @cindex @option{-gnatwh} (@command{gcc})
5284 @cindex Hiding of Declarations
5285 This switch activates warnings on hiding declarations.
5286 A declaration is considered hiding
5287 if it is for a non-overloadable entity, and it declares an entity with the
5288 same name as some other entity that is directly or use-visible. The default
5289 is that such warnings are not generated.
5290 Note that @option{-gnatwa} does not affect the setting of this warning option.
5291
5292 @item -gnatwH
5293 @emph{Suppress warnings on hiding.}
5294 @cindex @option{-gnatwH} (@command{gcc})
5295 This switch suppresses warnings on hiding declarations.
5296
5297 @item -gnatw.h
5298 @emph{Activate warnings on holes/gaps in records.}
5299 @cindex @option{-gnatw.h} (@command{gcc})
5300 @cindex Record Representation (gaps)
5301 This switch activates warnings on component clauses in record
5302 representation clauses that leave holes (gaps) in the record layout.
5303 If this warning option is active, then record representation clauses
5304 should specify a contiguous layout, adding unused fill fields if needed.
5305 Note that @option{-gnatwa} does not affect the setting of this warning option.
5306
5307 @item -gnatw.H
5308 @emph{Suppress warnings on holes/gaps in records.}
5309 @cindex @option{-gnatw.H} (@command{gcc})
5310 This switch suppresses warnings on component clauses in record
5311 representation clauses that leave holes (haps) in the record layout.
5312
5313 @item -gnatwi
5314 @emph{Activate warnings on implementation units.}
5315 @cindex @option{-gnatwi} (@command{gcc})
5316 This switch activates warnings for a @code{with} of an internal GNAT
5317 implementation unit, defined as any unit from the @code{Ada},
5318 @code{Interfaces}, @code{GNAT},
5319 ^^@code{DEC},^ or @code{System}
5320 hierarchies that is not
5321 documented in either the Ada Reference Manual or the GNAT
5322 Programmer's Reference Manual. Such units are intended only
5323 for internal implementation purposes and should not be @code{with}'ed
5324 by user programs. The default is that such warnings are generated
5325 This warning can also be turned on using @option{-gnatwa}.
5326
5327 @item -gnatwI
5328 @emph{Disable warnings on implementation units.}
5329 @cindex @option{-gnatwI} (@command{gcc})
5330 This switch disables warnings for a @code{with} of an internal GNAT
5331 implementation unit.
5332
5333 @item -gnatw.i
5334 @emph{Activate warnings on overlapping actuals.}
5335 @cindex @option{-gnatw.i} (@command{gcc})
5336 This switch enables a warning on statically detectable overlapping actuals in
5337 a subprogram call, when one of the actuals is an in-out parameter, and the
5338 types of the actuals are not by-copy types. The warning is off by default,
5339 and is not included under -gnatwa.
5340
5341 @item -gnatw.I
5342 @emph{Disable warnings on overlapping actuals.}
5343 @cindex @option{-gnatw.I} (@command{gcc})
5344 This switch disables warnings on overlapping actuals in a call..
5345
5346 @item -gnatwj
5347 @emph{Activate warnings on obsolescent features (Annex J).}
5348 @cindex @option{-gnatwj} (@command{gcc})
5349 @cindex Features, obsolescent
5350 @cindex Obsolescent features
5351 If this warning option is activated, then warnings are generated for
5352 calls to subprograms marked with @code{pragma Obsolescent} and
5353 for use of features in Annex J of the Ada Reference Manual. In the
5354 case of Annex J, not all features are flagged. In particular use
5355 of the renamed packages (like @code{Text_IO}) and use of package
5356 @code{ASCII} are not flagged, since these are very common and
5357 would generate many annoying positive warnings. The default is that
5358 such warnings are not generated. This warning is also turned on by
5359 the use of @option{-gnatwa}.
5360
5361 In addition to the above cases, warnings are also generated for
5362 GNAT features that have been provided in past versions but which
5363 have been superseded (typically by features in the new Ada standard).
5364 For example, @code{pragma Ravenscar} will be flagged since its
5365 function is replaced by @code{pragma Profile(Ravenscar)}.
5366
5367 Note that this warning option functions differently from the
5368 restriction @code{No_Obsolescent_Features} in two respects.
5369 First, the restriction applies only to annex J features.
5370 Second, the restriction does flag uses of package @code{ASCII}.
5371
5372 @item -gnatwJ
5373 @emph{Suppress warnings on obsolescent features (Annex J).}
5374 @cindex @option{-gnatwJ} (@command{gcc})
5375 This switch disables warnings on use of obsolescent features.
5376
5377 @item -gnatwk
5378 @emph{Activate warnings on variables that could be constants.}
5379 @cindex @option{-gnatwk} (@command{gcc})
5380 This switch activates warnings for variables that are initialized but
5381 never modified, and then could be declared constants. The default is that
5382 such warnings are not given.
5383 This warning can also be turned on using @option{-gnatwa}.
5384
5385 @item -gnatwK
5386 @emph{Suppress warnings on variables that could be constants.}
5387 @cindex @option{-gnatwK} (@command{gcc})
5388 This switch disables warnings on variables that could be declared constants.
5389
5390 @item -gnatwl
5391 @emph{Activate warnings for elaboration pragmas.}
5392 @cindex @option{-gnatwl} (@command{gcc})
5393 @cindex Elaboration, warnings
5394 This switch activates warnings on missing
5395 @code{Elaborate_All} and @code{Elaborate} pragmas.
5396 See the section in this guide on elaboration checking for details on
5397 when such pragmas should be used. In dynamic elaboration mode, this switch
5398 generations warnings about the need to add elaboration pragmas. Note however,
5399 that if you blindly follow these warnings, and add @code{Elaborate_All}
5400 warnings wherever they are recommended, you basically end up with the
5401 equivalent of the static elaboration model, which may not be what you want for
5402 legacy code for which the static model does not work.
5403
5404 For the static model, the messages generated are labeled "info:" (for
5405 information messages). They are not warnings to add elaboration pragmas,
5406 merely informational messages showing what implicit elaboration pragmas
5407 have been added, for use in analyzing elaboration circularity problems.
5408
5409 Warnings are also generated if you
5410 are using the static mode of elaboration, and a @code{pragma Elaborate}
5411 is encountered. The default is that such warnings
5412 are not generated.
5413 This warning is not automatically turned on by the use of @option{-gnatwa}.
5414
5415 @item -gnatwL
5416 @emph{Suppress warnings for elaboration pragmas.}
5417 @cindex @option{-gnatwL} (@command{gcc})
5418 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5419 See the section in this guide on elaboration checking for details on
5420 when such pragmas should be used.
5421
5422 @item -gnatwm
5423 @emph{Activate warnings on modified but unreferenced variables.}
5424 @cindex @option{-gnatwm} (@command{gcc})
5425 This switch activates warnings for variables that are assigned (using
5426 an initialization value or with one or more assignment statements) but
5427 whose value is never read. The warning is suppressed for volatile
5428 variables and also for variables that are renamings of other variables
5429 or for which an address clause is given.
5430 This warning can also be turned on using @option{-gnatwa}.
5431 The default is that these warnings are not given.
5432
5433 @item -gnatwM
5434 @emph{Disable warnings on modified but unreferenced variables.}
5435 @cindex @option{-gnatwM} (@command{gcc})
5436 This switch disables warnings for variables that are assigned or
5437 initialized, but never read.
5438
5439 @item -gnatw.m
5440 @emph{Activate warnings on suspicious modulus values.}
5441 @cindex @option{-gnatw.m} (@command{gcc})
5442 This switch activates warnings for modulus values that seem suspicious.
5443 The cases caught are where the size is the same as the modulus (e.g.
5444 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5445 with no size clause. The guess in both cases is that 2**x was intended
5446 rather than x. The default is that these warnings are given.
5447
5448 @item -gnatw.M
5449 @emph{Disable warnings on suspicious modulus values.}
5450 @cindex @option{-gnatw.M} (@command{gcc})
5451 This switch disables warnings for suspicious modulus values.
5452
5453 @item -gnatwn
5454 @emph{Set normal warnings mode.}
5455 @cindex @option{-gnatwn} (@command{gcc})
5456 This switch sets normal warning mode, in which enabled warnings are
5457 issued and treated as warnings rather than errors. This is the default
5458 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5459 an explicit @option{-gnatws} or
5460 @option{-gnatwe}. It also cancels the effect of the
5461 implicit @option{-gnatwe} that is activated by the
5462 use of @option{-gnatg}.
5463
5464 @item -gnatwo
5465 @emph{Activate warnings on address clause overlays.}
5466 @cindex @option{-gnatwo} (@command{gcc})
5467 @cindex Address Clauses, warnings
5468 This switch activates warnings for possibly unintended initialization
5469 effects of defining address clauses that cause one variable to overlap
5470 another. The default is that such warnings are generated.
5471 This warning can also be turned on using @option{-gnatwa}.
5472
5473 @item -gnatwO
5474 @emph{Suppress warnings on address clause overlays.}
5475 @cindex @option{-gnatwO} (@command{gcc})
5476 This switch suppresses warnings on possibly unintended initialization
5477 effects of defining address clauses that cause one variable to overlap
5478 another.
5479
5480 @item -gnatw.o
5481 @emph{Activate warnings on modified but unreferenced out parameters.}
5482 @cindex @option{-gnatw.o} (@command{gcc})
5483 This switch activates warnings for variables that are modified by using
5484 them as actuals for a call to a procedure with an out mode formal, where
5485 the resulting assigned value is never read. It is applicable in the case
5486 where there is more than one out mode formal. If there is only one out
5487 mode formal, the warning is issued by default (controlled by -gnatwu).
5488 The warning is suppressed for volatile
5489 variables and also for variables that are renamings of other variables
5490 or for which an address clause is given.
5491 The default is that these warnings are not given. Note that this warning
5492 is not included in -gnatwa, it must be activated explicitly.
5493
5494 @item -gnatw.O
5495 @emph{Disable warnings on modified but unreferenced out parameters.}
5496 @cindex @option{-gnatw.O} (@command{gcc})
5497 This switch suppresses warnings for variables that are modified by using
5498 them as actuals for a call to a procedure with an out mode formal, where
5499 the resulting assigned value is never read.
5500
5501 @item -gnatwp
5502 @emph{Activate warnings on ineffective pragma Inlines.}
5503 @cindex @option{-gnatwp} (@command{gcc})
5504 @cindex Inlining, warnings
5505 This switch activates warnings for failure of front end inlining
5506 (activated by @option{-gnatN}) to inline a particular call. There are
5507 many reasons for not being able to inline a call, including most
5508 commonly that the call is too complex to inline. The default is
5509 that such warnings are not given.
5510 This warning can also be turned on using @option{-gnatwa}.
5511 Warnings on ineffective inlining by the gcc back-end can be activated
5512 separately, using the gcc switch -Winline.
5513
5514 @item -gnatwP
5515 @emph{Suppress warnings on ineffective pragma Inlines.}
5516 @cindex @option{-gnatwP} (@command{gcc})
5517 This switch suppresses warnings on ineffective pragma Inlines. If the
5518 inlining mechanism cannot inline a call, it will simply ignore the
5519 request silently.
5520
5521 @item -gnatw.p
5522 @emph{Activate warnings on parameter ordering.}
5523 @cindex @option{-gnatw.p} (@command{gcc})
5524 @cindex Parameter order, warnings
5525 This switch activates warnings for cases of suspicious parameter
5526 ordering when the list of arguments are all simple identifiers that
5527 match the names of the formals, but are in a different order. The
5528 warning is suppressed if any use of named parameter notation is used,
5529 so this is the appropriate way to suppress a false positive (and
5530 serves to emphasize that the "misordering" is deliberate). The
5531 default is
5532 that such warnings are not given.
5533 This warning can also be turned on using @option{-gnatwa}.
5534
5535 @item -gnatw.P
5536 @emph{Suppress warnings on parameter ordering.}
5537 @cindex @option{-gnatw.P} (@command{gcc})
5538 This switch suppresses warnings on cases of suspicious parameter
5539 ordering.
5540
5541 @item -gnatwq
5542 @emph{Activate warnings on questionable missing parentheses.}
5543 @cindex @option{-gnatwq} (@command{gcc})
5544 @cindex Parentheses, warnings
5545 This switch activates warnings for cases where parentheses are not used and
5546 the result is potential ambiguity from a readers point of view. For example
5547 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5548 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5549 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5550 follow the rule of always parenthesizing to make the association clear, and
5551 this warning switch warns if such parentheses are not present. The default
5552 is that these warnings are given.
5553 This warning can also be turned on using @option{-gnatwa}.
5554
5555 @item -gnatwQ
5556 @emph{Suppress warnings on questionable missing parentheses.}
5557 @cindex @option{-gnatwQ} (@command{gcc})
5558 This switch suppresses warnings for cases where the association is not
5559 clear and the use of parentheses is preferred.
5560
5561 @item -gnatwr
5562 @emph{Activate warnings on redundant constructs.}
5563 @cindex @option{-gnatwr} (@command{gcc})
5564 This switch activates warnings for redundant constructs. The following
5565 is the current list of constructs regarded as redundant:
5566
5567 @itemize @bullet
5568 @item
5569 Assignment of an item to itself.
5570 @item
5571 Type conversion that converts an expression to its own type.
5572 @item
5573 Use of the attribute @code{Base} where @code{typ'Base} is the same
5574 as @code{typ}.
5575 @item
5576 Use of pragma @code{Pack} when all components are placed by a record
5577 representation clause.
5578 @item
5579 Exception handler containing only a reraise statement (raise with no
5580 operand) which has no effect.
5581 @item
5582 Use of the operator abs on an operand that is known at compile time
5583 to be non-negative
5584 @item
5585 Comparison of boolean expressions to an explicit True value.
5586 @end itemize
5587
5588 This warning can also be turned on using @option{-gnatwa}.
5589 The default is that warnings for redundant constructs are not given.
5590
5591 @item -gnatwR
5592 @emph{Suppress warnings on redundant constructs.}
5593 @cindex @option{-gnatwR} (@command{gcc})
5594 This switch suppresses warnings for redundant constructs.
5595
5596 @item -gnatw.r
5597 @emph{Activate warnings for object renaming function.}
5598 @cindex @option{-gnatw.r} (@command{gcc})
5599 This switch activates warnings for an object renaming that renames a
5600 function call, which is equivalent to a constant declaration (as
5601 opposed to renaming the function itself).  The default is that these
5602 warnings are given.  This warning can also be turned on using
5603 @option{-gnatwa}.
5604
5605 @item -gnatw.R
5606 @emph{Suppress warnings for object renaming function.}
5607 @cindex @option{-gnatwT} (@command{gcc})
5608 This switch suppresses warnings for object renaming function.
5609
5610 @item -gnatws
5611 @emph{Suppress all warnings.}
5612 @cindex @option{-gnatws} (@command{gcc})
5613 This switch completely suppresses the
5614 output of all warning messages from the GNAT front end.
5615 Note that it does not suppress warnings from the @command{gcc} back end.
5616 To suppress these back end warnings as well, use the switch @option{-w}
5617 in addition to @option{-gnatws}. Also this switch has no effect on the
5618 handling of style check messages.
5619
5620 @item -gnatw.s
5621 @emph{Activate warnings on overridden size clauses.}
5622 @cindex @option{-gnatw.s} (@command{gcc})
5623 @cindex Record Representation (component sizes)
5624 This switch activates warnings on component clauses in record
5625 representation clauses where the length given overrides that
5626 specified by an explicit size clause for the component type. A
5627 warning is similarly given in the array case if a specified
5628 component size overrides an explicit size clause for the array
5629 component type.
5630 Note that @option{-gnatwa} does not affect the setting of this warning option.
5631
5632 @item -gnatw.S
5633 @emph{Suppress warnings on overridden size clauses.}
5634 @cindex @option{-gnatw.S} (@command{gcc})
5635 This switch suppresses warnings on component clauses in record
5636 representation clauses that override size clauses, and similar
5637 warnings when an array component size overrides a size clause.
5638
5639 @item -gnatwt
5640 @emph{Activate warnings for tracking of deleted conditional code.}
5641 @cindex @option{-gnatwt} (@command{gcc})
5642 @cindex Deactivated code, warnings
5643 @cindex Deleted code, warnings
5644 This switch activates warnings for tracking of code in conditionals (IF and
5645 CASE statements) that is detected to be dead code which cannot be executed, and
5646 which is removed by the front end. This warning is off by default, and is not
5647 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5648 useful for detecting deactivated code in certified applications.
5649
5650 @item -gnatwT
5651 @emph{Suppress warnings for tracking of deleted conditional code.}
5652 @cindex @option{-gnatwT} (@command{gcc})
5653 This switch suppresses warnings for tracking of deleted conditional code.
5654
5655 @item -gnatwu
5656 @emph{Activate warnings on unused entities.}
5657 @cindex @option{-gnatwu} (@command{gcc})
5658 This switch activates warnings to be generated for entities that
5659 are declared but not referenced, and for units that are @code{with}'ed
5660 and not
5661 referenced. In the case of packages, a warning is also generated if
5662 no entities in the package are referenced. This means that if a with'ed
5663 package is referenced but the only references are in @code{use}
5664 clauses or @code{renames}
5665 declarations, a warning is still generated. A warning is also generated
5666 for a generic package that is @code{with}'ed but never instantiated.
5667 In the case where a package or subprogram body is compiled, and there
5668 is a @code{with} on the corresponding spec
5669 that is only referenced in the body,
5670 a warning is also generated, noting that the
5671 @code{with} can be moved to the body. The default is that
5672 such warnings are not generated.
5673 This switch also activates warnings on unreferenced formals
5674 (it includes the effect of @option{-gnatwf}).
5675 This warning can also be turned on using @option{-gnatwa}.
5676
5677 @item -gnatwU
5678 @emph{Suppress warnings on unused entities.}
5679 @cindex @option{-gnatwU} (@command{gcc})
5680 This switch suppresses warnings for unused entities and packages.
5681 It also turns off warnings on unreferenced formals (and thus includes
5682 the effect of @option{-gnatwF}).
5683
5684 @item -gnatw.u
5685 @emph{Activate warnings on unordered enumeration types.}
5686 @cindex @option{-gnatw.u} (@command{gcc})
5687 This switch causes enumeration types to be considered as conceptually
5688 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5689 The effect is to generate warnings in clients that use explicit comparisons
5690 or subranges, since these constructs both treat objects of the type as
5691 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5692 which the type is declared, or its body or subunits.) Please refer to
5693 the description of pragma @code{Ordered} in the
5694 @cite{@value{EDITION} Reference Manual} for further details.
5695
5696 @item -gnatw.U
5697 @emph{Deactivate warnings on unordered enumeration types.}
5698 @cindex @option{-gnatw.U} (@command{gcc})
5699 This switch causes all enumeration types to be considered as ordered, so
5700 that no warnings are given for comparisons or subranges for any type.
5701
5702 @item -gnatwv
5703 @emph{Activate warnings on unassigned variables.}
5704 @cindex @option{-gnatwv} (@command{gcc})
5705 @cindex Unassigned variable warnings
5706 This switch activates warnings for access to variables which
5707 may not be properly initialized. The default is that
5708 such warnings are generated.
5709 This warning can also be turned on using @option{-gnatwa}.
5710
5711 @item -gnatwV
5712 @emph{Suppress warnings on unassigned variables.}
5713 @cindex @option{-gnatwV} (@command{gcc})
5714 This switch suppresses warnings for access to variables which
5715 may not be properly initialized.
5716 For variables of a composite type, the warning can also be suppressed in
5717 Ada 2005 by using a default initialization with a box. For example, if
5718 Table is an array of records whose components are only partially uninitialized,
5719 then the following code:
5720
5721 @smallexample @c ada
5722    Tab : Table := (others => <>);
5723 @end smallexample
5724
5725 will suppress warnings on subsequent statements that access components
5726 of variable Tab.
5727
5728 @item -gnatww
5729 @emph{Activate warnings on wrong low bound assumption.}
5730 @cindex @option{-gnatww} (@command{gcc})
5731 @cindex String indexing warnings
5732 This switch activates warnings for indexing an unconstrained string parameter
5733 with a literal or S'Length. This is a case where the code is assuming that the
5734 low bound is one, which is in general not true (for example when a slice is
5735 passed). The default is that such warnings are generated.
5736 This warning can also be turned on using @option{-gnatwa}.
5737
5738 @item -gnatwW
5739 @emph{Suppress warnings on wrong low bound assumption.}
5740 @cindex @option{-gnatwW} (@command{gcc})
5741 This switch suppresses warnings for indexing an unconstrained string parameter
5742 with a literal or S'Length. Note that this warning can also be suppressed
5743 in a particular case by adding an
5744 assertion that the lower bound is 1,
5745 as shown in the following example.
5746
5747 @smallexample @c ada
5748    procedure K (S : String) is
5749       pragma Assert (S'First = 1);
5750       @dots{}
5751 @end smallexample
5752
5753 @item -gnatw.w
5754 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5755 @cindex @option{-gnatw.w} (@command{gcc})
5756 @cindex Warnings Off control
5757 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5758 where either the pragma is entirely useless (because it suppresses no
5759 warnings), or it could be replaced by @code{pragma Unreferenced} or
5760 @code{pragma Unmodified}. The default is that these warnings are not given.
5761 Note that this warning is not included in -gnatwa, it must be
5762 activated explicitly.
5763
5764 @item -gnatw.W
5765 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5766 @cindex @option{-gnatw.W} (@command{gcc})
5767 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5768
5769 @item -gnatwx
5770 @emph{Activate warnings on Export/Import pragmas.}
5771 @cindex @option{-gnatwx} (@command{gcc})
5772 @cindex Export/Import pragma warnings
5773 This switch activates warnings on Export/Import pragmas when
5774 the compiler detects a possible conflict between the Ada and
5775 foreign language calling sequences. For example, the use of
5776 default parameters in a convention C procedure is dubious
5777 because the C compiler cannot supply the proper default, so
5778 a warning is issued. The default is that such warnings are
5779 generated.
5780 This warning can also be turned on using @option{-gnatwa}.
5781
5782 @item -gnatwX
5783 @emph{Suppress warnings on Export/Import pragmas.}
5784 @cindex @option{-gnatwX} (@command{gcc})
5785 This switch suppresses warnings on Export/Import pragmas.
5786 The sense of this is that you are telling the compiler that
5787 you know what you are doing in writing the pragma, and it
5788 should not complain at you.
5789
5790 @item -gnatw.x
5791 @emph{Activate warnings for No_Exception_Propagation mode.}
5792 @cindex @option{-gnatwm} (@command{gcc})
5793 This switch activates warnings for exception usage when pragma Restrictions
5794 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5795 explicit exception raises which are not covered by a local handler, and for
5796 exception handlers which do not cover a local raise. The default is that these
5797 warnings are not given.
5798
5799 @item -gnatw.X
5800 @emph{Disable warnings for No_Exception_Propagation mode.}
5801 This switch disables warnings for exception usage when pragma Restrictions
5802 (No_Exception_Propagation) is in effect.
5803
5804 @item -gnatwy
5805 @emph{Activate warnings for Ada compatibility issues.}
5806 @cindex @option{-gnatwy} (@command{gcc})
5807 @cindex Ada compatibility issues warnings
5808 For the most part, newer versions of Ada are upwards compatible
5809 with older versions. For example, Ada 2005 programs will almost
5810 always work when compiled as Ada 2012.
5811 However there are some exceptions (for example the fact that
5812 @code{some} is now a reserved word in Ada 2012). This
5813 switch activates several warnings to help in identifying
5814 and correcting such incompatibilities. The default is that
5815 these warnings are generated. Note that at one point Ada 2005
5816 was called Ada 0Y, hence the choice of character.
5817 This warning can also be turned on using @option{-gnatwa}.
5818
5819 @item -gnatwY
5820 @emph{Disable warnings for Ada compatibility issues.}
5821 @cindex @option{-gnatwY} (@command{gcc})
5822 @cindex Ada compatibility issues warnings
5823 This switch suppresses the warnings intended to help in identifying
5824 incompatibilities between Ada language versions.
5825
5826 @item -gnatwz
5827 @emph{Activate warnings on unchecked conversions.}
5828 @cindex @option{-gnatwz} (@command{gcc})
5829 @cindex Unchecked_Conversion warnings
5830 This switch activates warnings for unchecked conversions
5831 where the types are known at compile time to have different
5832 sizes. The default
5833 is that such warnings are generated. Warnings are also
5834 generated for subprogram pointers with different conventions,
5835 and, on VMS only, for data pointers with different conventions.
5836 This warning can also be turned on using @option{-gnatwa}.
5837
5838 @item -gnatwZ
5839 @emph{Suppress warnings on unchecked conversions.}
5840 @cindex @option{-gnatwZ} (@command{gcc})
5841 This switch suppresses warnings for unchecked conversions
5842 where the types are known at compile time to have different
5843 sizes or conventions.
5844
5845 @item ^-Wunused^WARNINGS=UNUSED^
5846 @cindex @option{-Wunused}
5847 The warnings controlled by the @option{-gnatw} switch are generated by
5848 the front end of the compiler. The @option{GCC} back end can provide
5849 additional warnings and they are controlled by the @option{-W} switch.
5850 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5851 warnings for entities that are declared but not referenced.
5852
5853 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5854 @cindex @option{-Wuninitialized}
5855 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5856 the back end warning for uninitialized variables. This switch must be
5857 used in conjunction with an optimization level greater than zero.
5858
5859 @item -Wstack-usage=@var{len}
5860 @cindex @option{-Wstack-usage}
5861 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5862 See @ref{Static Stack Usage Analysis} for details.
5863
5864 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5865 @cindex @option{-Wall}
5866 This switch enables most warnings from the @option{GCC} back end.
5867 The code generator detects a number of warning situations that are missed
5868 by the @option{GNAT} front end, and this switch can be used to activate them.
5869 The use of this switch also sets the default front end warning mode to
5870 @option{-gnatwa}, that is, most front end warnings activated as well.
5871
5872 @item ^-w^/NO_BACK_END_WARNINGS^
5873 @cindex @option{-w}
5874 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5875 The use of this switch also sets the default front end warning mode to
5876 @option{-gnatws}, that is, front end warnings suppressed as well.
5877
5878 @end table
5879
5880 @noindent
5881 @ifclear vms
5882 A string of warning parameters can be used in the same parameter. For example:
5883
5884 @smallexample
5885 -gnatwaLe
5886 @end smallexample
5887
5888 @noindent
5889 will turn on all optional warnings except for elaboration pragma warnings,
5890 and also specify that warnings should be treated as errors.
5891 @end ifclear
5892 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5893
5894 @table @option
5895 @c !sort!
5896 @item -gnatwC
5897 @item -gnatwD
5898 @item -gnatwF
5899 @item -gnatwg
5900 @item -gnatwH
5901 @item -gnatwi
5902 @item -gnatwJ
5903 @item -gnatwK
5904 @item -gnatwL
5905 @item -gnatwM
5906 @item -gnatwn
5907 @item -gnatwo
5908 @item -gnatwP
5909 @item -gnatwR
5910 @item -gnatwU
5911 @item -gnatwv
5912 @item -gnatwz
5913 @item -gnatwx
5914
5915 @end table
5916
5917 @node Debugging and Assertion Control
5918 @subsection Debugging and Assertion Control
5919
5920 @table @option
5921 @item -gnata
5922 @cindex @option{-gnata} (@command{gcc})
5923 @findex Assert
5924 @findex Debug
5925 @cindex Assertions
5926
5927 @noindent
5928 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5929 are ignored. This switch, where @samp{a} stands for assert, causes
5930 @code{Assert} and @code{Debug} pragmas to be activated.
5931
5932 The pragmas have the form:
5933
5934 @smallexample
5935 @cartouche
5936    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5937                       @var{static-string-expression}@r{]})
5938    @b{pragma} Debug (@var{procedure call})
5939 @end cartouche
5940 @end smallexample
5941
5942 @noindent
5943 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5944 If the result is @code{True}, the pragma has no effect (other than
5945 possible side effects from evaluating the expression). If the result is
5946 @code{False}, the exception @code{Assert_Failure} declared in the package
5947 @code{System.Assertions} is
5948 raised (passing @var{static-string-expression}, if present, as the
5949 message associated with the exception). If no string expression is
5950 given the default is a string giving the file name and line number
5951 of the pragma.
5952
5953 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5954 @code{pragma Debug} may appear within a declaration sequence, allowing
5955 debugging procedures to be called between declarations.
5956
5957 @ifset vms
5958 @item /DEBUG@r{[}=debug-level@r{]}
5959 @itemx  /NODEBUG
5960 Specifies how much debugging information is to be included in
5961 the resulting object file where 'debug-level' is one of the following:
5962 @table @code
5963 @item   TRACEBACK
5964 Include both debugger symbol records and traceback
5965 the object file.
5966 This is the default setting.
5967 @item   ALL
5968 Include both debugger symbol records and traceback in
5969 object file.
5970 @item   NONE
5971 Excludes both debugger symbol records and traceback
5972 the object file. Same as /NODEBUG.
5973 @item   SYMBOLS
5974 Includes only debugger symbol records in the object
5975 file. Note that this doesn't include traceback information.
5976 @end table
5977 @end ifset
5978 @end table
5979
5980 @node Validity Checking
5981 @subsection Validity Checking
5982 @findex Validity Checking
5983
5984 @noindent
5985 The Ada Reference Manual defines the concept of invalid values (see
5986 RM 13.9.1). The primary source of invalid values is uninitialized
5987 variables. A scalar variable that is left uninitialized may contain
5988 an invalid value; the concept of invalid does not apply to access or
5989 composite types.
5990
5991 It is an error to read an invalid value, but the RM does not require
5992 run-time checks to detect such errors, except for some minimal
5993 checking to prevent erroneous execution (i.e. unpredictable
5994 behavior). This corresponds to the @option{-gnatVd} switch below,
5995 which is the default. For example, by default, if the expression of a
5996 case statement is invalid, it will raise Constraint_Error rather than
5997 causing a wild jump, and if an array index on the left-hand side of an
5998 assignment is invalid, it will raise Constraint_Error rather than
5999 overwriting an arbitrary memory location.
6000
6001 The @option{-gnatVa} may be used to enable additional validity checks,
6002 which are not required by the RM. These checks are often very
6003 expensive (which is why the RM does not require them). These checks
6004 are useful in tracking down uninitialized variables, but they are
6005 not usually recommended for production builds.
6006
6007 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6008 control; you can enable whichever validity checks you desire. However,
6009 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6010 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6011 sufficient for non-debugging use.
6012
6013 The @option{-gnatB} switch tells the compiler to assume that all
6014 values are valid (that is, within their declared subtype range)
6015 except in the context of a use of the Valid attribute. This means
6016 the compiler can generate more efficient code, since the range
6017 of values is better known at compile time. However, an uninitialized
6018 variable can cause wild jumps and memory corruption in this mode.
6019
6020 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6021 checking mode as described below.
6022 @ifclear vms
6023 The @code{x} argument is a string of letters that
6024 indicate validity checks that are performed or not performed in addition
6025 to the default checks required by Ada as described above.
6026 @end ifclear
6027 @ifset vms
6028 The options allowed for this qualifier
6029 indicate validity checks that are performed or not performed in addition
6030 to the default checks required by Ada as described above.
6031 @end ifset
6032
6033 @table @option
6034 @c !sort!
6035 @item -gnatVa
6036 @emph{All validity checks.}
6037 @cindex @option{-gnatVa} (@command{gcc})
6038 All validity checks are turned on.
6039 @ifclear vms
6040 That is, @option{-gnatVa} is
6041 equivalent to @option{gnatVcdfimorst}.
6042 @end ifclear
6043
6044 @item -gnatVc
6045 @emph{Validity checks for copies.}
6046 @cindex @option{-gnatVc} (@command{gcc})
6047 The right hand side of assignments, and the initializing values of
6048 object declarations are validity checked.
6049
6050 @item -gnatVd
6051 @emph{Default (RM) validity checks.}
6052 @cindex @option{-gnatVd} (@command{gcc})
6053 Some validity checks are done by default following normal Ada semantics
6054 (RM 13.9.1 (9-11)).
6055 A check is done in case statements that the expression is within the range
6056 of the subtype. If it is not, Constraint_Error is raised.
6057 For assignments to array components, a check is done that the expression used
6058 as index is within the range. If it is not, Constraint_Error is raised.
6059 Both these validity checks may be turned off using switch @option{-gnatVD}.
6060 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6061 switch @option{-gnatVd} will leave the checks turned on.
6062 Switch @option{-gnatVD} should be used only if you are sure that all such
6063 expressions have valid values. If you use this switch and invalid values
6064 are present, then the program is erroneous, and wild jumps or memory
6065 overwriting may occur.
6066
6067 @item -gnatVe
6068 @emph{Validity checks for elementary components.}
6069 @cindex @option{-gnatVe} (@command{gcc})
6070 In the absence of this switch, assignments to record or array components are
6071 not validity checked, even if validity checks for assignments generally
6072 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6073 require valid data, but assignment of individual components does. So for
6074 example, there is a difference between copying the elements of an array with a
6075 slice assignment, compared to assigning element by element in a loop. This
6076 switch allows you to turn off validity checking for components, even when they
6077 are assigned component by component.
6078
6079 @item -gnatVf
6080 @emph{Validity checks for floating-point values.}
6081 @cindex @option{-gnatVf} (@command{gcc})
6082 In the absence of this switch, validity checking occurs only for discrete
6083 values. If @option{-gnatVf} is specified, then validity checking also applies
6084 for floating-point values, and NaNs and infinities are considered invalid,
6085 as well as out of range values for constrained types. Note that this means
6086 that standard IEEE infinity mode is not allowed. The exact contexts
6087 in which floating-point values are checked depends on the setting of other
6088 options. For example,
6089 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6090 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6091 (the order does not matter) specifies that floating-point parameters of mode
6092 @code{in} should be validity checked.
6093
6094 @item -gnatVi
6095 @emph{Validity checks for @code{in} mode parameters}
6096 @cindex @option{-gnatVi} (@command{gcc})
6097 Arguments for parameters of mode @code{in} are validity checked in function
6098 and procedure calls at the point of call.
6099
6100 @item -gnatVm
6101 @emph{Validity checks for @code{in out} mode parameters.}
6102 @cindex @option{-gnatVm} (@command{gcc})
6103 Arguments for parameters of mode @code{in out} are validity checked in
6104 procedure calls at the point of call. The @code{'m'} here stands for
6105 modify, since this concerns parameters that can be modified by the call.
6106 Note that there is no specific option to test @code{out} parameters,
6107 but any reference within the subprogram will be tested in the usual
6108 manner, and if an invalid value is copied back, any reference to it
6109 will be subject to validity checking.
6110
6111 @item -gnatVn
6112 @emph{No validity checks.}
6113 @cindex @option{-gnatVn} (@command{gcc})
6114 This switch turns off all validity checking, including the default checking
6115 for case statements and left hand side subscripts. Note that the use of
6116 the switch @option{-gnatp} suppresses all run-time checks, including
6117 validity checks, and thus implies @option{-gnatVn}. When this switch
6118 is used, it cancels any other @option{-gnatV} previously issued.
6119
6120 @item -gnatVo
6121 @emph{Validity checks for operator and attribute operands.}
6122 @cindex @option{-gnatVo} (@command{gcc})
6123 Arguments for predefined operators and attributes are validity checked.
6124 This includes all operators in package @code{Standard},
6125 the shift operators defined as intrinsic in package @code{Interfaces}
6126 and operands for attributes such as @code{Pos}. Checks are also made
6127 on individual component values for composite comparisons, and on the
6128 expressions in type conversions and qualified expressions. Checks are
6129 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6130
6131 @item -gnatVp
6132 @emph{Validity checks for parameters.}
6133 @cindex @option{-gnatVp} (@command{gcc})
6134 This controls the treatment of parameters within a subprogram (as opposed
6135 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6136 of parameters on a call. If either of these call options is used, then
6137 normally an assumption is made within a subprogram that the input arguments
6138 have been validity checking at the point of call, and do not need checking
6139 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6140 is not made, and parameters are not assumed to be valid, so their validity
6141 will be checked (or rechecked) within the subprogram.
6142
6143 @item -gnatVr
6144 @emph{Validity checks for function returns.}
6145 @cindex @option{-gnatVr} (@command{gcc})
6146 The expression in @code{return} statements in functions is validity
6147 checked.
6148
6149 @item -gnatVs
6150 @emph{Validity checks for subscripts.}
6151 @cindex @option{-gnatVs} (@command{gcc})
6152 All subscripts expressions are checked for validity, whether they appear
6153 on the right side or left side (in default mode only left side subscripts
6154 are validity checked).
6155
6156 @item -gnatVt
6157 @emph{Validity checks for tests.}
6158 @cindex @option{-gnatVt} (@command{gcc})
6159 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6160 statements are checked, as well as guard expressions in entry calls.
6161
6162 @end table
6163
6164 @noindent
6165 The @option{-gnatV} switch may be followed by
6166 ^a string of letters^a list of options^
6167 to turn on a series of validity checking options.
6168 For example,
6169 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6170 specifies that in addition to the default validity checking, copies and
6171 function return expressions are to be validity checked.
6172 In order to make it easier
6173 to specify the desired combination of effects,
6174 @ifclear vms
6175 the upper case letters @code{CDFIMORST} may
6176 be used to turn off the corresponding lower case option.
6177 @end ifclear
6178 @ifset vms
6179 the prefix @code{NO} on an option turns off the corresponding validity
6180 checking:
6181 @itemize @bullet
6182 @item @code{NOCOPIES}
6183 @item @code{NODEFAULT}
6184 @item @code{NOFLOATS}
6185 @item @code{NOIN_PARAMS}
6186 @item @code{NOMOD_PARAMS}
6187 @item @code{NOOPERANDS}
6188 @item @code{NORETURNS}
6189 @item @code{NOSUBSCRIPTS}
6190 @item @code{NOTESTS}
6191 @end itemize
6192 @end ifset
6193 Thus
6194 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6195 turns on all validity checking options except for
6196 checking of @code{@b{in out}} procedure arguments.
6197
6198 The specification of additional validity checking generates extra code (and
6199 in the case of @option{-gnatVa} the code expansion can be substantial).
6200 However, these additional checks can be very useful in detecting
6201 uninitialized variables, incorrect use of unchecked conversion, and other
6202 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6203 is useful in conjunction with the extra validity checking, since this
6204 ensures that wherever possible uninitialized variables have invalid values.
6205
6206 See also the pragma @code{Validity_Checks} which allows modification of
6207 the validity checking mode at the program source level, and also allows for
6208 temporary disabling of validity checks.
6209
6210 @node Style Checking
6211 @subsection Style Checking
6212 @findex Style checking
6213
6214 @noindent
6215 The @option{-gnaty^x^(option,option,@dots{})^} switch
6216 @cindex @option{-gnaty} (@command{gcc})
6217 causes the compiler to
6218 enforce specified style rules. A limited set of style rules has been used
6219 in writing the GNAT sources themselves. This switch allows user programs
6220 to activate all or some of these checks. If the source program fails a
6221 specified style check, an appropriate message is given, preceded by
6222 the character sequence ``(style)''. This message does not prevent
6223 successful compilation (unless the @option{-gnatwe} switch is used).
6224
6225 Note that this is by no means intended to be a general facility for
6226 checking arbitrary coding standards. It is simply an embedding of the
6227 style rules we have chosen for the GNAT sources. If you are starting
6228 a project which does not have established style standards, you may
6229 find it useful to adopt the entire set of GNAT coding standards, or
6230 some subset of them. If you already have an established set of coding
6231 standards, then it may be that selected style checking options do
6232 indeed correspond to choices you have made, but for general checking
6233 of an existing set of coding rules, you should look to the gnatcheck
6234 tool, which is designed for that purpose.
6235
6236 @ifset vms
6237 @code{(option,option,@dots{})} is a sequence of keywords
6238 @end ifset
6239 @ifclear vms
6240 The string @var{x} is a sequence of letters or digits
6241 @end ifclear
6242 indicating the particular style
6243 checks to be performed. The following checks are defined:
6244
6245 @table @option
6246 @c !sort!
6247 @item 0-9
6248 @emph{Specify indentation level.}
6249 If a digit from 1-9 appears
6250 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6251 then proper indentation is checked, with the digit indicating the
6252 indentation level required. A value of zero turns off this style check.
6253 The general style of required indentation is as specified by
6254 the examples in the Ada Reference Manual. Full line comments must be
6255 aligned with the @code{--} starting on a column that is a multiple of
6256 the alignment level, or they may be aligned the same way as the following
6257 non-blank line (this is useful when full line comments appear in the middle
6258 of a statement.
6259
6260 @item ^a^ATTRIBUTE^
6261 @emph{Check attribute casing.}
6262 Attribute names, including the case of keywords such as @code{digits}
6263 used as attributes names, must be written in mixed case, that is, the
6264 initial letter and any letter following an underscore must be uppercase.
6265 All other letters must be lowercase.
6266
6267 @item ^A^ARRAY_INDEXES^
6268 @emph{Use of array index numbers in array attributes.}
6269 When using the array attributes First, Last, Range,
6270 or Length, the index number must be omitted for one-dimensional arrays
6271 and is required for multi-dimensional arrays.
6272
6273 @item ^b^BLANKS^
6274 @emph{Blanks not allowed at statement end.}
6275 Trailing blanks are not allowed at the end of statements. The purpose of this
6276 rule, together with h (no horizontal tabs), is to enforce a canonical format
6277 for the use of blanks to separate source tokens.
6278
6279 @item ^B^BOOLEAN_OPERATORS^
6280 @emph{Check Boolean operators.}
6281 The use of AND/OR operators is not permitted except in the cases of modular
6282 operands, array operands, and simple stand-alone boolean variables or
6283 boolean constants. In all other cases AND THEN/OR ELSE are required.
6284
6285 @item ^c^COMMENTS^ (double space)
6286 @emph{Check comments, double space.}
6287 Comments must meet the following set of rules:
6288
6289 @itemize @bullet
6290
6291 @item
6292 The ``@code{--}'' that starts the column must either start in column one,
6293 or else at least one blank must precede this sequence.
6294
6295 @item
6296 Comments that follow other tokens on a line must have at least one blank
6297 following the ``@code{--}'' at the start of the comment.
6298
6299 @item
6300 Full line comments must have at least two blanks following the
6301 ``@code{--}'' that starts the comment, with the following exceptions.
6302
6303 @item
6304 A line consisting only of the ``@code{--}'' characters, possibly preceded
6305 by blanks is permitted.
6306
6307 @item
6308 A comment starting with ``@code{--x}'' where @code{x} is a special character
6309 is permitted.
6310 This allows proper processing of the output generated by specialized tools
6311 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6312 annotation
6313 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6314 special character is defined as being in one of the ASCII ranges
6315 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6316 Note that this usage is not permitted
6317 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6318
6319 @item
6320 A line consisting entirely of minus signs, possibly preceded by blanks, is
6321 permitted. This allows the construction of box comments where lines of minus
6322 signs are used to form the top and bottom of the box.
6323
6324 @item
6325 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6326 least one blank follows the initial ``@code{--}''. Together with the preceding
6327 rule, this allows the construction of box comments, as shown in the following
6328 example:
6329 @smallexample
6330 ---------------------------
6331 -- This is a box comment --
6332 -- with two text lines.  --
6333 ---------------------------
6334 @end smallexample
6335 @end itemize
6336
6337 @item ^C^COMMENTS1^ (single space)
6338 @emph{Check comments, single space.}
6339 This is identical to @code{^c^COMMENTS^} except that only one space
6340 is required following the @code{--} of a comment instead of two.
6341
6342 @item ^d^DOS_LINE_ENDINGS^
6343 @emph{Check no DOS line terminators present.}
6344 All lines must be terminated by a single ASCII.LF
6345 character (in particular the DOS line terminator sequence CR/LF is not
6346 allowed).
6347
6348 @item ^e^END^
6349 @emph{Check end/exit labels.}
6350 Optional labels on @code{end} statements ending subprograms and on
6351 @code{exit} statements exiting named loops, are required to be present.
6352
6353 @item ^f^VTABS^
6354 @emph{No form feeds or vertical tabs.}
6355 Neither form feeds nor vertical tab characters are permitted
6356 in the source text.
6357
6358 @item ^g^GNAT^
6359 @emph{GNAT style mode}
6360 The set of style check switches is set to match that used by the GNAT sources.
6361 This may be useful when developing code that is eventually intended to be
6362 incorporated into GNAT. For further details, see GNAT sources.
6363
6364 @item ^h^HTABS^
6365 @emph{No horizontal tabs.}
6366 Horizontal tab characters are not permitted in the source text.
6367 Together with the b (no blanks at end of line) check, this
6368 enforces a canonical form for the use of blanks to separate
6369 source tokens.
6370
6371 @item ^i^IF_THEN^
6372 @emph{Check if-then layout.}
6373 The keyword @code{then} must appear either on the same
6374 line as corresponding @code{if}, or on a line on its own, lined
6375 up under the @code{if} with at least one non-blank line in between
6376 containing all or part of the condition to be tested.
6377
6378 @item ^I^IN_MODE^
6379 @emph{check mode IN keywords}
6380 Mode @code{in} (the default mode) is not
6381 allowed to be given explicitly. @code{in out} is fine,
6382 but not @code{in} on its own.
6383
6384 @item ^k^KEYWORD^
6385 @emph{Check keyword casing.}
6386 All keywords must be in lower case (with the exception of keywords
6387 such as @code{digits} used as attribute names to which this check
6388 does not apply).
6389
6390 @item ^l^LAYOUT^
6391 @emph{Check layout.}
6392 Layout of statement and declaration constructs must follow the
6393 recommendations in the Ada Reference Manual, as indicated by the
6394 form of the syntax rules. For example an @code{else} keyword must
6395 be lined up with the corresponding @code{if} keyword.
6396
6397 There are two respects in which the style rule enforced by this check
6398 option are more liberal than those in the Ada Reference Manual. First
6399 in the case of record declarations, it is permissible to put the
6400 @code{record} keyword on the same line as the @code{type} keyword, and
6401 then the @code{end} in @code{end record} must line up under @code{type}.
6402 This is also permitted when the type declaration is split on two lines.
6403 For example, any of the following three layouts is acceptable:
6404
6405 @smallexample @c ada
6406 @cartouche
6407 type q is record
6408    a : integer;
6409    b : integer;
6410 end record;
6411
6412 type q is
6413    record
6414       a : integer;
6415       b : integer;
6416    end record;
6417
6418 type q is
6419    record
6420       a : integer;
6421       b : integer;
6422 end record;
6423
6424 @end cartouche
6425 @end smallexample
6426
6427 @noindent
6428 Second, in the case of a block statement, a permitted alternative
6429 is to put the block label on the same line as the @code{declare} or
6430 @code{begin} keyword, and then line the @code{end} keyword up under
6431 the block label. For example both the following are permitted:
6432
6433 @smallexample @c ada
6434 @cartouche
6435 Block : declare
6436    A : Integer := 3;
6437 begin
6438    Proc (A, A);
6439 end Block;
6440
6441 Block :
6442    declare
6443       A : Integer := 3;
6444    begin
6445       Proc (A, A);
6446    end Block;
6447 @end cartouche
6448 @end smallexample
6449
6450 @noindent
6451 The same alternative format is allowed for loops. For example, both of
6452 the following are permitted:
6453
6454 @smallexample @c ada
6455 @cartouche
6456 Clear : while J < 10 loop
6457    A (J) := 0;
6458 end loop Clear;
6459
6460 Clear :
6461    while J < 10 loop
6462       A (J) := 0;
6463    end loop Clear;
6464 @end cartouche
6465 @end smallexample
6466
6467 @item ^Lnnn^MAX_NESTING=nnn^
6468 @emph{Set maximum nesting level}
6469 The maximum level of nesting of constructs (including subprograms, loops,
6470 blocks, packages, and conditionals) may not exceed the given value
6471 @option{nnn}. A value of zero disconnects this style check.
6472
6473 @item ^m^LINE_LENGTH^
6474 @emph{Check maximum line length.}
6475 The length of source lines must not exceed 79 characters, including
6476 any trailing blanks. The value of 79 allows convenient display on an
6477 80 character wide device or window, allowing for possible special
6478 treatment of 80 character lines. Note that this count is of
6479 characters in the source text. This means that a tab character counts
6480 as one character in this count but a wide character sequence counts as
6481 a single character (however many bytes are needed in the encoding).
6482
6483 @item ^Mnnn^MAX_LENGTH=nnn^
6484 @emph{Set maximum line length.}
6485 The length of lines must not exceed the
6486 given value @option{nnn}. The maximum value that can be specified is 32767.
6487
6488 @item ^n^STANDARD_CASING^
6489 @emph{Check casing of entities in Standard.}
6490 Any identifier from Standard must be cased
6491 to match the presentation in the Ada Reference Manual (for example,
6492 @code{Integer} and @code{ASCII.NUL}).
6493
6494 @item ^N^NONE^
6495 @emph{Turn off all style checks}
6496 All style check options are turned off.
6497
6498 @item ^o^ORDERED_SUBPROGRAMS^
6499 @emph{Check order of subprogram bodies.}
6500 All subprogram bodies in a given scope
6501 (e.g.@: a package body) must be in alphabetical order. The ordering
6502 rule uses normal Ada rules for comparing strings, ignoring casing
6503 of letters, except that if there is a trailing numeric suffix, then
6504 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6505 before Junk10).
6506
6507 @item ^O^OVERRIDING_INDICATORS^
6508 @emph{Check that overriding subprograms are explicitly marked as such.}
6509 The declaration of a primitive operation of a type extension that overrides
6510 an inherited operation must carry an overriding indicator.
6511
6512 @item ^p^PRAGMA^
6513 @emph{Check pragma casing.}
6514 Pragma names must be written in mixed case, that is, the
6515 initial letter and any letter following an underscore must be uppercase.
6516 All other letters must be lowercase.
6517
6518 @item ^r^REFERENCES^
6519 @emph{Check references.}
6520 All identifier references must be cased in the same way as the
6521 corresponding declaration. No specific casing style is imposed on
6522 identifiers. The only requirement is for consistency of references
6523 with declarations.
6524
6525 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6526 @emph{Check no statements after THEN/ELSE.}
6527 No statements are allowed
6528 on the same line as a THEN or ELSE keyword following the
6529 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6530 and a special exception allows a pragma to appear after ELSE.
6531
6532 @item ^s^SPECS^
6533 @emph{Check separate specs.}
6534 Separate declarations (``specs'') are required for subprograms (a
6535 body is not allowed to serve as its own declaration). The only
6536 exception is that parameterless library level procedures are
6537 not required to have a separate declaration. This exception covers
6538 the most frequent form of main program procedures.
6539
6540 @item ^t^TOKEN^
6541 @emph{Check token spacing.}
6542 The following token spacing rules are enforced:
6543
6544 @itemize @bullet
6545
6546 @item
6547 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6548
6549 @item
6550 The token @code{=>} must be surrounded by spaces.
6551
6552 @item
6553 The token @code{<>} must be preceded by a space or a left parenthesis.
6554
6555 @item
6556 Binary operators other than @code{**} must be surrounded by spaces.
6557 There is no restriction on the layout of the @code{**} binary operator.
6558
6559 @item
6560 Colon must be surrounded by spaces.
6561
6562 @item
6563 Colon-equal (assignment, initialization) must be surrounded by spaces.
6564
6565 @item
6566 Comma must be the first non-blank character on the line, or be
6567 immediately preceded by a non-blank character, and must be followed
6568 by a space.
6569
6570 @item
6571 If the token preceding a left parenthesis ends with a letter or digit, then
6572 a space must separate the two tokens.
6573
6574 @item
6575 if the token following a right parenthesis starts with a letter or digit, then
6576 a space must separate the two tokens.
6577
6578 @item
6579 A right parenthesis must either be the first non-blank character on
6580 a line, or it must be preceded by a non-blank character.
6581
6582 @item
6583 A semicolon must not be preceded by a space, and must not be followed by
6584 a non-blank character.
6585
6586 @item
6587 A unary plus or minus may not be followed by a space.
6588
6589 @item
6590 A vertical bar must be surrounded by spaces.
6591 @end itemize
6592
6593 @item ^u^UNNECESSARY_BLANK_LINES^
6594 @emph{Check unnecessary blank lines.}
6595 Unnecessary blank lines are not allowed. A blank line is considered
6596 unnecessary if it appears at the end of the file, or if more than
6597 one blank line occurs in sequence.
6598
6599 @item ^x^XTRA_PARENS^
6600 @emph{Check extra parentheses.}
6601 Unnecessary extra level of parentheses (C-style) are not allowed
6602 around conditions in @code{if} statements, @code{while} statements and
6603 @code{exit} statements.
6604
6605 @item ^y^ALL_BUILTIN^
6606 @emph{Set all standard style check options}
6607 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6608 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6609 @option{-gnatyS}, @option{-gnatyLnnn},
6610 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6611
6612 @ifclear vms
6613 @item -
6614 @emph{Remove style check options}
6615 This causes any subsequent options in the string to act as canceling the
6616 corresponding style check option. To cancel maximum nesting level control,
6617 use @option{L} parameter witout any integer value after that, because any
6618 digit following @option{-} in the parameter string of the @option{-gnaty}
6619 option will be threated as canceling indentation check. The same is true
6620 for @option{M} parameter. @option{y} and @option{N} parameters are not
6621 allowed after @option{-}.
6622
6623 @item +
6624 This causes any subsequent options in the string to enable the corresponding
6625 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6626 if any.
6627 @end ifclear
6628
6629 @ifset vms
6630 @item NOxxx
6631 @emph{Removing style check options}
6632 If the name of a style check is preceded by @option{NO} then the corresponding
6633 style check is turned off. For example @option{NOCOMMENTS} turns off style
6634 checking for comments.
6635 @end ifset
6636 @end table
6637
6638 @noindent
6639 In the above rules, appearing in column one is always permitted, that is,
6640 counts as meeting either a requirement for a required preceding space,
6641 or as meeting a requirement for no preceding space.
6642
6643 Appearing at the end of a line is also always permitted, that is, counts
6644 as meeting either a requirement for a following space, or as meeting
6645 a requirement for no following space.
6646
6647 @noindent
6648 If any of these style rules is violated, a message is generated giving
6649 details on the violation. The initial characters of such messages are
6650 always ``@code{(style)}''. Note that these messages are treated as warning
6651 messages, so they normally do not prevent the generation of an object
6652 file. The @option{-gnatwe} switch can be used to treat warning messages,
6653 including style messages, as fatal errors.
6654
6655 The switch
6656 @ifclear vms
6657 @option{-gnaty} on its own (that is not
6658 followed by any letters or digits), then the effect is equivalent
6659 to the use of @option{-gnatyy}, as described above, that is all
6660 built-in standard style check options are enabled.
6661
6662 @end ifclear
6663 @ifset vms
6664 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6665 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6666 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6667 @end ifset
6668
6669 The switch
6670 @ifclear vms
6671 @option{-gnatyN}
6672 @end ifclear
6673 @ifset vms
6674 /STYLE_CHECKS=NONE
6675 @end ifset
6676 clears any previously set style checks.
6677
6678 @node Run-Time Checks
6679 @subsection Run-Time Checks
6680 @cindex Division by zero
6681 @cindex Access before elaboration
6682 @cindex Checks, division by zero
6683 @cindex Checks, access before elaboration
6684 @cindex Checks, stack overflow checking
6685
6686 @noindent
6687 By default, the following checks are suppressed: integer overflow
6688 checks, stack overflow checks, and checks for access before
6689 elaboration on subprogram calls. All other checks, including range
6690 checks and array bounds checks, are turned on by default. The
6691 following @command{gcc} switches refine this default behavior.
6692
6693 @table @option
6694 @c !sort!
6695 @item -gnatp
6696 @cindex @option{-gnatp} (@command{gcc})
6697 @cindex Suppressing checks
6698 @cindex Checks, suppressing
6699 @findex Suppress
6700 This switch causes the unit to be compiled
6701 as though @code{pragma Suppress (All_checks)}
6702 had been present in the source. Validity checks are also eliminated (in
6703 other words @option{-gnatp} also implies @option{-gnatVn}.
6704 Use this switch to improve the performance
6705 of the code at the expense of safety in the presence of invalid data or
6706 program bugs.
6707
6708 Note that when checks are suppressed, the compiler is allowed, but not
6709 required, to omit the checking code. If the run-time cost of the
6710 checking code is zero or near-zero, the compiler will generate it even
6711 if checks are suppressed. In particular, if the compiler can prove
6712 that a certain check will necessarily fail, it will generate code to
6713 do an unconditional ``raise'', even if checks are suppressed. The
6714 compiler warns in this case. Another case in which checks may not be
6715 eliminated is when they are embedded in certain run time routines such
6716 as math library routines.
6717
6718 Of course, run-time checks are omitted whenever the compiler can prove
6719 that they will not fail, whether or not checks are suppressed.
6720
6721 Note that if you suppress a check that would have failed, program
6722 execution is erroneous, which means the behavior is totally
6723 unpredictable. The program might crash, or print wrong answers, or
6724 do anything else. It might even do exactly what you wanted it to do
6725 (and then it might start failing mysteriously next week or next
6726 year). The compiler will generate code based on the assumption that
6727 the condition being checked is true, which can result in disaster if
6728 that assumption is wrong.
6729
6730 The @option{-gnatp} switch has no effect if a subsequent
6731 @option{-gnat-p} switch appears.
6732
6733 @item -gnat-p
6734 @cindex @option{-gnat-p} (@command{gcc})
6735 @cindex Suppressing checks
6736 @cindex Checks, suppressing
6737 @findex Suppress
6738 This switch cancels the effect of a previous @option{gnatp} switch.
6739
6740 @item -gnato
6741 @cindex @option{-gnato} (@command{gcc})
6742 @cindex Overflow checks
6743 @cindex Check, overflow
6744 Enables overflow checking for integer operations.
6745 This causes GNAT to generate slower and larger executable
6746 programs by adding code to check for overflow (resulting in raising
6747 @code{Constraint_Error} as required by standard Ada
6748 semantics). These overflow checks correspond to situations in which
6749 the true value of the result of an operation may be outside the base
6750 range of the result type. The following example shows the distinction:
6751
6752 @smallexample @c ada
6753 X1 : Integer := "Integer'Last";
6754 X2 : Integer range 1 .. 5 := "5";
6755 X3 : Integer := "Integer'Last";
6756 X4 : Integer range 1 .. 5 := "5";
6757 F  : Float := "2.0E+20";
6758 @dots{}
6759 X1 := X1 + 1;
6760 X2 := X2 + 1;
6761 X3 := Integer (F);
6762 X4 := Integer (F);
6763 @end smallexample
6764
6765 @noindent
6766 Note that if explicit values are assigned at compile time, the
6767 compiler may be able to detect overflow at compile time, in which case
6768 no actual run-time checking code is required, and Constraint_Error
6769 will be raised unconditionally, with or without
6770 @option{-gnato}. That's why the assigned values in the above fragment
6771 are in quotes, the meaning is "assign a value not known to the
6772 compiler that happens to be equal to ...". The remaining discussion
6773 assumes that the compiler cannot detect the values at compile time.
6774
6775 Here the first addition results in a value that is outside the base range
6776 of Integer, and hence requires an overflow check for detection of the
6777 constraint error. Thus the first assignment to @code{X1} raises a
6778 @code{Constraint_Error} exception only if @option{-gnato} is set.
6779
6780 The second increment operation results in a violation of the explicit
6781 range constraint; such range checks are performed by default, and are
6782 unaffected by @option{-gnato}.
6783
6784 The two conversions of @code{F} both result in values that are outside
6785 the base range of type @code{Integer} and thus will raise
6786 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6787 The fact that the result of the second conversion is assigned to
6788 variable @code{X4} with a restricted range is irrelevant, since the problem
6789 is in the conversion, not the assignment.
6790
6791 Basically the rule is that in the default mode (@option{-gnato} not
6792 used), the generated code assures that all integer variables stay
6793 within their declared ranges, or within the base range if there is
6794 no declared range. This prevents any serious problems like indexes
6795 out of range for array operations.
6796
6797 What is not checked in default mode is an overflow that results in
6798 an in-range, but incorrect value. In the above example, the assignments
6799 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6800 range of the target variable, but the result is wrong in the sense that
6801 it is too large to be represented correctly. Typically the assignment
6802 to @code{X1} will result in wrap around to the largest negative number.
6803 The conversions of @code{F} will result in some @code{Integer} value
6804 and if that integer value is out of the @code{X4} range then the
6805 subsequent assignment would generate an exception.
6806
6807 @findex Machine_Overflows
6808 Note that the @option{-gnato} switch does not affect the code generated
6809 for any floating-point operations; it applies only to integer
6810 semantics).
6811 For floating-point, GNAT has the @code{Machine_Overflows}
6812 attribute set to @code{False} and the normal mode of operation is to
6813 generate IEEE NaN and infinite values on overflow or invalid operations
6814 (such as dividing 0.0 by 0.0).
6815
6816 The reason that we distinguish overflow checking from other kinds of
6817 range constraint checking is that a failure of an overflow check, unlike
6818 for example the failure of a range check, can result in an incorrect
6819 value, but cannot cause random memory destruction (like an out of range
6820 subscript), or a wild jump (from an out of range case value). Overflow
6821 checking is also quite expensive in time and space, since in general it
6822 requires the use of double length arithmetic.
6823
6824 Note again that @option{-gnato} is off by default, so overflow checking is
6825 not performed in default mode. This means that out of the box, with the
6826 default settings, GNAT does not do all the checks expected from the
6827 language description in the Ada Reference Manual. If you want all constraint
6828 checks to be performed, as described in this Manual, then you must
6829 explicitly use the -gnato switch either on the @command{gnatmake} or
6830 @command{gcc} command.
6831
6832 @item -gnatE
6833 @cindex @option{-gnatE} (@command{gcc})
6834 @cindex Elaboration checks
6835 @cindex Check, elaboration
6836 Enables dynamic checks for access-before-elaboration
6837 on subprogram calls and generic instantiations.
6838 Note that @option{-gnatE} is not necessary for safety, because in the
6839 default mode, GNAT ensures statically that the checks would not fail.
6840 For full details of the effect and use of this switch,
6841 @xref{Compiling Using gcc}.
6842
6843 @item -fstack-check
6844 @cindex @option{-fstack-check} (@command{gcc})
6845 @cindex Stack Overflow Checking
6846 @cindex Checks, stack overflow checking
6847 Activates stack overflow checking. For full details of the effect and use of
6848 this switch see @ref{Stack Overflow Checking}.
6849 @end table
6850
6851 @findex Unsuppress
6852 @noindent
6853 The setting of these switches only controls the default setting of the
6854 checks. You may modify them using either @code{Suppress} (to remove
6855 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6856 the program source.
6857
6858 @node Using gcc for Syntax Checking
6859 @subsection Using @command{gcc} for Syntax Checking
6860 @table @option
6861 @item -gnats
6862 @cindex @option{-gnats} (@command{gcc})
6863 @ifclear vms
6864
6865 @noindent
6866 The @code{s} stands for ``syntax''.
6867 @end ifclear
6868
6869 Run GNAT in syntax checking only mode. For
6870 example, the command
6871
6872 @smallexample
6873 $ gcc -c -gnats x.adb
6874 @end smallexample
6875
6876 @noindent
6877 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6878 series of files in a single command
6879 @ifclear vms
6880 , and can use wild cards to specify such a group of files.
6881 Note that you must specify the @option{-c} (compile
6882 only) flag in addition to the @option{-gnats} flag.
6883 @end ifclear
6884 .
6885 You may use other switches in conjunction with @option{-gnats}. In
6886 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6887 format of any generated error messages.
6888
6889 When the source file is empty or contains only empty lines and/or comments,
6890 the output is a warning:
6891
6892 @smallexample
6893 $ gcc -c -gnats -x ada toto.txt
6894 toto.txt:1:01: warning: empty file, contains no compilation units
6895 $
6896 @end smallexample
6897
6898 Otherwise, the output is simply the error messages, if any. No object file or
6899 ALI file is generated by a syntax-only compilation. Also, no units other
6900 than the one specified are accessed. For example, if a unit @code{X}
6901 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6902 check only mode does not access the source file containing unit
6903 @code{Y}.
6904
6905 @cindex Multiple units, syntax checking
6906 Normally, GNAT allows only a single unit in a source file. However, this
6907 restriction does not apply in syntax-check-only mode, and it is possible
6908 to check a file containing multiple compilation units concatenated
6909 together. This is primarily used by the @code{gnatchop} utility
6910 (@pxref{Renaming Files Using gnatchop}).
6911 @end table
6912
6913 @node Using gcc for Semantic Checking
6914 @subsection Using @command{gcc} for Semantic Checking
6915 @table @option
6916 @item -gnatc
6917 @cindex @option{-gnatc} (@command{gcc})
6918
6919 @ifclear vms
6920 @noindent
6921 The @code{c} stands for ``check''.
6922 @end ifclear
6923 Causes the compiler to operate in semantic check mode,
6924 with full checking for all illegalities specified in the
6925 Ada Reference Manual, but without generation of any object code
6926 (no object file is generated).
6927
6928 Because dependent files must be accessed, you must follow the GNAT
6929 semantic restrictions on file structuring to operate in this mode:
6930
6931 @itemize @bullet
6932 @item
6933 The needed source files must be accessible
6934 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6935
6936 @item
6937 Each file must contain only one compilation unit.
6938
6939 @item
6940 The file name and unit name must match (@pxref{File Naming Rules}).
6941 @end itemize
6942
6943 The output consists of error messages as appropriate. No object file is
6944 generated. An @file{ALI} file is generated for use in the context of
6945 cross-reference tools, but this file is marked as not being suitable
6946 for binding (since no object file is generated).
6947 The checking corresponds exactly to the notion of
6948 legality in the Ada Reference Manual.
6949
6950 Any unit can be compiled in semantics-checking-only mode, including
6951 units that would not normally be compiled (subunits,
6952 and specifications where a separate body is present).
6953 @end table
6954
6955 @node Compiling Different Versions of Ada
6956 @subsection Compiling Different Versions of Ada
6957
6958 @noindent
6959 The switches described in this section allow you to explicitly specify
6960 the version of the Ada language that your programs are written in.
6961 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6962 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6963 indicate Ada 83 compatibility mode.
6964
6965 @table @option
6966 @cindex Compatibility with Ada 83
6967
6968 @item -gnat83 (Ada 83 Compatibility Mode)
6969 @cindex @option{-gnat83} (@command{gcc})
6970 @cindex ACVC, Ada 83 tests
6971 @cindex Ada 83 mode
6972
6973 @noindent
6974 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6975 specifies that the program is to be compiled in Ada 83 mode. With
6976 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6977 semantics where this can be done easily.
6978 It is not possible to guarantee this switch does a perfect
6979 job; some subtle tests, such as are
6980 found in earlier ACVC tests (and that have been removed from the ACATS suite
6981 for Ada 95), might not compile correctly.
6982 Nevertheless, this switch may be useful in some circumstances, for example
6983 where, due to contractual reasons, existing code needs to be maintained
6984 using only Ada 83 features.
6985
6986 With few exceptions (most notably the need to use @code{<>} on
6987 @cindex Generic formal parameters
6988 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6989 reserved words, and the use of packages
6990 with optional bodies), it is not necessary to specify the
6991 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6992 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6993 a correct Ada 83 program is usually also a correct program
6994 in these later versions of the language standard.
6995 For further information, please refer to @ref{Compatibility and Porting Guide}.
6996
6997 @item -gnat95 (Ada 95 mode)
6998 @cindex @option{-gnat95} (@command{gcc})
6999 @cindex Ada 95 mode
7000
7001 @noindent
7002 This switch directs the compiler to implement the Ada 95 version of the
7003 language.
7004 Since Ada 95 is almost completely upwards
7005 compatible with Ada 83, Ada 83 programs may generally be compiled using
7006 this switch (see the description of the @option{-gnat83} switch for further
7007 information about Ada 83 mode).
7008 If an Ada 2005 program is compiled in Ada 95 mode,
7009 uses of the new Ada 2005 features will cause error
7010 messages or warnings.
7011
7012 This switch also can be used to cancel the effect of a previous
7013 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7014 switch earlier in the command line.
7015
7016 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7017 @cindex @option{-gnat05} (@command{gcc})
7018 @cindex @option{-gnat2005} (@command{gcc})
7019 @cindex Ada 2005 mode
7020
7021 @noindent
7022 This switch directs the compiler to implement the Ada 2005 version of the
7023 language, as documented in the official Ada standards document.
7024 Since Ada 2005 is almost completely upwards
7025 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7026 may generally be compiled using this switch (see the description of the
7027 @option{-gnat83} and @option{-gnat95} switches for further
7028 information).
7029
7030 @ifset PROEDITION
7031 Note that even though Ada 2005 is the current official version of the
7032 language, GNAT still compiles in Ada 95 mode by default, so if you are
7033 using Ada 2005 features in your program, you must use this switch (or
7034 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7035 @end ifset
7036
7037 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7038 @cindex @option{-gnat12} (@command{gcc})
7039 @cindex @option{-gnat2012} (@command{gcc})
7040 @cindex Ada 2012 mode
7041
7042 @noindent
7043 This switch directs the compiler to implement the Ada 2012 version of the
7044 language.
7045 Since Ada 2012 is almost completely upwards
7046 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7047 Ada 83 and Ada 95 programs
7048 may generally be compiled using this switch (see the description of the
7049 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7050 for further information).
7051
7052 For information about the approved ``Ada Issues'' that have been incorporated
7053 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7054 Included with GNAT releases is a file @file{features-ada12} that describes
7055 the set of implemented Ada 2012 features.
7056
7057 @item -gnatX (Enable GNAT Extensions)
7058 @cindex @option{-gnatX} (@command{gcc})
7059 @cindex Ada language extensions
7060 @cindex GNAT extensions
7061
7062 @noindent
7063 This switch directs the compiler to implement the latest version of the
7064 language (currently Ada 2012) and also to enable certain GNAT implementation
7065 extensions that are not part of any Ada standard. For a full list of these
7066 extensions, see the GNAT reference manual.
7067
7068 @end table
7069
7070 @node Character Set Control
7071 @subsection Character Set Control
7072 @table @option
7073 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7074 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7075
7076 @noindent
7077 Normally GNAT recognizes the Latin-1 character set in source program
7078 identifiers, as described in the Ada Reference Manual.
7079 This switch causes
7080 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7081 single character ^^or word^ indicating the character set, as follows:
7082
7083 @table @code
7084 @item 1
7085 ISO 8859-1 (Latin-1) identifiers
7086
7087 @item 2
7088 ISO 8859-2 (Latin-2) letters allowed in identifiers
7089
7090 @item 3
7091 ISO 8859-3 (Latin-3) letters allowed in identifiers
7092
7093 @item 4
7094 ISO 8859-4 (Latin-4) letters allowed in identifiers
7095
7096 @item 5
7097 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7098
7099 @item 9
7100 ISO 8859-15 (Latin-9) letters allowed in identifiers
7101
7102 @item ^p^PC^
7103 IBM PC letters (code page 437) allowed in identifiers
7104
7105 @item ^8^PC850^
7106 IBM PC letters (code page 850) allowed in identifiers
7107
7108 @item ^f^FULL_UPPER^
7109 Full upper-half codes allowed in identifiers
7110
7111 @item ^n^NO_UPPER^
7112 No upper-half codes allowed in identifiers
7113
7114 @item ^w^WIDE^
7115 Wide-character codes (that is, codes greater than 255)
7116 allowed in identifiers
7117 @end table
7118
7119 @xref{Foreign Language Representation}, for full details on the
7120 implementation of these character sets.
7121
7122 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7123 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7124 Specify the method of encoding for wide characters.
7125 @var{e} is one of the following:
7126
7127 @table @code
7128
7129 @item ^h^HEX^
7130 Hex encoding (brackets coding also recognized)
7131
7132 @item ^u^UPPER^
7133 Upper half encoding (brackets encoding also recognized)
7134
7135 @item ^s^SHIFT_JIS^
7136 Shift/JIS encoding (brackets encoding also recognized)
7137
7138 @item ^e^EUC^
7139 EUC encoding (brackets encoding also recognized)
7140
7141 @item ^8^UTF8^
7142 UTF-8 encoding (brackets encoding also recognized)
7143
7144 @item ^b^BRACKETS^
7145 Brackets encoding only (default value)
7146 @end table
7147 For full details on these encoding
7148 methods see @ref{Wide Character Encodings}.
7149 Note that brackets coding is always accepted, even if one of the other
7150 options is specified, so for example @option{-gnatW8} specifies that both
7151 brackets and UTF-8 encodings will be recognized. The units that are
7152 with'ed directly or indirectly will be scanned using the specified
7153 representation scheme, and so if one of the non-brackets scheme is
7154 used, it must be used consistently throughout the program. However,
7155 since brackets encoding is always recognized, it may be conveniently
7156 used in standard libraries, allowing these libraries to be used with
7157 any of the available coding schemes.
7158 scheme.
7159
7160 If no @option{-gnatW?} parameter is present, then the default
7161 representation is normally Brackets encoding only. However, if the
7162 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7163 byte order mark or BOM for UTF-8), then these three characters are
7164 skipped and the default representation for the file is set to UTF-8.
7165
7166 Note that the wide character representation that is specified (explicitly
7167 or by default) for the main program also acts as the default encoding used
7168 for Wide_Text_IO files if not specifically overridden by a WCEM form
7169 parameter.
7170
7171 @end table
7172 @node File Naming Control
7173 @subsection File Naming Control
7174
7175 @table @option
7176 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7177 @cindex @option{-gnatk} (@command{gcc})
7178 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7179 1-999, indicates the maximum allowable length of a file name (not
7180 including the @file{.ads} or @file{.adb} extension). The default is not
7181 to enable file name krunching.
7182
7183 For the source file naming rules, @xref{File Naming Rules}.
7184 @end table
7185
7186 @node Subprogram Inlining Control
7187 @subsection Subprogram Inlining Control
7188
7189 @table @option
7190 @c !sort!
7191 @item -gnatn
7192 @cindex @option{-gnatn} (@command{gcc})
7193 @ifclear vms
7194 The @code{n} here is intended to suggest the first syllable of the
7195 word ``inline''.
7196 @end ifclear
7197 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7198 inlining to actually occur, optimization must be enabled. To enable
7199 inlining of subprograms specified by pragma @code{Inline},
7200 you must also specify this switch.
7201 In the absence of this switch, GNAT does not attempt
7202 inlining and does not need to access the bodies of
7203 subprograms for which @code{pragma Inline} is specified if they are not
7204 in the current unit.
7205
7206 If you specify this switch the compiler will access these bodies,
7207 creating an extra source dependency for the resulting object file, and
7208 where possible, the call will be inlined.
7209 For further details on when inlining is possible
7210 see @ref{Inlining of Subprograms}.
7211
7212 @item -gnatN
7213 @cindex @option{-gnatN} (@command{gcc})
7214 This switch activates front-end inlining which also
7215 generates additional dependencies.
7216
7217 When using a gcc-based back end (in practice this means using any version
7218 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7219 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7220 Historically front end inlining was more extensive than the gcc back end
7221 inlining, but that is no longer the case.
7222 @end table
7223
7224 @node Auxiliary Output Control
7225 @subsection Auxiliary Output Control
7226
7227 @table @option
7228 @item -gnatt
7229 @cindex @option{-gnatt} (@command{gcc})
7230 @cindex Writing internal trees
7231 @cindex Internal trees, writing to file
7232 Causes GNAT to write the internal tree for a unit to a file (with the
7233 extension @file{.adt}.
7234 This not normally required, but is used by separate analysis tools.
7235 Typically
7236 these tools do the necessary compilations automatically, so you should
7237 not have to specify this switch in normal operation.
7238 Note that the combination of switches @option{-gnatct}
7239 generates a tree in the form required by ASIS applications.
7240
7241 @item -gnatu
7242 @cindex @option{-gnatu} (@command{gcc})
7243 Print a list of units required by this compilation on @file{stdout}.
7244 The listing includes all units on which the unit being compiled depends
7245 either directly or indirectly.
7246
7247 @ifclear vms
7248 @item -pass-exit-codes
7249 @cindex @option{-pass-exit-codes} (@command{gcc})
7250 If this switch is not used, the exit code returned by @command{gcc} when
7251 compiling multiple files indicates whether all source files have
7252 been successfully used to generate object files or not.
7253
7254 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7255 exit status and allows an integrated development environment to better
7256 react to a compilation failure. Those exit status are:
7257
7258 @table @asis
7259 @item 5
7260 There was an error in at least one source file.
7261 @item 3
7262 At least one source file did not generate an object file.
7263 @item 2
7264 The compiler died unexpectedly (internal error for example).
7265 @item 0
7266 An object file has been generated for every source file.
7267 @end table
7268 @end ifclear
7269 @end table
7270
7271 @node Debugging Control
7272 @subsection Debugging Control
7273
7274 @table @option
7275 @c !sort!
7276 @cindex Debugging options
7277 @ifclear vms
7278 @item -gnatd@var{x}
7279 @cindex @option{-gnatd} (@command{gcc})
7280 Activate internal debugging switches. @var{x} is a letter or digit, or
7281 string of letters or digits, which specifies the type of debugging
7282 outputs desired. Normally these are used only for internal development
7283 or system debugging purposes. You can find full documentation for these
7284 switches in the body of the @code{Debug} unit in the compiler source
7285 file @file{debug.adb}.
7286 @end ifclear
7287
7288 @item -gnatG[=nn]
7289 @cindex @option{-gnatG} (@command{gcc})
7290 This switch causes the compiler to generate auxiliary output containing
7291 a pseudo-source listing of the generated expanded code. Like most Ada
7292 compilers, GNAT works by first transforming the high level Ada code into
7293 lower level constructs. For example, tasking operations are transformed
7294 into calls to the tasking run-time routines. A unique capability of GNAT
7295 is to list this expanded code in a form very close to normal Ada source.
7296 This is very useful in understanding the implications of various Ada
7297 usage on the efficiency of the generated code. There are many cases in
7298 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7299 generate a lot of run-time code. By using @option{-gnatG} you can identify
7300 these cases, and consider whether it may be desirable to modify the coding
7301 approach to improve efficiency.
7302
7303 The optional parameter @code{nn} if present after -gnatG specifies an
7304 alternative maximum line length that overrides the normal default of 72.
7305 This value is in the range 40-999999, values less than 40 being silently
7306 reset to 40. The equal sign is optional.
7307
7308 The format of the output is very similar to standard Ada source, and is
7309 easily understood by an Ada programmer. The following special syntactic
7310 additions correspond to low level features used in the generated code that
7311 do not have any exact analogies in pure Ada source form. The following
7312 is a partial list of these special constructions. See the spec
7313 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7314
7315 If the switch @option{-gnatL} is used in conjunction with
7316 @cindex @option{-gnatL} (@command{gcc})
7317 @option{-gnatG}, then the original source lines are interspersed
7318 in the expanded source (as comment lines with the original line number).
7319
7320 @table @code
7321 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7322 Shows the storage pool being used for an allocator.
7323
7324 @item at end @var{procedure-name};
7325 Shows the finalization (cleanup) procedure for a scope.
7326
7327 @item (if @var{expr} then @var{expr} else @var{expr})
7328 Conditional expression equivalent to the @code{x?y:z} construction in C.
7329
7330 @item @var{target}^^^(@var{source})
7331 A conversion with floating-point truncation instead of rounding.
7332
7333 @item @var{target}?(@var{source})
7334 A conversion that bypasses normal Ada semantic checking. In particular
7335 enumeration types and fixed-point types are treated simply as integers.
7336
7337 @item @var{target}?^^^(@var{source})
7338 Combines the above two cases.
7339
7340 @item @var{x} #/ @var{y}
7341 @itemx @var{x} #mod @var{y}
7342 @itemx @var{x} #* @var{y}
7343 @itemx @var{x} #rem @var{y}
7344 A division or multiplication of fixed-point values which are treated as
7345 integers without any kind of scaling.
7346
7347 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7348 Shows the storage pool associated with a @code{free} statement.
7349
7350 @item [subtype or type declaration]
7351 Used to list an equivalent declaration for an internally generated
7352 type that is referenced elsewhere in the listing.
7353
7354 @c @item freeze @var{type-name} @ovar{actions}
7355 @c Expanding @ovar macro inline (explanation in macro def comments)
7356 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7357 Shows the point at which @var{type-name} is frozen, with possible
7358 associated actions to be performed at the freeze point.
7359
7360 @item reference @var{itype}
7361 Reference (and hence definition) to internal type @var{itype}.
7362
7363 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7364 Intrinsic function call.
7365
7366 @item @var{label-name} : label
7367 Declaration of label @var{labelname}.
7368
7369 @item #$ @var{subprogram-name}
7370 An implicit call to a run-time support routine
7371 (to meet the requirement of H.3.1(9) in a
7372 convenient manner).
7373
7374 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7375 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7376 @var{expr}, but handled more efficiently).
7377
7378 @item [constraint_error]
7379 Raise the @code{Constraint_Error} exception.
7380
7381 @item @var{expression}'reference
7382 A pointer to the result of evaluating @var{expression}.
7383
7384 @item @var{target-type}!(@var{source-expression})
7385 An unchecked conversion of @var{source-expression} to @var{target-type}.
7386
7387 @item [@var{numerator}/@var{denominator}]
7388 Used to represent internal real literals (that) have no exact
7389 representation in base 2-16 (for example, the result of compile time
7390 evaluation of the expression 1.0/27.0).
7391 @end table
7392
7393 @item -gnatD[=nn]
7394 @cindex @option{-gnatD} (@command{gcc})
7395 When used in conjunction with @option{-gnatG}, this switch causes
7396 the expanded source, as described above for
7397 @option{-gnatG} to be written to files with names
7398 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7399 instead of to the standard output file. For
7400 example, if the source file name is @file{hello.adb}, then a file
7401 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7402 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7403 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7404 you to do source level debugging using the generated code which is
7405 sometimes useful for complex code, for example to find out exactly
7406 which part of a complex construction raised an exception. This switch
7407 also suppress generation of cross-reference information (see
7408 @option{-gnatx}) since otherwise the cross-reference information
7409 would refer to the @file{^.dg^.DG^} file, which would cause
7410 confusion since this is not the original source file.
7411
7412 Note that @option{-gnatD} actually implies @option{-gnatG}
7413 automatically, so it is not necessary to give both options.
7414 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7415
7416 If the switch @option{-gnatL} is used in conjunction with
7417 @cindex @option{-gnatL} (@command{gcc})
7418 @option{-gnatDG}, then the original source lines are interspersed
7419 in the expanded source (as comment lines with the original line number).
7420
7421 The optional parameter @code{nn} if present after -gnatD specifies an
7422 alternative maximum line length that overrides the normal default of 72.
7423 This value is in the range 40-999999, values less than 40 being silently
7424 reset to 40. The equal sign is optional.
7425
7426 @item -gnatr
7427 @cindex @option{-gnatr} (@command{gcc})
7428 @cindex pragma Restrictions
7429 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7430 so that violation of restrictions causes warnings rather than illegalities.
7431 This is useful during the development process when new restrictions are added
7432 or investigated. The switch also causes pragma Profile to be treated as
7433 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7434 restriction warnings rather than restrictions.
7435
7436 @ifclear vms
7437 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7438 @cindex @option{-gnatR} (@command{gcc})
7439 This switch controls output from the compiler of a listing showing
7440 representation information for declared types and objects. For
7441 @option{-gnatR0}, no information is output (equivalent to omitting
7442 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7443 so @option{-gnatR} with no parameter has the same effect), size and alignment
7444 information is listed for declared array and record types. For
7445 @option{-gnatR2}, size and alignment information is listed for all
7446 declared types and objects. Finally @option{-gnatR3} includes symbolic
7447 expressions for values that are computed at run time for
7448 variant records. These symbolic expressions have a mostly obvious
7449 format with #n being used to represent the value of the n'th
7450 discriminant. See source files @file{repinfo.ads/adb} in the
7451 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7452 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7453 the output is to a file with the name @file{^file.rep^file_REP^} where
7454 file is the name of the corresponding source file.
7455 @end ifclear
7456 @ifset vms
7457 @item /REPRESENTATION_INFO
7458 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7459 This qualifier controls output from the compiler of a listing showing
7460 representation information for declared types and objects. For
7461 @option{/REPRESENTATION_INFO=NONE}, no information is output
7462 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7463 @option{/REPRESENTATION_INFO} without option is equivalent to
7464 @option{/REPRESENTATION_INFO=ARRAYS}.
7465 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7466 information is listed for declared array and record types. For
7467 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7468 is listed for all expression information for values that are computed
7469 at run time for variant records. These symbolic expressions have a mostly
7470 obvious format with #n being used to represent the value of the n'th
7471 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7472 @code{GNAT} sources for full details on the format of
7473 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7474 If _FILE is added at the end of an option
7475 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7476 then the output is to a file with the name @file{file_REP} where
7477 file is the name of the corresponding source file.
7478 @end ifset
7479 Note that it is possible for record components to have zero size. In
7480 this case, the component clause uses an obvious extension of permitted
7481 Ada syntax, for example @code{at 0 range 0 .. -1}.
7482
7483 Representation information requires that code be generated (since it is the
7484 code generator that lays out complex data structures). If an attempt is made
7485 to output representation information when no code is generated, for example
7486 when a subunit is compiled on its own, then no information can be generated
7487 and the compiler outputs a message to this effect.
7488
7489 @item -gnatS
7490 @cindex @option{-gnatS} (@command{gcc})
7491 The use of the switch @option{-gnatS} for an
7492 Ada compilation will cause the compiler to output a
7493 representation of package Standard in a form very
7494 close to standard Ada. It is not quite possible to
7495 do this entirely in standard Ada (since new
7496 numeric base types cannot be created in standard
7497 Ada), but the output is easily
7498 readable to any Ada programmer, and is useful to
7499 determine the characteristics of target dependent
7500 types in package Standard.
7501
7502 @item -gnatx
7503 @cindex @option{-gnatx} (@command{gcc})
7504 Normally the compiler generates full cross-referencing information in
7505 the @file{ALI} file. This information is used by a number of tools,
7506 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7507 suppresses this information. This saves some space and may slightly
7508 speed up compilation, but means that these tools cannot be used.
7509 @end table
7510
7511 @node Exception Handling Control
7512 @subsection Exception Handling Control
7513
7514 @noindent
7515 GNAT uses two methods for handling exceptions at run-time. The
7516 @code{setjmp/longjmp} method saves the context when entering
7517 a frame with an exception handler. Then when an exception is
7518 raised, the context can be restored immediately, without the
7519 need for tracing stack frames. This method provides very fast
7520 exception propagation, but introduces significant overhead for
7521 the use of exception handlers, even if no exception is raised.
7522
7523 The other approach is called ``zero cost'' exception handling.
7524 With this method, the compiler builds static tables to describe
7525 the exception ranges. No dynamic code is required when entering
7526 a frame containing an exception handler. When an exception is
7527 raised, the tables are used to control a back trace of the
7528 subprogram invocation stack to locate the required exception
7529 handler. This method has considerably poorer performance for
7530 the propagation of exceptions, but there is no overhead for
7531 exception handlers if no exception is raised. Note that in this
7532 mode and in the context of mixed Ada and C/C++ programming,
7533 to propagate an exception through a C/C++ code, the C/C++ code
7534 must be compiled with the @option{-funwind-tables} GCC's
7535 option.
7536
7537 The following switches may be used to control which of the
7538 two exception handling methods is used.
7539
7540 @table @option
7541 @c !sort!
7542
7543 @item --RTS=sjlj
7544 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7545 This switch causes the setjmp/longjmp run-time (when available) to be used
7546 for exception handling. If the default
7547 mechanism for the target is zero cost exceptions, then
7548 this switch can be used to modify this default, and must be
7549 used for all units in the partition.
7550 This option is rarely used. One case in which it may be
7551 advantageous is if you have an application where exception
7552 raising is common and the overall performance of the
7553 application is improved by favoring exception propagation.
7554
7555 @item --RTS=zcx
7556 @cindex @option{--RTS=zcx} (@command{gnatmake})
7557 @cindex Zero Cost Exceptions
7558 This switch causes the zero cost approach to be used
7559 for exception handling. If this is the default mechanism for the
7560 target (see below), then this switch is unneeded. If the default
7561 mechanism for the target is setjmp/longjmp exceptions, then
7562 this switch can be used to modify this default, and must be
7563 used for all units in the partition.
7564 This option can only be used if the zero cost approach
7565 is available for the target in use, otherwise it will generate an error.
7566 @end table
7567
7568 @noindent
7569 The same option @option{--RTS} must be used both for @command{gcc}
7570 and @command{gnatbind}. Passing this option to @command{gnatmake}
7571 (@pxref{Switches for gnatmake}) will ensure the required consistency
7572 through the compilation and binding steps.
7573
7574 @node Units to Sources Mapping Files
7575 @subsection Units to Sources Mapping Files
7576
7577 @table @option
7578
7579 @item -gnatem=@var{path}
7580 @cindex @option{-gnatem} (@command{gcc})
7581 A mapping file is a way to communicate to the compiler two mappings:
7582 from unit names to file names (without any directory information) and from
7583 file names to path names (with full directory information). These mappings
7584 are used by the compiler to short-circuit the path search.
7585
7586 The use of mapping files is not required for correct operation of the
7587 compiler, but mapping files can improve efficiency, particularly when
7588 sources are read over a slow network connection. In normal operation,
7589 you need not be concerned with the format or use of mapping files,
7590 and the @option{-gnatem} switch is not a switch that you would use
7591 explicitly. It is intended primarily for use by automatic tools such as
7592 @command{gnatmake} running under the project file facility. The
7593 description here of the format of mapping files is provided
7594 for completeness and for possible use by other tools.
7595
7596 A mapping file is a sequence of sets of three lines. In each set, the
7597 first line is the unit name, in lower case, with @code{%s} appended
7598 for specs and @code{%b} appended for bodies; the second line is the
7599 file name; and the third line is the path name.
7600
7601 Example:
7602 @smallexample
7603    main%b
7604    main.2.ada
7605    /gnat/project1/sources/main.2.ada
7606 @end smallexample
7607
7608 When the switch @option{-gnatem} is specified, the compiler will
7609 create in memory the two mappings from the specified file. If there is
7610 any problem (nonexistent file, truncated file or duplicate entries),
7611 no mapping will be created.
7612
7613 Several @option{-gnatem} switches may be specified; however, only the
7614 last one on the command line will be taken into account.
7615
7616 When using a project file, @command{gnatmake} creates a temporary
7617 mapping file and communicates it to the compiler using this switch.
7618
7619 @end table
7620
7621 @node Integrated Preprocessing
7622 @subsection Integrated Preprocessing
7623
7624 @noindent
7625 GNAT sources may be preprocessed immediately before compilation.
7626 In this case, the actual
7627 text of the source is not the text of the source file, but is derived from it
7628 through a process called preprocessing. Integrated preprocessing is specified
7629 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7630 indicates, through a text file, the preprocessing data to be used.
7631 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7632
7633 @noindent
7634 Note that when integrated preprocessing is used, the output from the
7635 preprocessor is not written to any external file. Instead it is passed
7636 internally to the compiler. If you need to preserve the result of
7637 preprocessing in a file, then you should use @command{gnatprep}
7638 to perform the desired preprocessing in stand-alone mode.
7639
7640 @noindent
7641 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7642 used when Integrated Preprocessing is used. The reason is that preprocessing
7643 with another Preprocessing Data file without changing the sources will
7644 not trigger recompilation without this switch.
7645
7646 @noindent
7647 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7648 always trigger recompilation for sources that are preprocessed,
7649 because @command{gnatmake} cannot compute the checksum of the source after
7650 preprocessing.
7651
7652 @noindent
7653 The actual preprocessing function is described in details in section
7654 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7655 preprocessing is triggered and parameterized.
7656
7657 @table @code
7658
7659 @item -gnatep=@var{file}
7660 @cindex @option{-gnatep} (@command{gcc})
7661 This switch indicates to the compiler the file name (without directory
7662 information) of the preprocessor data file to use. The preprocessor data file
7663 should be found in the source directories. Note that when the compiler is
7664 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7665 file, if the object directory is not also a source directory, the builder needs
7666 to be called with @option{-x}.
7667
7668 @noindent
7669 A preprocessing data file is a text file with significant lines indicating
7670 how should be preprocessed either a specific source or all sources not
7671 mentioned in other lines. A significant line is a nonempty, non-comment line.
7672 Comments are similar to Ada comments.
7673
7674 @noindent
7675 Each significant line starts with either a literal string or the character '*'.
7676 A literal string is the file name (without directory information) of the source
7677 to preprocess. A character '*' indicates the preprocessing for all the sources
7678 that are not specified explicitly on other lines (order of the lines is not
7679 significant). It is an error to have two lines with the same file name or two
7680 lines starting with the character '*'.
7681
7682 @noindent
7683 After the file name or the character '*', another optional literal string
7684 indicating the file name of the definition file to be used for preprocessing
7685 (@pxref{Form of Definitions File}). The definition files are found by the
7686 compiler in one of the source directories. In some cases, when compiling
7687 a source in a directory other than the current directory, if the definition
7688 file is in the current directory, it may be necessary to add the current
7689 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7690 the compiler would not find the definition file.
7691
7692 @noindent
7693 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7694 be found. Those ^switches^switches^ are:
7695
7696 @table @code
7697
7698 @item -b
7699 Causes both preprocessor lines and the lines deleted by
7700 preprocessing to be replaced by blank lines, preserving the line number.
7701 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7702 it cancels the effect of @option{-c}.
7703
7704 @item -c
7705 Causes both preprocessor lines and the lines deleted
7706 by preprocessing to be retained as comments marked
7707 with the special string ``@code{--! }''.
7708
7709 @item -Dsymbol=value
7710 Define or redefine a symbol, associated with value. A symbol is an Ada
7711 identifier, or an Ada reserved word, with the exception of @code{if},
7712 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7713 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7714 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7715 same name defined in a definition file.
7716
7717 @item -s
7718 Causes a sorted list of symbol names and values to be
7719 listed on the standard output file.
7720
7721 @item -u
7722 Causes undefined symbols to be treated as having the value @code{FALSE}
7723 in the context
7724 of a preprocessor test. In the absence of this option, an undefined symbol in
7725 a @code{#if} or @code{#elsif} test will be treated as an error.
7726
7727 @end table
7728
7729 @noindent
7730 Examples of valid lines in a preprocessor data file:
7731
7732 @smallexample
7733   "toto.adb"  "prep.def" -u
7734   --  preprocess "toto.adb", using definition file "prep.def",
7735   --  undefined symbol are False.
7736
7737   * -c -DVERSION=V101
7738   --  preprocess all other sources without a definition file;
7739   --  suppressed lined are commented; symbol VERSION has the value V101.
7740
7741   "titi.adb" "prep2.def" -s
7742   --  preprocess "titi.adb", using definition file "prep2.def";
7743   --  list all symbols with their values.
7744 @end smallexample
7745
7746 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7747 @cindex @option{-gnateD} (@command{gcc})
7748 Define or redefine a preprocessing symbol, associated with value. If no value
7749 is given on the command line, then the value of the symbol is @code{True}.
7750 A symbol is an identifier, following normal Ada (case-insensitive)
7751 rules for its syntax, and value is any sequence (including an empty sequence)
7752 of characters from the set (letters, digits, period, underline).
7753 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7754 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7755
7756 @noindent
7757 A symbol declared with this ^switch^switch^ on the command line replaces a
7758 symbol with the same name either in a definition file or specified with a
7759 ^switch^switch^ -D in the preprocessor data file.
7760
7761 @noindent
7762 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7763
7764 @item -gnateG
7765 When integrated preprocessing is performed and the preprocessor modifies
7766 the source text, write the result of this preprocessing into a file
7767 <source>^.prep^_prep^.
7768
7769 @end table
7770
7771 @node Code Generation Control
7772 @subsection Code Generation Control
7773
7774 @noindent
7775
7776 The GCC technology provides a wide range of target dependent
7777 @option{-m} switches for controlling
7778 details of code generation with respect to different versions of
7779 architectures. This includes variations in instruction sets (e.g.@:
7780 different members of the power pc family), and different requirements
7781 for optimal arrangement of instructions (e.g.@: different members of
7782 the x86 family). The list of available @option{-m} switches may be
7783 found in the GCC documentation.
7784
7785 Use of these @option{-m} switches may in some cases result in improved
7786 code performance.
7787
7788 The @value{EDITION} technology is tested and qualified without any
7789 @option{-m} switches,
7790 so generally the most reliable approach is to avoid the use of these
7791 switches. However, we generally expect most of these switches to work
7792 successfully with @value{EDITION}, and many customers have reported successful
7793 use of these options.
7794
7795 Our general advice is to avoid the use of @option{-m} switches unless
7796 special needs lead to requirements in this area. In particular,
7797 there is no point in using @option{-m} switches to improve performance
7798 unless you actually see a performance improvement.
7799
7800 @ifset vms
7801 @node Return Codes
7802 @subsection Return Codes
7803 @cindex Return Codes
7804 @cindex @option{/RETURN_CODES=VMS}
7805
7806 @noindent
7807 On VMS, GNAT compiled programs return POSIX-style codes by default,
7808 e.g.@: @option{/RETURN_CODES=POSIX}.
7809
7810 To enable VMS style return codes, use GNAT BIND and LINK with the option
7811 @option{/RETURN_CODES=VMS}. For example:
7812
7813 @smallexample
7814 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7815 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7816 @end smallexample
7817
7818 @noindent
7819 Programs built with /RETURN_CODES=VMS are suitable to be called in
7820 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7821 are suitable for spawning with appropriate GNAT RTL routines.
7822
7823 @end ifset
7824
7825 @node Search Paths and the Run-Time Library (RTL)
7826 @section Search Paths and the Run-Time Library (RTL)
7827
7828 @noindent
7829 With the GNAT source-based library system, the compiler must be able to
7830 find source files for units that are needed by the unit being compiled.
7831 Search paths are used to guide this process.
7832
7833 The compiler compiles one source file whose name must be given
7834 explicitly on the command line. In other words, no searching is done
7835 for this file. To find all other source files that are needed (the most
7836 common being the specs of units), the compiler examines the following
7837 directories, in the following order:
7838
7839 @enumerate
7840 @item
7841 The directory containing the source file of the main unit being compiled
7842 (the file name on the command line).
7843
7844 @item
7845 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7846 @command{gcc} command line, in the order given.
7847
7848 @item
7849 @findex ADA_PRJ_INCLUDE_FILE
7850 Each of the directories listed in the text file whose name is given
7851 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7852
7853 @noindent
7854 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7855 driver when project files are used. It should not normally be set
7856 by other means.
7857
7858 @item
7859 @findex ADA_INCLUDE_PATH
7860 Each of the directories listed in the value of the
7861 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7862 @ifclear vms
7863 Construct this value
7864 exactly as the @env{PATH} environment variable: a list of directory
7865 names separated by colons (semicolons when working with the NT version).
7866 @end ifclear
7867 @ifset vms
7868 Normally, define this value as a logical name containing a comma separated
7869 list of directory names.
7870
7871 This variable can also be defined by means of an environment string
7872 (an argument to the HP C exec* set of functions).
7873
7874 Logical Name:
7875 @smallexample
7876 DEFINE ANOTHER_PATH FOO:[BAG]
7877 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7878 @end smallexample
7879
7880 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7881 first, followed by the standard Ada
7882 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7883 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7884 (Text_IO, Sequential_IO, etc)
7885 instead of the standard Ada packages. Thus, in order to get the standard Ada
7886 packages by default, ADA_INCLUDE_PATH must be redefined.
7887 @end ifset
7888
7889 @item
7890 The content of the @file{ada_source_path} file which is part of the GNAT
7891 installation tree and is used to store standard libraries such as the
7892 GNAT Run Time Library (RTL) source files.
7893 @ifclear vms
7894 @ref{Installing a library}
7895 @end ifclear
7896 @end enumerate
7897
7898 @noindent
7899 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7900 inhibits the use of the directory
7901 containing the source file named in the command line. You can still
7902 have this directory on your search path, but in this case it must be
7903 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7904
7905 Specifying the switch @option{-nostdinc}
7906 inhibits the search of the default location for the GNAT Run Time
7907 Library (RTL) source files.
7908
7909 The compiler outputs its object files and ALI files in the current
7910 working directory.
7911 @ifclear vms
7912 Caution: The object file can be redirected with the @option{-o} switch;
7913 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7914 so the @file{ALI} file will not go to the right place. Therefore, you should
7915 avoid using the @option{-o} switch.
7916 @end ifclear
7917
7918 @findex System.IO
7919 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7920 children make up the GNAT RTL, together with the simple @code{System.IO}
7921 package used in the @code{"Hello World"} example. The sources for these units
7922 are needed by the compiler and are kept together in one directory. Not
7923 all of the bodies are needed, but all of the sources are kept together
7924 anyway. In a normal installation, you need not specify these directory
7925 names when compiling or binding. Either the environment variables or
7926 the built-in defaults cause these files to be found.
7927
7928 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7929 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7930 consisting of child units of @code{GNAT}. This is a collection of generally
7931 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7932 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7933
7934 Besides simplifying access to the RTL, a major use of search paths is
7935 in compiling sources from multiple directories. This can make
7936 development environments much more flexible.
7937
7938 @node Order of Compilation Issues
7939 @section Order of Compilation Issues
7940
7941 @noindent
7942 If, in our earlier example, there was a spec for the @code{hello}
7943 procedure, it would be contained in the file @file{hello.ads}; yet this
7944 file would not have to be explicitly compiled. This is the result of the
7945 model we chose to implement library management. Some of the consequences
7946 of this model are as follows:
7947
7948 @itemize @bullet
7949 @item
7950 There is no point in compiling specs (except for package
7951 specs with no bodies) because these are compiled as needed by clients. If
7952 you attempt a useless compilation, you will receive an error message.
7953 It is also useless to compile subunits because they are compiled as needed
7954 by the parent.
7955
7956 @item
7957 There are no order of compilation requirements: performing a
7958 compilation never obsoletes anything. The only way you can obsolete
7959 something and require recompilations is to modify one of the
7960 source files on which it depends.
7961
7962 @item
7963 There is no library as such, apart from the ALI files
7964 (@pxref{The Ada Library Information Files}, for information on the format
7965 of these files). For now we find it convenient to create separate ALI files,
7966 but eventually the information therein may be incorporated into the object
7967 file directly.
7968
7969 @item
7970 When you compile a unit, the source files for the specs of all units
7971 that it @code{with}'s, all its subunits, and the bodies of any generics it
7972 instantiates must be available (reachable by the search-paths mechanism
7973 described above), or you will receive a fatal error message.
7974 @end itemize
7975
7976 @node Examples
7977 @section Examples
7978
7979 @noindent
7980 The following are some typical Ada compilation command line examples:
7981
7982 @table @code
7983 @item $ gcc -c xyz.adb
7984 Compile body in file @file{xyz.adb} with all default options.
7985
7986 @ifclear vms
7987 @item $ gcc -c -O2 -gnata xyz-def.adb
7988 @end ifclear
7989 @ifset vms
7990 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7991 @end ifset
7992
7993 Compile the child unit package in file @file{xyz-def.adb} with extensive
7994 optimizations, and pragma @code{Assert}/@code{Debug} statements
7995 enabled.
7996
7997 @item $ gcc -c -gnatc abc-def.adb
7998 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7999 mode.
8000 @end table
8001
8002 @node Binding Using gnatbind
8003 @chapter Binding Using @code{gnatbind}
8004 @findex gnatbind
8005
8006 @menu
8007 * Running gnatbind::
8008 * Switches for gnatbind::
8009 * Command-Line Access::
8010 * Search Paths for gnatbind::
8011 * Examples of gnatbind Usage::
8012 @end menu
8013
8014 @noindent
8015 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8016 to bind compiled GNAT objects.
8017
8018 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8019 driver (see @ref{The GNAT Driver and Project Files}).
8020
8021 The @code{gnatbind} program performs four separate functions:
8022
8023 @enumerate
8024 @item
8025 Checks that a program is consistent, in accordance with the rules in
8026 Chapter 10 of the Ada Reference Manual. In particular, error
8027 messages are generated if a program uses inconsistent versions of a
8028 given unit.
8029
8030 @item
8031 Checks that an acceptable order of elaboration exists for the program
8032 and issues an error message if it cannot find an order of elaboration
8033 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8034
8035 @item
8036 Generates a main program incorporating the given elaboration order.
8037 This program is a small Ada package (body and spec) that
8038 must be subsequently compiled
8039 using the GNAT compiler. The necessary compilation step is usually
8040 performed automatically by @command{gnatlink}. The two most important
8041 functions of this program
8042 are to call the elaboration routines of units in an appropriate order
8043 and to call the main program.
8044
8045 @item
8046 Determines the set of object files required by the given main program.
8047 This information is output in the forms of comments in the generated program,
8048 to be read by the @command{gnatlink} utility used to link the Ada application.
8049 @end enumerate
8050
8051 @node Running gnatbind
8052 @section Running @code{gnatbind}
8053
8054 @noindent
8055 The form of the @code{gnatbind} command is
8056
8057 @smallexample
8058 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8059 @c Expanding @ovar macro inline (explanation in macro def comments)
8060 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8061 @end smallexample
8062
8063 @noindent
8064 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8065 unit body. @code{gnatbind} constructs an Ada
8066 package in two files whose names are
8067 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8068 For example, if given the
8069 parameter @file{hello.ali}, for a main program contained in file
8070 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8071 and @file{b~hello.adb}.
8072
8073 When doing consistency checking, the binder takes into consideration
8074 any source files it can locate. For example, if the binder determines
8075 that the given main program requires the package @code{Pack}, whose
8076 @file{.ALI}
8077 file is @file{pack.ali} and whose corresponding source spec file is
8078 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8079 (using the same search path conventions as previously described for the
8080 @command{gcc} command). If it can locate this source file, it checks that
8081 the time stamps
8082 or source checksums of the source and its references to in @file{ALI} files
8083 match. In other words, any @file{ALI} files that mentions this spec must have
8084 resulted from compiling this version of the source file (or in the case
8085 where the source checksums match, a version close enough that the
8086 difference does not matter).
8087
8088 @cindex Source files, use by binder
8089 The effect of this consistency checking, which includes source files, is
8090 that the binder ensures that the program is consistent with the latest
8091 version of the source files that can be located at bind time. Editing a
8092 source file without compiling files that depend on the source file cause
8093 error messages to be generated by the binder.
8094
8095 For example, suppose you have a main program @file{hello.adb} and a
8096 package @code{P}, from file @file{p.ads} and you perform the following
8097 steps:
8098
8099 @enumerate
8100 @item
8101 Enter @code{gcc -c hello.adb} to compile the main program.
8102
8103 @item
8104 Enter @code{gcc -c p.ads} to compile package @code{P}.
8105
8106 @item
8107 Edit file @file{p.ads}.
8108
8109 @item
8110 Enter @code{gnatbind hello}.
8111 @end enumerate
8112
8113 @noindent
8114 At this point, the file @file{p.ali} contains an out-of-date time stamp
8115 because the file @file{p.ads} has been edited. The attempt at binding
8116 fails, and the binder generates the following error messages:
8117
8118 @smallexample
8119 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8120 error: "p.ads" has been modified and must be recompiled
8121 @end smallexample
8122
8123 @noindent
8124 Now both files must be recompiled as indicated, and then the bind can
8125 succeed, generating a main program. You need not normally be concerned
8126 with the contents of this file, but for reference purposes a sample
8127 binder output file is given in @ref{Example of Binder Output File}.
8128
8129 In most normal usage, the default mode of @command{gnatbind} which is to
8130 generate the main package in Ada, as described in the previous section.
8131 In particular, this means that any Ada programmer can read and understand
8132 the generated main program. It can also be debugged just like any other
8133 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8134 @command{gnatbind} and @command{gnatlink}.
8135
8136 @node Switches for gnatbind
8137 @section Switches for @command{gnatbind}
8138
8139 @noindent
8140 The following switches are available with @code{gnatbind}; details will
8141 be presented in subsequent sections.
8142
8143 @menu
8144 * Consistency-Checking Modes::
8145 * Binder Error Message Control::
8146 * Elaboration Control::
8147 * Output Control::
8148 * Dynamic Allocation Control::
8149 * Binding with Non-Ada Main Programs::
8150 * Binding Programs with No Main Subprogram::
8151 @end menu
8152
8153 @table @option
8154 @c !sort!
8155
8156 @item --version
8157 @cindex @option{--version} @command{gnatbind}
8158 Display Copyright and version, then exit disregarding all other options.
8159
8160 @item --help
8161 @cindex @option{--help} @command{gnatbind}
8162 If @option{--version} was not used, display usage, then exit disregarding
8163 all other options.
8164
8165 @item -a
8166 @cindex @option{-a} @command{gnatbind}
8167 Indicates that, if supported by the platform, the adainit procedure should
8168 be treated as an initialisation routine by the linker (a constructor). This
8169 is intended to be used by the Project Manager to automatically initialize
8170 shared Stand-Alone Libraries.
8171
8172 @item ^-aO^/OBJECT_SEARCH^
8173 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8174 Specify directory to be searched for ALI files.
8175
8176 @item ^-aI^/SOURCE_SEARCH^
8177 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8178 Specify directory to be searched for source file.
8179
8180 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8181 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8182 Output ALI list (to standard output or to the named file).
8183
8184 @item ^-b^/REPORT_ERRORS=BRIEF^
8185 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8186 Generate brief messages to @file{stderr} even if verbose mode set.
8187
8188 @item ^-c^/NOOUTPUT^
8189 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8190 Check only, no generation of binder output file.
8191
8192 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8193 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8194 This switch can be used to change the default task stack size value
8195 to a specified size @var{nn}, which is expressed in bytes by default, or
8196 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8197 with @var{m}.
8198 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8199 in effect, to completing all task specs with
8200 @smallexample @c ada
8201    pragma Storage_Size (nn);
8202 @end smallexample
8203 When they do not already have such a pragma.
8204
8205 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8206 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8207 This switch can be used to change the default secondary stack size value
8208 to a specified size @var{nn}, which is expressed in bytes by default, or
8209 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8210 with @var{m}.
8211
8212 The secondary stack is used to deal with functions that return a variable
8213 sized result, for example a function returning an unconstrained
8214 String. There are two ways in which this secondary stack is allocated.
8215
8216 For most targets, the secondary stack is growing on demand and is allocated
8217 as a chain of blocks in the heap. The -D option is not very
8218 relevant. It only give some control over the size of the allocated
8219 blocks (whose size is the minimum of the default secondary stack size value,
8220 and the actual size needed for the current allocation request).
8221
8222 For certain targets, notably VxWorks 653,
8223 the secondary stack is allocated by carving off a fixed ratio chunk of the
8224 primary task stack. The -D option is used to define the
8225 size of the environment task's secondary stack.
8226
8227 @item ^-e^/ELABORATION_DEPENDENCIES^
8228 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8229 Output complete list of elaboration-order dependencies.
8230
8231 @item ^-E^/STORE_TRACEBACKS^
8232 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8233 Store tracebacks in exception occurrences when the target supports it.
8234 @ignore
8235 @c The following may get moved to an appendix
8236 This option is currently supported on the following targets:
8237 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8238 @end ignore
8239 See also the packages @code{GNAT.Traceback} and
8240 @code{GNAT.Traceback.Symbolic} for more information.
8241 @ifclear vms
8242 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8243 @command{gcc} option.
8244 @end ifclear
8245
8246 @item ^-F^/FORCE_ELABS_FLAGS^
8247 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8248 Force the checks of elaboration flags. @command{gnatbind} does not normally
8249 generate checks of elaboration flags for the main executable, except when
8250 a Stand-Alone Library is used. However, there are cases when this cannot be
8251 detected by gnatbind. An example is importing an interface of a Stand-Alone
8252 Library through a pragma Import and only specifying through a linker switch
8253 this Stand-Alone Library. This switch is used to guarantee that elaboration
8254 flag checks are generated.
8255
8256 @item ^-h^/HELP^
8257 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8258 Output usage (help) information
8259
8260 @item ^-H32^/32_MALLOC^
8261 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8262 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8263 For further details see @ref{Dynamic Allocation Control}.
8264
8265 @item ^-H64^/64_MALLOC^
8266 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8267 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8268 @cindex @code{__gnat_malloc}
8269 For further details see @ref{Dynamic Allocation Control}.
8270
8271 @item ^-I^/SEARCH^
8272 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8273 Specify directory to be searched for source and ALI files.
8274
8275 @item ^-I-^/NOCURRENT_DIRECTORY^
8276 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8277 Do not look for sources in the current directory where @code{gnatbind} was
8278 invoked, and do not look for ALI files in the directory containing the
8279 ALI file named in the @code{gnatbind} command line.
8280
8281 @item ^-l^/ORDER_OF_ELABORATION^
8282 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8283 Output chosen elaboration order.
8284
8285 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8286 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8287 Bind the units for library building. In this case the adainit and
8288 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8289 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8290 ^@var{xxx}final^@var{XXX}FINAL^.
8291 Implies ^-n^/NOCOMPILE^.
8292 @ifclear vms
8293 (@xref{GNAT and Libraries}, for more details.)
8294 @end ifclear
8295 @ifset vms
8296 On OpenVMS, these init and final procedures are exported in uppercase
8297 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8298 the init procedure will be "TOTOINIT" and the exported name of the final
8299 procedure will be "TOTOFINAL".
8300 @end ifset
8301
8302 @item ^-Mxyz^/RENAME_MAIN=xyz^
8303 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8304 Rename generated main program from main to xyz. This option is
8305 supported on cross environments only.
8306
8307 @item ^-m^/ERROR_LIMIT=^@var{n}
8308 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8309 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8310 in the range 1..999999. The default value if no switch is
8311 given is 9999. If the number of warnings reaches this limit, then a
8312 message is output and further warnings are suppressed, the bind
8313 continues in this case. If the number of errors reaches this
8314 limit, then a message is output and the bind is abandoned.
8315 A value of zero means that no limit is enforced. The equal
8316 sign is optional.
8317
8318 @ifset unw
8319 Furthermore, under Windows, the sources pointed to by the libraries path
8320 set in the registry are not searched for.
8321 @end ifset
8322
8323 @item ^-n^/NOMAIN^
8324 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8325 No main program.
8326
8327 @item -nostdinc
8328 @cindex @option{-nostdinc} (@command{gnatbind})
8329 Do not look for sources in the system default directory.
8330
8331 @item -nostdlib
8332 @cindex @option{-nostdlib} (@command{gnatbind})
8333 Do not look for library files in the system default directory.
8334
8335 @item --RTS=@var{rts-path}
8336 @cindex @option{--RTS} (@code{gnatbind})
8337 Specifies the default location of the runtime library. Same meaning as the
8338 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8339
8340 @item ^-o ^/OUTPUT=^@var{file}
8341 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8342 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8343 Note that if this option is used, then linking must be done manually,
8344 gnatlink cannot be used.
8345
8346 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8347 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8348 Output object list (to standard output or to the named file).
8349
8350 @item ^-p^/PESSIMISTIC_ELABORATION^
8351 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8352 Pessimistic (worst-case) elaboration order
8353
8354 @item ^-P^-P^
8355 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8356 Generate binder file suitable for CodePeer.
8357
8358 @item ^-R^-R^
8359 @cindex @option{^-R^-R^} (@command{gnatbind})
8360 Output closure source list.
8361
8362 @item ^-s^/READ_SOURCES=ALL^
8363 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8364 Require all source files to be present.
8365
8366 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8367 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8368 Specifies the value to be used when detecting uninitialized scalar
8369 objects with pragma Initialize_Scalars.
8370 The @var{xxx} ^string specified with the switch^option^ may be either
8371 @itemize @bullet
8372 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8373 @item ``@option{^lo^LOW^}'' for the lowest possible value
8374 @item ``@option{^hi^HIGH^}'' for the highest possible value
8375 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8376 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8377 @end itemize
8378
8379 In addition, you can specify @option{-Sev} to indicate that the value is
8380 to be set at run time. In this case, the program will look for an environment
8381 @cindex GNAT_INIT_SCALARS
8382 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8383 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8384 If no environment variable is found, or if it does not have a valid value,
8385 then the default is @option{in} (invalid values).
8386
8387 @ifclear vms
8388 @item -static
8389 @cindex @option{-static} (@code{gnatbind})
8390 Link against a static GNAT run time.
8391
8392 @item -shared
8393 @cindex @option{-shared} (@code{gnatbind})
8394 Link against a shared GNAT run time when available.
8395 @end ifclear
8396
8397 @item ^-t^/NOTIME_STAMP_CHECK^
8398 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8399 Tolerate time stamp and other consistency errors
8400
8401 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8402 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8403 Set the time slice value to @var{n} milliseconds. If the system supports
8404 the specification of a specific time slice value, then the indicated value
8405 is used. If the system does not support specific time slice values, but
8406 does support some general notion of round-robin scheduling, then any
8407 nonzero value will activate round-robin scheduling.
8408
8409 A value of zero is treated specially. It turns off time
8410 slicing, and in addition, indicates to the tasking run time that the
8411 semantics should match as closely as possible the Annex D
8412 requirements of the Ada RM, and in particular sets the default
8413 scheduling policy to @code{FIFO_Within_Priorities}.
8414
8415 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8416 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8417 Enable dynamic stack usage, with @var{n} results stored and displayed
8418 at program termination. A result is generated when a task
8419 terminates. Results that can't be stored are displayed on the fly, at
8420 task termination. This option is currently not supported on Itanium
8421 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8422
8423 @item ^-v^/REPORT_ERRORS=VERBOSE^
8424 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8425 Verbose mode. Write error messages, header, summary output to
8426 @file{stdout}.
8427
8428 @ifclear vms
8429 @item -w@var{x}
8430 @cindex @option{-w} (@code{gnatbind})
8431 Warning mode (@var{x}=s/e for suppress/treat as error)
8432 @end ifclear
8433
8434 @ifset vms
8435 @item /WARNINGS=NORMAL
8436 @cindex @option{/WARNINGS} (@code{gnatbind})
8437 Normal warnings mode. Warnings are issued but ignored
8438
8439 @item /WARNINGS=SUPPRESS
8440 @cindex @option{/WARNINGS} (@code{gnatbind})
8441 All warning messages are suppressed
8442
8443 @item /WARNINGS=ERROR
8444 @cindex @option{/WARNINGS} (@code{gnatbind})
8445 Warning messages are treated as fatal errors
8446 @end ifset
8447
8448 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8449 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8450 Override default wide character encoding for standard Text_IO files.
8451
8452 @item ^-x^/READ_SOURCES=NONE^
8453 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8454 Exclude source files (check object consistency only).
8455
8456 @ifset vms
8457 @item /READ_SOURCES=AVAILABLE
8458 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8459 Default mode, in which sources are checked for consistency only if
8460 they are available.
8461 @end ifset
8462
8463 @item ^-y^/ENABLE_LEAP_SECONDS^
8464 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8465 Enable leap seconds support in @code{Ada.Calendar} and its children.
8466
8467 @item ^-z^/ZERO_MAIN^
8468 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8469 No main subprogram.
8470 @end table
8471
8472 @ifclear vms
8473 @noindent
8474 You may obtain this listing of switches by running @code{gnatbind} with
8475 no arguments.
8476 @end ifclear
8477
8478 @node Consistency-Checking Modes
8479 @subsection Consistency-Checking Modes
8480
8481 @noindent
8482 As described earlier, by default @code{gnatbind} checks
8483 that object files are consistent with one another and are consistent
8484 with any source files it can locate. The following switches control binder
8485 access to sources.
8486
8487 @table @option
8488 @c !sort!
8489 @item ^-s^/READ_SOURCES=ALL^
8490 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8491 Require source files to be present. In this mode, the binder must be
8492 able to locate all source files that are referenced, in order to check
8493 their consistency. In normal mode, if a source file cannot be located it
8494 is simply ignored. If you specify this switch, a missing source
8495 file is an error.
8496
8497 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8498 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8499 Override default wide character encoding for standard Text_IO files.
8500 Normally the default wide character encoding method used for standard
8501 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8502 the main source input (see description of switch
8503 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8504 use of this switch for the binder (which has the same set of
8505 possible arguments) overrides this default as specified.
8506
8507 @item ^-x^/READ_SOURCES=NONE^
8508 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8509 Exclude source files. In this mode, the binder only checks that ALI
8510 files are consistent with one another. Source files are not accessed.
8511 The binder runs faster in this mode, and there is still a guarantee that
8512 the resulting program is self-consistent.
8513 If a source file has been edited since it was last compiled, and you
8514 specify this switch, the binder will not detect that the object
8515 file is out of date with respect to the source file. Note that this is the
8516 mode that is automatically used by @command{gnatmake} because in this
8517 case the checking against sources has already been performed by
8518 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8519
8520 @ifset vms
8521 @item /READ_SOURCES=AVAILABLE
8522 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8523 This is the default mode in which source files are checked if they are
8524 available, and ignored if they are not available.
8525 @end ifset
8526 @end table
8527
8528 @node Binder Error Message Control
8529 @subsection Binder Error Message Control
8530
8531 @noindent
8532 The following switches provide control over the generation of error
8533 messages from the binder:
8534
8535 @table @option
8536 @c !sort!
8537 @item ^-v^/REPORT_ERRORS=VERBOSE^
8538 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8539 Verbose mode. In the normal mode, brief error messages are generated to
8540 @file{stderr}. If this switch is present, a header is written
8541 to @file{stdout} and any error messages are directed to @file{stdout}.
8542 All that is written to @file{stderr} is a brief summary message.
8543
8544 @item ^-b^/REPORT_ERRORS=BRIEF^
8545 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8546 Generate brief error messages to @file{stderr} even if verbose mode is
8547 specified. This is relevant only when used with the
8548 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8549
8550 @ifclear vms
8551 @item -m@var{n}
8552 @cindex @option{-m} (@code{gnatbind})
8553 Limits the number of error messages to @var{n}, a decimal integer in the
8554 range 1-999. The binder terminates immediately if this limit is reached.
8555
8556 @item -M@var{xxx}
8557 @cindex @option{-M} (@code{gnatbind})
8558 Renames the generated main program from @code{main} to @code{xxx}.
8559 This is useful in the case of some cross-building environments, where
8560 the actual main program is separate from the one generated
8561 by @code{gnatbind}.
8562 @end ifclear
8563
8564 @item ^-ws^/WARNINGS=SUPPRESS^
8565 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8566 @cindex Warnings
8567 Suppress all warning messages.
8568
8569 @item ^-we^/WARNINGS=ERROR^
8570 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8571 Treat any warning messages as fatal errors.
8572
8573 @ifset vms
8574 @item /WARNINGS=NORMAL
8575 Standard mode with warnings generated, but warnings do not get treated
8576 as errors.
8577 @end ifset
8578
8579 @item ^-t^/NOTIME_STAMP_CHECK^
8580 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8581 @cindex Time stamp checks, in binder
8582 @cindex Binder consistency checks
8583 @cindex Consistency checks, in binder
8584 The binder performs a number of consistency checks including:
8585
8586 @itemize @bullet
8587 @item
8588 Check that time stamps of a given source unit are consistent
8589 @item
8590 Check that checksums of a given source unit are consistent
8591 @item
8592 Check that consistent versions of @code{GNAT} were used for compilation
8593 @item
8594 Check consistency of configuration pragmas as required
8595 @end itemize
8596
8597 @noindent
8598 Normally failure of such checks, in accordance with the consistency
8599 requirements of the Ada Reference Manual, causes error messages to be
8600 generated which abort the binder and prevent the output of a binder
8601 file and subsequent link to obtain an executable.
8602
8603 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8604 into warnings, so that
8605 binding and linking can continue to completion even in the presence of such
8606 errors. The result may be a failed link (due to missing symbols), or a
8607 non-functional executable which has undefined semantics.
8608 @emph{This means that
8609 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8610 with extreme care.}
8611 @end table
8612
8613 @node Elaboration Control
8614 @subsection Elaboration Control
8615
8616 @noindent
8617 The following switches provide additional control over the elaboration
8618 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8619
8620 @table @option
8621 @item ^-p^/PESSIMISTIC_ELABORATION^
8622 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8623 Normally the binder attempts to choose an elaboration order that is
8624 likely to minimize the likelihood of an elaboration order error resulting
8625 in raising a @code{Program_Error} exception. This switch reverses the
8626 action of the binder, and requests that it deliberately choose an order
8627 that is likely to maximize the likelihood of an elaboration error.
8628 This is useful in ensuring portability and avoiding dependence on
8629 accidental fortuitous elaboration ordering.
8630
8631 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8632 switch if dynamic
8633 elaboration checking is used (@option{-gnatE} switch used for compilation).
8634 This is because in the default static elaboration mode, all necessary
8635 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8636 These implicit pragmas are still respected by the binder in
8637 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8638 safe elaboration order is assured.
8639 @end table
8640
8641 @node Output Control
8642 @subsection Output Control
8643
8644 @noindent
8645 The following switches allow additional control over the output
8646 generated by the binder.
8647
8648 @table @option
8649 @c !sort!
8650
8651 @item ^-c^/NOOUTPUT^
8652 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8653 Check only. Do not generate the binder output file. In this mode the
8654 binder performs all error checks but does not generate an output file.
8655
8656 @item ^-e^/ELABORATION_DEPENDENCIES^
8657 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8658 Output complete list of elaboration-order dependencies, showing the
8659 reason for each dependency. This output can be rather extensive but may
8660 be useful in diagnosing problems with elaboration order. The output is
8661 written to @file{stdout}.
8662
8663 @item ^-h^/HELP^
8664 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8665 Output usage information. The output is written to @file{stdout}.
8666
8667 @item ^-K^/LINKER_OPTION_LIST^
8668 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8669 Output linker options to @file{stdout}. Includes library search paths,
8670 contents of pragmas Ident and Linker_Options, and libraries added
8671 by @code{gnatbind}.
8672
8673 @item ^-l^/ORDER_OF_ELABORATION^
8674 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8675 Output chosen elaboration order. The output is written to @file{stdout}.
8676
8677 @item ^-O^/OBJECT_LIST^
8678 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8679 Output full names of all the object files that must be linked to provide
8680 the Ada component of the program. The output is written to @file{stdout}.
8681 This list includes the files explicitly supplied and referenced by the user
8682 as well as implicitly referenced run-time unit files. The latter are
8683 omitted if the corresponding units reside in shared libraries. The
8684 directory names for the run-time units depend on the system configuration.
8685
8686 @item ^-o ^/OUTPUT=^@var{file}
8687 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8688 Set name of output file to @var{file} instead of the normal
8689 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8690 binder generated body filename.
8691 Note that if this option is used, then linking must be done manually.
8692 It is not possible to use gnatlink in this case, since it cannot locate
8693 the binder file.
8694
8695 @item ^-r^/RESTRICTION_LIST^
8696 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8697 Generate list of @code{pragma Restrictions} that could be applied to
8698 the current unit. This is useful for code audit purposes, and also may
8699 be used to improve code generation in some cases.
8700
8701 @end table
8702
8703 @node Dynamic Allocation Control
8704 @subsection Dynamic Allocation Control
8705
8706 @noindent
8707 The heap control switches -- @option{-H32} and @option{-H64} --
8708 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8709 They only affect compiler-generated allocations via @code{__gnat_malloc};
8710 explicit calls to @code{malloc} and related functions from the C
8711 run-time library are unaffected.
8712
8713 @table @option
8714 @item -H32
8715 Allocate memory on 32-bit heap
8716
8717 @item -H64
8718 Allocate memory on 64-bit heap.  This is the default
8719 unless explicitly overridden by a @code{'Size} clause on the access type.
8720 @end table
8721
8722 @ifset vms
8723 @noindent
8724 See also @ref{Access types and 32/64-bit allocation}.
8725 @end ifset
8726 @ifclear vms
8727 @noindent
8728 These switches are only effective on VMS platforms.
8729 @end ifclear
8730
8731
8732 @node Binding with Non-Ada Main Programs
8733 @subsection Binding with Non-Ada Main Programs
8734
8735 @noindent
8736 In our description so far we have assumed that the main
8737 program is in Ada, and that the task of the binder is to generate a
8738 corresponding function @code{main} that invokes this Ada main
8739 program. GNAT also supports the building of executable programs where
8740 the main program is not in Ada, but some of the called routines are
8741 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8742 The following switch is used in this situation:
8743
8744 @table @option
8745 @item ^-n^/NOMAIN^
8746 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8747 No main program. The main program is not in Ada.
8748 @end table
8749
8750 @noindent
8751 In this case, most of the functions of the binder are still required,
8752 but instead of generating a main program, the binder generates a file
8753 containing the following callable routines:
8754
8755 @table @code
8756 @item adainit
8757 @findex adainit
8758 You must call this routine to initialize the Ada part of the program by
8759 calling the necessary elaboration routines. A call to @code{adainit} is
8760 required before the first call to an Ada subprogram.
8761
8762 Note that it is assumed that the basic execution environment must be setup
8763 to be appropriate for Ada execution at the point where the first Ada
8764 subprogram is called. In particular, if the Ada code will do any
8765 floating-point operations, then the FPU must be setup in an appropriate
8766 manner. For the case of the x86, for example, full precision mode is
8767 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8768 that the FPU is in the right state.
8769
8770 @item adafinal
8771 @findex adafinal
8772 You must call this routine to perform any library-level finalization
8773 required by the Ada subprograms. A call to @code{adafinal} is required
8774 after the last call to an Ada subprogram, and before the program
8775 terminates.
8776 @end table
8777
8778 @noindent
8779 If the @option{^-n^/NOMAIN^} switch
8780 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8781 @cindex Binder, multiple input files
8782 is given, more than one ALI file may appear on
8783 the command line for @code{gnatbind}. The normal @dfn{closure}
8784 calculation is performed for each of the specified units. Calculating
8785 the closure means finding out the set of units involved by tracing
8786 @code{with} references. The reason it is necessary to be able to
8787 specify more than one ALI file is that a given program may invoke two or
8788 more quite separate groups of Ada units.
8789
8790 The binder takes the name of its output file from the last specified ALI
8791 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8792 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8793 The output is an Ada unit in source form that can be compiled with GNAT.
8794 This compilation occurs automatically as part of the @command{gnatlink}
8795 processing.
8796
8797 Currently the GNAT run time requires a FPU using 80 bits mode
8798 precision. Under targets where this is not the default it is required to
8799 call GNAT.Float_Control.Reset before using floating point numbers (this
8800 include float computation, float input and output) in the Ada code. A
8801 side effect is that this could be the wrong mode for the foreign code
8802 where floating point computation could be broken after this call.
8803
8804 @node Binding Programs with No Main Subprogram
8805 @subsection Binding Programs with No Main Subprogram
8806
8807 @noindent
8808 It is possible to have an Ada program which does not have a main
8809 subprogram. This program will call the elaboration routines of all the
8810 packages, then the finalization routines.
8811
8812 The following switch is used to bind programs organized in this manner:
8813
8814 @table @option
8815 @item ^-z^/ZERO_MAIN^
8816 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8817 Normally the binder checks that the unit name given on the command line
8818 corresponds to a suitable main subprogram. When this switch is used,
8819 a list of ALI files can be given, and the execution of the program
8820 consists of elaboration of these units in an appropriate order. Note
8821 that the default wide character encoding method for standard Text_IO
8822 files is always set to Brackets if this switch is set (you can use
8823 the binder switch
8824 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8825 @end table
8826
8827 @node Command-Line Access
8828 @section Command-Line Access
8829
8830 @noindent
8831 The package @code{Ada.Command_Line} provides access to the command-line
8832 arguments and program name. In order for this interface to operate
8833 correctly, the two variables
8834
8835 @smallexample
8836 @group
8837 int gnat_argc;
8838 char **gnat_argv;
8839 @end group
8840 @end smallexample
8841
8842 @noindent
8843 @findex gnat_argv
8844 @findex gnat_argc
8845 are declared in one of the GNAT library routines. These variables must
8846 be set from the actual @code{argc} and @code{argv} values passed to the
8847 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8848 generates the C main program to automatically set these variables.
8849 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8850 set these variables. If they are not set, the procedures in
8851 @code{Ada.Command_Line} will not be available, and any attempt to use
8852 them will raise @code{Constraint_Error}. If command line access is
8853 required, your main program must set @code{gnat_argc} and
8854 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8855 it.
8856
8857 @node Search Paths for gnatbind
8858 @section Search Paths for @code{gnatbind}
8859
8860 @noindent
8861 The binder takes the name of an ALI file as its argument and needs to
8862 locate source files as well as other ALI files to verify object consistency.
8863
8864 For source files, it follows exactly the same search rules as @command{gcc}
8865 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8866 directories searched are:
8867
8868 @enumerate
8869 @item
8870 The directory containing the ALI file named in the command line, unless
8871 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8872
8873 @item
8874 All directories specified by @option{^-I^/SEARCH^}
8875 switches on the @code{gnatbind}
8876 command line, in the order given.
8877
8878 @item
8879 @findex ADA_PRJ_OBJECTS_FILE
8880 Each of the directories listed in the text file whose name is given
8881 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8882
8883 @noindent
8884 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8885 driver when project files are used. It should not normally be set
8886 by other means.
8887
8888 @item
8889 @findex ADA_OBJECTS_PATH
8890 Each of the directories listed in the value of the
8891 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8892 @ifset unw
8893 Construct this value
8894 exactly as the @env{PATH} environment variable: a list of directory
8895 names separated by colons (semicolons when working with the NT version
8896 of GNAT).
8897 @end ifset
8898 @ifset vms
8899 Normally, define this value as a logical name containing a comma separated
8900 list of directory names.
8901
8902 This variable can also be defined by means of an environment string
8903 (an argument to the HP C exec* set of functions).
8904
8905 Logical Name:
8906 @smallexample
8907 DEFINE ANOTHER_PATH FOO:[BAG]
8908 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8909 @end smallexample
8910
8911 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8912 first, followed by the standard Ada
8913 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8914 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8915 (Text_IO, Sequential_IO, etc)
8916 instead of the standard Ada packages. Thus, in order to get the standard Ada
8917 packages by default, ADA_OBJECTS_PATH must be redefined.
8918 @end ifset
8919
8920 @item
8921 The content of the @file{ada_object_path} file which is part of the GNAT
8922 installation tree and is used to store standard libraries such as the
8923 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8924 specified.
8925 @ifclear vms
8926 @ref{Installing a library}
8927 @end ifclear
8928 @end enumerate
8929
8930 @noindent
8931 In the binder the switch @option{^-I^/SEARCH^}
8932 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8933 is used to specify both source and
8934 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8935 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8936 instead if you want to specify
8937 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8938 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8939 if you want to specify library paths
8940 only. This means that for the binder
8941 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8942 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8943 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8944 The binder generates the bind file (a C language source file) in the
8945 current working directory.
8946
8947 @findex Ada
8948 @findex System
8949 @findex Interfaces
8950 @findex GNAT
8951 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8952 children make up the GNAT Run-Time Library, together with the package
8953 GNAT and its children, which contain a set of useful additional
8954 library functions provided by GNAT. The sources for these units are
8955 needed by the compiler and are kept together in one directory. The ALI
8956 files and object files generated by compiling the RTL are needed by the
8957 binder and the linker and are kept together in one directory, typically
8958 different from the directory containing the sources. In a normal
8959 installation, you need not specify these directory names when compiling
8960 or binding. Either the environment variables or the built-in defaults
8961 cause these files to be found.
8962
8963 Besides simplifying access to the RTL, a major use of search paths is
8964 in compiling sources from multiple directories. This can make
8965 development environments much more flexible.
8966
8967 @node Examples of gnatbind Usage
8968 @section Examples of @code{gnatbind} Usage
8969
8970 @noindent
8971 This section contains a number of examples of using the GNAT binding
8972 utility @code{gnatbind}.
8973
8974 @table @code
8975 @item gnatbind hello
8976 The main program @code{Hello} (source program in @file{hello.adb}) is
8977 bound using the standard switch settings. The generated main program is
8978 @file{b~hello.adb}. This is the normal, default use of the binder.
8979
8980 @ifclear vms
8981 @item gnatbind hello -o mainprog.adb
8982 @end ifclear
8983 @ifset vms
8984 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8985 @end ifset
8986 The main program @code{Hello} (source program in @file{hello.adb}) is
8987 bound using the standard switch settings. The generated main program is
8988 @file{mainprog.adb} with the associated spec in
8989 @file{mainprog.ads}. Note that you must specify the body here not the
8990 spec. Note that if this option is used, then linking must be done manually,
8991 since gnatlink will not be able to find the generated file.
8992 @end table
8993
8994 @c ------------------------------------
8995 @node Linking Using gnatlink
8996 @chapter Linking Using @command{gnatlink}
8997 @c ------------------------------------
8998 @findex gnatlink
8999
9000 @noindent
9001 This chapter discusses @command{gnatlink}, a tool that links
9002 an Ada program and builds an executable file. This utility
9003 invokes the system linker ^(via the @command{gcc} command)^^
9004 with a correct list of object files and library references.
9005 @command{gnatlink} automatically determines the list of files and
9006 references for the Ada part of a program. It uses the binder file
9007 generated by the @command{gnatbind} to determine this list.
9008
9009 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9010 driver (see @ref{The GNAT Driver and Project Files}).
9011
9012 @menu
9013 * Running gnatlink::
9014 * Switches for gnatlink::
9015 @end menu
9016
9017 @node Running gnatlink
9018 @section Running @command{gnatlink}
9019
9020 @noindent
9021 The form of the @command{gnatlink} command is
9022
9023 @smallexample
9024 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9025 @c            @ovar{non-Ada objects} @ovar{linker options}
9026 @c Expanding @ovar macro inline (explanation in macro def comments)
9027 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9028            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9029
9030 @end smallexample
9031
9032 @noindent
9033 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9034 non-Ada objects
9035 or linker options) may be in any order, provided that no non-Ada object may
9036 be mistaken for a main @file{ALI} file.
9037 Any file name @file{F} without the @file{.ali}
9038 extension will be taken as the main @file{ALI} file if a file exists
9039 whose name is the concatenation of @file{F} and @file{.ali}.
9040
9041 @noindent
9042 @file{@var{mainprog}.ali} references the ALI file of the main program.
9043 The @file{.ali} extension of this file can be omitted. From this
9044 reference, @command{gnatlink} locates the corresponding binder file
9045 @file{b~@var{mainprog}.adb} and, using the information in this file along
9046 with the list of non-Ada objects and linker options, constructs a
9047 linker command file to create the executable.
9048
9049 The arguments other than the @command{gnatlink} switches and the main
9050 @file{ALI} file are passed to the linker uninterpreted.
9051 They typically include the names of
9052 object files for units written in other languages than Ada and any library
9053 references required to resolve references in any of these foreign language
9054 units, or in @code{Import} pragmas in any Ada units.
9055
9056 @var{linker options} is an optional list of linker specific
9057 switches.
9058 The default linker called by gnatlink is @command{gcc} which in
9059 turn calls the appropriate system linker.
9060
9061 One useful option for the linker is @option{-s}: it reduces the size of the
9062 executable by removing all symbol table and relocation information from the
9063 executable.
9064
9065 Standard options for the linker such as @option{-lmy_lib} or
9066 @option{-Ldir} can be added as is.
9067 For options that are not recognized by
9068 @command{gcc} as linker options, use the @command{gcc} switches
9069 @option{-Xlinker} or @option{-Wl,}.
9070
9071 Refer to the GCC documentation for
9072 details.
9073
9074 Here is an example showing how to generate a linker map:
9075
9076 @smallexample
9077 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9078 @end smallexample
9079
9080 Using @var{linker options} it is possible to set the program stack and
9081 heap size.
9082 @ifset unw
9083 See @ref{Setting Stack Size from gnatlink} and
9084 @ref{Setting Heap Size from gnatlink}.
9085 @end ifset
9086
9087 @command{gnatlink} determines the list of objects required by the Ada
9088 program and prepends them to the list of objects passed to the linker.
9089 @command{gnatlink} also gathers any arguments set by the use of
9090 @code{pragma Linker_Options} and adds them to the list of arguments
9091 presented to the linker.
9092
9093 @ifset vms
9094 @command{gnatlink} accepts the following types of extra files on the command
9095 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9096 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9097 handled according to their extension.
9098 @end ifset
9099
9100 @node Switches for gnatlink
9101 @section Switches for @command{gnatlink}
9102
9103 @noindent
9104 The following switches are available with the @command{gnatlink} utility:
9105
9106 @table @option
9107 @c !sort!
9108
9109 @item --version
9110 @cindex @option{--version} @command{gnatlink}
9111 Display Copyright and version, then exit disregarding all other options.
9112
9113 @item --help
9114 @cindex @option{--help} @command{gnatlink}
9115 If @option{--version} was not used, display usage, then exit disregarding
9116 all other options.
9117
9118 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9119 @cindex Command line length
9120 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9121 On some targets, the command line length is limited, and @command{gnatlink}
9122 will generate a separate file for the linker if the list of object files
9123 is too long.
9124 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9125 to be generated even if
9126 the limit is not exceeded. This is useful in some cases to deal with
9127 special situations where the command line length is exceeded.
9128
9129 @item ^-g^/DEBUG^
9130 @cindex Debugging information, including
9131 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9132 The option to include debugging information causes the Ada bind file (in
9133 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9134 @option{^-g^/DEBUG^}.
9135 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9136 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9137 Without @option{^-g^/DEBUG^}, the binder removes these files by
9138 default. The same procedure apply if a C bind file was generated using
9139 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9140 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9141
9142 @item ^-n^/NOCOMPILE^
9143 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9144 Do not compile the file generated by the binder. This may be used when
9145 a link is rerun with different options, but there is no need to recompile
9146 the binder file.
9147
9148 @item ^-v^/VERBOSE^
9149 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9150 Causes additional information to be output, including a full list of the
9151 included object files. This switch option is most useful when you want
9152 to see what set of object files are being used in the link step.
9153
9154 @item ^-v -v^/VERBOSE/VERBOSE^
9155 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9156 Very verbose mode. Requests that the compiler operate in verbose mode when
9157 it compiles the binder file, and that the system linker run in verbose mode.
9158
9159 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9160 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9161 @var{exec-name} specifies an alternate name for the generated
9162 executable program. If this switch is omitted, the executable has the same
9163 name as the main unit. For example, @code{gnatlink try.ali} creates
9164 an executable called @file{^try^TRY.EXE^}.
9165
9166 @ifclear vms
9167 @item -b @var{target}
9168 @cindex @option{-b} (@command{gnatlink})
9169 Compile your program to run on @var{target}, which is the name of a
9170 system configuration. You must have a GNAT cross-compiler built if
9171 @var{target} is not the same as your host system.
9172
9173 @item -B@var{dir}
9174 @cindex @option{-B} (@command{gnatlink})
9175 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9176 from @var{dir} instead of the default location. Only use this switch
9177 when multiple versions of the GNAT compiler are available.
9178 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9179 for further details. You would normally use the @option{-b} or
9180 @option{-V} switch instead.
9181
9182 @item -M
9183 When linking an executable, create a map file. The name of the map file
9184 has the same name as the executable with extension ".map".
9185
9186 @item -M=mapfile
9187 When linking an executable, create a map file. The name of the map file is
9188 "mapfile".
9189
9190 @item --GCC=@var{compiler_name}
9191 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9192 Program used for compiling the binder file. The default is
9193 @command{gcc}. You need to use quotes around @var{compiler_name} if
9194 @code{compiler_name} contains spaces or other separator characters.
9195 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9196 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9197 inserted after your command name. Thus in the above example the compiler
9198 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9199 A limitation of this syntax is that the name and path name of the executable
9200 itself must not include any embedded spaces. If the compiler executable is
9201 different from the default one (gcc or <prefix>-gcc), then the back-end
9202 switches in the ALI file are not used to compile the binder generated source.
9203 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9204 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9205 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9206 is taken into account. However, all the additional switches are also taken
9207 into account. Thus,
9208 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9209 @option{--GCC="bar -x -y -z -t"}.
9210
9211 @item --LINK=@var{name}
9212 @cindex @option{--LINK=} (@command{gnatlink})
9213 @var{name} is the name of the linker to be invoked. This is especially
9214 useful in mixed language programs since languages such as C++ require
9215 their own linker to be used. When this switch is omitted, the default
9216 name for the linker is @command{gcc}. When this switch is used, the
9217 specified linker is called instead of @command{gcc} with exactly the same
9218 parameters that would have been passed to @command{gcc} so if the desired
9219 linker requires different parameters it is necessary to use a wrapper
9220 script that massages the parameters before invoking the real linker. It
9221 may be useful to control the exact invocation by using the verbose
9222 switch.
9223
9224 @end ifclear
9225
9226 @ifset vms
9227 @item /DEBUG=TRACEBACK
9228 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9229 This qualifier causes sufficient information to be included in the
9230 executable file to allow a traceback, but does not include the full
9231 symbol information needed by the debugger.
9232
9233 @item /IDENTIFICATION="<string>"
9234 @code{"<string>"} specifies the string to be stored in the image file
9235 identification field in the image header.
9236 It overrides any pragma @code{Ident} specified string.
9237
9238 @item /NOINHIBIT-EXEC
9239 Generate the executable file even if there are linker warnings.
9240
9241 @item /NOSTART_FILES
9242 Don't link in the object file containing the ``main'' transfer address.
9243 Used when linking with a foreign language main program compiled with an
9244 HP compiler.
9245
9246 @item /STATIC
9247 Prefer linking with object libraries over sharable images, even without
9248 /DEBUG.
9249 @end ifset
9250
9251 @end table
9252
9253 @node The GNAT Make Program gnatmake
9254 @chapter The GNAT Make Program @command{gnatmake}
9255 @findex gnatmake
9256
9257 @menu
9258 * Running gnatmake::
9259 * Switches for gnatmake::
9260 * Mode Switches for gnatmake::
9261 * Notes on the Command Line::
9262 * How gnatmake Works::
9263 * Examples of gnatmake Usage::
9264 @end menu
9265 @noindent
9266 A typical development cycle when working on an Ada program consists of
9267 the following steps:
9268
9269 @enumerate
9270 @item
9271 Edit some sources to fix bugs.
9272
9273 @item
9274 Add enhancements.
9275
9276 @item
9277 Compile all sources affected.
9278
9279 @item
9280 Rebind and relink.
9281
9282 @item
9283 Test.
9284 @end enumerate
9285
9286 @noindent
9287 The third step can be tricky, because not only do the modified files
9288 @cindex Dependency rules
9289 have to be compiled, but any files depending on these files must also be
9290 recompiled. The dependency rules in Ada can be quite complex, especially
9291 in the presence of overloading, @code{use} clauses, generics and inlined
9292 subprograms.
9293
9294 @command{gnatmake} automatically takes care of the third and fourth steps
9295 of this process. It determines which sources need to be compiled,
9296 compiles them, and binds and links the resulting object files.
9297
9298 Unlike some other Ada make programs, the dependencies are always
9299 accurately recomputed from the new sources. The source based approach of
9300 the GNAT compilation model makes this possible. This means that if
9301 changes to the source program cause corresponding changes in
9302 dependencies, they will always be tracked exactly correctly by
9303 @command{gnatmake}.
9304
9305 @node Running gnatmake
9306 @section Running @command{gnatmake}
9307
9308 @noindent
9309 The usual form of the @command{gnatmake} command is
9310
9311 @smallexample
9312 @c $ gnatmake @ovar{switches} @var{file_name}
9313 @c       @ovar{file_names} @ovar{mode_switches}
9314 @c Expanding @ovar macro inline (explanation in macro def comments)
9315 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9316       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9317 @end smallexample
9318
9319 @noindent
9320 The only required argument is one @var{file_name}, which specifies
9321 a compilation unit that is a main program. Several @var{file_names} can be
9322 specified: this will result in several executables being built.
9323 If @code{switches} are present, they can be placed before the first
9324 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9325 If @var{mode_switches} are present, they must always be placed after
9326 the last @var{file_name} and all @code{switches}.
9327
9328 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9329 extension may be omitted from the @var{file_name} arguments. However, if
9330 you are using non-standard extensions, then it is required that the
9331 extension be given. A relative or absolute directory path can be
9332 specified in a @var{file_name}, in which case, the input source file will
9333 be searched for in the specified directory only. Otherwise, the input
9334 source file will first be searched in the directory where
9335 @command{gnatmake} was invoked and if it is not found, it will be search on
9336 the source path of the compiler as described in
9337 @ref{Search Paths and the Run-Time Library (RTL)}.
9338
9339 All @command{gnatmake} output (except when you specify
9340 @option{^-M^/DEPENDENCIES_LIST^}) is to
9341 @file{stderr}. The output produced by the
9342 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9343 @file{stdout}.
9344
9345 @node Switches for gnatmake
9346 @section Switches for @command{gnatmake}
9347
9348 @noindent
9349 You may specify any of the following switches to @command{gnatmake}:
9350
9351 @table @option
9352 @c !sort!
9353
9354 @item --version
9355 @cindex @option{--version} @command{gnatmake}
9356 Display Copyright and version, then exit disregarding all other options.
9357
9358 @item --help
9359 @cindex @option{--help} @command{gnatmake}
9360 If @option{--version} was not used, display usage, then exit disregarding
9361 all other options.
9362
9363 @ifclear vms
9364 @item --GCC=@var{compiler_name}
9365 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9366 Program used for compiling. The default is `@command{gcc}'. You need to use
9367 quotes around @var{compiler_name} if @code{compiler_name} contains
9368 spaces or other separator characters. As an example @option{--GCC="foo -x
9369 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9370 compiler. A limitation of this syntax is that the name and path name of
9371 the executable itself must not include any embedded spaces. Note that
9372 switch @option{-c} is always inserted after your command name. Thus in the
9373 above example the compiler command that will be used by @command{gnatmake}
9374 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9375 used, only the last @var{compiler_name} is taken into account. However,
9376 all the additional switches are also taken into account. Thus,
9377 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9378 @option{--GCC="bar -x -y -z -t"}.
9379
9380 @item --GNATBIND=@var{binder_name}
9381 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9382 Program used for binding. The default is `@code{gnatbind}'. You need to
9383 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9384 or other separator characters. As an example @option{--GNATBIND="bar -x
9385 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9386 binder. Binder switches that are normally appended by @command{gnatmake}
9387 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9388 A limitation of this syntax is that the name and path name of the executable
9389 itself must not include any embedded spaces.
9390
9391 @item --GNATLINK=@var{linker_name}
9392 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9393 Program used for linking. The default is `@command{gnatlink}'. You need to
9394 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9395 or other separator characters. As an example @option{--GNATLINK="lan -x
9396 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9397 linker. Linker switches that are normally appended by @command{gnatmake} to
9398 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9399 A limitation of this syntax is that the name and path name of the executable
9400 itself must not include any embedded spaces.
9401
9402 @end ifclear
9403
9404 @item ^--subdirs^/SUBDIRS^=subdir
9405 Actual object directory of each project file is the subdirectory subdir of the
9406 object directory specified or defaulted in the project file.
9407
9408 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9409 Disallow simultaneous compilations in the same object directory when
9410 project files are used.
9411
9412 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9413 By default, shared library projects are not allowed to import static library
9414 projects. When this switch is used on the command line, this restriction is
9415 relaxed.
9416
9417 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9418 Specify a source info file. This switch is active only when project files
9419 are used. If the source info file is specified as a relative path, then it is
9420 relative to the object directory of the main project. If the source info file
9421 does not exist, then after the Project Manager has successfully parsed and
9422 processed the project files and found the sources, it creates the source info
9423 file. If the source info file already exists and can be read successfully,
9424 then the Project Manager will get all the needed information about the sources
9425 from the source info file and will not look for them. This reduces the time
9426 to process the project files, especially when looking for sources that take a
9427 long time. If the source info file exists but cannot be parsed successfully,
9428 the Project Manager will attempt to recreate it. If the Project Manager fails
9429 to create the source info file, a message is issued, but gnatmake does not
9430 fail. @command{gnatmake} "trusts" the source info file. This means that
9431 if the source files have changed (addition, deletion, moving to a different
9432 source directory), then the source info file need to be deleted and recreated.
9433
9434 @ifclear vms
9435 @item --create-map-file
9436 When linking an executable, create a map file. The name of the map file
9437 has the same name as the executable with extension ".map".
9438
9439 @item --create-map-file=mapfile
9440 When linking an executable, create a map file. The name of the map file is
9441 "mapfile".
9442
9443 @end ifclear
9444
9445 @item ^-a^/ALL_FILES^
9446 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9447 Consider all files in the make process, even the GNAT internal system
9448 files (for example, the predefined Ada library files), as well as any
9449 locked files. Locked files are files whose ALI file is write-protected.
9450 By default,
9451 @command{gnatmake} does not check these files,
9452 because the assumption is that the GNAT internal files are properly up
9453 to date, and also that any write protected ALI files have been properly
9454 installed. Note that if there is an installation problem, such that one
9455 of these files is not up to date, it will be properly caught by the
9456 binder.
9457 You may have to specify this switch if you are working on GNAT
9458 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9459 in conjunction with @option{^-f^/FORCE_COMPILE^}
9460 if you need to recompile an entire application,
9461 including run-time files, using special configuration pragmas,
9462 such as a @code{Normalize_Scalars} pragma.
9463
9464 By default
9465 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9466 internal files with
9467 @ifclear vms
9468 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9469 @end ifclear
9470 @ifset vms
9471 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9472 @end ifset
9473
9474 @item ^-b^/ACTIONS=BIND^
9475 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9476 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9477 compilation and binding, but no link.
9478 Can be combined with @option{^-l^/ACTIONS=LINK^}
9479 to do binding and linking. When not combined with
9480 @option{^-c^/ACTIONS=COMPILE^}
9481 all the units in the closure of the main program must have been previously
9482 compiled and must be up to date. The root unit specified by @var{file_name}
9483 may be given without extension, with the source extension or, if no GNAT
9484 Project File is specified, with the ALI file extension.
9485
9486 @item ^-c^/ACTIONS=COMPILE^
9487 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9488 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9489 is also specified. Do not perform linking, except if both
9490 @option{^-b^/ACTIONS=BIND^} and
9491 @option{^-l^/ACTIONS=LINK^} are also specified.
9492 If the root unit specified by @var{file_name} is not a main unit, this is the
9493 default. Otherwise @command{gnatmake} will attempt binding and linking
9494 unless all objects are up to date and the executable is more recent than
9495 the objects.
9496
9497 @item ^-C^/MAPPING^
9498 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9499 Use a temporary mapping file. A mapping file is a way to communicate
9500 to the compiler two mappings: from unit names to file names (without
9501 any directory information) and from file names to path names (with
9502 full directory information). A mapping file can make the compiler's
9503 file searches faster, especially if there are many source directories,
9504 or the sources are read over a slow network connection. If
9505 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9506 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9507 is initially populated based on the project file. If
9508 @option{^-C^/MAPPING^} is used without
9509 @option{^-P^/PROJECT_FILE^},
9510 the mapping file is initially empty. Each invocation of the compiler
9511 will add any newly accessed sources to the mapping file.
9512
9513 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9514 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9515 Use a specific mapping file. The file, specified as a path name (absolute or
9516 relative) by this switch, should already exist, otherwise the switch is
9517 ineffective. The specified mapping file will be communicated to the compiler.
9518 This switch is not compatible with a project file
9519 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9520 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9521
9522 @item ^-d^/DISPLAY_PROGRESS^
9523 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9524 Display progress for each source, up to date or not, as a single line
9525
9526 @smallexample
9527 completed x out of y (zz%)
9528 @end smallexample
9529
9530 If the file needs to be compiled this is displayed after the invocation of
9531 the compiler. These lines are displayed even in quiet output mode.
9532
9533 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9534 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9535 Put all object files and ALI file in directory @var{dir}.
9536 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9537 and ALI files go in the current working directory.
9538
9539 This switch cannot be used when using a project file.
9540
9541 @item -eInnn
9542 @cindex @option{-eI} (@command{gnatmake})
9543 Indicates that the main source is a multi-unit source and the rank of the unit
9544 in the source file is nnn. nnn needs to be a positive number and a valid
9545 index in the source. This switch cannot be used when @command{gnatmake} is
9546 invoked for several mains.
9547
9548 @ifclear vms
9549 @item -eL
9550 @cindex @option{-eL} (@command{gnatmake})
9551 @cindex symbolic links
9552 Follow all symbolic links when processing project files.
9553 This should be used if your project uses symbolic links for files or
9554 directories, but is not needed in other cases.
9555
9556 @cindex naming scheme
9557 This also assumes that no directory matches the naming scheme for files (for
9558 instance that you do not have a directory called "sources.ads" when using the
9559 default GNAT naming scheme).
9560
9561 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9562 save a lot of system calls (several per source file and object file), which
9563 can result in a significant speed up to load and manipulate a project file,
9564 especially when using source files from a remote system.
9565
9566 @end ifclear
9567
9568 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9569 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9570 Output the commands for the compiler, the binder and the linker
9571 on ^standard output^SYS$OUTPUT^,
9572 instead of ^standard error^SYS$ERROR^.
9573
9574 @item ^-f^/FORCE_COMPILE^
9575 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9576 Force recompilations. Recompile all sources, even though some object
9577 files may be up to date, but don't recompile predefined or GNAT internal
9578 files or locked files (files with a write-protected ALI file),
9579 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9580
9581 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9582 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9583 When using project files, if some errors or warnings are detected during
9584 parsing and verbose mode is not in effect (no use of switch
9585 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9586 file, rather than its simple file name.
9587
9588 @item ^-g^/DEBUG^
9589 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9590 Enable debugging. This switch is simply passed to the compiler and to the
9591 linker.
9592
9593 @item ^-i^/IN_PLACE^
9594 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9595 In normal mode, @command{gnatmake} compiles all object files and ALI files
9596 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9597 then instead object files and ALI files that already exist are overwritten
9598 in place. This means that once a large project is organized into separate
9599 directories in the desired manner, then @command{gnatmake} will automatically
9600 maintain and update this organization. If no ALI files are found on the
9601 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9602 the new object and ALI files are created in the
9603 directory containing the source being compiled. If another organization
9604 is desired, where objects and sources are kept in different directories,
9605 a useful technique is to create dummy ALI files in the desired directories.
9606 When detecting such a dummy file, @command{gnatmake} will be forced to
9607 recompile the corresponding source file, and it will be put the resulting
9608 object and ALI files in the directory where it found the dummy file.
9609
9610 @item ^-j^/PROCESSES=^@var{n}
9611 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9612 @cindex Parallel make
9613 Use @var{n} processes to carry out the (re)compilations. On a
9614 multiprocessor machine compilations will occur in parallel. In the
9615 event of compilation errors, messages from various compilations might
9616 get interspersed (but @command{gnatmake} will give you the full ordered
9617 list of failing compiles at the end). If this is problematic, rerun
9618 the make process with n set to 1 to get a clean list of messages.
9619
9620 @item ^-k^/CONTINUE_ON_ERROR^
9621 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9622 Keep going. Continue as much as possible after a compilation error. To
9623 ease the programmer's task in case of compilation errors, the list of
9624 sources for which the compile fails is given when @command{gnatmake}
9625 terminates.
9626
9627 If @command{gnatmake} is invoked with several @file{file_names} and with this
9628 switch, if there are compilation errors when building an executable,
9629 @command{gnatmake} will not attempt to build the following executables.
9630
9631 @item ^-l^/ACTIONS=LINK^
9632 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9633 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9634 and linking. Linking will not be performed if combined with
9635 @option{^-c^/ACTIONS=COMPILE^}
9636 but not with @option{^-b^/ACTIONS=BIND^}.
9637 When not combined with @option{^-b^/ACTIONS=BIND^}
9638 all the units in the closure of the main program must have been previously
9639 compiled and must be up to date, and the main program needs to have been bound.
9640 The root unit specified by @var{file_name}
9641 may be given without extension, with the source extension or, if no GNAT
9642 Project File is specified, with the ALI file extension.
9643
9644 @item ^-m^/MINIMAL_RECOMPILATION^
9645 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9646 Specify that the minimum necessary amount of recompilations
9647 be performed. In this mode @command{gnatmake} ignores time
9648 stamp differences when the only
9649 modifications to a source file consist in adding/removing comments,
9650 empty lines, spaces or tabs. This means that if you have changed the
9651 comments in a source file or have simply reformatted it, using this
9652 switch will tell @command{gnatmake} not to recompile files that depend on it
9653 (provided other sources on which these files depend have undergone no
9654 semantic modifications). Note that the debugging information may be
9655 out of date with respect to the sources if the @option{-m} switch causes
9656 a compilation to be switched, so the use of this switch represents a
9657 trade-off between compilation time and accurate debugging information.
9658
9659 @item ^-M^/DEPENDENCIES_LIST^
9660 @cindex Dependencies, producing list
9661 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9662 Check if all objects are up to date. If they are, output the object
9663 dependences to @file{stdout} in a form that can be directly exploited in
9664 a @file{Makefile}. By default, each source file is prefixed with its
9665 (relative or absolute) directory name. This name is whatever you
9666 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9667 and @option{^-I^/SEARCH^} switches. If you use
9668 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9669 @option{^-q^/QUIET^}
9670 (see below), only the source file names,
9671 without relative paths, are output. If you just specify the
9672 @option{^-M^/DEPENDENCIES_LIST^}
9673 switch, dependencies of the GNAT internal system files are omitted. This
9674 is typically what you want. If you also specify
9675 the @option{^-a^/ALL_FILES^} switch,
9676 dependencies of the GNAT internal files are also listed. Note that
9677 dependencies of the objects in external Ada libraries (see switch
9678 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9679 are never reported.
9680
9681 @item ^-n^/DO_OBJECT_CHECK^
9682 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9683 Don't compile, bind, or link. Checks if all objects are up to date.
9684 If they are not, the full name of the first file that needs to be
9685 recompiled is printed.
9686 Repeated use of this option, followed by compiling the indicated source
9687 file, will eventually result in recompiling all required units.
9688
9689 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9690 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9691 Output executable name. The name of the final executable program will be
9692 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9693 name for the executable will be the name of the input file in appropriate form
9694 for an executable file on the host system.
9695
9696 This switch cannot be used when invoking @command{gnatmake} with several
9697 @file{file_names}.
9698
9699 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9700 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9701 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9702 automatically missing object directories, library directories and exec
9703 directories.
9704
9705 @item ^-P^/PROJECT_FILE=^@var{project}
9706 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9707 Use project file @var{project}. Only one such switch can be used.
9708 @xref{gnatmake and Project Files}.
9709
9710 @item ^-q^/QUIET^
9711 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9712 Quiet. When this flag is not set, the commands carried out by
9713 @command{gnatmake} are displayed.
9714
9715 @item ^-s^/SWITCH_CHECK/^
9716 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9717 Recompile if compiler switches have changed since last compilation.
9718 All compiler switches but -I and -o are taken into account in the
9719 following way:
9720 orders between different ``first letter'' switches are ignored, but
9721 orders between same switches are taken into account. For example,
9722 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9723 is equivalent to @option{-O -g}.
9724
9725 This switch is recommended when Integrated Preprocessing is used.
9726
9727 @item ^-u^/UNIQUE^
9728 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9729 Unique. Recompile at most the main files. It implies -c. Combined with
9730 -f, it is equivalent to calling the compiler directly. Note that using
9731 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9732 (@pxref{Project Files and Main Subprograms}).
9733
9734 @item ^-U^/ALL_PROJECTS^
9735 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9736 When used without a project file or with one or several mains on the command
9737 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9738 on the command line, all sources of all project files are checked and compiled
9739 if not up to date, and libraries are rebuilt, if necessary.
9740
9741 @item ^-v^/REASONS^
9742 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9743 Verbose. Display the reason for all recompilations @command{gnatmake}
9744 decides are necessary, with the highest verbosity level.
9745
9746 @item ^-vl^/LOW_VERBOSITY^
9747 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9748 Verbosity level Low. Display fewer lines than in verbosity Medium.
9749
9750 @item ^-vm^/MEDIUM_VERBOSITY^
9751 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9752 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9753
9754 @item ^-vh^/HIGH_VERBOSITY^
9755 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9756 Verbosity level High. Equivalent to ^-v^/REASONS^.
9757
9758 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9759 Indicate the verbosity of the parsing of GNAT project files.
9760 @xref{Switches Related to Project Files}.
9761
9762 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9763 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9764 Indicate that sources that are not part of any Project File may be compiled.
9765 Normally, when using Project Files, only sources that are part of a Project
9766 File may be compile. When this switch is used, a source outside of all Project
9767 Files may be compiled. The ALI file and the object file will be put in the
9768 object directory of the main Project. The compilation switches used will only
9769 be those specified on the command line. Even when
9770 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9771 command line need to be sources of a project file.
9772
9773 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9774 Indicate that external variable @var{name} has the value @var{value}.
9775 The Project Manager will use this value for occurrences of
9776 @code{external(name)} when parsing the project file.
9777 @xref{Switches Related to Project Files}.
9778
9779 @item ^-z^/NOMAIN^
9780 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9781 No main subprogram. Bind and link the program even if the unit name
9782 given on the command line is a package name. The resulting executable
9783 will execute the elaboration routines of the package and its closure,
9784 then the finalization routines.
9785
9786 @end table
9787
9788 @table @asis
9789 @item @command{gcc} @asis{switches}
9790 @ifclear vms
9791 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9792 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9793 @end ifclear
9794 @ifset vms
9795 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9796 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9797 automatically treated as a compiler switch, and passed on to all
9798 compilations that are carried out.
9799 @end ifset
9800 @end table
9801
9802 @noindent
9803 Source and library search path switches:
9804
9805 @table @option
9806 @c !sort!
9807 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9808 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9809 When looking for source files also look in directory @var{dir}.
9810 The order in which source files search is undertaken is
9811 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9812
9813 @item ^-aL^/SKIP_MISSING=^@var{dir}
9814 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9815 Consider @var{dir} as being an externally provided Ada library.
9816 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9817 files have been located in directory @var{dir}. This allows you to have
9818 missing bodies for the units in @var{dir} and to ignore out of date bodies
9819 for the same units. You still need to specify
9820 the location of the specs for these units by using the switches
9821 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9822 or @option{^-I^/SEARCH=^@var{dir}}.
9823 Note: this switch is provided for compatibility with previous versions
9824 of @command{gnatmake}. The easier method of causing standard libraries
9825 to be excluded from consideration is to write-protect the corresponding
9826 ALI files.
9827
9828 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9829 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9830 When searching for library and object files, look in directory
9831 @var{dir}. The order in which library files are searched is described in
9832 @ref{Search Paths for gnatbind}.
9833
9834 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9835 @cindex Search paths, for @command{gnatmake}
9836 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9837 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9838 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9839
9840 @item ^-I^/SEARCH=^@var{dir}
9841 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9842 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9843 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9844
9845 @item ^-I-^/NOCURRENT_DIRECTORY^
9846 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9847 @cindex Source files, suppressing search
9848 Do not look for source files in the directory containing the source
9849 file named in the command line.
9850 Do not look for ALI or object files in the directory
9851 where @command{gnatmake} was invoked.
9852
9853 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9854 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9855 @cindex Linker libraries
9856 Add directory @var{dir} to the list of directories in which the linker
9857 will search for libraries. This is equivalent to
9858 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9859 @ifclear vms
9860 Furthermore, under Windows, the sources pointed to by the libraries path
9861 set in the registry are not searched for.
9862 @end ifclear
9863
9864 @item -nostdinc
9865 @cindex @option{-nostdinc} (@command{gnatmake})
9866 Do not look for source files in the system default directory.
9867
9868 @item -nostdlib
9869 @cindex @option{-nostdlib} (@command{gnatmake})
9870 Do not look for library files in the system default directory.
9871
9872 @item --RTS=@var{rts-path}
9873 @cindex @option{--RTS} (@command{gnatmake})
9874 Specifies the default location of the runtime library. GNAT looks for the
9875 runtime
9876 in the following directories, and stops as soon as a valid runtime is found
9877 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9878 @file{ada_object_path} present):
9879
9880 @itemize @bullet
9881 @item <current directory>/$rts_path
9882
9883 @item <default-search-dir>/$rts_path
9884
9885 @item <default-search-dir>/rts-$rts_path
9886 @end itemize
9887
9888 @noindent
9889 The selected path is handled like a normal RTS path.
9890
9891 @end table
9892
9893 @node Mode Switches for gnatmake
9894 @section Mode Switches for @command{gnatmake}
9895
9896 @noindent
9897 The mode switches (referred to as @code{mode_switches}) allow the
9898 inclusion of switches that are to be passed to the compiler itself, the
9899 binder or the linker. The effect of a mode switch is to cause all
9900 subsequent switches up to the end of the switch list, or up to the next
9901 mode switch, to be interpreted as switches to be passed on to the
9902 designated component of GNAT.
9903
9904 @table @option
9905 @c !sort!
9906 @item -cargs @var{switches}
9907 @cindex @option{-cargs} (@command{gnatmake})
9908 Compiler switches. Here @var{switches} is a list of switches
9909 that are valid switches for @command{gcc}. They will be passed on to
9910 all compile steps performed by @command{gnatmake}.
9911
9912 @item -bargs @var{switches}
9913 @cindex @option{-bargs} (@command{gnatmake})
9914 Binder switches. Here @var{switches} is a list of switches
9915 that are valid switches for @code{gnatbind}. They will be passed on to
9916 all bind steps performed by @command{gnatmake}.
9917
9918 @item -largs @var{switches}
9919 @cindex @option{-largs} (@command{gnatmake})
9920 Linker switches. Here @var{switches} is a list of switches
9921 that are valid switches for @command{gnatlink}. They will be passed on to
9922 all link steps performed by @command{gnatmake}.
9923
9924 @item -margs @var{switches}
9925 @cindex @option{-margs} (@command{gnatmake})
9926 Make switches. The switches are directly interpreted by @command{gnatmake},
9927 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9928 or @option{-largs}.
9929 @end table
9930
9931 @node Notes on the Command Line
9932 @section Notes on the Command Line
9933
9934 @noindent
9935 This section contains some additional useful notes on the operation
9936 of the @command{gnatmake} command.
9937
9938 @itemize @bullet
9939 @item
9940 @cindex Recompilation, by @command{gnatmake}
9941 If @command{gnatmake} finds no ALI files, it recompiles the main program
9942 and all other units required by the main program.
9943 This means that @command{gnatmake}
9944 can be used for the initial compile, as well as during subsequent steps of
9945 the development cycle.
9946
9947 @item
9948 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9949 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9950 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9951 warning.
9952
9953 @item
9954 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9955 is used to specify both source and
9956 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9957 instead if you just want to specify
9958 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9959 if you want to specify library paths
9960 only.
9961
9962 @item
9963 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9964 This may conveniently be used to exclude standard libraries from
9965 consideration and in particular it means that the use of the
9966 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9967 unless @option{^-a^/ALL_FILES^} is also specified.
9968
9969 @item
9970 @command{gnatmake} has been designed to make the use of Ada libraries
9971 particularly convenient. Assume you have an Ada library organized
9972 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9973 of your Ada compilation units,
9974 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9975 specs of these units, but no bodies. Then to compile a unit
9976 stored in @code{main.adb}, which uses this Ada library you would just type
9977
9978 @smallexample
9979 @ifclear vms
9980 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9981 @end ifclear
9982 @ifset vms
9983 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9984            /SKIP_MISSING=@i{[OBJ_DIR]} main
9985 @end ifset
9986 @end smallexample
9987
9988 @item
9989 Using @command{gnatmake} along with the
9990 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9991 switch provides a mechanism for avoiding unnecessary recompilations. Using
9992 this switch,
9993 you can update the comments/format of your
9994 source files without having to recompile everything. Note, however, that
9995 adding or deleting lines in a source files may render its debugging
9996 info obsolete. If the file in question is a spec, the impact is rather
9997 limited, as that debugging info will only be useful during the
9998 elaboration phase of your program. For bodies the impact can be more
9999 significant. In all events, your debugger will warn you if a source file
10000 is more recent than the corresponding object, and alert you to the fact
10001 that the debugging information may be out of date.
10002 @end itemize
10003
10004 @node How gnatmake Works
10005 @section How @command{gnatmake} Works
10006
10007 @noindent
10008 Generally @command{gnatmake} automatically performs all necessary
10009 recompilations and you don't need to worry about how it works. However,
10010 it may be useful to have some basic understanding of the @command{gnatmake}
10011 approach and in particular to understand how it uses the results of
10012 previous compilations without incorrectly depending on them.
10013
10014 First a definition: an object file is considered @dfn{up to date} if the
10015 corresponding ALI file exists and if all the source files listed in the
10016 dependency section of this ALI file have time stamps matching those in
10017 the ALI file. This means that neither the source file itself nor any
10018 files that it depends on have been modified, and hence there is no need
10019 to recompile this file.
10020
10021 @command{gnatmake} works by first checking if the specified main unit is up
10022 to date. If so, no compilations are required for the main unit. If not,
10023 @command{gnatmake} compiles the main program to build a new ALI file that
10024 reflects the latest sources. Then the ALI file of the main unit is
10025 examined to find all the source files on which the main program depends,
10026 and @command{gnatmake} recursively applies the above procedure on all these
10027 files.
10028
10029 This process ensures that @command{gnatmake} only trusts the dependencies
10030 in an existing ALI file if they are known to be correct. Otherwise it
10031 always recompiles to determine a new, guaranteed accurate set of
10032 dependencies. As a result the program is compiled ``upside down'' from what may
10033 be more familiar as the required order of compilation in some other Ada
10034 systems. In particular, clients are compiled before the units on which
10035 they depend. The ability of GNAT to compile in any order is critical in
10036 allowing an order of compilation to be chosen that guarantees that
10037 @command{gnatmake} will recompute a correct set of new dependencies if
10038 necessary.
10039
10040 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10041 imported by several of the executables, it will be recompiled at most once.
10042
10043 Note: when using non-standard naming conventions
10044 (@pxref{Using Other File Names}), changing through a configuration pragmas
10045 file the version of a source and invoking @command{gnatmake} to recompile may
10046 have no effect, if the previous version of the source is still accessible
10047 by @command{gnatmake}. It may be necessary to use the switch
10048 ^-f^/FORCE_COMPILE^.
10049
10050 @node Examples of gnatmake Usage
10051 @section Examples of @command{gnatmake} Usage
10052
10053 @table @code
10054 @item gnatmake hello.adb
10055 Compile all files necessary to bind and link the main program
10056 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10057 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10058
10059 @item gnatmake main1 main2 main3
10060 Compile all files necessary to bind and link the main programs
10061 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10062 (containing unit @code{Main2}) and @file{main3.adb}
10063 (containing unit @code{Main3}) and bind and link the resulting object files
10064 to generate three executable files @file{^main1^MAIN1.EXE^},
10065 @file{^main2^MAIN2.EXE^}
10066 and @file{^main3^MAIN3.EXE^}.
10067
10068 @ifclear vms
10069 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10070 @end ifclear
10071
10072 @ifset vms
10073 @item gnatmake Main_Unit /QUIET
10074 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10075 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10076 @end ifset
10077 Compile all files necessary to bind and link the main program unit
10078 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10079 be done with optimization level 2 and the order of elaboration will be
10080 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10081 displaying commands it is executing.
10082 @end table
10083
10084 @c *************************
10085 @node Improving Performance
10086 @chapter Improving Performance
10087 @cindex Improving performance
10088
10089 @noindent
10090 This chapter presents several topics related to program performance.
10091 It first describes some of the tradeoffs that need to be considered
10092 and some of the techniques for making your program run faster.
10093 It then documents the @command{gnatelim} tool and unused subprogram/data
10094 elimination feature, which can reduce the size of program executables.
10095
10096 @ifnottex
10097 @menu
10098 * Performance Considerations::
10099 * Text_IO Suggestions::
10100 * Reducing Size of Ada Executables with gnatelim::
10101 * Reducing Size of Executables with unused subprogram/data elimination::
10102 @end menu
10103 @end ifnottex
10104
10105 @c *****************************
10106 @node Performance Considerations
10107 @section Performance Considerations
10108
10109 @noindent
10110 The GNAT system provides a number of options that allow a trade-off
10111 between
10112
10113 @itemize @bullet
10114 @item
10115 performance of the generated code
10116
10117 @item
10118 speed of compilation
10119
10120 @item
10121 minimization of dependences and recompilation
10122
10123 @item
10124 the degree of run-time checking.
10125 @end itemize
10126
10127 @noindent
10128 The defaults (if no options are selected) aim at improving the speed
10129 of compilation and minimizing dependences, at the expense of performance
10130 of the generated code:
10131
10132 @itemize @bullet
10133 @item
10134 no optimization
10135
10136 @item
10137 no inlining of subprogram calls
10138
10139 @item
10140 all run-time checks enabled except overflow and elaboration checks
10141 @end itemize
10142
10143 @noindent
10144 These options are suitable for most program development purposes. This
10145 chapter describes how you can modify these choices, and also provides
10146 some guidelines on debugging optimized code.
10147
10148 @menu
10149 * Controlling Run-Time Checks::
10150 * Use of Restrictions::
10151 * Optimization Levels::
10152 * Debugging Optimized Code::
10153 * Inlining of Subprograms::
10154 * Vectorization of loops::
10155 * Other Optimization Switches::
10156 * Optimization and Strict Aliasing::
10157
10158 @ifset vms
10159 * Coverage Analysis::
10160 @end ifset
10161 @end menu
10162
10163 @node Controlling Run-Time Checks
10164 @subsection Controlling Run-Time Checks
10165
10166 @noindent
10167 By default, GNAT generates all run-time checks, except integer overflow
10168 checks, stack overflow checks, and checks for access before elaboration on
10169 subprogram calls. The latter are not required in default mode, because all
10170 necessary checking is done at compile time.
10171 @cindex @option{-gnatp} (@command{gcc})
10172 @cindex @option{-gnato} (@command{gcc})
10173 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10174 be modified. @xref{Run-Time Checks}.
10175
10176 Our experience is that the default is suitable for most development
10177 purposes.
10178
10179 We treat integer overflow specially because these
10180 are quite expensive and in our experience are not as important as other
10181 run-time checks in the development process. Note that division by zero
10182 is not considered an overflow check, and divide by zero checks are
10183 generated where required by default.
10184
10185 Elaboration checks are off by default, and also not needed by default, since
10186 GNAT uses a static elaboration analysis approach that avoids the need for
10187 run-time checking. This manual contains a full chapter discussing the issue
10188 of elaboration checks, and if the default is not satisfactory for your use,
10189 you should read this chapter.
10190
10191 For validity checks, the minimal checks required by the Ada Reference
10192 Manual (for case statements and assignments to array elements) are on
10193 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10194 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10195 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10196 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10197 are also suppressed entirely if @option{-gnatp} is used.
10198
10199 @cindex Overflow checks
10200 @cindex Checks, overflow
10201 @findex Suppress
10202 @findex Unsuppress
10203 @cindex pragma Suppress
10204 @cindex pragma Unsuppress
10205 Note that the setting of the switches controls the default setting of
10206 the checks. They may be modified using either @code{pragma Suppress} (to
10207 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10208 checks) in the program source.
10209
10210 @node Use of Restrictions
10211 @subsection Use of Restrictions
10212
10213 @noindent
10214 The use of pragma Restrictions allows you to control which features are
10215 permitted in your program. Apart from the obvious point that if you avoid
10216 relatively expensive features like finalization (enforceable by the use
10217 of pragma Restrictions (No_Finalization), the use of this pragma does not
10218 affect the generated code in most cases.
10219
10220 One notable exception to this rule is that the possibility of task abort
10221 results in some distributed overhead, particularly if finalization or
10222 exception handlers are used. The reason is that certain sections of code
10223 have to be marked as non-abortable.
10224
10225 If you use neither the @code{abort} statement, nor asynchronous transfer
10226 of control (@code{select @dots{} then abort}), then this distributed overhead
10227 is removed, which may have a general positive effect in improving
10228 overall performance.  Especially code involving frequent use of tasking
10229 constructs and controlled types will show much improved performance.
10230 The relevant restrictions pragmas are
10231
10232 @smallexample @c ada
10233    pragma Restrictions (No_Abort_Statements);
10234    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10235 @end smallexample
10236
10237 @noindent
10238 It is recommended that these restriction pragmas be used if possible. Note
10239 that this also means that you can write code without worrying about the
10240 possibility of an immediate abort at any point.
10241
10242 @node Optimization Levels
10243 @subsection Optimization Levels
10244 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10245
10246 @noindent
10247 Without any optimization ^option,^qualifier,^
10248 the compiler's goal is to reduce the cost of
10249 compilation and to make debugging produce the expected results.
10250 Statements are independent: if you stop the program with a breakpoint between
10251 statements, you can then assign a new value to any variable or change
10252 the program counter to any other statement in the subprogram and get exactly
10253 the results you would expect from the source code.
10254
10255 Turning on optimization makes the compiler attempt to improve the
10256 performance and/or code size at the expense of compilation time and
10257 possibly the ability to debug the program.
10258
10259 If you use multiple
10260 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10261 the last such option is the one that is effective.
10262
10263 @noindent
10264 The default is optimization off. This results in the fastest compile
10265 times, but GNAT makes absolutely no attempt to optimize, and the
10266 generated programs are considerably larger and slower than when
10267 optimization is enabled. You can use the
10268 @ifclear vms
10269 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10270 @option{-O2}, @option{-O3}, and @option{-Os})
10271 @end ifclear
10272 @ifset vms
10273 @code{OPTIMIZE} qualifier
10274 @end ifset
10275 to @command{gcc} to control the optimization level:
10276
10277 @table @option
10278 @item ^-O0^/OPTIMIZE=NONE^
10279 No optimization (the default);
10280 generates unoptimized code but has
10281 the fastest compilation time.
10282
10283 Note that many other compilers do fairly extensive optimization
10284 even if ``no optimization'' is specified. With gcc, it is
10285 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10286 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10287 really does mean no optimization at all. This difference between
10288 gcc and other compilers should be kept in mind when doing
10289 performance comparisons.
10290
10291 @item ^-O1^/OPTIMIZE=SOME^
10292 Moderate optimization;
10293 optimizes reasonably well but does not
10294 degrade compilation time significantly.
10295
10296 @item ^-O2^/OPTIMIZE=ALL^
10297 @ifset vms
10298 @itemx /OPTIMIZE=DEVELOPMENT
10299 @end ifset
10300 Full optimization;
10301 generates highly optimized code and has
10302 the slowest compilation time.
10303
10304 @item ^-O3^/OPTIMIZE=INLINING^
10305 Full optimization as in @option{-O2};
10306 also uses more aggressive automatic inlining of subprograms within a unit
10307 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10308
10309 @item ^-Os^/OPTIMIZE=SPACE^
10310 Optimize space usage (code and data) of resulting program.
10311 @end table
10312
10313 @noindent
10314 Higher optimization levels perform more global transformations on the
10315 program and apply more expensive analysis algorithms in order to generate
10316 faster and more compact code. The price in compilation time, and the
10317 resulting improvement in execution time,
10318 both depend on the particular application and the hardware environment.
10319 You should experiment to find the best level for your application.
10320
10321 Since the precise set of optimizations done at each level will vary from
10322 release to release (and sometime from target to target), it is best to think
10323 of the optimization settings in general terms.
10324 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10325 the GNU Compiler Collection (GCC)}, for details about
10326 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10327 individually enable or disable specific optimizations.
10328
10329 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10330 been tested extensively at all optimization levels. There are some bugs
10331 which appear only with optimization turned on, but there have also been
10332 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10333 level of optimization does not improve the reliability of the code
10334 generator, which in practice is highly reliable at all optimization
10335 levels.
10336
10337 Note regarding the use of @option{-O3}: The use of this optimization level
10338 is generally discouraged with GNAT, since it often results in larger
10339 executables which may run more slowly. See further discussion of this point
10340 in @ref{Inlining of Subprograms}.
10341
10342 @node Debugging Optimized Code
10343 @subsection Debugging Optimized Code
10344 @cindex Debugging optimized code
10345 @cindex Optimization and debugging
10346
10347 @noindent
10348 Although it is possible to do a reasonable amount of debugging at
10349 @ifclear vms
10350 nonzero optimization levels,
10351 the higher the level the more likely that
10352 @end ifclear
10353 @ifset vms
10354 @option{/OPTIMIZE} settings other than @code{NONE},
10355 such settings will make it more likely that
10356 @end ifset
10357 source-level constructs will have been eliminated by optimization.
10358 For example, if a loop is strength-reduced, the loop
10359 control variable may be completely eliminated and thus cannot be
10360 displayed in the debugger.
10361 This can only happen at @option{-O2} or @option{-O3}.
10362 Explicit temporary variables that you code might be eliminated at
10363 ^level^setting^ @option{-O1} or higher.
10364
10365 The use of the @option{^-g^/DEBUG^} switch,
10366 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10367 which is needed for source-level debugging,
10368 affects the size of the program executable on disk,
10369 and indeed the debugging information can be quite large.
10370 However, it has no effect on the generated code (and thus does not
10371 degrade performance)
10372
10373 Since the compiler generates debugging tables for a compilation unit before
10374 it performs optimizations, the optimizing transformations may invalidate some
10375 of the debugging data.  You therefore need to anticipate certain
10376 anomalous situations that may arise while debugging optimized code.
10377 These are the most common cases:
10378
10379 @enumerate
10380 @item
10381 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10382 commands show
10383 the PC bouncing back and forth in the code.  This may result from any of
10384 the following optimizations:
10385
10386 @itemize @bullet
10387 @item
10388 @i{Common subexpression elimination:} using a single instance of code for a
10389 quantity that the source computes several times.  As a result you
10390 may not be able to stop on what looks like a statement.
10391
10392 @item
10393 @i{Invariant code motion:} moving an expression that does not change within a
10394 loop, to the beginning of the loop.
10395
10396 @item
10397 @i{Instruction scheduling:} moving instructions so as to
10398 overlap loads and stores (typically) with other code, or in
10399 general to move computations of values closer to their uses. Often
10400 this causes you to pass an assignment statement without the assignment
10401 happening and then later bounce back to the statement when the
10402 value is actually needed.  Placing a breakpoint on a line of code
10403 and then stepping over it may, therefore, not always cause all the
10404 expected side-effects.
10405 @end itemize
10406
10407 @item
10408 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10409 two identical pieces of code are merged and the program counter suddenly
10410 jumps to a statement that is not supposed to be executed, simply because
10411 it (and the code following) translates to the same thing as the code
10412 that @emph{was} supposed to be executed.  This effect is typically seen in
10413 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10414 a @code{break} in a C @code{^switch^switch^} statement.
10415
10416 @item
10417 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10418 There are various reasons for this effect:
10419
10420 @itemize @bullet
10421 @item
10422 In a subprogram prologue, a parameter may not yet have been moved to its
10423 ``home''.
10424
10425 @item
10426 A variable may be dead, and its register re-used.  This is
10427 probably the most common cause.
10428
10429 @item
10430 As mentioned above, the assignment of a value to a variable may
10431 have been moved.
10432
10433 @item
10434 A variable may be eliminated entirely by value propagation or
10435 other means.  In this case, GCC may incorrectly generate debugging
10436 information for the variable
10437 @end itemize
10438
10439 @noindent
10440 In general, when an unexpected value appears for a local variable or parameter
10441 you should first ascertain if that value was actually computed by
10442 your program, as opposed to being incorrectly reported by the debugger.
10443 Record fields or
10444 array elements in an object designated by an access value
10445 are generally less of a problem, once you have ascertained that the access
10446 value is sensible.
10447 Typically, this means checking variables in the preceding code and in the
10448 calling subprogram to verify that the value observed is explainable from other
10449 values (one must apply the procedure recursively to those
10450 other values); or re-running the code and stopping a little earlier
10451 (perhaps before the call) and stepping to better see how the variable obtained
10452 the value in question; or continuing to step @emph{from} the point of the
10453 strange value to see if code motion had simply moved the variable's
10454 assignments later.
10455 @end enumerate
10456
10457 @noindent
10458 In light of such anomalies, a recommended technique is to use @option{-O0}
10459 early in the software development cycle, when extensive debugging capabilities
10460 are most needed, and then move to @option{-O1} and later @option{-O2} as
10461 the debugger becomes less critical.
10462 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10463 a release management issue.
10464 @ifclear vms
10465 Note that if you use @option{-g} you can then use the @command{strip} program
10466 on the resulting executable,
10467 which removes both debugging information and global symbols.
10468 @end ifclear
10469
10470 @node Inlining of Subprograms
10471 @subsection Inlining of Subprograms
10472
10473 @noindent
10474 A call to a subprogram in the current unit is inlined if all the
10475 following conditions are met:
10476
10477 @itemize @bullet
10478 @item
10479 The optimization level is at least @option{-O1}.
10480
10481 @item
10482 The called subprogram is suitable for inlining: It must be small enough
10483 and not contain something that @command{gcc} cannot support in inlined
10484 subprograms.
10485
10486 @item
10487 @cindex pragma Inline
10488 @findex Inline
10489 Any one of the following applies: @code{pragma Inline} is applied to the
10490 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10491 subprogram is local to the unit and called once from within it; the
10492 subprogram is small and optimization level @option{-O2} is specified;
10493 optimization level @option{-O3}) is specified.
10494 @end itemize
10495
10496 @noindent
10497 Calls to subprograms in @code{with}'ed units are normally not inlined.
10498 To achieve actual inlining (that is, replacement of the call by the code
10499 in the body of the subprogram), the following conditions must all be true.
10500
10501 @itemize @bullet
10502 @item
10503 The optimization level is at least @option{-O1}.
10504
10505 @item
10506 The called subprogram is suitable for inlining: It must be small enough
10507 and not contain something that @command{gcc} cannot support in inlined
10508 subprograms.
10509
10510 @item
10511 The call appears in a body (not in a package spec).
10512
10513 @item
10514 There is a @code{pragma Inline} for the subprogram.
10515
10516 @item
10517 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10518 @end itemize
10519
10520 Even if all these conditions are met, it may not be possible for
10521 the compiler to inline the call, due to the length of the body,
10522 or features in the body that make it impossible for the compiler
10523 to do the inlining.
10524
10525 Note that specifying the @option{-gnatn} switch causes additional
10526 compilation dependencies. Consider the following:
10527
10528 @smallexample @c ada
10529 @cartouche
10530 package R is
10531    procedure Q;
10532    pragma Inline (Q);
10533 end R;
10534 package body R is
10535    @dots{}
10536 end R;
10537
10538 with R;
10539 procedure Main is
10540 begin
10541    @dots{}
10542    R.Q;
10543 end Main;
10544 @end cartouche
10545 @end smallexample
10546
10547 @noindent
10548 With the default behavior (no @option{-gnatn} switch specified), the
10549 compilation of the @code{Main} procedure depends only on its own source,
10550 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10551 means that editing the body of @code{R} does not require recompiling
10552 @code{Main}.
10553
10554 On the other hand, the call @code{R.Q} is not inlined under these
10555 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10556 is compiled, the call will be inlined if the body of @code{Q} is small
10557 enough, but now @code{Main} depends on the body of @code{R} in
10558 @file{r.adb} as well as on the spec. This means that if this body is edited,
10559 the main program must be recompiled. Note that this extra dependency
10560 occurs whether or not the call is in fact inlined by @command{gcc}.
10561
10562 The use of front end inlining with @option{-gnatN} generates similar
10563 additional dependencies.
10564
10565 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10566 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10567 can be used to prevent
10568 all inlining. This switch overrides all other conditions and ensures
10569 that no inlining occurs. The extra dependences resulting from
10570 @option{-gnatn} will still be active, even if
10571 this switch is used to suppress the resulting inlining actions.
10572
10573 @cindex @option{-fno-inline-functions} (@command{gcc})
10574 Note: The @option{-fno-inline-functions} switch can be used to prevent
10575 automatic inlining of subprograms if @option{-O3} is used.
10576
10577 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10578 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10579 automatic inlining of small subprograms if @option{-O2} is used.
10580
10581 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10582 Note: The @option{-fno-inline-functions-called-once} switch
10583 can be used to prevent inlining of subprograms local to the unit
10584 and called once from within it if @option{-O1} is used.
10585
10586 Note regarding the use of @option{-O3}: There is no difference in inlining
10587 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10588 pragma @code{Inline} assuming the use of @option{-gnatn}
10589 or @option{-gnatN} (the switches that activate inlining). If you have used
10590 pragma @code{Inline} in appropriate cases, then it is usually much better
10591 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10592 in this case only has the effect of inlining subprograms you did not
10593 think should be inlined. We often find that the use of @option{-O3} slows
10594 down code by performing excessive inlining, leading to increased instruction
10595 cache pressure from the increased code size. So the bottom line here is
10596 that you should not automatically assume that @option{-O3} is better than
10597 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10598 it actually improves performance.
10599
10600 @node Vectorization of loops
10601 @subsection Vectorization of loops
10602 @cindex Optimization Switches
10603
10604 You can take advantage of the auto-vectorizer present in the @command{gcc}
10605 back end to vectorize loops with GNAT.  The corresponding command line switch
10606 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10607 and other aggressive optimizations helpful for vectorization also are enabled
10608 by default at this level, using @option{-O3} directly is recommended.
10609
10610 You also need to make sure that the target architecture features a supported
10611 SIMD instruction set.  For example, for the x86 architecture, you should at
10612 least specify @option{-msse2} to get significant vectorization (but you don't
10613 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10614 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10615
10616 The preferred loop form for vectorization is the @code{for} iteration scheme.
10617 Loops with a @code{while} iteration scheme can also be vectorized if they are
10618 very simple, but the vectorizer will quickly give up otherwise.  With either
10619 iteration scheme, the flow of control must be straight, in particular no
10620 @code{exit} statement may appear in the loop body.  The loop may however
10621 contain a single nested loop, if it can be vectorized when considered alone:
10622
10623 @smallexample @c ada
10624 @cartouche
10625    A : array (1..4, 1..4) of Long_Float;
10626    S : array (1..4) of Long_Float;
10627
10628    procedure Sum is
10629    begin
10630       for I in A'Range(1) loop
10631          for J in A'Range(2) loop
10632             S (I) := S (I) + A (I, J);
10633          end loop;
10634       end loop;
10635    end Sum;
10636 @end cartouche
10637 @end smallexample
10638
10639 The vectorizable operations depend on the targeted SIMD instruction set, but
10640 the adding and some of the multiplying operators are generally supported, as
10641 well as the logical operators for modular types.  Note that, in the former
10642 case, enabling overflow checks, for example with @option{-gnato}, totally
10643 disables vectorization.  The other checks are not supposed to have the same
10644 definitive effect, although compiling with @option{-gnatp} might well reveal
10645 cases where some checks do thwart vectorization.
10646
10647 Type conversions may also prevent vectorization if they involve semantics that
10648 are not directly supported by the code generator or the SIMD instruction set.
10649 A typical example is direct conversion from floating-point to integer types.
10650 The solution in this case is to use the following idiom:
10651
10652 @smallexample @c ada
10653    Integer (S'Truncation (F))
10654 @end smallexample
10655
10656 @noindent
10657 if @code{S} is the subtype of floating-point object @code{F}.
10658
10659 In most cases, the vectorizable loops are loops that iterate over arrays.
10660 All kinds of array types are supported, i.e. constrained array types with
10661 static bounds:
10662
10663 @smallexample @c ada
10664    type Array_Type is array (1 .. 4) of Long_Float;
10665 @end smallexample
10666
10667 @noindent
10668 constrained array types with dynamic bounds:
10669
10670 @smallexample @c ada
10671    type Array_Type is array (1 .. Q.N) of Long_Float;
10672
10673    type Array_Type is array (Q.K .. 4) of Long_Float;
10674
10675    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10676 @end smallexample
10677
10678 @noindent
10679 or unconstrained array types:
10680
10681 @smallexample @c ada
10682   type Array_Type is array (Positive range <>) of Long_Float;
10683 @end smallexample
10684
10685 @noindent
10686 The quality of the generated code decreases when the dynamic aspect of the
10687 array type increases, the worst code being generated for unconstrained array
10688 types.  This is so because, the less information the compiler has about the
10689 bounds of the array, the more fallback code it needs to generate in order to
10690 fix things up at run time.
10691
10692 You can obtain information about the vectorization performed by the compiler
10693 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10694 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10695 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10696
10697 @node Other Optimization Switches
10698 @subsection Other Optimization Switches
10699 @cindex Optimization Switches
10700
10701 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10702 @command{gcc} optimization switches are potentially usable. These switches
10703 have not been extensively tested with GNAT but can generally be expected
10704 to work. Examples of switches in this category are @option{-funroll-loops}
10705 and the various target-specific @option{-m} options (in particular, it has
10706 been observed that @option{-march=xxx} can significantly improve performance
10707 on appropriate machines). For full details of these switches, see
10708 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10709 the GNU Compiler Collection (GCC)}.
10710
10711 @node Optimization and Strict Aliasing
10712 @subsection Optimization and Strict Aliasing
10713 @cindex Aliasing
10714 @cindex Strict Aliasing
10715 @cindex No_Strict_Aliasing
10716
10717 @noindent
10718 The strong typing capabilities of Ada allow an optimizer to generate
10719 efficient code in situations where other languages would be forced to
10720 make worst case assumptions preventing such optimizations. Consider
10721 the following example:
10722
10723 @smallexample @c ada
10724 @cartouche
10725 procedure R is
10726    type Int1 is new Integer;
10727    type Int2 is new Integer;
10728    type Int1A is access Int1;
10729    type Int2A is access Int2;
10730    Int1V : Int1A;
10731    Int2V : Int2A;
10732    @dots{}
10733
10734 begin
10735    @dots{}
10736    for J in Data'Range loop
10737       if Data (J) = Int1V.all then
10738          Int2V.all := Int2V.all + 1;
10739       end if;
10740    end loop;
10741    @dots{}
10742 end R;
10743 @end cartouche
10744 @end smallexample
10745
10746 @noindent
10747 In this example, since the variable @code{Int1V} can only access objects
10748 of type @code{Int1}, and @code{Int2V} can only access objects of type
10749 @code{Int2}, there is no possibility that the assignment to
10750 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10751 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10752 for all iterations of the loop and avoid the extra memory reference
10753 required to dereference it each time through the loop.
10754
10755 This kind of optimization, called strict aliasing analysis, is
10756 triggered by specifying an optimization level of @option{-O2} or
10757 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10758 when access values are involved.
10759
10760 However, although this optimization is always correct in terms of
10761 the formal semantics of the Ada Reference Manual, difficulties can
10762 arise if features like @code{Unchecked_Conversion} are used to break
10763 the typing system. Consider the following complete program example:
10764
10765 @smallexample @c ada
10766 @cartouche
10767 package p1 is
10768    type int1 is new integer;
10769    type int2 is new integer;
10770    type a1 is access int1;
10771    type a2 is access int2;
10772 end p1;
10773
10774 with p1; use p1;
10775 package p2 is
10776    function to_a2 (Input : a1) return a2;
10777 end p2;
10778
10779 with Unchecked_Conversion;
10780 package body p2 is
10781    function to_a2 (Input : a1) return a2 is
10782       function to_a2u is
10783         new Unchecked_Conversion (a1, a2);
10784    begin
10785       return to_a2u (Input);
10786    end to_a2;
10787 end p2;
10788
10789 with p2; use p2;
10790 with p1; use p1;
10791 with Text_IO; use Text_IO;
10792 procedure m is
10793    v1 : a1 := new int1;
10794    v2 : a2 := to_a2 (v1);
10795 begin
10796    v1.all := 1;
10797    v2.all := 0;
10798    put_line (int1'image (v1.all));
10799 end;
10800 @end cartouche
10801 @end smallexample
10802
10803 @noindent
10804 This program prints out 0 in @option{-O0} or @option{-O1}
10805 mode, but it prints out 1 in @option{-O2} mode. That's
10806 because in strict aliasing mode, the compiler can and
10807 does assume that the assignment to @code{v2.all} could not
10808 affect the value of @code{v1.all}, since different types
10809 are involved.
10810
10811 This behavior is not a case of non-conformance with the standard, since
10812 the Ada RM specifies that an unchecked conversion where the resulting
10813 bit pattern is not a correct value of the target type can result in an
10814 abnormal value and attempting to reference an abnormal value makes the
10815 execution of a program erroneous.  That's the case here since the result
10816 does not point to an object of type @code{int2}.  This means that the
10817 effect is entirely unpredictable.
10818
10819 However, although that explanation may satisfy a language
10820 lawyer, in practice an applications programmer expects an
10821 unchecked conversion involving pointers to create true
10822 aliases and the behavior of printing 1 seems plain wrong.
10823 In this case, the strict aliasing optimization is unwelcome.
10824
10825 Indeed the compiler recognizes this possibility, and the
10826 unchecked conversion generates a warning:
10827
10828 @smallexample
10829 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10830 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10831 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10832 @end smallexample
10833
10834 @noindent
10835 Unfortunately the problem is recognized when compiling the body of
10836 package @code{p2}, but the actual "bad" code is generated while
10837 compiling the body of @code{m} and this latter compilation does not see
10838 the suspicious @code{Unchecked_Conversion}.
10839
10840 As implied by the warning message, there are approaches you can use to
10841 avoid the unwanted strict aliasing optimization in a case like this.
10842
10843 One possibility is to simply avoid the use of @option{-O2}, but
10844 that is a bit drastic, since it throws away a number of useful
10845 optimizations that do not involve strict aliasing assumptions.
10846
10847 A less drastic approach is to compile the program using the
10848 option @option{-fno-strict-aliasing}. Actually it is only the
10849 unit containing the dereferencing of the suspicious pointer
10850 that needs to be compiled. So in this case, if we compile
10851 unit @code{m} with this switch, then we get the expected
10852 value of zero printed. Analyzing which units might need
10853 the switch can be painful, so a more reasonable approach
10854 is to compile the entire program with options @option{-O2}
10855 and @option{-fno-strict-aliasing}. If the performance is
10856 satisfactory with this combination of options, then the
10857 advantage is that the entire issue of possible "wrong"
10858 optimization due to strict aliasing is avoided.
10859
10860 To avoid the use of compiler switches, the configuration
10861 pragma @code{No_Strict_Aliasing} with no parameters may be
10862 used to specify that for all access types, the strict
10863 aliasing optimization should be suppressed.
10864
10865 However, these approaches are still overkill, in that they causes
10866 all manipulations of all access values to be deoptimized. A more
10867 refined approach is to concentrate attention on the specific
10868 access type identified as problematic.
10869
10870 First, if a careful analysis of uses of the pointer shows
10871 that there are no possible problematic references, then
10872 the warning can be suppressed by bracketing the
10873 instantiation of @code{Unchecked_Conversion} to turn
10874 the warning off:
10875
10876 @smallexample @c ada
10877    pragma Warnings (Off);
10878    function to_a2u is
10879      new Unchecked_Conversion (a1, a2);
10880    pragma Warnings (On);
10881 @end smallexample
10882
10883 @noindent
10884 Of course that approach is not appropriate for this particular
10885 example, since indeed there is a problematic reference. In this
10886 case we can take one of two other approaches.
10887
10888 The first possibility is to move the instantiation of unchecked
10889 conversion to the unit in which the type is declared. In
10890 this example, we would move the instantiation of
10891 @code{Unchecked_Conversion} from the body of package
10892 @code{p2} to the spec of package @code{p1}. Now the
10893 warning disappears. That's because any use of the
10894 access type knows there is a suspicious unchecked
10895 conversion, and the strict aliasing optimization
10896 is automatically suppressed for the type.
10897
10898 If it is not practical to move the unchecked conversion to the same unit
10899 in which the destination access type is declared (perhaps because the
10900 source type is not visible in that unit), you may use pragma
10901 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10902 same declarative sequence as the declaration of the access type:
10903
10904 @smallexample @c ada
10905    type a2 is access int2;
10906    pragma No_Strict_Aliasing (a2);
10907 @end smallexample
10908
10909 @noindent
10910 Here again, the compiler now knows that the strict aliasing optimization
10911 should be suppressed for any reference to type @code{a2} and the
10912 expected behavior is obtained.
10913
10914 Finally, note that although the compiler can generate warnings for
10915 simple cases of unchecked conversions, there are tricker and more
10916 indirect ways of creating type incorrect aliases which the compiler
10917 cannot detect. Examples are the use of address overlays and unchecked
10918 conversions involving composite types containing access types as
10919 components. In such cases, no warnings are generated, but there can
10920 still be aliasing problems. One safe coding practice is to forbid the
10921 use of address clauses for type overlaying, and to allow unchecked
10922 conversion only for primitive types. This is not really a significant
10923 restriction since any possible desired effect can be achieved by
10924 unchecked conversion of access values.
10925
10926 The aliasing analysis done in strict aliasing mode can certainly
10927 have significant benefits. We have seen cases of large scale
10928 application code where the time is increased by up to 5% by turning
10929 this optimization off. If you have code that includes significant
10930 usage of unchecked conversion, you might want to just stick with
10931 @option{-O1} and avoid the entire issue. If you get adequate
10932 performance at this level of optimization level, that's probably
10933 the safest approach. If tests show that you really need higher
10934 levels of optimization, then you can experiment with @option{-O2}
10935 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10936 has on size and speed of the code. If you really need to use
10937 @option{-O2} with strict aliasing in effect, then you should
10938 review any uses of unchecked conversion of access types,
10939 particularly if you are getting the warnings described above.
10940
10941 @ifset vms
10942 @node Coverage Analysis
10943 @subsection Coverage Analysis
10944
10945 @noindent
10946 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10947 the user to determine the distribution of execution time across a program,
10948 @pxref{Profiling} for details of usage.
10949 @end ifset
10950
10951
10952 @node Text_IO Suggestions
10953 @section @code{Text_IO} Suggestions
10954 @cindex @code{Text_IO} and performance
10955
10956 @noindent
10957 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10958 the requirement of maintaining page and line counts. If performance
10959 is critical, a recommendation is to use @code{Stream_IO} instead of
10960 @code{Text_IO} for volume output, since this package has less overhead.
10961
10962 If @code{Text_IO} must be used, note that by default output to the standard
10963 output and standard error files is unbuffered (this provides better
10964 behavior when output statements are used for debugging, or if the
10965 progress of a program is observed by tracking the output, e.g. by
10966 using the Unix @command{tail -f} command to watch redirected output.
10967
10968 If you are generating large volumes of output with @code{Text_IO} and
10969 performance is an important factor, use a designated file instead
10970 of the standard output file, or change the standard output file to
10971 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10972
10973
10974
10975 @node Reducing Size of Ada Executables with gnatelim
10976 @section Reducing Size of Ada Executables with @code{gnatelim}
10977 @findex gnatelim
10978
10979 @noindent
10980 This section describes @command{gnatelim}, a tool which detects unused
10981 subprograms and helps the compiler to create a smaller executable for your
10982 program.
10983
10984 @menu
10985 * About gnatelim::
10986 * Running gnatelim::
10987 * Processing Precompiled Libraries::
10988 * Correcting the List of Eliminate Pragmas::
10989 * Making Your Executables Smaller::
10990 * Summary of the gnatelim Usage Cycle::
10991 @end menu
10992
10993 @node About gnatelim
10994 @subsection About @code{gnatelim}
10995
10996 @noindent
10997 When a program shares a set of Ada
10998 packages with other programs, it may happen that this program uses
10999 only a fraction of the subprograms defined in these packages. The code
11000 created for these unused subprograms increases the size of the executable.
11001
11002 @code{gnatelim} tracks unused subprograms in an Ada program and
11003 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11004 subprograms that are declared but never called. By placing the list of
11005 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11006 recompiling your program, you may decrease the size of its executable,
11007 because the compiler will not generate the code for 'eliminated' subprograms.
11008 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11009 information about this pragma.
11010
11011 @code{gnatelim} needs as its input data the name of the main subprogram.
11012
11013 If a set of source files is specified as @code{gnatelim} arguments, it
11014 treats these files as a complete set of sources making up a program to
11015 analyse, and analyses only these sources.
11016
11017 After a full successful build of the main subprogram @code{gnatelim} can be
11018 called without  specifying sources to analyse, in this case it computes
11019 the source closure of the main unit from the @file{ALI} files.
11020
11021 The following command will create the set of @file{ALI} files needed for
11022 @code{gnatelim}:
11023
11024 @smallexample
11025 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11026 @end smallexample
11027
11028 Note that @code{gnatelim} does not need object files.
11029
11030 @node Running gnatelim
11031 @subsection Running @code{gnatelim}
11032
11033 @noindent
11034 @code{gnatelim} has the following command-line interface:
11035
11036 @smallexample
11037 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11038 @end smallexample
11039
11040 @noindent
11041 @var{main_unit_name} should be a name of a source file that contains the main
11042 subprogram of a program (partition).
11043
11044 Each @var{filename} is the name (including the extension) of a source
11045 file to process. ``Wildcards'' are allowed, and
11046 the file name may contain path information.
11047
11048 @samp{@var{gcc_switches}} is a list of switches for
11049 @command{gcc}. They will be passed on to all compiler invocations made by
11050 @command{gnatelim} to generate the ASIS trees. Here you can provide
11051 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11052 use the @option{-gnatec} switch to set the configuration file,
11053 use the @option{-gnat05} switch if sources should be compiled in
11054 Ada 2005 mode etc.
11055
11056 @code{gnatelim} has the following switches:
11057
11058 @table @option
11059 @c !sort!
11060 @item ^-files^/FILES^=@var{filename}
11061 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11062 Take the argument source files from the specified file. This file should be an
11063 ordinary text file containing file names separated by spaces or
11064 line breaks. You can use this switch more than once in the same call to
11065 @command{gnatelim}. You also can combine this switch with
11066 an explicit list of files.
11067
11068 @item ^-log^/LOG^
11069 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11070 Duplicate all the output sent to @file{stderr} into a log file. The log file
11071 is named @file{gnatelim.log} and is located in the current directory.
11072
11073 @item ^-log^/LOGFILE^=@var{filename}
11074 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11075 Duplicate all the output sent to @file{stderr} into a specified log file.
11076
11077 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11078 @item ^--no-elim-dispatch^/NO_DISPATCH^
11079 Do not generate pragmas for dispatching operations.
11080
11081 @item ^--ignore^/IGNORE^=@var{filename}
11082 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11083 Do not generate pragmas for subprograms declared in the sources
11084 listed in a specified file
11085
11086 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11087 @item ^-o^/OUTPUT^=@var{report_file}
11088 Put @command{gnatelim} output into a specified file. If this file already exists,
11089 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11090 into @file{stderr}
11091
11092 @item ^-q^/QUIET^
11093 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11094 Quiet mode: by default @code{gnatelim} outputs to the standard error
11095 stream the number of program units left to be processed. This option turns
11096 this trace off.
11097
11098 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11099 @item ^-t^/TIME^
11100 Print out execution time.
11101
11102 @item ^-v^/VERBOSE^
11103 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11104 Verbose mode: @code{gnatelim} version information is printed as Ada
11105 comments to the standard output stream. Also, in addition to the number of
11106 program units left @code{gnatelim} will output the name of the current unit
11107 being processed.
11108
11109 @item ^-wq^/WARNINGS=QUIET^
11110 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11111 Quiet warning mode - some warnings are suppressed. In particular warnings that
11112 indicate that the analysed set of sources is incomplete to make up a
11113 partition and that some subprogram bodies are missing are not generated.
11114 @end table
11115
11116 @noindent
11117 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11118 driver (see @ref{The GNAT Driver and Project Files}).
11119
11120 @node Processing Precompiled Libraries
11121 @subsection Processing Precompiled Libraries
11122
11123 @noindent
11124 If some program uses a precompiled Ada library, it can be processed by
11125 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11126 Eliminate pragma for a subprogram if the body of this subprogram has not
11127 been analysed, this is a typical case for subprograms from precompiled
11128 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11129 warnings about missing source files and non-analyzed subprogram bodies
11130 that can be generated when processing precompiled Ada libraries.
11131
11132 @node Correcting the List of Eliminate Pragmas
11133 @subsection Correcting the List of Eliminate Pragmas
11134
11135 @noindent
11136 In some rare cases @code{gnatelim} may try to eliminate
11137 subprograms that are actually called in the program. In this case, the
11138 compiler will generate an error message of the form:
11139
11140 @smallexample
11141 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11142 @end smallexample
11143
11144 @noindent
11145 You will need to manually remove the wrong @code{Eliminate} pragmas from
11146 the configuration file indicated in the error message. You should recompile
11147 your program from scratch after that, because you need a consistent
11148 configuration file(s) during the entire compilation.
11149
11150 @node Making Your Executables Smaller
11151 @subsection Making Your Executables Smaller
11152
11153 @noindent
11154 In order to get a smaller executable for your program you now have to
11155 recompile the program completely with the configuration file containing
11156 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11157 @file{gnat.adc} file located in your current directory, just do:
11158
11159 @smallexample
11160 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11161 @end smallexample
11162
11163 @noindent
11164 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11165 recompile everything
11166 with the set of pragmas @code{Eliminate} that you have obtained with
11167 @command{gnatelim}).
11168
11169 Be aware that the set of @code{Eliminate} pragmas is specific to each
11170 program. It is not recommended to merge sets of @code{Eliminate}
11171 pragmas created for different programs in one configuration file.
11172
11173 @node Summary of the gnatelim Usage Cycle
11174 @subsection Summary of the @code{gnatelim} Usage Cycle
11175
11176 @noindent
11177 Here is a quick summary of the steps to be taken in order to reduce
11178 the size of your executables with @code{gnatelim}. You may use
11179 other GNAT options to control the optimization level,
11180 to produce the debugging information, to set search path, etc.
11181
11182 @enumerate
11183 @item
11184 Create a complete set of @file{ALI} files (if the program has not been
11185 built already)
11186
11187 @smallexample
11188 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11189 @end smallexample
11190
11191 @item
11192 Generate a list of @code{Eliminate} pragmas in default configuration file
11193 @file{gnat.adc} in the current directory
11194 @smallexample
11195 @ifset vms
11196 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11197 @end ifset
11198 @ifclear vms
11199 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11200 @end ifclear
11201 @end smallexample
11202
11203 @item
11204 Recompile the application
11205
11206 @smallexample
11207 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11208 @end smallexample
11209
11210 @end enumerate
11211
11212 @node Reducing Size of Executables with unused subprogram/data elimination
11213 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11214 @findex unused subprogram/data elimination
11215
11216 @noindent
11217 This section describes how you can eliminate unused subprograms and data from
11218 your executable just by setting options at compilation time.
11219
11220 @menu
11221 * About unused subprogram/data elimination::
11222 * Compilation options::
11223 * Example of unused subprogram/data elimination::
11224 @end menu
11225
11226 @node About unused subprogram/data elimination
11227 @subsection About unused subprogram/data elimination
11228
11229 @noindent
11230 By default, an executable contains all code and data of its composing objects
11231 (directly linked or coming from statically linked libraries), even data or code
11232 never used by this executable.
11233
11234 This feature will allow you to eliminate such unused code from your
11235 executable, making it smaller (in disk and in memory).
11236
11237 This functionality is available on all Linux platforms except for the IA-64
11238 architecture and on all cross platforms using the ELF binary file format.
11239 In both cases GNU binutils version 2.16 or later are required to enable it.
11240
11241 @node Compilation options
11242 @subsection Compilation options
11243
11244 @noindent
11245 The operation of eliminating the unused code and data from the final executable
11246 is directly performed by the linker.
11247
11248 In order to do this, it has to work with objects compiled with the
11249 following options:
11250 @option{-ffunction-sections} @option{-fdata-sections}.
11251 @cindex @option{-ffunction-sections} (@command{gcc})
11252 @cindex @option{-fdata-sections} (@command{gcc})
11253 These options are usable with C and Ada files.
11254 They will place respectively each
11255 function or data in a separate section in the resulting object file.
11256
11257 Once the objects and static libraries are created with these options, the
11258 linker can perform the dead code elimination. You can do this by setting
11259 the @option{-Wl,--gc-sections} option to gcc command or in the
11260 @option{-largs} section of @command{gnatmake}. This will perform a
11261 garbage collection of code and data never referenced.
11262
11263 If the linker performs a partial link (@option{-r} ld linker option), then you
11264 will need to provide one or several entry point using the
11265 @option{-e} / @option{--entry} ld option.
11266
11267 Note that objects compiled without the @option{-ffunction-sections} and
11268 @option{-fdata-sections} options can still be linked with the executable.
11269 However, no dead code elimination will be performed on those objects (they will
11270 be linked as is).
11271
11272 The GNAT static library is now compiled with -ffunction-sections and
11273 -fdata-sections on some platforms. This allows you to eliminate the unused code
11274 and data of the GNAT library from your executable.
11275
11276 @node Example of unused subprogram/data elimination
11277 @subsection Example of unused subprogram/data elimination
11278
11279 @noindent
11280 Here is a simple example:
11281
11282 @smallexample @c ada
11283 with Aux;
11284
11285 procedure Test is
11286 begin
11287    Aux.Used (10);
11288 end Test;
11289
11290 package Aux is
11291    Used_Data   : Integer;
11292    Unused_Data : Integer;
11293
11294    procedure Used   (Data : Integer);
11295    procedure Unused (Data : Integer);
11296 end Aux;
11297
11298 package body Aux is
11299    procedure Used (Data : Integer) is
11300    begin
11301       Used_Data := Data;
11302    end Used;
11303
11304    procedure Unused (Data : Integer) is
11305    begin
11306       Unused_Data := Data;
11307    end Unused;
11308 end Aux;
11309 @end smallexample
11310
11311 @noindent
11312 @code{Unused} and @code{Unused_Data} are never referenced in this code
11313 excerpt, and hence they may be safely removed from the final executable.
11314
11315 @smallexample
11316 $ gnatmake test
11317
11318 $ nm test | grep used
11319 020015f0 T aux__unused
11320 02005d88 B aux__unused_data
11321 020015cc T aux__used
11322 02005d84 B aux__used_data
11323
11324 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11325      -largs -Wl,--gc-sections
11326
11327 $ nm test | grep used
11328 02005350 T aux__used
11329 0201ffe0 B aux__used_data
11330 @end smallexample
11331
11332 @noindent
11333 It can be observed that the procedure @code{Unused} and the object
11334 @code{Unused_Data} are removed by the linker when using the
11335 appropriate options.
11336
11337 @c ********************************
11338 @node Renaming Files Using gnatchop
11339 @chapter Renaming Files Using @code{gnatchop}
11340 @findex gnatchop
11341
11342 @noindent
11343 This chapter discusses how to handle files with multiple units by using
11344 the @code{gnatchop} utility. This utility is also useful in renaming
11345 files to meet the standard GNAT default file naming conventions.
11346
11347 @menu
11348 * Handling Files with Multiple Units::
11349 * Operating gnatchop in Compilation Mode::
11350 * Command Line for gnatchop::
11351 * Switches for gnatchop::
11352 * Examples of gnatchop Usage::
11353 @end menu
11354
11355 @node Handling Files with Multiple Units
11356 @section Handling Files with Multiple Units
11357
11358 @noindent
11359 The basic compilation model of GNAT requires that a file submitted to the
11360 compiler have only one unit and there be a strict correspondence
11361 between the file name and the unit name.
11362
11363 The @code{gnatchop} utility allows both of these rules to be relaxed,
11364 allowing GNAT to process files which contain multiple compilation units
11365 and files with arbitrary file names. @code{gnatchop}
11366 reads the specified file and generates one or more output files,
11367 containing one unit per file. The unit and the file name correspond,
11368 as required by GNAT.
11369
11370 If you want to permanently restructure a set of ``foreign'' files so that
11371 they match the GNAT rules, and do the remaining development using the
11372 GNAT structure, you can simply use @command{gnatchop} once, generate the
11373 new set of files and work with them from that point on.
11374
11375 Alternatively, if you want to keep your files in the ``foreign'' format,
11376 perhaps to maintain compatibility with some other Ada compilation
11377 system, you can set up a procedure where you use @command{gnatchop} each
11378 time you compile, regarding the source files that it writes as temporary
11379 files that you throw away.
11380
11381 Note that if your file containing multiple units starts with a byte order
11382 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11383 will each start with a copy of this BOM, meaning that they can be compiled
11384 automatically in UTF-8 mode without needing to specify an explicit encoding.
11385
11386 @node Operating gnatchop in Compilation Mode
11387 @section Operating gnatchop in Compilation Mode
11388
11389 @noindent
11390 The basic function of @code{gnatchop} is to take a file with multiple units
11391 and split it into separate files. The boundary between files is reasonably
11392 clear, except for the issue of comments and pragmas. In default mode, the
11393 rule is that any pragmas between units belong to the previous unit, except
11394 that configuration pragmas always belong to the following unit. Any comments
11395 belong to the following unit. These rules
11396 almost always result in the right choice of
11397 the split point without needing to mark it explicitly and most users will
11398 find this default to be what they want. In this default mode it is incorrect to
11399 submit a file containing only configuration pragmas, or one that ends in
11400 configuration pragmas, to @code{gnatchop}.
11401
11402 However, using a special option to activate ``compilation mode'',
11403 @code{gnatchop}
11404 can perform another function, which is to provide exactly the semantics
11405 required by the RM for handling of configuration pragmas in a compilation.
11406 In the absence of configuration pragmas (at the main file level), this
11407 option has no effect, but it causes such configuration pragmas to be handled
11408 in a quite different manner.
11409
11410 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11411 only configuration pragmas, then this file is appended to the
11412 @file{gnat.adc} file in the current directory. This behavior provides
11413 the required behavior described in the RM for the actions to be taken
11414 on submitting such a file to the compiler, namely that these pragmas
11415 should apply to all subsequent compilations in the same compilation
11416 environment. Using GNAT, the current directory, possibly containing a
11417 @file{gnat.adc} file is the representation
11418 of a compilation environment. For more information on the
11419 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11420
11421 Second, in compilation mode, if @code{gnatchop}
11422 is given a file that starts with
11423 configuration pragmas, and contains one or more units, then these
11424 configuration pragmas are prepended to each of the chopped files. This
11425 behavior provides the required behavior described in the RM for the
11426 actions to be taken on compiling such a file, namely that the pragmas
11427 apply to all units in the compilation, but not to subsequently compiled
11428 units.
11429
11430 Finally, if configuration pragmas appear between units, they are appended
11431 to the previous unit. This results in the previous unit being illegal,
11432 since the compiler does not accept configuration pragmas that follow
11433 a unit. This provides the required RM behavior that forbids configuration
11434 pragmas other than those preceding the first compilation unit of a
11435 compilation.
11436
11437 For most purposes, @code{gnatchop} will be used in default mode. The
11438 compilation mode described above is used only if you need exactly
11439 accurate behavior with respect to compilations, and you have files
11440 that contain multiple units and configuration pragmas. In this
11441 circumstance the use of @code{gnatchop} with the compilation mode
11442 switch provides the required behavior, and is for example the mode
11443 in which GNAT processes the ACVC tests.
11444
11445 @node Command Line for gnatchop
11446 @section Command Line for @code{gnatchop}
11447
11448 @noindent
11449 The @code{gnatchop} command has the form:
11450
11451 @smallexample
11452 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11453 @c      @ovar{directory}
11454 @c Expanding @ovar macro inline (explanation in macro def comments)
11455 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11456       @r{[}@var{directory}@r{]}
11457 @end smallexample
11458
11459 @noindent
11460 The only required argument is the file name of the file to be chopped.
11461 There are no restrictions on the form of this file name. The file itself
11462 contains one or more Ada units, in normal GNAT format, concatenated
11463 together. As shown, more than one file may be presented to be chopped.
11464
11465 When run in default mode, @code{gnatchop} generates one output file in
11466 the current directory for each unit in each of the files.
11467
11468 @var{directory}, if specified, gives the name of the directory to which
11469 the output files will be written. If it is not specified, all files are
11470 written to the current directory.
11471
11472 For example, given a
11473 file called @file{hellofiles} containing
11474
11475 @smallexample @c ada
11476 @group
11477 @cartouche
11478 procedure hello;
11479
11480 with Text_IO; use Text_IO;
11481 procedure hello is
11482 begin
11483    Put_Line ("Hello");
11484 end hello;
11485 @end cartouche
11486 @end group
11487 @end smallexample
11488
11489 @noindent
11490 the command
11491
11492 @smallexample
11493 $ gnatchop ^hellofiles^HELLOFILES.^
11494 @end smallexample
11495
11496 @noindent
11497 generates two files in the current directory, one called
11498 @file{hello.ads} containing the single line that is the procedure spec,
11499 and the other called @file{hello.adb} containing the remaining text. The
11500 original file is not affected. The generated files can be compiled in
11501 the normal manner.
11502
11503 @noindent
11504 When gnatchop is invoked on a file that is empty or that contains only empty
11505 lines and/or comments, gnatchop will not fail, but will not produce any
11506 new sources.
11507
11508 For example, given a
11509 file called @file{toto.txt} containing
11510
11511 @smallexample @c ada
11512 @group
11513 @cartouche
11514 --  Just a comment
11515 @end cartouche
11516 @end group
11517 @end smallexample
11518
11519 @noindent
11520 the command
11521
11522 @smallexample
11523 $ gnatchop ^toto.txt^TOT.TXT^
11524 @end smallexample
11525
11526 @noindent
11527 will not produce any new file and will result in the following warnings:
11528
11529 @smallexample
11530 toto.txt:1:01: warning: empty file, contains no compilation units
11531 no compilation units found
11532 no source files written
11533 @end smallexample
11534
11535 @node Switches for gnatchop
11536 @section Switches for @code{gnatchop}
11537
11538 @noindent
11539 @command{gnatchop} recognizes the following switches:
11540
11541 @table @option
11542 @c !sort!
11543
11544 @item --version
11545 @cindex @option{--version} @command{gnatchop}
11546 Display Copyright and version, then exit disregarding all other options.
11547
11548 @item --help
11549 @cindex @option{--help} @command{gnatchop}
11550 If @option{--version} was not used, display usage, then exit disregarding
11551 all other options.
11552
11553 @item ^-c^/COMPILATION^
11554 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11555 Causes @code{gnatchop} to operate in compilation mode, in which
11556 configuration pragmas are handled according to strict RM rules. See
11557 previous section for a full description of this mode.
11558
11559 @ifclear vms
11560 @item -gnat@var{xxx}
11561 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11562 used to parse the given file. Not all @var{xxx} options make sense,
11563 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11564 process a source file that uses Latin-2 coding for identifiers.
11565 @end ifclear
11566
11567 @item ^-h^/HELP^
11568 Causes @code{gnatchop} to generate a brief help summary to the standard
11569 output file showing usage information.
11570
11571 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11572 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11573 Limit generated file names to the specified number @code{mm}
11574 of characters.
11575 This is useful if the
11576 resulting set of files is required to be interoperable with systems
11577 which limit the length of file names.
11578 @ifset vms
11579 If no value is given, or
11580 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11581 a default of 39, suitable for OpenVMS Alpha
11582 Systems, is assumed
11583 @end ifset
11584 @ifclear vms
11585 No space is allowed between the @option{-k} and the numeric value. The numeric
11586 value may be omitted in which case a default of @option{-k8},
11587 suitable for use
11588 with DOS-like file systems, is used. If no @option{-k} switch
11589 is present then
11590 there is no limit on the length of file names.
11591 @end ifclear
11592
11593 @item ^-p^/PRESERVE^
11594 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11595 Causes the file ^modification^creation^ time stamp of the input file to be
11596 preserved and used for the time stamp of the output file(s). This may be
11597 useful for preserving coherency of time stamps in an environment where
11598 @code{gnatchop} is used as part of a standard build process.
11599
11600 @item ^-q^/QUIET^
11601 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11602 Causes output of informational messages indicating the set of generated
11603 files to be suppressed. Warnings and error messages are unaffected.
11604
11605 @item ^-r^/REFERENCE^
11606 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11607 @findex Source_Reference
11608 Generate @code{Source_Reference} pragmas. Use this switch if the output
11609 files are regarded as temporary and development is to be done in terms
11610 of the original unchopped file. This switch causes
11611 @code{Source_Reference} pragmas to be inserted into each of the
11612 generated files to refers back to the original file name and line number.
11613 The result is that all error messages refer back to the original
11614 unchopped file.
11615 In addition, the debugging information placed into the object file (when
11616 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11617 specified)
11618 also refers back to this original file so that tools like profilers and
11619 debuggers will give information in terms of the original unchopped file.
11620
11621 If the original file to be chopped itself contains
11622 a @code{Source_Reference}
11623 pragma referencing a third file, then gnatchop respects
11624 this pragma, and the generated @code{Source_Reference} pragmas
11625 in the chopped file refer to the original file, with appropriate
11626 line numbers. This is particularly useful when @code{gnatchop}
11627 is used in conjunction with @code{gnatprep} to compile files that
11628 contain preprocessing statements and multiple units.
11629
11630 @item ^-v^/VERBOSE^
11631 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11632 Causes @code{gnatchop} to operate in verbose mode. The version
11633 number and copyright notice are output, as well as exact copies of
11634 the gnat1 commands spawned to obtain the chop control information.
11635
11636 @item ^-w^/OVERWRITE^
11637 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11638 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11639 fatal error if there is already a file with the same name as a
11640 file it would otherwise output, in other words if the files to be
11641 chopped contain duplicated units. This switch bypasses this
11642 check, and causes all but the last instance of such duplicated
11643 units to be skipped.
11644
11645 @ifclear vms
11646 @item --GCC=@var{xxxx}
11647 @cindex @option{--GCC=} (@code{gnatchop})
11648 Specify the path of the GNAT parser to be used. When this switch is used,
11649 no attempt is made to add the prefix to the GNAT parser executable.
11650 @end ifclear
11651 @end table
11652
11653 @node Examples of gnatchop Usage
11654 @section Examples of @code{gnatchop} Usage
11655
11656 @table @code
11657 @ifset vms
11658 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11659 @end ifset
11660 @ifclear vms
11661 @item gnatchop -w hello_s.ada prerelease/files
11662 @end ifclear
11663
11664 Chops the source file @file{hello_s.ada}. The output files will be
11665 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11666 overwriting any
11667 files with matching names in that directory (no files in the current
11668 directory are modified).
11669
11670 @item gnatchop ^archive^ARCHIVE.^
11671 Chops the source file @file{^archive^ARCHIVE.^}
11672 into the current directory. One
11673 useful application of @code{gnatchop} is in sending sets of sources
11674 around, for example in email messages. The required sources are simply
11675 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11676 command), and then
11677 @command{gnatchop} is used at the other end to reconstitute the original
11678 file names.
11679
11680 @item gnatchop file1 file2 file3 direc
11681 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11682 the resulting files in the directory @file{direc}. Note that if any units
11683 occur more than once anywhere within this set of files, an error message
11684 is generated, and no files are written. To override this check, use the
11685 @option{^-w^/OVERWRITE^} switch,
11686 in which case the last occurrence in the last file will
11687 be the one that is output, and earlier duplicate occurrences for a given
11688 unit will be skipped.
11689 @end table
11690
11691 @node Configuration Pragmas
11692 @chapter Configuration Pragmas
11693 @cindex Configuration pragmas
11694 @cindex Pragmas, configuration
11695
11696 @noindent
11697 Configuration pragmas include those pragmas described as
11698 such in the Ada Reference Manual, as well as
11699 implementation-dependent pragmas that are configuration pragmas.
11700 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11701 for details on these additional GNAT-specific configuration pragmas.
11702 Most notably, the pragma @code{Source_File_Name}, which allows
11703 specifying non-default names for source files, is a configuration
11704 pragma. The following is a complete list of configuration pragmas
11705 recognized by GNAT:
11706
11707 @smallexample
11708    Ada_83
11709    Ada_95
11710    Ada_05
11711    Ada_2005
11712    Ada_12
11713    Ada_2012
11714    Annotate
11715    Assertion_Policy
11716    Assume_No_Invalid_Values
11717    C_Pass_By_Copy
11718    Check_Name
11719    Check_Policy
11720    Compile_Time_Error
11721    Compile_Time_Warning
11722    Compiler_Unit
11723    Component_Alignment
11724    Convention_Identifier
11725    Debug_Policy
11726    Detect_Blocking
11727    Default_Storage_Pool
11728    Discard_Names
11729    Elaboration_Checks
11730    Eliminate
11731    Extend_System
11732    Extensions_Allowed
11733    External_Name_Casing
11734    Fast_Math
11735    Favor_Top_Level
11736    Float_Representation
11737    Implicit_Packing
11738    Initialize_Scalars
11739    Interrupt_State
11740    License
11741    Locking_Policy
11742    Long_Float
11743    No_Run_Time
11744    No_Strict_Aliasing
11745    Normalize_Scalars
11746    Optimize_Alignment
11747    Persistent_BSS
11748    Polling
11749    Priority_Specific_Dispatching
11750    Profile
11751    Profile_Warnings
11752    Propagate_Exceptions
11753    Queuing_Policy
11754    Ravenscar
11755    Restricted_Run_Time
11756    Restrictions
11757    Restrictions_Warnings
11758    Reviewable
11759    Short_Circuit_And_Or
11760    Source_File_Name
11761    Source_File_Name_Project
11762    Style_Checks
11763    Suppress
11764    Suppress_Exception_Locations
11765    Task_Dispatching_Policy
11766    Universal_Data
11767    Unsuppress
11768    Use_VADS_Size
11769    Validity_Checks
11770    Warnings
11771    Wide_Character_Encoding
11772
11773 @end smallexample
11774
11775 @menu
11776 * Handling of Configuration Pragmas::
11777 * The Configuration Pragmas Files::
11778 @end menu
11779
11780 @node Handling of Configuration Pragmas
11781 @section Handling of Configuration Pragmas
11782
11783 Configuration pragmas may either appear at the start of a compilation
11784 unit, in which case they apply only to that unit, or they may apply to
11785 all compilations performed in a given compilation environment.
11786
11787 GNAT also provides the @code{gnatchop} utility to provide an automatic
11788 way to handle configuration pragmas following the semantics for
11789 compilations (that is, files with multiple units), described in the RM.
11790 See @ref{Operating gnatchop in Compilation Mode} for details.
11791 However, for most purposes, it will be more convenient to edit the
11792 @file{gnat.adc} file that contains configuration pragmas directly,
11793 as described in the following section.
11794
11795 @node The Configuration Pragmas Files
11796 @section The Configuration Pragmas Files
11797 @cindex @file{gnat.adc}
11798
11799 @noindent
11800 In GNAT a compilation environment is defined by the current
11801 directory at the time that a compile command is given. This current
11802 directory is searched for a file whose name is @file{gnat.adc}. If
11803 this file is present, it is expected to contain one or more
11804 configuration pragmas that will be applied to the current compilation.
11805 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11806 considered.
11807
11808 Configuration pragmas may be entered into the @file{gnat.adc} file
11809 either by running @code{gnatchop} on a source file that consists only of
11810 configuration pragmas, or more conveniently  by
11811 direct editing of the @file{gnat.adc} file, which is a standard format
11812 source file.
11813
11814 In addition to @file{gnat.adc}, additional files containing configuration
11815 pragmas may be applied to the current compilation using the switch
11816 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11817 contains only configuration pragmas. These configuration pragmas are
11818 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11819 is present and switch @option{-gnatA} is not used).
11820
11821 It is allowed to specify several switches @option{-gnatec}, all of which
11822 will be taken into account.
11823
11824 If you are using project file, a separate mechanism is provided using
11825 project attributes, see @ref{Specifying Configuration Pragmas} for more
11826 details.
11827
11828 @ifset vms
11829 Of special interest to GNAT OpenVMS Alpha is the following
11830 configuration pragma:
11831
11832 @smallexample @c ada
11833 @cartouche
11834 pragma Extend_System (Aux_DEC);
11835 @end cartouche
11836 @end smallexample
11837
11838 @noindent
11839 In the presence of this pragma, GNAT adds to the definition of the
11840 predefined package SYSTEM all the additional types and subprograms that are
11841 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11842 @end ifset
11843
11844 @node Handling Arbitrary File Naming Conventions Using gnatname
11845 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11846 @cindex Arbitrary File Naming Conventions
11847
11848 @menu
11849 * Arbitrary File Naming Conventions::
11850 * Running gnatname::
11851 * Switches for gnatname::
11852 * Examples of gnatname Usage::
11853 @end menu
11854
11855 @node Arbitrary File Naming Conventions
11856 @section Arbitrary File Naming Conventions
11857
11858 @noindent
11859 The GNAT compiler must be able to know the source file name of a compilation
11860 unit.  When using the standard GNAT default file naming conventions
11861 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11862 does not need additional information.
11863
11864 @noindent
11865 When the source file names do not follow the standard GNAT default file naming
11866 conventions, the GNAT compiler must be given additional information through
11867 a configuration pragmas file (@pxref{Configuration Pragmas})
11868 or a project file.
11869 When the non-standard file naming conventions are well-defined,
11870 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11871 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11872 if the file naming conventions are irregular or arbitrary, a number
11873 of pragma @code{Source_File_Name} for individual compilation units
11874 must be defined.
11875 To help maintain the correspondence between compilation unit names and
11876 source file names within the compiler,
11877 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11878 set of files.
11879
11880 @node Running gnatname
11881 @section Running @code{gnatname}
11882
11883 @noindent
11884 The usual form of the @code{gnatname} command is
11885
11886 @smallexample
11887 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11888 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11889 @c Expanding @ovar macro inline (explanation in macro def comments)
11890 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11891       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11892 @end smallexample
11893
11894 @noindent
11895 All of the arguments are optional. If invoked without any argument,
11896 @code{gnatname} will display its usage.
11897
11898 @noindent
11899 When used with at least one naming pattern, @code{gnatname} will attempt to
11900 find all the compilation units in files that follow at least one of the
11901 naming patterns. To find these compilation units,
11902 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11903 regular files.
11904
11905 @noindent
11906 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11907 Each Naming Pattern is enclosed between double quotes (or single
11908 quotes on Windows).
11909 A Naming Pattern is a regular expression similar to the wildcard patterns
11910 used in file names by the Unix shells or the DOS prompt.
11911
11912 @noindent
11913 @code{gnatname} may be called with several sections of directories/patterns.
11914 Sections are separated by switch @code{--and}. In each section, there must be
11915 at least one pattern. If no directory is specified in a section, the current
11916 directory (or the project directory is @code{-P} is used) is implied.
11917 The options other that the directory switches and the patterns apply globally
11918 even if they are in different sections.
11919
11920 @noindent
11921 Examples of Naming Patterns are
11922
11923 @smallexample
11924    "*.[12].ada"
11925    "*.ad[sb]*"
11926    "body_*"    "spec_*"
11927 @end smallexample
11928
11929 @noindent
11930 For a more complete description of the syntax of Naming Patterns,
11931 see the second kind of regular expressions described in @file{g-regexp.ads}
11932 (the ``Glob'' regular expressions).
11933
11934 @noindent
11935 When invoked with no switch @code{-P}, @code{gnatname} will create a
11936 configuration pragmas file @file{gnat.adc} in the current working directory,
11937 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11938 unit.
11939
11940 @node Switches for gnatname
11941 @section Switches for @code{gnatname}
11942
11943 @noindent
11944 Switches for @code{gnatname} must precede any specified Naming Pattern.
11945
11946 @noindent
11947 You may specify any of the following switches to @code{gnatname}:
11948
11949 @table @option
11950 @c !sort!
11951
11952 @item --version
11953 @cindex @option{--version} @command{gnatname}
11954 Display Copyright and version, then exit disregarding all other options.
11955
11956 @item --help
11957 @cindex @option{--help} @command{gnatname}
11958 If @option{--version} was not used, display usage, then exit disregarding
11959 all other options.
11960
11961 @item --and
11962 Start another section of directories/patterns.
11963
11964 @item ^-c^/CONFIG_FILE=^@file{file}
11965 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11966 Create a configuration pragmas file @file{file} (instead of the default
11967 @file{gnat.adc}).
11968 @ifclear vms
11969 There may be zero, one or more space between @option{-c} and
11970 @file{file}.
11971 @end ifclear
11972 @file{file} may include directory information. @file{file} must be
11973 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11974 When a switch @option{^-c^/CONFIG_FILE^} is
11975 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11976
11977 @item ^-d^/SOURCE_DIRS=^@file{dir}
11978 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11979 Look for source files in directory @file{dir}. There may be zero, one or more
11980 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11981 When a switch @option{^-d^/SOURCE_DIRS^}
11982 is specified, the current working directory will not be searched for source
11983 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11984 or @option{^-D^/DIR_FILES^} switch.
11985 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11986 If @file{dir} is a relative path, it is relative to the directory of
11987 the configuration pragmas file specified with switch
11988 @option{^-c^/CONFIG_FILE^},
11989 or to the directory of the project file specified with switch
11990 @option{^-P^/PROJECT_FILE^} or,
11991 if neither switch @option{^-c^/CONFIG_FILE^}
11992 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11993 current working directory. The directory
11994 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11995
11996 @item ^-D^/DIRS_FILE=^@file{file}
11997 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11998 Look for source files in all directories listed in text file @file{file}.
11999 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12000 and @file{file}.
12001 @file{file} must be an existing, readable text file.
12002 Each nonempty line in @file{file} must be a directory.
12003 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12004 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12005 @file{file}.
12006
12007 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12008 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12009 Foreign patterns. Using this switch, it is possible to add sources of languages
12010 other than Ada to the list of sources of a project file.
12011 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12012 For example,
12013 @smallexample
12014 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12015 @end smallexample
12016 @noindent
12017 will look for Ada units in all files with the @file{.ada} extension,
12018 and will add to the list of file for project @file{prj.gpr} the C files
12019 with extension @file{.^c^C^}.
12020
12021 @item ^-h^/HELP^
12022 @cindex @option{^-h^/HELP^} (@code{gnatname})
12023 Output usage (help) information. The output is written to @file{stdout}.
12024
12025 @item ^-P^/PROJECT_FILE=^@file{proj}
12026 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12027 Create or update project file @file{proj}. There may be zero, one or more space
12028 between @option{-P} and @file{proj}. @file{proj} may include directory
12029 information. @file{proj} must be writable.
12030 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12031 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12032 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12033
12034 @item ^-v^/VERBOSE^
12035 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12036 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12037 This includes name of the file written, the name of the directories to search
12038 and, for each file in those directories whose name matches at least one of
12039 the Naming Patterns, an indication of whether the file contains a unit,
12040 and if so the name of the unit.
12041
12042 @item ^-v -v^/VERBOSE /VERBOSE^
12043 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12044 Very Verbose mode. In addition to the output produced in verbose mode,
12045 for each file in the searched directories whose name matches none of
12046 the Naming Patterns, an indication is given that there is no match.
12047
12048 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12049 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12050 Excluded patterns. Using this switch, it is possible to exclude some files
12051 that would match the name patterns. For example,
12052 @smallexample
12053 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12054 @end smallexample
12055 @noindent
12056 will look for Ada units in all files with the @file{.ada} extension,
12057 except those whose names end with @file{_nt.ada}.
12058
12059 @end table
12060
12061 @node Examples of gnatname Usage
12062 @section Examples of @code{gnatname} Usage
12063
12064 @ifset vms
12065 @smallexample
12066 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12067 @end smallexample
12068 @end ifset
12069
12070 @ifclear vms
12071 @smallexample
12072 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12073 @end smallexample
12074 @end ifclear
12075
12076 @noindent
12077 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12078 and be writable. In addition, the directory
12079 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12080 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12081
12082 @ifclear vms
12083 Note the optional spaces after @option{-c} and @option{-d}.
12084 @end ifclear
12085
12086 @smallexample
12087 @ifclear vms
12088 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12089   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12090 @end ifclear
12091 @ifset vms
12092 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12093   /EXCLUDED_PATTERN=*_nt_body.ada
12094   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12095   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12096 @end ifset
12097 @end smallexample
12098
12099 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12100 even in conjunction with one or several switches
12101 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12102 are used in this example.
12103
12104 @c *****************************************
12105 @c * G N A T  P r o j e c t  M a n a g e r *
12106 @c *****************************************
12107
12108 @c ------ macros for projects.texi
12109 @c These macros are needed when building the gprbuild documentation, but
12110 @c should have no effect in the gnat user's guide
12111
12112 @macro CODESAMPLE{TXT}
12113 @smallexample
12114 @group
12115 \TXT\
12116 @end group
12117 @end smallexample
12118 @end macro
12119
12120 @macro PROJECTFILE{TXT}
12121 @CODESAMPLE{\TXT\}
12122 @end macro
12123
12124 @c simulates a newline when in a @CODESAMPLE
12125 @macro NL{}
12126 @end macro
12127
12128 @macro TIP{TXT}
12129 @quotation
12130 @noindent
12131 \TXT\
12132 @end quotation
12133 @end macro
12134
12135 @macro TIPHTML{TXT}
12136 \TXT\
12137 @end macro
12138
12139 @macro IMPORTANT{TXT}
12140 @quotation
12141 @noindent
12142 \TXT\
12143 @end quotation
12144
12145 @end macro
12146
12147 @macro NOTE{TXT}
12148 @quotation
12149 @noindent
12150 \TXT\
12151 @end quotation
12152 @end macro
12153
12154 @include projects.texi
12155
12156 @c *****************************************
12157 @c * Cross-referencing tools
12158 @c *****************************************
12159
12160 @node The Cross-Referencing Tools gnatxref and gnatfind
12161 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12162 @findex gnatxref
12163 @findex gnatfind
12164
12165 @noindent
12166 The compiler generates cross-referencing information (unless
12167 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12168 This information indicates where in the source each entity is declared and
12169 referenced. Note that entities in package Standard are not included, but
12170 entities in all other predefined units are included in the output.
12171
12172 Before using any of these two tools, you need to compile successfully your
12173 application, so that GNAT gets a chance to generate the cross-referencing
12174 information.
12175
12176 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12177 information to provide the user with the capability to easily locate the
12178 declaration and references to an entity. These tools are quite similar,
12179 the difference being that @code{gnatfind} is intended for locating
12180 definitions and/or references to a specified entity or entities, whereas
12181 @code{gnatxref} is oriented to generating a full report of all
12182 cross-references.
12183
12184 To use these tools, you must not compile your application using the
12185 @option{-gnatx} switch on the @command{gnatmake} command line
12186 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12187 information will not be generated.
12188
12189 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12190 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12191
12192 @menu
12193 * Switches for gnatxref::
12194 * Switches for gnatfind::
12195 * Project Files for gnatxref and gnatfind::
12196 * Regular Expressions in gnatfind and gnatxref::
12197 * Examples of gnatxref Usage::
12198 * Examples of gnatfind Usage::
12199 @end menu
12200
12201 @node Switches for gnatxref
12202 @section @code{gnatxref} Switches
12203
12204 @noindent
12205 The command invocation for @code{gnatxref} is:
12206 @smallexample
12207 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12208 @c Expanding @ovar macro inline (explanation in macro def comments)
12209 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12210 @end smallexample
12211
12212 @noindent
12213 where
12214
12215 @table @var
12216 @item sourcefile1
12217 @itemx sourcefile2
12218 identifies the source files for which a report is to be generated. The
12219 ``with''ed units will be processed too. You must provide at least one file.
12220
12221 These file names are considered to be regular expressions, so for instance
12222 specifying @file{source*.adb} is the same as giving every file in the current
12223 directory whose name starts with @file{source} and whose extension is
12224 @file{adb}.
12225
12226 You shouldn't specify any directory name, just base names. @command{gnatxref}
12227 and @command{gnatfind} will be able to locate these files by themselves using
12228 the source path. If you specify directories, no result is produced.
12229
12230 @end table
12231
12232 @noindent
12233 The switches can be:
12234 @table @option
12235 @c !sort!
12236 @item --version
12237 @cindex @option{--version} @command{gnatxref}
12238 Display Copyright and version, then exit disregarding all other options.
12239
12240 @item --help
12241 @cindex @option{--help} @command{gnatxref}
12242 If @option{--version} was not used, display usage, then exit disregarding
12243 all other options.
12244
12245 @item ^-a^/ALL_FILES^
12246 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12247 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12248 the read-only files found in the library search path. Otherwise, these files
12249 will be ignored. This option can be used to protect Gnat sources or your own
12250 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12251 much faster, and their output much smaller. Read-only here refers to access
12252 or permissions status in the file system for the current user.
12253
12254 @item -aIDIR
12255 @cindex @option{-aIDIR} (@command{gnatxref})
12256 When looking for source files also look in directory DIR. The order in which
12257 source file search is undertaken is the same as for @command{gnatmake}.
12258
12259 @item -aODIR
12260 @cindex @option{-aODIR} (@command{gnatxref})
12261 When searching for library and object files, look in directory
12262 DIR. The order in which library files are searched is the same as for
12263 @command{gnatmake}.
12264
12265 @item -nostdinc
12266 @cindex @option{-nostdinc} (@command{gnatxref})
12267 Do not look for sources in the system default directory.
12268
12269 @item -nostdlib
12270 @cindex @option{-nostdlib} (@command{gnatxref})
12271 Do not look for library files in the system default directory.
12272
12273 @item --ext=@var{extension}
12274 @cindex @option{--ext} (@command{gnatxref})
12275 Specify an alternate ali file extension. The default is @code{ali} and other
12276 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12277 switch. Note that if this switch overrides the default, which means that only
12278 the new extension will be considered.
12279
12280 @item --RTS=@var{rts-path}
12281 @cindex @option{--RTS} (@command{gnatxref})
12282 Specifies the default location of the runtime library. Same meaning as the
12283 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12284
12285 @item ^-d^/DERIVED_TYPES^
12286 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12287 If this switch is set @code{gnatxref} will output the parent type
12288 reference for each matching derived types.
12289
12290 @item ^-f^/FULL_PATHNAME^
12291 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12292 If this switch is set, the output file names will be preceded by their
12293 directory (if the file was found in the search path). If this switch is
12294 not set, the directory will not be printed.
12295
12296 @item ^-g^/IGNORE_LOCALS^
12297 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12298 If this switch is set, information is output only for library-level
12299 entities, ignoring local entities. The use of this switch may accelerate
12300 @code{gnatfind} and @code{gnatxref}.
12301
12302 @item -IDIR
12303 @cindex @option{-IDIR} (@command{gnatxref})
12304 Equivalent to @samp{-aODIR -aIDIR}.
12305
12306 @item -pFILE
12307 @cindex @option{-pFILE} (@command{gnatxref})
12308 Specify a project file to use @xref{GNAT Project Manager}.
12309 If you need to use the @file{.gpr}
12310 project files, you should use gnatxref through the GNAT driver
12311 (@command{gnat xref -Pproject}).
12312
12313 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12314 project file in the current directory.
12315
12316 If a project file is either specified or found by the tools, then the content
12317 of the source directory and object directory lines are added as if they
12318 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12319 and @samp{^-aO^OBJECT_SEARCH^}.
12320 @item ^-u^/UNUSED^
12321 Output only unused symbols. This may be really useful if you give your
12322 main compilation unit on the command line, as @code{gnatxref} will then
12323 display every unused entity and 'with'ed package.
12324
12325 @ifclear vms
12326 @item -v
12327 Instead of producing the default output, @code{gnatxref} will generate a
12328 @file{tags} file that can be used by vi. For examples how to use this
12329 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12330 to the standard output, thus you will have to redirect it to a file.
12331 @end ifclear
12332
12333 @end table
12334
12335 @noindent
12336 All these switches may be in any order on the command line, and may even
12337 appear after the file names. They need not be separated by spaces, thus
12338 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12339 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12340
12341 @node Switches for gnatfind
12342 @section @code{gnatfind} Switches
12343
12344 @noindent
12345 The command line for @code{gnatfind} is:
12346
12347 @smallexample
12348 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12349 @c       @r{[}@var{file1} @var{file2} @dots{}]
12350 @c Expanding @ovar macro inline (explanation in macro def comments)
12351 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12352       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12353 @end smallexample
12354
12355 @noindent
12356 where
12357
12358 @table @var
12359 @item pattern
12360 An entity will be output only if it matches the regular expression found
12361 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12362
12363 Omitting the pattern is equivalent to specifying @samp{*}, which
12364 will match any entity. Note that if you do not provide a pattern, you
12365 have to provide both a sourcefile and a line.
12366
12367 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12368 for matching purposes. At the current time there is no support for
12369 8-bit codes other than Latin-1, or for wide characters in identifiers.
12370
12371 @item sourcefile
12372 @code{gnatfind} will look for references, bodies or declarations
12373 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12374 and column @var{column}. See @ref{Examples of gnatfind Usage}
12375 for syntax examples.
12376
12377 @item line
12378 is a decimal integer identifying the line number containing
12379 the reference to the entity (or entities) to be located.
12380
12381 @item column
12382 is a decimal integer identifying the exact location on the
12383 line of the first character of the identifier for the
12384 entity reference. Columns are numbered from 1.
12385
12386 @item file1 file2 @dots{}
12387 The search will be restricted to these source files. If none are given, then
12388 the search will be done for every library file in the search path.
12389 These file must appear only after the pattern or sourcefile.
12390
12391 These file names are considered to be regular expressions, so for instance
12392 specifying @file{source*.adb} is the same as giving every file in the current
12393 directory whose name starts with @file{source} and whose extension is
12394 @file{adb}.
12395
12396 The location of the spec of the entity will always be displayed, even if it
12397 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12398 occurrences of the entity in the separate units of the ones given on the
12399 command line will also be displayed.
12400
12401 Note that if you specify at least one file in this part, @code{gnatfind} may
12402 sometimes not be able to find the body of the subprograms.
12403
12404 @end table
12405
12406 @noindent
12407 At least one of 'sourcefile' or 'pattern' has to be present on
12408 the command line.
12409
12410 The following switches are available:
12411 @table @option
12412 @c !sort!
12413
12414 @cindex @option{--version} @command{gnatfind}
12415 Display Copyright and version, then exit disregarding all other options.
12416
12417 @item --help
12418 @cindex @option{--help} @command{gnatfind}
12419 If @option{--version} was not used, display usage, then exit disregarding
12420 all other options.
12421
12422 @item ^-a^/ALL_FILES^
12423 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12424 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12425 the read-only files found in the library search path. Otherwise, these files
12426 will be ignored. This option can be used to protect Gnat sources or your own
12427 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12428 much faster, and their output much smaller. Read-only here refers to access
12429 or permission status in the file system for the current user.
12430
12431 @item -aIDIR
12432 @cindex @option{-aIDIR} (@command{gnatfind})
12433 When looking for source files also look in directory DIR. The order in which
12434 source file search is undertaken is the same as for @command{gnatmake}.
12435
12436 @item -aODIR
12437 @cindex @option{-aODIR} (@command{gnatfind})
12438 When searching for library and object files, look in directory
12439 DIR. The order in which library files are searched is the same as for
12440 @command{gnatmake}.
12441
12442 @item -nostdinc
12443 @cindex @option{-nostdinc} (@command{gnatfind})
12444 Do not look for sources in the system default directory.
12445
12446 @item -nostdlib
12447 @cindex @option{-nostdlib} (@command{gnatfind})
12448 Do not look for library files in the system default directory.
12449
12450 @item --ext=@var{extension}
12451 @cindex @option{--ext} (@command{gnatfind})
12452 Specify an alternate ali file extension. The default is @code{ali} and other
12453 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12454 switch. Note that if this switch overrides the default, which means that only
12455 the new extension will be considered.
12456
12457 @item --RTS=@var{rts-path}
12458 @cindex @option{--RTS} (@command{gnatfind})
12459 Specifies the default location of the runtime library. Same meaning as the
12460 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12461
12462 @item ^-d^/DERIVED_TYPE_INFORMATION^
12463 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12464 If this switch is set, then @code{gnatfind} will output the parent type
12465 reference for each matching derived types.
12466
12467 @item ^-e^/EXPRESSIONS^
12468 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12469 By default, @code{gnatfind} accept the simple regular expression set for
12470 @samp{pattern}. If this switch is set, then the pattern will be
12471 considered as full Unix-style regular expression.
12472
12473 @item ^-f^/FULL_PATHNAME^
12474 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12475 If this switch is set, the output file names will be preceded by their
12476 directory (if the file was found in the search path). If this switch is
12477 not set, the directory will not be printed.
12478
12479 @item ^-g^/IGNORE_LOCALS^
12480 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12481 If this switch is set, information is output only for library-level
12482 entities, ignoring local entities. The use of this switch may accelerate
12483 @code{gnatfind} and @code{gnatxref}.
12484
12485 @item -IDIR
12486 @cindex @option{-IDIR} (@command{gnatfind})
12487 Equivalent to @samp{-aODIR -aIDIR}.
12488
12489 @item -pFILE
12490 @cindex @option{-pFILE} (@command{gnatfind})
12491 Specify a project file (@pxref{GNAT Project Manager}) to use.
12492 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12493 project file in the current directory.
12494
12495 If a project file is either specified or found by the tools, then the content
12496 of the source directory and object directory lines are added as if they
12497 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12498 @samp{^-aO^/OBJECT_SEARCH^}.
12499
12500 @item ^-r^/REFERENCES^
12501 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12502 By default, @code{gnatfind} will output only the information about the
12503 declaration, body or type completion of the entities. If this switch is
12504 set, the @code{gnatfind} will locate every reference to the entities in
12505 the files specified on the command line (or in every file in the search
12506 path if no file is given on the command line).
12507
12508 @item ^-s^/PRINT_LINES^
12509 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12510 If this switch is set, then @code{gnatfind} will output the content
12511 of the Ada source file lines were the entity was found.
12512
12513 @item ^-t^/TYPE_HIERARCHY^
12514 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12515 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12516 the specified type. It act like -d option but recursively from parent
12517 type to parent type. When this switch is set it is not possible to
12518 specify more than one file.
12519
12520 @end table
12521
12522 @noindent
12523 All these switches may be in any order on the command line, and may even
12524 appear after the file names. They need not be separated by spaces, thus
12525 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12526 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12527
12528 As stated previously, gnatfind will search in every directory in the
12529 search path. You can force it to look only in the current directory if
12530 you specify @code{*} at the end of the command line.
12531
12532 @node Project Files for gnatxref and gnatfind
12533 @section Project Files for @command{gnatxref} and @command{gnatfind}
12534
12535 @noindent
12536 Project files allow a programmer to specify how to compile its
12537 application, where to find sources, etc.  These files are used
12538 @ifclear vms
12539 primarily by GPS, but they can also be used
12540 @end ifclear
12541 by the two tools
12542 @code{gnatxref} and @code{gnatfind}.
12543
12544 A project file name must end with @file{.gpr}. If a single one is
12545 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12546 extract the information from it. If multiple project files are found, none of
12547 them is read, and you have to use the @samp{-p} switch to specify the one
12548 you want to use.
12549
12550 The following lines can be included, even though most of them have default
12551 values which can be used in most cases.
12552 The lines can be entered in any order in the file.
12553 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12554 each line. If you have multiple instances, only the last one is taken into
12555 account.
12556
12557 @table @code
12558 @item src_dir=DIR
12559 [default: @code{"^./^[]^"}]
12560 specifies a directory where to look for source files. Multiple @code{src_dir}
12561 lines can be specified and they will be searched in the order they
12562 are specified.
12563
12564 @item obj_dir=DIR
12565 [default: @code{"^./^[]^"}]
12566 specifies a directory where to look for object and library files. Multiple
12567 @code{obj_dir} lines can be specified, and they will be searched in the order
12568 they are specified
12569
12570 @item comp_opt=SWITCHES
12571 [default: @code{""}]
12572 creates a variable which can be referred to subsequently by using
12573 the @code{$@{comp_opt@}} notation. This is intended to store the default
12574 switches given to @command{gnatmake} and @command{gcc}.
12575
12576 @item bind_opt=SWITCHES
12577 [default: @code{""}]
12578 creates a variable which can be referred to subsequently by using
12579 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12580 switches given to @command{gnatbind}.
12581
12582 @item link_opt=SWITCHES
12583 [default: @code{""}]
12584 creates a variable which can be referred to subsequently by using
12585 the @samp{$@{link_opt@}} notation. This is intended to store the default
12586 switches given to @command{gnatlink}.
12587
12588 @item main=EXECUTABLE
12589 [default: @code{""}]
12590 specifies the name of the executable for the application. This variable can
12591 be referred to in the following lines by using the @samp{$@{main@}} notation.
12592
12593 @ifset vms
12594 @item comp_cmd=COMMAND
12595 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12596 @end ifset
12597 @ifclear vms
12598 @item comp_cmd=COMMAND
12599 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12600 @end ifclear
12601 specifies the command used to compile a single file in the application.
12602
12603 @ifset vms
12604 @item make_cmd=COMMAND
12605 [default: @code{"GNAT MAKE $@{main@}
12606 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12607 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12608 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12609 @end ifset
12610 @ifclear vms
12611 @item make_cmd=COMMAND
12612 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12613 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12614 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12615 @end ifclear
12616 specifies the command used to recompile the whole application.
12617
12618 @item run_cmd=COMMAND
12619 [default: @code{"$@{main@}"}]
12620 specifies the command used to run the application.
12621
12622 @item debug_cmd=COMMAND
12623 [default: @code{"gdb $@{main@}"}]
12624 specifies the command used to debug the application
12625
12626 @end table
12627
12628 @noindent
12629 @command{gnatxref} and @command{gnatfind} only take into account the
12630 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12631
12632 @node Regular Expressions in gnatfind and gnatxref
12633 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12634
12635 @noindent
12636 As specified in the section about @command{gnatfind}, the pattern can be a
12637 regular expression. Actually, there are to set of regular expressions
12638 which are recognized by the program:
12639
12640 @table @code
12641 @item globbing patterns
12642 These are the most usual regular expression. They are the same that you
12643 generally used in a Unix shell command line, or in a DOS session.
12644
12645 Here is a more formal grammar:
12646 @smallexample
12647 @group
12648 @iftex
12649 @leftskip=.5cm
12650 @end iftex
12651 regexp ::= term
12652 term   ::= elmt            -- matches elmt
12653 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12654 term   ::= *               -- any string of 0 or more characters
12655 term   ::= ?               -- matches any character
12656 term   ::= [char @{char@}]   -- matches any character listed
12657 term   ::= [char - char]   -- matches any character in range
12658 @end group
12659 @end smallexample
12660
12661 @item full regular expression
12662 The second set of regular expressions is much more powerful. This is the
12663 type of regular expressions recognized by utilities such a @file{grep}.
12664
12665 The following is the form of a regular expression, expressed in Ada
12666 reference manual style BNF is as follows
12667
12668 @smallexample
12669 @iftex
12670 @leftskip=.5cm
12671 @end iftex
12672 @group
12673 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12674
12675 term ::= item @{item@}       -- concatenation (item then item)
12676
12677 item ::= elmt              -- match elmt
12678 item ::= elmt *            -- zero or more elmt's
12679 item ::= elmt +            -- one or more elmt's
12680 item ::= elmt ?            -- matches elmt or nothing
12681 @end group
12682 @group
12683 elmt ::= nschar            -- matches given character
12684 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12685 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12686 elmt ::= [char - char]     -- matches chars in given range
12687 elmt ::= \ char            -- matches given character
12688 elmt ::= .                 -- matches any single character
12689 elmt ::= ( regexp )        -- parens used for grouping
12690
12691 char ::= any character, including special characters
12692 nschar ::= any character except ()[].*+?^^^
12693 @end group
12694 @end smallexample
12695
12696 Following are a few examples:
12697
12698 @table @samp
12699 @item abcde|fghi
12700 will match any of the two strings @samp{abcde} and @samp{fghi},
12701
12702 @item abc*d
12703 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12704 @samp{abcccd}, and so on,
12705
12706 @item [a-z]+
12707 will match any string which has only lowercase characters in it (and at
12708 least one character.
12709
12710 @end table
12711 @end table
12712
12713 @node Examples of gnatxref Usage
12714 @section Examples of @code{gnatxref} Usage
12715
12716 @subsection General Usage
12717
12718 @noindent
12719 For the following examples, we will consider the following units:
12720
12721 @smallexample @c ada
12722 @group
12723 @cartouche
12724 main.ads:
12725 1: with Bar;
12726 2: package Main is
12727 3:     procedure Foo (B : in Integer);
12728 4:     C : Integer;
12729 5: private
12730 6:     D : Integer;
12731 7: end Main;
12732
12733 main.adb:
12734 1: package body Main is
12735 2:     procedure Foo (B : in Integer) is
12736 3:     begin
12737 4:        C := B;
12738 5:        D := B;
12739 6:        Bar.Print (B);
12740 7:        Bar.Print (C);
12741 8:     end Foo;
12742 9: end Main;
12743
12744 bar.ads:
12745 1: package Bar is
12746 2:     procedure Print (B : Integer);
12747 3: end bar;
12748 @end cartouche
12749 @end group
12750 @end smallexample
12751
12752 @table @code
12753
12754 @noindent
12755 The first thing to do is to recompile your application (for instance, in
12756 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12757 the cross-referencing information.
12758 You can then issue any of the following commands:
12759
12760 @item gnatxref main.adb
12761 @code{gnatxref} generates cross-reference information for main.adb
12762 and every unit 'with'ed by main.adb.
12763
12764 The output would be:
12765 @smallexample
12766 @iftex
12767 @leftskip=0cm
12768 @end iftex
12769 B                                                      Type: Integer
12770   Decl: bar.ads           2:22
12771 B                                                      Type: Integer
12772   Decl: main.ads          3:20
12773   Body: main.adb          2:20
12774   Ref:  main.adb          4:13     5:13     6:19
12775 Bar                                                    Type: Unit
12776   Decl: bar.ads           1:9
12777   Ref:  main.adb          6:8      7:8
12778        main.ads           1:6
12779 C                                                      Type: Integer
12780   Decl: main.ads          4:5
12781   Modi: main.adb          4:8
12782   Ref:  main.adb          7:19
12783 D                                                      Type: Integer
12784   Decl: main.ads          6:5
12785   Modi: main.adb          5:8
12786 Foo                                                    Type: Unit
12787   Decl: main.ads          3:15
12788   Body: main.adb          2:15
12789 Main                                                    Type: Unit
12790   Decl: main.ads          2:9
12791   Body: main.adb          1:14
12792 Print                                                   Type: Unit
12793   Decl: bar.ads           2:15
12794   Ref:  main.adb          6:12     7:12
12795 @end smallexample
12796
12797 @noindent
12798 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12799 its body is in main.adb, line 1, column 14 and is not referenced any where.
12800
12801 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12802 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12803
12804 @item gnatxref package1.adb package2.ads
12805 @code{gnatxref} will generates cross-reference information for
12806 package1.adb, package2.ads and any other package 'with'ed by any
12807 of these.
12808
12809 @end table
12810
12811 @ifclear vms
12812 @subsection Using gnatxref with vi
12813
12814 @code{gnatxref} can generate a tags file output, which can be used
12815 directly from @command{vi}. Note that the standard version of @command{vi}
12816 will not work properly with overloaded symbols. Consider using another
12817 free implementation of @command{vi}, such as @command{vim}.
12818
12819 @smallexample
12820 $ gnatxref -v gnatfind.adb > tags
12821 @end smallexample
12822
12823 @noindent
12824 will generate the tags file for @code{gnatfind} itself (if the sources
12825 are in the search path!).
12826
12827 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12828 (replacing @var{entity} by whatever you are looking for), and vi will
12829 display a new file with the corresponding declaration of entity.
12830 @end ifclear
12831
12832 @node Examples of gnatfind Usage
12833 @section Examples of @code{gnatfind} Usage
12834
12835 @table @code
12836
12837 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12838 Find declarations for all entities xyz referenced at least once in
12839 main.adb. The references are search in every library file in the search
12840 path.
12841
12842 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12843 switch is set)
12844
12845 The output will look like:
12846 @smallexample
12847 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12848 ^directory/^[directory]^main.adb:24:10: xyz <= body
12849 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12850 @end smallexample
12851
12852 @noindent
12853 that is to say, one of the entities xyz found in main.adb is declared at
12854 line 12 of main.ads (and its body is in main.adb), and another one is
12855 declared at line 45 of foo.ads
12856
12857 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12858 This is the same command as the previous one, instead @code{gnatfind} will
12859 display the content of the Ada source file lines.
12860
12861 The output will look like:
12862
12863 @smallexample
12864 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12865    procedure xyz;
12866 ^directory/^[directory]^main.adb:24:10: xyz <= body
12867    procedure xyz is
12868 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12869    xyz : Integer;
12870 @end smallexample
12871
12872 @noindent
12873 This can make it easier to find exactly the location your are looking
12874 for.
12875
12876 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12877 Find references to all entities containing an x that are
12878 referenced on line 123 of main.ads.
12879 The references will be searched only in main.ads and foo.adb.
12880
12881 @item gnatfind main.ads:123
12882 Find declarations and bodies for all entities that are referenced on
12883 line 123 of main.ads.
12884
12885 This is the same as @code{gnatfind "*":main.adb:123}.
12886
12887 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12888 Find the declaration for the entity referenced at column 45 in
12889 line 123 of file main.adb in directory mydir. Note that it
12890 is usual to omit the identifier name when the column is given,
12891 since the column position identifies a unique reference.
12892
12893 The column has to be the beginning of the identifier, and should not
12894 point to any character in the middle of the identifier.
12895
12896 @end table
12897
12898 @c *********************************
12899 @node The GNAT Pretty-Printer gnatpp
12900 @chapter The GNAT Pretty-Printer @command{gnatpp}
12901 @findex gnatpp
12902 @cindex Pretty-Printer
12903
12904 @noindent
12905 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12906 for source reformatting / pretty-printing.
12907 It takes an Ada source file as input and generates a reformatted
12908 version as output.
12909 You can specify various style directives via switches; e.g.,
12910 identifier case conventions, rules of indentation, and comment layout.
12911
12912 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12913 tree for the input source and thus requires the input to be syntactically and
12914 semantically legal.
12915 If this condition is not met, @command{gnatpp} will terminate with an
12916 error message; no output file will be generated.
12917
12918 If the source files presented to @command{gnatpp} contain
12919 preprocessing directives, then the output file will
12920 correspond to the generated source after all
12921 preprocessing is carried out. There is no way
12922 using @command{gnatpp} to obtain pretty printed files that
12923 include the preprocessing directives.
12924
12925 If the compilation unit
12926 contained in the input source depends semantically upon units located
12927 outside the current directory, you have to provide the source search path
12928 when invoking @command{gnatpp}, if these units are contained in files with
12929 names that do not follow the GNAT file naming rules, you have to provide
12930 the configuration file describing the corresponding naming scheme;
12931 see the description of the @command{gnatpp}
12932 switches below. Another possibility is to use a project file and to
12933 call @command{gnatpp} through the @command{gnat} driver
12934 (see @ref{The GNAT Driver and Project Files}).
12935
12936 The @command{gnatpp} command has the form
12937
12938 @smallexample
12939 @c $ gnatpp @ovar{switches} @var{filename}
12940 @c Expanding @ovar macro inline (explanation in macro def comments)
12941 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12942 @end smallexample
12943
12944 @noindent
12945 where
12946 @itemize @bullet
12947 @item
12948 @var{switches} is an optional sequence of switches defining such properties as
12949 the formatting rules, the source search path, and the destination for the
12950 output source file
12951
12952 @item
12953 @var{filename} is the name (including the extension) of the source file to
12954 reformat; ``wildcards'' or several file names on the same gnatpp command are
12955 allowed.  The file name may contain path information; it does not have to
12956 follow the GNAT file naming rules
12957
12958 @item
12959 @samp{@var{gcc_switches}} is a list of switches for
12960 @command{gcc}. They will be passed on to all compiler invocations made by
12961 @command{gnatelim} to generate the ASIS trees. Here you can provide
12962 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12963 use the @option{-gnatec} switch to set the configuration file,
12964 use the @option{-gnat05} switch if sources should be compiled in
12965 Ada 2005 mode  etc.
12966 @end itemize
12967
12968 @menu
12969 * Switches for gnatpp::
12970 * Formatting Rules::
12971 @end menu
12972
12973 @node Switches for gnatpp
12974 @section Switches for @command{gnatpp}
12975
12976 @noindent
12977 The following subsections describe the various switches accepted by
12978 @command{gnatpp}, organized by category.
12979
12980 @ifclear vms
12981 You specify a switch by supplying a name and generally also a value.
12982 In many cases the values for a switch with a given name are incompatible with
12983 each other
12984 (for example the switch that controls the casing of a reserved word may have
12985 exactly one value: upper case, lower case, or
12986 mixed case) and thus exactly one such switch can be in effect for an
12987 invocation of @command{gnatpp}.
12988 If more than one is supplied, the last one is used.
12989 However, some values for the same switch are mutually compatible.
12990 You may supply several such switches to @command{gnatpp}, but then
12991 each must be specified in full, with both the name and the value.
12992 Abbreviated forms (the name appearing once, followed by each value) are
12993 not permitted.
12994 For example, to set
12995 the alignment of the assignment delimiter both in declarations and in
12996 assignment statements, you must write @option{-A2A3}
12997 (or @option{-A2 -A3}), but not @option{-A23}.
12998 @end ifclear
12999
13000 @ifset vms
13001 In many cases the set of options for a given qualifier are incompatible with
13002 each other (for example the qualifier that controls the casing of a reserved
13003 word may have exactly one option, which specifies either upper case, lower
13004 case, or mixed case), and thus exactly one such option can be in effect for
13005 an invocation of @command{gnatpp}.
13006 If more than one is supplied, the last one is used.
13007 However, some qualifiers have options that are mutually compatible,
13008 and then you may then supply several such options when invoking
13009 @command{gnatpp}.
13010 @end ifset
13011
13012 In most cases, it is obvious whether or not the
13013 ^values for a switch with a given name^options for a given qualifier^
13014 are compatible with each other.
13015 When the semantics might not be evident, the summaries below explicitly
13016 indicate the effect.
13017
13018 @menu
13019 * Alignment Control::
13020 * Casing Control::
13021 * Construct Layout Control::
13022 * General Text Layout Control::
13023 * Other Formatting Options::
13024 * Setting the Source Search Path::
13025 * Output File Control::
13026 * Other gnatpp Switches::
13027 @end menu
13028
13029 @node Alignment Control
13030 @subsection Alignment Control
13031 @cindex Alignment control in @command{gnatpp}
13032
13033 @noindent
13034 Programs can be easier to read if certain constructs are vertically aligned.
13035 By default all alignments are set ON.
13036 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13037 OFF, and then use one or more of the other
13038 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13039 to activate alignment for specific constructs.
13040
13041 @table @option
13042 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13043
13044 @ifset vms
13045 @item /ALIGN=ON
13046 Set all alignments to ON
13047 @end ifset
13048
13049 @item ^-A0^/ALIGN=OFF^
13050 Set all alignments to OFF
13051
13052 @item ^-A1^/ALIGN=COLONS^
13053 Align @code{:} in declarations
13054
13055 @item ^-A2^/ALIGN=DECLARATIONS^
13056 Align @code{:=} in initializations in declarations
13057
13058 @item ^-A3^/ALIGN=STATEMENTS^
13059 Align @code{:=} in assignment statements
13060
13061 @item ^-A4^/ALIGN=ARROWS^
13062 Align @code{=>} in associations
13063
13064 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13065 Align @code{at} keywords in the component clauses in record
13066 representation clauses
13067 @end table
13068
13069 @noindent
13070 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13071 is allowed.
13072
13073 @node Casing Control
13074 @subsection Casing Control
13075 @cindex Casing control in @command{gnatpp}
13076
13077 @noindent
13078 @command{gnatpp} allows you to specify the casing for reserved words,
13079 pragma names, attribute designators and identifiers.
13080 For identifiers you may define a
13081 general rule for name casing but also override this rule
13082 via a set of dictionary files.
13083
13084 Three types of casing are supported: lower case, upper case, and mixed case.
13085 Lower and upper case are self-explanatory (but since some letters in
13086 Latin1 and other GNAT-supported character sets
13087 exist only in lower-case form, an upper case conversion will have no
13088 effect on them.)
13089 ``Mixed case'' means that the first letter, and also each letter immediately
13090 following an underscore, are converted to their uppercase forms;
13091 all the other letters are converted to their lowercase forms.
13092
13093 @table @option
13094 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13095 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13096 Attribute designators are lower case
13097
13098 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13099 Attribute designators are upper case
13100
13101 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13102 Attribute designators are mixed case (this is the default)
13103
13104 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13105 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13106 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13107 lower case (this is the default)
13108
13109 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13110 Keywords are upper case
13111
13112 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13113 @item ^-nD^/NAME_CASING=AS_DECLARED^
13114 Name casing for defining occurrences are as they appear in the source file
13115 (this is the default)
13116
13117 @item ^-nU^/NAME_CASING=UPPER_CASE^
13118 Names are in upper case
13119
13120 @item ^-nL^/NAME_CASING=LOWER_CASE^
13121 Names are in lower case
13122
13123 @item ^-nM^/NAME_CASING=MIXED_CASE^
13124 Names are in mixed case
13125
13126 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13127 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13128 Enumeration literal casing for defining occurrences are as they appear in the
13129 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13130
13131 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13132 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13133 setting.
13134
13135 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13136 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13137 setting.
13138
13139 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13140 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13141 setting.
13142
13143 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13144 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13145 Pragma names are lower case
13146
13147 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13148 Pragma names are upper case
13149
13150 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13151 Pragma names are mixed case (this is the default)
13152
13153 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13154 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13155 Use @var{file} as a @emph{dictionary file} that defines
13156 the casing for a set of specified names,
13157 thereby overriding the effect on these names by
13158 any explicit or implicit
13159 ^-n^/NAME_CASING^ switch.
13160 To supply more than one dictionary file,
13161 use ^several @option{-D} switches^a list of files as options^.
13162
13163 @noindent
13164 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13165 to define the casing for the Ada predefined names and
13166 the names declared in the GNAT libraries.
13167
13168 @item ^-D-^/SPECIFIC_CASING^
13169 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13170 Do not use the default dictionary file;
13171 instead, use the casing
13172 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13173 dictionary file(s)
13174 @end table
13175
13176 @noindent
13177 The structure of a dictionary file, and details on the conventions
13178 used in the default dictionary file, are defined in @ref{Name Casing}.
13179
13180 The @option{^-D-^/SPECIFIC_CASING^} and
13181 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13182 compatible.
13183
13184 @node Construct Layout Control
13185 @subsection Construct Layout Control
13186 @cindex Layout control in @command{gnatpp}
13187
13188 @noindent
13189 This group of @command{gnatpp} switches controls the layout of comments and
13190 complex syntactic constructs.  See @ref{Formatting Comments} for details
13191 on their effect.
13192
13193 @table @option
13194 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13195 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13196 All the comments remain unchanged
13197
13198 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13199 GNAT-style comment line indentation (this is the default).
13200
13201 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13202 Reference-manual comment line indentation.
13203
13204 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13205 GNAT-style comment beginning
13206
13207 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13208 Reformat comment blocks
13209
13210 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13211 Keep unchanged special form comments
13212
13213 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13214 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13215 GNAT-style layout (this is the default)
13216
13217 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13218 Compact layout
13219
13220 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13221 Uncompact layout
13222
13223 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13224 @item ^-N^/NOTABS^
13225 All the VT characters are removed from the comment text. All the HT characters
13226 are expanded with the sequences of space characters to get to the next tab
13227 stops.
13228
13229 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13230 @item ^--no-separate-is^/NO_SEPARATE_IS^
13231 Do not place the keyword @code{is} on a separate line in a subprogram body in
13232 case if the spec occupies more then one line.
13233
13234 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13235 @item ^--separate-label^/SEPARATE_LABEL^
13236 Place statement label(s) on a separate line, with the following statement
13237 on the next line.
13238
13239 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13240 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13241 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13242 keyword @code{then} in IF statements on a separate line.
13243
13244 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13245 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13246 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13247 keyword @code{then} in IF statements on a separate line. This option is
13248 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13249
13250 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13251 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13252 Start each USE clause in a context clause from a separate line.
13253
13254 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13255 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13256 Use a separate line for a loop or block statement name, but do not use an extra
13257 indentation level for the statement itself.
13258
13259 @end table
13260
13261 @ifclear vms
13262 @noindent
13263 The @option{-c1} and @option{-c2} switches are incompatible.
13264 The @option{-c3} and @option{-c4} switches are compatible with each other and
13265 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13266 the other comment formatting switches.
13267
13268 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13269 @end ifclear
13270
13271 @ifset vms
13272 @noindent
13273 For the @option{/COMMENTS_LAYOUT} qualifier:
13274 @itemize @bullet
13275 @item
13276 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13277 @item
13278 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13279 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13280 @end itemize
13281
13282 @noindent
13283 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13284 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13285 @end ifset
13286
13287 @node General Text Layout Control
13288 @subsection General Text Layout Control
13289
13290 @noindent
13291 These switches allow control over line length and indentation.
13292
13293 @table @option
13294 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13295 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13296 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13297
13298 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13299 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13300 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13301
13302 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13303 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13304 Indentation level for continuation lines (relative to the line being
13305 continued), @var{nnn} from 1@dots{}9.
13306 The default
13307 value is one less then the (normal) indentation level, unless the
13308 indentation is set to 1 (in which case the default value for continuation
13309 line indentation is also 1)
13310 @end table
13311
13312 @node Other Formatting Options
13313 @subsection Other Formatting Options
13314
13315 @noindent
13316 These switches control the inclusion of missing end/exit labels, and
13317 the indentation level in @b{case} statements.
13318
13319 @table @option
13320 @item ^-e^/NO_MISSED_LABELS^
13321 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13322 Do not insert missing end/exit labels. An end label is the name of
13323 a construct that may optionally be repeated at the end of the
13324 construct's declaration;
13325 e.g., the names of packages, subprograms, and tasks.
13326 An exit label is the name of a loop that may appear as target
13327 of an exit statement within the loop.
13328 By default, @command{gnatpp} inserts these end/exit labels when
13329 they are absent from the original source. This option suppresses such
13330 insertion, so that the formatted source reflects the original.
13331
13332 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13333 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13334 Insert a Form Feed character after a pragma Page.
13335
13336 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13337 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13338 Do not use an additional indentation level for @b{case} alternatives
13339 and variants if there are @var{nnn} or more (the default
13340 value is 10).
13341 If @var{nnn} is 0, an additional indentation level is
13342 used for @b{case} alternatives and variants regardless of their number.
13343 @end table
13344
13345 @node Setting the Source Search Path
13346 @subsection Setting the Source Search Path
13347
13348 @noindent
13349 To define the search path for the input source file, @command{gnatpp}
13350 uses the same switches as the GNAT compiler, with the same effects.
13351
13352 @table @option
13353 @item ^-I^/SEARCH=^@var{dir}
13354 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13355 The same as the corresponding gcc switch
13356
13357 @item ^-I-^/NOCURRENT_DIRECTORY^
13358 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13359 The same as the corresponding gcc switch
13360
13361 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13362 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13363 The same as the corresponding gcc switch
13364
13365 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13366 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13367 The same as the corresponding gcc switch
13368
13369 @end table
13370
13371 @node Output File Control
13372 @subsection Output File Control
13373
13374 @noindent
13375 By default the output is sent to the file whose name is obtained by appending
13376 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13377 (if the file with this name already exists, it is unconditionally overwritten).
13378 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13379 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13380 as output file.
13381 The output may be redirected by the following switches:
13382
13383 @table @option
13384 @item ^-pipe^/STANDARD_OUTPUT^
13385 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13386 Send the output to @code{Standard_Output}
13387
13388 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13389 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13390 Write the output into @var{output_file}.
13391 If @var{output_file} already exists, @command{gnatpp} terminates without
13392 reading or processing the input file.
13393
13394 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13395 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13396 Write the output into @var{output_file}, overwriting the existing file
13397 (if one is present).
13398
13399 @item ^-r^/REPLACE^
13400 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13401 Replace the input source file with the reformatted output, and copy the
13402 original input source into the file whose name is obtained by appending the
13403 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13404 If a file with this name already exists, @command{gnatpp} terminates without
13405 reading or processing the input file.
13406
13407 @item ^-rf^/OVERRIDING_REPLACE^
13408 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13409 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13410 already exists, it is overwritten.
13411
13412 @item ^-rnb^/REPLACE_NO_BACKUP^
13413 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13414 Replace the input source file with the reformatted output without
13415 creating any backup copy of the input source.
13416
13417 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13418 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13419 Specifies the format of the reformatted output file. The @var{xxx}
13420 ^string specified with the switch^option^ may be either
13421 @itemize @bullet
13422 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13423 @item ``@option{^crlf^CRLF^}''
13424 the same as @option{^crlf^CRLF^}
13425 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13426 @item ``@option{^lf^LF^}''
13427 the same as @option{^unix^UNIX^}
13428 @end itemize
13429
13430 @item ^-W^/RESULT_ENCODING=^@var{e}
13431 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13432 Specify the wide character encoding method used to write the code in the
13433 result file
13434 @var{e} is one of the following:
13435
13436 @itemize @bullet
13437
13438 @item ^h^HEX^
13439 Hex encoding
13440
13441 @item ^u^UPPER^
13442 Upper half encoding
13443
13444 @item ^s^SHIFT_JIS^
13445 Shift/JIS encoding
13446
13447 @item ^e^EUC^
13448 EUC encoding
13449
13450 @item ^8^UTF8^
13451 UTF-8 encoding
13452
13453 @item ^b^BRACKETS^
13454 Brackets encoding (default value)
13455 @end itemize
13456
13457 @end table
13458
13459 @noindent
13460 Options @option{^-pipe^/STANDARD_OUTPUT^},
13461 @option{^-o^/OUTPUT^} and
13462 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13463 contains only one file to reformat.
13464 Option
13465 @option{^--eol^/END_OF_LINE^}
13466 and
13467 @option{^-W^/RESULT_ENCODING^}
13468 cannot be used together
13469 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13470
13471 @node Other gnatpp Switches
13472 @subsection Other @code{gnatpp} Switches
13473
13474 @noindent
13475 The additional @command{gnatpp} switches are defined in this subsection.
13476
13477 @table @option
13478 @item ^-files @var{filename}^/FILES=@var{filename}^
13479 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13480 Take the argument source files from the specified file. This file should be an
13481 ordinary text file containing file names separated by spaces or
13482 line breaks. You can use this switch more than once in the same call to
13483 @command{gnatpp}. You also can combine this switch with an explicit list of
13484 files.
13485
13486 @item ^-v^/VERBOSE^
13487 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13488 Verbose mode;
13489 @command{gnatpp} generates version information and then
13490 a trace of the actions it takes to produce or obtain the ASIS tree.
13491
13492 @item ^-w^/WARNINGS^
13493 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13494 Warning mode;
13495 @command{gnatpp} generates a warning whenever it cannot provide
13496 a required layout in the result source.
13497 @end table
13498
13499 @node Formatting Rules
13500 @section Formatting Rules
13501
13502 @noindent
13503 The following subsections show how @command{gnatpp} treats ``white space'',
13504 comments, program layout, and name casing.
13505 They provide the detailed descriptions of the switches shown above.
13506
13507 @menu
13508 * White Space and Empty Lines::
13509 * Formatting Comments::
13510 * Construct Layout::
13511 * Name Casing::
13512 @end menu
13513
13514 @node White Space and Empty Lines
13515 @subsection White Space and Empty Lines
13516
13517 @noindent
13518 @command{gnatpp} does not have an option to control space characters.
13519 It will add or remove spaces according to the style illustrated by the
13520 examples in the @cite{Ada Reference Manual}.
13521
13522 The only format effectors
13523 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13524 that will appear in the output file are platform-specific line breaks,
13525 and also format effectors within (but not at the end of) comments.
13526 In particular, each horizontal tab character that is not inside
13527 a comment will be treated as a space and thus will appear in the
13528 output file as zero or more spaces depending on
13529 the reformatting of the line in which it appears.
13530 The only exception is a Form Feed character, which is inserted after a
13531 pragma @code{Page} when @option{-ff} is set.
13532
13533 The output file will contain no lines with trailing ``white space'' (spaces,
13534 format effectors).
13535
13536 Empty lines in the original source are preserved
13537 only if they separate declarations or statements.
13538 In such contexts, a
13539 sequence of two or more empty lines is replaced by exactly one empty line.
13540 Note that a blank line will be removed if it separates two ``comment blocks''
13541 (a comment block is a sequence of whole-line comments).
13542 In order to preserve a visual separation between comment blocks, use an
13543 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13544 Likewise, if for some reason you wish to have a sequence of empty lines,
13545 use a sequence of empty comments instead.
13546
13547 @node Formatting Comments
13548 @subsection Formatting Comments
13549
13550 @noindent
13551 Comments in Ada code are of two kinds:
13552 @itemize @bullet
13553 @item
13554 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13555 ``white space'') on a line
13556
13557 @item
13558 an @emph{end-of-line comment}, which follows some other Ada lexical element
13559 on the same line.
13560 @end itemize
13561
13562 @noindent
13563 The indentation of a whole-line comment is that of either
13564 the preceding or following line in
13565 the formatted source, depending on switch settings as will be described below.
13566
13567 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13568 between the end of the preceding Ada lexical element and the beginning
13569 of the comment as appear in the original source,
13570 unless either the comment has to be split to
13571 satisfy the line length limitation, or else the next line contains a
13572 whole line comment that is considered a continuation of this end-of-line
13573 comment (because it starts at the same position).
13574 In the latter two
13575 cases, the start of the end-of-line comment is moved right to the nearest
13576 multiple of the indentation level.
13577 This may result in a ``line overflow'' (the right-shifted comment extending
13578 beyond the maximum line length), in which case the comment is split as
13579 described below.
13580
13581 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13582 (GNAT-style comment line indentation)
13583 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13584 (reference-manual comment line indentation).
13585 With reference-manual style, a whole-line comment is indented as if it
13586 were a declaration or statement at the same place
13587 (i.e., according to the indentation of the preceding line(s)).
13588 With GNAT style, a whole-line comment that is immediately followed by an
13589 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13590 word @b{begin}, is indented based on the construct that follows it.
13591
13592 For example:
13593 @smallexample @c ada
13594 @cartouche
13595 if A then
13596     null;
13597        -- some comment
13598 else
13599    null;
13600 end if;
13601 @end cartouche
13602 @end smallexample
13603
13604 @noindent
13605 Reference-manual indentation produces:
13606
13607 @smallexample @c ada
13608 @cartouche
13609 if A then
13610    null;
13611    --  some comment
13612 else
13613    null;
13614 end if;
13615 @end cartouche
13616 @end smallexample
13617
13618 @noindent
13619 while GNAT-style indentation produces:
13620
13621 @smallexample @c ada
13622 @cartouche
13623 if A then
13624    null;
13625 --  some comment
13626 else
13627    null;
13628 end if;
13629 @end cartouche
13630 @end smallexample
13631
13632 @noindent
13633 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13634 (GNAT style comment beginning) has the following
13635 effect:
13636
13637 @itemize @bullet
13638 @item
13639 For each whole-line comment that does not end with two hyphens,
13640 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13641 to ensure that there are at least two spaces between these hyphens and the
13642 first non-blank character of the comment.
13643 @end itemize
13644
13645 @noindent
13646 For an end-of-line comment, if in the original source the next line is a
13647 whole-line comment that starts at the same position
13648 as the end-of-line comment,
13649 then the whole-line comment (and all whole-line comments
13650 that follow it and that start at the same position)
13651 will start at this position in the output file.
13652
13653 @noindent
13654 That is, if in the original source we have:
13655
13656 @smallexample @c ada
13657 @cartouche
13658 begin
13659 A := B + C;            --  B must be in the range Low1..High1
13660                        --  C must be in the range Low2..High2
13661              --B+C will be in the range Low1+Low2..High1+High2
13662 X := X + 1;
13663 @end cartouche
13664 @end smallexample
13665
13666 @noindent
13667 Then in the formatted source we get
13668
13669 @smallexample @c ada
13670 @cartouche
13671 begin
13672    A := B + C;            --  B must be in the range Low1..High1
13673                           --  C must be in the range Low2..High2
13674    --  B+C will be in the range Low1+Low2..High1+High2
13675    X := X + 1;
13676 @end cartouche
13677 @end smallexample
13678
13679 @noindent
13680 A comment that exceeds the line length limit will be split.
13681 Unless switch
13682 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13683 the line belongs to a reformattable block, splitting the line generates a
13684 @command{gnatpp} warning.
13685 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13686 comments may be reformatted in typical
13687 word processor style (that is, moving words between lines and putting as
13688 many words in a line as possible).
13689
13690 @noindent
13691 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13692 that has a special format (that is, a character that is neither a letter nor digit
13693 not white space nor line break immediately following the leading @code{--} of
13694 the comment) should be without any change moved from the argument source
13695 into reformatted source. This switch allows to preserve comments that are used
13696 as a special marks in the code (e.g.@: SPARK annotation).
13697
13698 @node Construct Layout
13699 @subsection Construct Layout
13700
13701 @noindent
13702 In several cases the suggested layout in the Ada Reference Manual includes
13703 an extra level of indentation that many programmers prefer to avoid. The
13704 affected cases include:
13705
13706 @itemize @bullet
13707
13708 @item Record type declaration (RM 3.8)
13709
13710 @item Record representation clause (RM 13.5.1)
13711
13712 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13713
13714 @item Block statement in case if a block has a statement identifier (RM 5.6)
13715 @end itemize
13716
13717 @noindent
13718 In compact mode (when GNAT style layout or compact layout is set),
13719 the pretty printer uses one level of indentation instead
13720 of two. This is achieved in the record definition and record representation
13721 clause cases by putting the @code{record} keyword on the same line as the
13722 start of the declaration or representation clause, and in the block and loop
13723 case by putting the block or loop header on the same line as the statement
13724 identifier.
13725
13726 @noindent
13727 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13728 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13729 layout on the one hand, and uncompact layout
13730 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13731 can be illustrated by the following examples:
13732
13733 @iftex
13734 @cartouche
13735 @multitable @columnfractions .5 .5
13736 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13737
13738 @item
13739 @smallexample @c ada
13740 type q is record
13741    a : integer;
13742    b : integer;
13743 end record;
13744 @end smallexample
13745 @tab
13746 @smallexample @c ada
13747 type q is
13748    record
13749       a : integer;
13750       b : integer;
13751    end record;
13752 @end smallexample
13753
13754 @item
13755 @smallexample @c ada
13756 for q use record
13757    a at 0 range  0 .. 31;
13758    b at 4 range  0 .. 31;
13759 end record;
13760 @end smallexample
13761 @tab
13762 @smallexample @c ada
13763 for q use
13764    record
13765       a at 0 range  0 .. 31;
13766       b at 4 range  0 .. 31;
13767    end record;
13768 @end smallexample
13769
13770 @item
13771 @smallexample @c ada
13772 Block : declare
13773    A : Integer := 3;
13774 begin
13775    Proc (A, A);
13776 end Block;
13777 @end smallexample
13778 @tab
13779 @smallexample @c ada
13780 Block :
13781    declare
13782       A : Integer := 3;
13783    begin
13784       Proc (A, A);
13785    end Block;
13786 @end smallexample
13787
13788 @item
13789 @smallexample @c ada
13790 Clear : for J in 1 .. 10 loop
13791    A (J) := 0;
13792 end loop Clear;
13793 @end smallexample
13794 @tab
13795 @smallexample @c ada
13796 Clear :
13797    for J in 1 .. 10 loop
13798       A (J) := 0;
13799    end loop Clear;
13800 @end smallexample
13801 @end multitable
13802 @end cartouche
13803 @end iftex
13804
13805 @ifnottex
13806 @smallexample
13807 @cartouche
13808 GNAT style, compact layout              Uncompact layout
13809
13810 type q is record                        type q is
13811    a : integer;                            record
13812    b : integer;                               a : integer;
13813 end record;                                   b : integer;
13814                                            end record;
13815
13816 for q use record                        for q use
13817    a at 0 range  0 .. 31;                  record
13818    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13819 end record;                                   b at 4 range  0 .. 31;
13820                                            end record;
13821
13822 Block : declare                         Block :
13823    A : Integer := 3;                       declare
13824 begin                                         A : Integer := 3;
13825    Proc (A, A);                            begin
13826 end Block;                                    Proc (A, A);
13827                                            end Block;
13828
13829 Clear : for J in 1 .. 10 loop           Clear :
13830    A (J) := 0;                             for J in 1 .. 10 loop
13831 end loop Clear;                               A (J) := 0;
13832                                            end loop Clear;
13833 @end cartouche
13834 @end smallexample
13835 @end ifnottex
13836
13837 @noindent
13838 A further difference between GNAT style layout and compact layout is that
13839 GNAT style layout inserts empty lines as separation for
13840 compound statements, return statements and bodies.
13841
13842 Note that the layout specified by
13843 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13844 for named block and loop statements overrides the layout defined by these
13845 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13846 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13847 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13848
13849 @node Name Casing
13850 @subsection Name Casing
13851
13852 @noindent
13853 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13854 the same casing as the corresponding defining identifier.
13855
13856 You control the casing for defining occurrences via the
13857 @option{^-n^/NAME_CASING^} switch.
13858 @ifclear vms
13859 With @option{-nD} (``as declared'', which is the default),
13860 @end ifclear
13861 @ifset vms
13862 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13863 @end ifset
13864 defining occurrences appear exactly as in the source file
13865 where they are declared.
13866 The other ^values for this switch^options for this qualifier^ ---
13867 @option{^-nU^UPPER_CASE^},
13868 @option{^-nL^LOWER_CASE^},
13869 @option{^-nM^MIXED_CASE^} ---
13870 result in
13871 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13872 If @command{gnatpp} changes the casing of a defining
13873 occurrence, it analogously changes the casing of all the
13874 usage occurrences of this name.
13875
13876 If the defining occurrence of a name is not in the source compilation unit
13877 currently being processed by @command{gnatpp}, the casing of each reference to
13878 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13879 switch (subject to the dictionary file mechanism described below).
13880 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13881 had affected the
13882 casing for the defining occurrence of the name.
13883
13884 Some names may need to be spelled with casing conventions that are not
13885 covered by the upper-, lower-, and mixed-case transformations.
13886 You can arrange correct casing by placing such names in a
13887 @emph{dictionary file},
13888 and then supplying a @option{^-D^/DICTIONARY^} switch.
13889 The casing of names from dictionary files overrides
13890 any @option{^-n^/NAME_CASING^} switch.
13891
13892 To handle the casing of Ada predefined names and the names from GNAT libraries,
13893 @command{gnatpp} assumes a default dictionary file.
13894 The name of each predefined entity is spelled with the same casing as is used
13895 for the entity in the @cite{Ada Reference Manual}.
13896 The name of each entity in the GNAT libraries is spelled with the same casing
13897 as is used in the declaration of that entity.
13898
13899 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13900 default dictionary file.
13901 Instead, the casing for predefined and GNAT-defined names will be established
13902 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13903 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13904 will appear as just shown,
13905 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13906 To ensure that even such names are rendered in uppercase,
13907 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13908 (or else, less conveniently, place these names in upper case in a dictionary
13909 file).
13910
13911 A dictionary file is
13912 a plain text file; each line in this file can be either a blank line
13913 (containing only space characters and ASCII.HT characters), an Ada comment
13914 line, or the specification of exactly one @emph{casing schema}.
13915
13916 A casing schema is a string that has the following syntax:
13917
13918 @smallexample
13919 @cartouche
13920   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13921
13922   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13923 @end cartouche
13924 @end smallexample
13925
13926 @noindent
13927 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13928 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13929
13930 The casing schema string can be followed by white space and/or an Ada-style
13931 comment; any amount of white space is allowed before the string.
13932
13933 If a dictionary file is passed as
13934 @ifclear vms
13935 the value of a @option{-D@var{file}} switch
13936 @end ifclear
13937 @ifset vms
13938 an option to the @option{/DICTIONARY} qualifier
13939 @end ifset
13940 then for every
13941 simple name and every identifier, @command{gnatpp} checks if the dictionary
13942 defines the casing for the name or for some of its parts (the term ``subword''
13943 is used below to denote the part of a name which is delimited by ``_'' or by
13944 the beginning or end of the word and which does not contain any ``_'' inside):
13945
13946 @itemize @bullet
13947 @item
13948 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13949 the casing defined by the dictionary; no subwords are checked for this word
13950
13951 @item
13952 for every subword @command{gnatpp} checks if the dictionary contains the
13953 corresponding string of the form @code{*@var{simple_identifier}*},
13954 and if it does, the casing of this @var{simple_identifier} is used
13955 for this subword
13956
13957 @item
13958 if the whole name does not contain any ``_'' inside, and if for this name
13959 the dictionary contains two entries - one of the form @var{identifier},
13960 and another - of the form *@var{simple_identifier}*, then the first one
13961 is applied to define the casing of this name
13962
13963 @item
13964 if more than one dictionary file is passed as @command{gnatpp} switches, each
13965 dictionary adds new casing exceptions and overrides all the existing casing
13966 exceptions set by the previous dictionaries
13967
13968 @item
13969 when @command{gnatpp} checks if the word or subword is in the dictionary,
13970 this check is not case sensitive
13971 @end itemize
13972
13973 @noindent
13974 For example, suppose we have the following source to reformat:
13975
13976 @smallexample @c ada
13977 @cartouche
13978 procedure test is
13979    name1 : integer := 1;
13980    name4_name3_name2 : integer := 2;
13981    name2_name3_name4 : Boolean;
13982    name1_var : Float;
13983 begin
13984    name2_name3_name4 := name4_name3_name2 > name1;
13985 end;
13986 @end cartouche
13987 @end smallexample
13988
13989 @noindent
13990 And suppose we have two dictionaries:
13991
13992 @smallexample
13993 @cartouche
13994 @i{dict1:}
13995    NAME1
13996    *NaMe3*
13997    *Name1*
13998 @end cartouche
13999
14000 @cartouche
14001 @i{dict2:}
14002   *NAME3*
14003 @end cartouche
14004 @end smallexample
14005
14006 @noindent
14007 If @command{gnatpp} is called with the following switches:
14008
14009 @smallexample
14010 @ifclear vms
14011 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14012 @end ifclear
14013 @ifset vms
14014 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14015 @end ifset
14016 @end smallexample
14017
14018 @noindent
14019 then we will get the following name casing in the @command{gnatpp} output:
14020
14021 @smallexample @c ada
14022 @cartouche
14023 procedure Test is
14024    NAME1             : Integer := 1;
14025    Name4_NAME3_Name2 : Integer := 2;
14026    Name2_NAME3_Name4 : Boolean;
14027    Name1_Var         : Float;
14028 begin
14029    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14030 end Test;
14031 @end cartouche
14032 @end smallexample
14033
14034 @c *********************************
14035 @node The GNAT Metric Tool gnatmetric
14036 @chapter The GNAT Metric Tool @command{gnatmetric}
14037 @findex gnatmetric
14038 @cindex Metric tool
14039
14040 @noindent
14041 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
14042 for computing various program metrics.
14043 It takes an Ada source file as input and generates a file containing the
14044 metrics data as output. Various switches control which
14045 metrics are computed and output.
14046
14047 @command{gnatmetric} generates and uses the ASIS
14048 tree for the input source and thus requires the input to be syntactically and
14049 semantically legal.
14050 If this condition is not met, @command{gnatmetric} will generate
14051 an error message; no metric information for this file will be
14052 computed and reported.
14053
14054 If the compilation unit contained in the input source depends semantically
14055 upon units in files located outside the current directory, you have to provide
14056 the source search path when invoking @command{gnatmetric}.
14057 If it depends semantically upon units that are contained
14058 in files with names that do not follow the GNAT file naming rules, you have to
14059 provide the configuration file describing the corresponding naming scheme (see
14060 the description of the @command{gnatmetric} switches below.)
14061 Alternatively, you may use a project file and invoke @command{gnatmetric}
14062 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14063
14064 The @command{gnatmetric} command has the form
14065
14066 @smallexample
14067 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14068 @c Expanding @ovar macro inline (explanation in macro def comments)
14069 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
14070 @end smallexample
14071
14072 @noindent
14073 where
14074 @itemize @bullet
14075 @item
14076 @var{switches} specify the metrics to compute and define the destination for
14077 the output
14078
14079 @item
14080 Each @var{filename} is the name (including the extension) of a source
14081 file to process. ``Wildcards'' are allowed, and
14082 the file name may contain path information.
14083 If no @var{filename} is supplied, then the @var{switches} list must contain
14084 at least one
14085 @option{-files} switch (@pxref{Other gnatmetric Switches}).
14086 Including both a @option{-files} switch and one or more
14087 @var{filename} arguments is permitted.
14088
14089 @item
14090 @samp{@var{gcc_switches}} is a list of switches for
14091 @command{gcc}. They will be passed on to all compiler invocations made by
14092 @command{gnatmetric} to generate the ASIS trees. Here you can provide
14093 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14094 and use the @option{-gnatec} switch to set the configuration file,
14095 use the @option{-gnat05} switch if sources should be compiled in
14096 Ada 2005 mode etc.
14097 @end itemize
14098
14099 @menu
14100 * Switches for gnatmetric::
14101 @end menu
14102
14103 @node Switches for gnatmetric
14104 @section Switches for @command{gnatmetric}
14105
14106 @noindent
14107 The following subsections describe the various switches accepted by
14108 @command{gnatmetric}, organized by category.
14109
14110 @menu
14111 * Output Files Control::
14112 * Disable Metrics For Local Units::
14113 * Specifying a set of metrics to compute::
14114 * Other gnatmetric Switches::
14115 * Generate project-wide metrics::
14116 @end menu
14117
14118 @node Output Files Control
14119 @subsection Output File Control
14120 @cindex Output file control in @command{gnatmetric}
14121
14122 @noindent
14123 @command{gnatmetric} has two output formats. It can generate a
14124 textual (human-readable) form, and also XML. By default only textual
14125 output is generated.
14126
14127 When generating the output in textual form, @command{gnatmetric} creates
14128 for each Ada source file a corresponding text file
14129 containing the computed metrics, except for the case when the set of metrics
14130 specified by gnatmetric parameters consists only of metrics that are computed
14131 for the whole set of analyzed sources, but not for each Ada source.
14132 By default, this file is placed in the same directory as where the source
14133 file is located, and its name is obtained
14134 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14135 input file.
14136
14137 All the output information generated in XML format is placed in a single
14138 file. By default this file is placed in the current directory and has the
14139 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14140
14141 Some of the computed metrics are summed over the units passed to
14142 @command{gnatmetric}; for example, the total number of lines of code.
14143 By default this information is sent to @file{stdout}, but a file
14144 can be specified with the @option{-og} switch.
14145
14146 The following switches control the @command{gnatmetric} output:
14147
14148 @table @option
14149 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14150 @item ^-x^/XML^
14151 Generate the XML output
14152
14153 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14154 @item ^-xs^/XSD^
14155 Generate the XML output and the XML schema file that describes the structure
14156 of the XML metric report, this schema is assigned to the XML file. The schema
14157 file has the same name as the XML output file with @file{.xml} suffix replaced
14158 with @file{.xsd}
14159
14160 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14161 @item ^-nt^/NO_TEXT^
14162 Do not generate the output in text form (implies @option{^-x^/XML^})
14163
14164 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14165 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14166 Put text files with detailed metrics into @var{output_dir}
14167
14168 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14169 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14170 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14171 in the name of the output file.
14172
14173 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14174 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14175 Put global metrics into @var{file_name}
14176
14177 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14178 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14179 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14180
14181 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14182 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14183 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14184 output includes the name(s) of the Ada source file(s) from which the metrics
14185 are computed.  By default each name includes the absolute path. The
14186 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14187 to exclude all directory information from the file names that are output.)
14188
14189 @end table
14190
14191 @node Disable Metrics For Local Units
14192 @subsection Disable Metrics For Local Units
14193 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14194
14195 @noindent
14196 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14197 one compilation
14198 unit per one source file. It computes line metrics for the whole source
14199 file, and it also computes syntax
14200 and complexity metrics for the file's outermost unit.
14201
14202 By default, @command{gnatmetric} will also compute all metrics for certain
14203 kinds of locally declared program units:
14204
14205 @itemize @bullet
14206 @item
14207 subprogram (and generic subprogram) bodies;
14208
14209 @item
14210 package (and generic package) specs and bodies;
14211
14212 @item
14213 task object and type specifications and bodies;
14214
14215 @item
14216 protected object and type specifications and bodies.
14217 @end itemize
14218
14219 @noindent
14220 These kinds of entities will be referred to as
14221 @emph{eligible local program units}, or simply @emph{eligible local units},
14222 @cindex Eligible local unit (for @command{gnatmetric})
14223 in the discussion below.
14224
14225 Note that a subprogram declaration, generic instantiation,
14226 or renaming declaration only receives metrics
14227 computation when it appear as the outermost entity
14228 in a source file.
14229
14230 Suppression of metrics computation for eligible local units can be
14231 obtained via the following switch:
14232
14233 @table @option
14234 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14235 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14236 Do not compute detailed metrics for eligible local program units
14237
14238 @end table
14239
14240 @node Specifying a set of metrics to compute
14241 @subsection Specifying a set of metrics to compute
14242
14243 @noindent
14244 By default all the metrics are computed and reported. The switches
14245 described in this subsection allow you to control, on an individual
14246 basis, whether metrics are computed and
14247 reported. If at least one positive metric
14248 switch is specified (that is, a switch that defines that a given
14249 metric or set of metrics is to be computed), then only
14250 explicitly specified metrics are reported.
14251
14252 @menu
14253 * Line Metrics Control::
14254 * Syntax Metrics Control::
14255 * Complexity Metrics Control::
14256 * Coupling Metrics Control::
14257 @end menu
14258
14259 @node Line Metrics Control
14260 @subsubsection Line Metrics Control
14261 @cindex Line metrics control in @command{gnatmetric}
14262
14263 @noindent
14264 For any (legal) source file, and for each of its
14265 eligible local program units, @command{gnatmetric} computes the following
14266 metrics:
14267
14268 @itemize @bullet
14269 @item
14270 the total number of lines;
14271
14272 @item
14273 the total number of code lines (i.e., non-blank lines that are not comments)
14274
14275 @item
14276 the number of comment lines
14277
14278 @item
14279 the number of code lines containing end-of-line comments;
14280
14281 @item
14282 the comment percentage: the ratio between the number of lines that contain
14283 comments and the number of all non-blank lines, expressed as a percentage;
14284
14285 @item
14286 the number of empty lines and lines containing only space characters and/or
14287 format effectors (blank lines)
14288
14289 @item
14290 the average number of code lines in subprogram bodies, task bodies, entry
14291 bodies and statement sequences in package bodies (this metric is only computed
14292 across the whole set of the analyzed units)
14293
14294 @end itemize
14295
14296 @noindent
14297 @command{gnatmetric} sums the values of the line metrics for all the
14298 files being processed and then generates the cumulative results. The tool
14299 also computes for all the files being processed the average number of code
14300 lines in bodies.
14301
14302 You can use the following switches to select the specific line metrics
14303 to be computed and reported.
14304
14305 @table @option
14306 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14307
14308 @ifclear vms
14309 @cindex @option{--no-lines@var{x}}
14310 @end ifclear
14311
14312 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14313 Report all the line metrics
14314
14315 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14316 Do not report any of line metrics
14317
14318 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14319 Report the number of all lines
14320
14321 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14322 Do not report the number of all lines
14323
14324 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14325 Report the number of code lines
14326
14327 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14328 Do not report the number of code lines
14329
14330 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14331 Report the number of comment lines
14332
14333 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14334 Do not report the number of comment lines
14335
14336 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14337 Report the number of code lines containing
14338 end-of-line comments
14339
14340 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14341 Do not report the number of code lines containing
14342 end-of-line comments
14343
14344 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14345 Report the comment percentage in the program text
14346
14347 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14348 Do not report the comment percentage in the program text
14349
14350 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14351 Report the number of blank lines
14352
14353 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14354 Do not report the number of blank lines
14355
14356 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14357 Report the average number of code lines in subprogram bodies, task bodies,
14358 entry bodies and statement sequences in package bodies. The metric is computed
14359 and reported for the whole set of processed Ada sources only.
14360
14361 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14362 Do not report the average number of code lines in subprogram bodies,
14363 task bodies, entry bodies and statement sequences in package bodies.
14364
14365 @end table
14366
14367 @node Syntax Metrics Control
14368 @subsubsection Syntax Metrics Control
14369 @cindex Syntax metrics control in @command{gnatmetric}
14370
14371 @noindent
14372 @command{gnatmetric} computes various syntactic metrics for the
14373 outermost unit and for each eligible local unit:
14374
14375 @table @emph
14376 @item LSLOC (``Logical Source Lines Of Code'')
14377 The total number of declarations and the total number of statements. Note
14378 that the definition of declarations is the one given in the reference
14379 manual:
14380
14381 @noindent
14382 ``Each of the following is defined to be a declaration: any basic_declaration;
14383 an enumeration_literal_specification; a discriminant_specification;
14384 a component_declaration; a loop_parameter_specification; a
14385 parameter_specification; a subprogram_body; an entry_declaration;
14386 an entry_index_specification; a choice_parameter_specification;
14387 a generic_formal_parameter_declaration.''
14388
14389 This means for example that each enumeration literal adds one to the count,
14390 as well as each subprogram parameter.
14391
14392 Thus the results from this metric will be significantly greater than might
14393 be expected from a naive view of counting semicolons.
14394
14395 @item Maximal static nesting level of inner program units
14396 According to
14397 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14398 package, a task unit, a protected unit, a
14399 protected entry, a generic unit, or an explicitly declared subprogram other
14400 than an enumeration literal.''
14401
14402 @item Maximal nesting level of composite syntactic constructs
14403 This corresponds to the notion of the
14404 maximum nesting level in the GNAT built-in style checks
14405 (@pxref{Style Checking})
14406 @end table
14407
14408 @noindent
14409 For the outermost unit in the file, @command{gnatmetric} additionally computes
14410 the following metrics:
14411
14412 @table @emph
14413 @item Public subprograms
14414 This metric is computed for package specs. It is the
14415 number of subprograms and generic subprograms declared in the visible
14416 part (including the visible part of nested packages, protected objects, and
14417 protected types).
14418
14419 @item All subprograms
14420 This metric is computed for bodies and subunits. The
14421 metric is equal to a total number of subprogram bodies in the compilation
14422 unit.
14423 Neither generic instantiations nor renamings-as-a-body nor body stubs
14424 are counted. Any subprogram body is counted, independently of its nesting
14425 level and enclosing constructs. Generic bodies and bodies of protected
14426 subprograms are counted in the same way as ``usual'' subprogram bodies.
14427
14428 @item Public types
14429 This metric is computed for package specs and
14430 generic package declarations. It is the total number of types
14431 that can be referenced from outside this compilation unit, plus the
14432 number of types from all the visible parts of all the visible generic
14433 packages. Generic formal types are not counted.  Only types, not subtypes,
14434 are included.
14435
14436 @noindent
14437 Along with the total number of public types, the following
14438 types are counted and reported separately:
14439
14440 @itemize @bullet
14441 @item
14442 Abstract types
14443
14444 @item
14445 Root tagged types (abstract, non-abstract, private, non-private). Type
14446 extensions are @emph{not} counted
14447
14448 @item
14449 Private types (including private extensions)
14450
14451 @item
14452 Task types
14453
14454 @item
14455 Protected types
14456
14457 @end itemize
14458
14459 @item All types
14460 This metric is computed for any compilation unit. It is equal to the total
14461 number of the declarations of different types given in the compilation unit.
14462 The private and the corresponding full type declaration are counted as one
14463 type declaration. Incomplete type declarations and generic formal types
14464 are not counted.
14465 No distinction is made among different kinds of types (abstract,
14466 private etc.); the total number of types is computed and reported.
14467
14468 @end table
14469
14470 @noindent
14471 By default, all the syntax metrics are computed and reported. You can use the
14472 following switches to select specific syntax metrics.
14473
14474 @table @option
14475
14476 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14477
14478 @ifclear vms
14479 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14480 @end ifclear
14481
14482 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14483 Report all the syntax metrics
14484
14485 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14486 Do not report any of syntax metrics
14487
14488 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14489 Report the total number of declarations
14490
14491 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14492 Do not report the total number of declarations
14493
14494 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14495 Report the total number of statements
14496
14497 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14498 Do not report the total number of statements
14499
14500 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14501 Report the number of public subprograms in a compilation unit
14502
14503 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14504 Do not report the number of public subprograms in a compilation unit
14505
14506 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14507 Report the number of all the subprograms in a compilation unit
14508
14509 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14510 Do not report the number of all the subprograms in a compilation unit
14511
14512 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14513 Report the number of public types in a compilation unit
14514
14515 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14516 Do not report the number of public types in a compilation unit
14517
14518 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14519 Report the number of all the types in a compilation unit
14520
14521 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14522 Do not report the number of all the types in a compilation unit
14523
14524 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14525 Report the maximal program unit nesting level
14526
14527 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14528 Do not report the maximal program unit nesting level
14529
14530 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14531 Report the maximal construct nesting level
14532
14533 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14534 Do not report the maximal construct nesting level
14535
14536 @end table
14537
14538 @node Complexity Metrics Control
14539 @subsubsection Complexity Metrics Control
14540 @cindex Complexity metrics control in @command{gnatmetric}
14541
14542 @noindent
14543 For a program unit that is an executable body (a subprogram body (including
14544 generic bodies), task body, entry body or a package body containing
14545 its own statement sequence) @command{gnatmetric} computes the following
14546 complexity metrics:
14547
14548 @itemize @bullet
14549 @item
14550 McCabe cyclomatic complexity;
14551
14552 @item
14553 McCabe essential complexity;
14554
14555 @item
14556 maximal loop nesting level;
14557
14558 @item
14559 extra exit points (for subprograms);
14560 @end itemize
14561
14562 @noindent
14563 The McCabe cyclomatic complexity metric is defined
14564 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14565
14566 According to McCabe, both control statements and short-circuit control forms
14567 should be taken into account when computing cyclomatic complexity. For each
14568 body, we compute three metric values:
14569
14570 @itemize @bullet
14571 @item
14572 the complexity introduced by control
14573 statements only, without taking into account short-circuit forms,
14574
14575 @item
14576 the complexity introduced by short-circuit control forms only, and
14577
14578 @item
14579 the total
14580 cyclomatic complexity, which is the sum of these two values.
14581 @end itemize
14582
14583 @noindent
14584
14585 The origin of cyclomatic complexity metric is the need to estimate the number
14586 of independent paths in the control flow graph that in turn gives the number
14587 of tests needed to satisfy paths coverage testing completeness criterion.
14588 Considered from the testing point of view, a static Ada @code{loop} (that is,
14589 the @code{loop} statement having static subtype in loop parameter
14590 specification) does not add to cyclomatic complexity. By providing
14591 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14592 may specify that such loops should not be counted when computing the
14593 cyclomatic complexity metric
14594
14595 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14596 counted for the code that is reduced by excluding all the pure structural Ada
14597 control statements. An compound statement is considered as a non-structural
14598 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14599 or if it contains a @code{goto} statement that transfers the control outside
14600 the operator. A selective accept statement with @code{terminate} alternative
14601 is considered as non-structural statement. When computing this metric,
14602 @code{exit} statements are treated in the same way as @code{goto}
14603 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14604
14605 The Ada essential complexity metric defined here is intended to quantify
14606 the extent to which the software is unstructured. It is adapted from
14607 the McCabe essential complexity metric defined in
14608 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14609 suitable for typical Ada usage. For example, short circuit forms
14610 are not penalized as unstructured in the Ada essential complexity metric.
14611
14612 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14613 the code in the exception handlers and in all the nested program units.
14614
14615 By default, all the complexity metrics are computed and reported.
14616 For more fine-grained control you can use
14617 the following switches:
14618
14619 @table @option
14620 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14621
14622 @ifclear vms
14623 @cindex @option{--no-complexity@var{x}}
14624 @end ifclear
14625
14626 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14627 Report all the complexity metrics
14628
14629 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14630 Do not report any of complexity metrics
14631
14632 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14633 Report the McCabe Cyclomatic Complexity
14634
14635 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14636 Do not report the McCabe Cyclomatic Complexity
14637
14638 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14639 Report the Essential Complexity
14640
14641 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14642 Do not report the Essential Complexity
14643
14644 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14645 Report maximal loop nesting level
14646
14647 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14648 Do not report maximal loop nesting level
14649
14650 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14651 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14652 task bodies, entry bodies and statement sequences in package bodies.
14653 The metric is computed and reported for whole set of processed Ada sources
14654 only.
14655
14656 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14657 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14658 bodies, task bodies, entry bodies and statement sequences in package bodies
14659
14660 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14661 @item ^-ne^/NO_EXITS_AS_GOTOS^
14662 Do not consider @code{exit} statements as @code{goto}s when
14663 computing Essential Complexity
14664
14665 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14666 @item ^--no-static-loop^/NO_STATIC_LOOP^
14667 Do not consider static loops when computing cyclomatic complexity
14668
14669 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14670 Report the extra exit points for subprogram bodies. As an exit point, this
14671 metric counts @code{return} statements and raise statements in case when the
14672 raised exception is not handled in the same body. In case of a function this
14673 metric subtracts 1 from the number of exit points, because a function body
14674 must contain at least one @code{return} statement.
14675
14676 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14677 Do not report the extra exit points for subprogram bodies
14678 @end table
14679
14680
14681 @node Coupling Metrics Control
14682 @subsubsection Coupling Metrics Control
14683 @cindex Coupling metrics control in @command{gnatmetric}
14684
14685 @noindent
14686 @cindex Coupling metrics (in in @command{gnatmetric})
14687 Coupling metrics measure the dependencies between a given entity and other
14688 entities the program consists of. The goal of these metrics is to estimate the
14689 stability of the whole program considered as the collection of entities
14690 (modules, classes etc.).
14691
14692 Gnatmetric computes the following coupling metrics:
14693
14694 @itemize @bullet
14695
14696 @item
14697 @emph{object-oriented coupling} - for classes in traditional object-oriented
14698 sense;
14699
14700 @item
14701 @emph{unit coupling} - for all the program units making up a program;
14702
14703 @item
14704 @emph{control coupling} - this metric counts dependencies between a unit and
14705 only those units that define subprograms;
14706 @end itemize
14707
14708 @noindent
14709 Two kinds of coupling metrics are computed:
14710
14711 @table @asis
14712 @item fan-out coupling (efferent coupling)
14713 @cindex fan-out coupling
14714 @cindex efferent coupling
14715 the number of entities the given entity depends upon. It
14716 estimates in what extent the given entity depends on the changes in
14717 ``external world''
14718
14719 @item fan-in coupling (afferent coupling)
14720 @cindex fan-in coupling
14721 @cindex afferent coupling
14722 the number of entities that depend on a given entity.
14723 It estimates in what extent the ``external world'' depends on the changes in a
14724 given entity
14725 @end table
14726
14727 @noindent
14728
14729 Object-oriented coupling metrics are metrics that measure the dependencies
14730 between a given class (or a group of classes) and the other classes in the
14731 program. In this subsection the term ``class'' is used in its traditional
14732 object-oriented programming sense (an instantiable module that contains data
14733 and/or method members). A @emph{category} (of classes) is a group of closely
14734 related classes that are reused and/or modified together.
14735
14736 A class @code{K}'s fan-out coupling is the number of classes
14737 that @code{K} depends upon.
14738 A category's fan-out coupling is the number of classes outside the
14739 category that the classes inside the category depend upon.
14740
14741 A class @code{K}'s fan-in coupling is the number of classes
14742 that depend upon @code{K}.
14743 A category's fan-in coupling is the number of classes outside the
14744 category that depend on classes belonging to the category.
14745
14746 Ada's implementation of the object-oriented paradigm does not use the
14747 traditional class notion, so the definition of the coupling
14748 metrics for Ada maps the class and class category notions
14749 onto Ada constructs.
14750
14751 For the coupling metrics, several kinds of modules -- a library package,
14752 a library generic package, and a library generic package instantiation --
14753 that define a tagged type or an interface type are
14754 considered to be a class. A category consists of a library package (or
14755 a library generic package) that defines a tagged or an interface type,
14756 together with all its descendant (generic) packages that define tagged
14757 or interface types. That is a
14758 category is an Ada hierarchy of library-level program units. So class coupling
14759 in case of Ada is called as tagged coupling, and category coupling - as
14760 hierarchy coupling.
14761
14762 For any package counted as a class, its body and subunits (if any) are
14763 considered together with its spec when counting the dependencies, and coupling
14764 metrics are reported for spec units only. For dependencies between classes,
14765 the Ada semantic dependencies are considered. For object-oriented coupling
14766 metrics, only dependencies on units that are considered as classes, are
14767 considered.
14768
14769 For unit and control coupling also not compilation units but program units are
14770 counted. That is, for a package, its spec, its body and its subunits (if any)
14771 are considered as making up one unit, and the dependencies that are counted
14772 are the dependencies of all these compilation units collected together as
14773 the dependencies as a (whole) unit. And metrics are reported for spec
14774 compilation units only (or for a subprogram body unit in case if there is no
14775 separate spec for the given subprogram).
14776
14777 For unit coupling, dependencies between all kinds of program units are
14778 considered. For control coupling, for each unit the dependencies of this unit
14779 upon units that define subprograms are counted, so control fan-out coupling
14780 is reported for all units, but control fan-in coupling - only for the units
14781 that define subprograms.
14782
14783
14784
14785
14786
14787
14788 When computing coupling metrics, @command{gnatmetric} counts only
14789 dependencies between units that are arguments of the gnatmetric call.
14790 Coupling metrics are program-wide (or project-wide) metrics, so to
14791 get a valid result, you should call @command{gnatmetric} for
14792 the whole set of sources that make up your program. It can be done
14793 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14794 option (see @ref{The GNAT Driver and Project Files} for details).
14795
14796 By default, all the coupling metrics are disabled. You can use the following
14797 switches to specify the coupling metrics to be computed and reported:
14798
14799 @table @option
14800
14801 @ifclear vms
14802 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14803 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14804 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14805 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14806 @end ifclear
14807
14808 @ifset vms
14809 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14810 @end ifset
14811
14812 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14813 Report all the coupling metrics
14814
14815 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14816 Report tagged (class) fan-out coupling
14817
14818 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14819 Report tagged (class) fan-in coupling
14820
14821 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14822 Report hierarchy (category) fan-out coupling
14823
14824 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14825 Report hierarchy (category) fan-in coupling
14826
14827 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14828 Report unit fan-out coupling
14829
14830 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14831 Report unit fan-in coupling
14832
14833 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14834 Report control fan-out coupling
14835
14836 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14837 Report control fan-in coupling
14838 @end table
14839
14840 @node Other gnatmetric Switches
14841 @subsection Other @code{gnatmetric} Switches
14842
14843 @noindent
14844 Additional @command{gnatmetric} switches are as follows:
14845
14846 @table @option
14847 @item ^-files @var{filename}^/FILES=@var{filename}^
14848 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14849 Take the argument source files from the specified file. This file should be an
14850 ordinary text file containing file names separated by spaces or
14851 line breaks. You can use this switch more than once in the same call to
14852 @command{gnatmetric}. You also can combine this switch with
14853 an explicit list of files.
14854
14855 @item ^-v^/VERBOSE^
14856 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14857 Verbose mode;
14858 @command{gnatmetric} generates version information and then
14859 a trace of sources being processed.
14860
14861 @item ^-q^/QUIET^
14862 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14863 Quiet mode.
14864 @end table
14865
14866 @node Generate project-wide metrics
14867 @subsection Generate project-wide metrics
14868
14869 In order to compute metrics on all units of a given project, you can use
14870 the @command{gnat} driver along with the @option{-P} option:
14871 @smallexample
14872    gnat metric -Pproj
14873 @end smallexample
14874
14875 @noindent
14876 If the project @code{proj} depends upon other projects, you can compute
14877 the metrics on the project closure using the @option{-U} option:
14878 @smallexample
14879    gnat metric -Pproj -U
14880 @end smallexample
14881
14882 @noindent
14883 Finally, if not all the units are relevant to a particular main
14884 program in the project closure, you can generate metrics for the set
14885 of units needed to create a given main program (unit closure) using
14886 the @option{-U} option followed by the name of the main unit:
14887 @smallexample
14888    gnat metric -Pproj -U main
14889 @end smallexample
14890
14891
14892 @c ***********************************
14893 @node File Name Krunching Using gnatkr
14894 @chapter File Name Krunching Using @code{gnatkr}
14895 @findex gnatkr
14896
14897 @noindent
14898 This chapter discusses the method used by the compiler to shorten
14899 the default file names chosen for Ada units so that they do not
14900 exceed the maximum length permitted. It also describes the
14901 @code{gnatkr} utility that can be used to determine the result of
14902 applying this shortening.
14903 @menu
14904 * About gnatkr::
14905 * Using gnatkr::
14906 * Krunching Method::
14907 * Examples of gnatkr Usage::
14908 @end menu
14909
14910 @node About gnatkr
14911 @section About @code{gnatkr}
14912
14913 @noindent
14914 The default file naming rule in GNAT
14915 is that the file name must be derived from
14916 the unit name. The exact default rule is as follows:
14917 @itemize @bullet
14918 @item
14919 Take the unit name and replace all dots by hyphens.
14920 @item
14921 If such a replacement occurs in the
14922 second character position of a name, and the first character is
14923 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14924 then replace the dot by the character
14925 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14926 instead of a minus.
14927 @end itemize
14928 The reason for this exception is to avoid clashes
14929 with the standard names for children of System, Ada, Interfaces,
14930 and GNAT, which use the prefixes
14931 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14932 respectively.
14933
14934 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14935 switch of the compiler activates a ``krunching''
14936 circuit that limits file names to nn characters (where nn is a decimal
14937 integer). For example, using OpenVMS,
14938 where the maximum file name length is
14939 39, the value of nn is usually set to 39, but if you want to generate
14940 a set of files that would be usable if ported to a system with some
14941 different maximum file length, then a different value can be specified.
14942 The default value of 39 for OpenVMS need not be specified.
14943
14944 The @code{gnatkr} utility can be used to determine the krunched name for
14945 a given file, when krunched to a specified maximum length.
14946
14947 @node Using gnatkr
14948 @section Using @code{gnatkr}
14949
14950 @noindent
14951 The @code{gnatkr} command has the form
14952
14953 @ifclear vms
14954 @smallexample
14955 @c $ gnatkr @var{name} @ovar{length}
14956 @c Expanding @ovar macro inline (explanation in macro def comments)
14957 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14958 @end smallexample
14959 @end ifclear
14960
14961 @ifset vms
14962 @smallexample
14963 $ gnatkr @var{name} /COUNT=nn
14964 @end smallexample
14965 @end ifset
14966
14967 @noindent
14968 @var{name} is the uncrunched file name, derived from the name of the unit
14969 in the standard manner described in the previous section (i.e., in particular
14970 all dots are replaced by hyphens). The file name may or may not have an
14971 extension (defined as a suffix of the form period followed by arbitrary
14972 characters other than period). If an extension is present then it will
14973 be preserved in the output. For example, when krunching @file{hellofile.ads}
14974 to eight characters, the result will be hellofil.ads.
14975
14976 Note: for compatibility with previous versions of @code{gnatkr} dots may
14977 appear in the name instead of hyphens, but the last dot will always be
14978 taken as the start of an extension. So if @code{gnatkr} is given an argument
14979 such as @file{Hello.World.adb} it will be treated exactly as if the first
14980 period had been a hyphen, and for example krunching to eight characters
14981 gives the result @file{hellworl.adb}.
14982
14983 Note that the result is always all lower case (except on OpenVMS where it is
14984 all upper case). Characters of the other case are folded as required.
14985
14986 @var{length} represents the length of the krunched name. The default
14987 when no argument is given is ^8^39^ characters. A length of zero stands for
14988 unlimited, in other words do not chop except for system files where the
14989 implied crunching length is always eight characters.
14990
14991 @noindent
14992 The output is the krunched name. The output has an extension only if the
14993 original argument was a file name with an extension.
14994
14995 @node Krunching Method
14996 @section Krunching Method
14997
14998 @noindent
14999 The initial file name is determined by the name of the unit that the file
15000 contains. The name is formed by taking the full expanded name of the
15001 unit and replacing the separating dots with hyphens and
15002 using ^lowercase^uppercase^
15003 for all letters, except that a hyphen in the second character position is
15004 replaced by a ^tilde^dollar sign^ if the first character is
15005 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
15006 The extension is @code{.ads} for a
15007 spec and @code{.adb} for a body.
15008 Krunching does not affect the extension, but the file name is shortened to
15009 the specified length by following these rules:
15010
15011 @itemize @bullet
15012 @item
15013 The name is divided into segments separated by hyphens, tildes or
15014 underscores and all hyphens, tildes, and underscores are
15015 eliminated. If this leaves the name short enough, we are done.
15016
15017 @item
15018 If the name is too long, the longest segment is located (left-most
15019 if there are two of equal length), and shortened by dropping
15020 its last character. This is repeated until the name is short enough.
15021
15022 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15023 to fit the name into 8 characters as required by some operating systems.
15024
15025 @smallexample
15026 our-strings-wide_fixed 22
15027 our strings wide fixed 19
15028 our string  wide fixed 18
15029 our strin   wide fixed 17
15030 our stri    wide fixed 16
15031 our stri    wide fixe  15
15032 our str     wide fixe  14
15033 our str     wid  fixe  13
15034 our str     wid  fix   12
15035 ou  str     wid  fix   11
15036 ou  st      wid  fix   10
15037 ou  st      wi   fix   9
15038 ou  st      wi   fi    8
15039 Final file name: oustwifi.adb
15040 @end smallexample
15041
15042 @item
15043 The file names for all predefined units are always krunched to eight
15044 characters. The krunching of these predefined units uses the following
15045 special prefix replacements:
15046
15047 @table @file
15048 @item ada-
15049 replaced by @file{^a^A^-}
15050
15051 @item gnat-
15052 replaced by @file{^g^G^-}
15053
15054 @item interfaces-
15055 replaced by @file{^i^I^-}
15056
15057 @item system-
15058 replaced by @file{^s^S^-}
15059 @end table
15060
15061 These system files have a hyphen in the second character position. That
15062 is why normal user files replace such a character with a
15063 ^tilde^dollar sign^, to
15064 avoid confusion with system file names.
15065
15066 As an example of this special rule, consider
15067 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15068
15069 @smallexample
15070 ada-strings-wide_fixed 22
15071 a-  strings wide fixed 18
15072 a-  string  wide fixed 17
15073 a-  strin   wide fixed 16
15074 a-  stri    wide fixed 15
15075 a-  stri    wide fixe  14
15076 a-  str     wide fixe  13
15077 a-  str     wid  fixe  12
15078 a-  str     wid  fix   11
15079 a-  st      wid  fix   10
15080 a-  st      wi   fix   9
15081 a-  st      wi   fi    8
15082 Final file name: a-stwifi.adb
15083 @end smallexample
15084 @end itemize
15085
15086 Of course no file shortening algorithm can guarantee uniqueness over all
15087 possible unit names, and if file name krunching is used then it is your
15088 responsibility to ensure that no name clashes occur. The utility
15089 program @code{gnatkr} is supplied for conveniently determining the
15090 krunched name of a file.
15091
15092 @node Examples of gnatkr Usage
15093 @section Examples of @code{gnatkr} Usage
15094
15095 @smallexample
15096 @iftex
15097 @leftskip=0cm
15098 @end iftex
15099 @ifclear vms
15100 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15101 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15102 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15103 $ gnatkr grandparent-parent-child     --> grparchi
15104 @end ifclear
15105 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15106 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15107 @end smallexample
15108
15109 @node Preprocessing Using gnatprep
15110 @chapter Preprocessing Using @code{gnatprep}
15111 @findex gnatprep
15112
15113 @noindent
15114 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15115 preprocessing.
15116 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15117 special GNAT features.
15118 For further discussion of conditional compilation in general, see
15119 @ref{Conditional Compilation}.
15120
15121 @menu
15122 * Preprocessing Symbols::
15123 * Using gnatprep::
15124 * Switches for gnatprep::
15125 * Form of Definitions File::
15126 * Form of Input Text for gnatprep::
15127 @end menu
15128
15129 @node Preprocessing Symbols
15130 @section Preprocessing Symbols
15131
15132 @noindent
15133 Preprocessing symbols are defined in definition files and referred to in
15134 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15135 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15136 all characters need to be in the ASCII set (no accented letters).
15137
15138 @node Using gnatprep
15139 @section Using @code{gnatprep}
15140
15141 @noindent
15142 To call @code{gnatprep} use
15143
15144 @smallexample
15145 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15146 @c Expanding @ovar macro inline (explanation in macro def comments)
15147 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15148 @end smallexample
15149
15150 @noindent
15151 where
15152 @table @var
15153 @item switches
15154 is an optional sequence of switches as described in the next section.
15155
15156 @item infile
15157 is the full name of the input file, which is an Ada source
15158 file containing preprocessor directives.
15159
15160 @item outfile
15161 is the full name of the output file, which is an Ada source
15162 in standard Ada form. When used with GNAT, this file name will
15163 normally have an ads or adb suffix.
15164
15165 @item deffile
15166 is the full name of a text file containing definitions of
15167 preprocessing symbols to be referenced by the preprocessor. This argument is
15168 optional, and can be replaced by the use of the @option{-D} switch.
15169
15170 @end table
15171
15172 @node Switches for gnatprep
15173 @section Switches for @code{gnatprep}
15174
15175 @table @option
15176 @c !sort!
15177
15178 @item ^-b^/BLANK_LINES^
15179 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15180 Causes both preprocessor lines and the lines deleted by
15181 preprocessing to be replaced by blank lines in the output source file,
15182 preserving line numbers in the output file.
15183
15184 @item ^-c^/COMMENTS^
15185 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15186 Causes both preprocessor lines and the lines deleted
15187 by preprocessing to be retained in the output source as comments marked
15188 with the special string @code{"--! "}. This option will result in line numbers
15189 being preserved in the output file.
15190
15191 @item ^-C^/REPLACE_IN_COMMENTS^
15192 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15193 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15194 If this option is specified, then comments are scanned and any $symbol
15195 substitutions performed as in program text. This is particularly useful
15196 when structured comments are used (e.g., when writing programs in the
15197 SPARK dialect of Ada). Note that this switch is not available when
15198 doing integrated preprocessing (it would be useless in this context
15199 since comments are ignored by the compiler in any case).
15200
15201 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15202 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15203 Defines a new preprocessing symbol, associated with value. If no value is given
15204 on the command line, then symbol is considered to be @code{True}. This switch
15205 can be used in place of a definition file.
15206
15207 @ifset vms
15208 @item /REMOVE
15209 @cindex @option{/REMOVE} (@command{gnatprep})
15210 This is the default setting which causes lines deleted by preprocessing
15211 to be entirely removed from the output file.
15212 @end ifset
15213
15214 @item ^-r^/REFERENCE^
15215 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15216 Causes a @code{Source_Reference} pragma to be generated that
15217 references the original input file, so that error messages will use
15218 the file name of this original file. The use of this switch implies
15219 that preprocessor lines are not to be removed from the file, so its
15220 use will force @option{^-b^/BLANK_LINES^} mode if
15221 @option{^-c^/COMMENTS^}
15222 has not been specified explicitly.
15223
15224 Note that if the file to be preprocessed contains multiple units, then
15225 it will be necessary to @code{gnatchop} the output file from
15226 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15227 in the preprocessed file, it will be respected by
15228 @code{gnatchop ^-r^/REFERENCE^}
15229 so that the final chopped files will correctly refer to the original
15230 input source file for @code{gnatprep}.
15231
15232 @item ^-s^/SYMBOLS^
15233 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15234 Causes a sorted list of symbol names and values to be
15235 listed on the standard output file.
15236
15237 @item ^-u^/UNDEFINED^
15238 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15239 Causes undefined symbols to be treated as having the value FALSE in the context
15240 of a preprocessor test. In the absence of this option, an undefined symbol in
15241 a @code{#if} or @code{#elsif} test will be treated as an error.
15242
15243 @end table
15244
15245 @ifclear vms
15246 @noindent
15247 Note: if neither @option{-b} nor @option{-c} is present,
15248 then preprocessor lines and
15249 deleted lines are completely removed from the output, unless -r is
15250 specified, in which case -b is assumed.
15251 @end ifclear
15252
15253 @node Form of Definitions File
15254 @section Form of Definitions File
15255
15256 @noindent
15257 The definitions file contains lines of the form
15258
15259 @smallexample
15260 symbol := value
15261 @end smallexample
15262
15263 @noindent
15264 where symbol is a preprocessing symbol, and value is one of the following:
15265
15266 @itemize @bullet
15267 @item
15268 Empty, corresponding to a null substitution
15269 @item
15270 A string literal using normal Ada syntax
15271 @item
15272 Any sequence of characters from the set
15273 (letters, digits, period, underline).
15274 @end itemize
15275
15276 @noindent
15277 Comment lines may also appear in the definitions file, starting with
15278 the usual @code{--},
15279 and comments may be added to the definitions lines.
15280
15281 @node Form of Input Text for gnatprep
15282 @section Form of Input Text for @code{gnatprep}
15283
15284 @noindent
15285 The input text may contain preprocessor conditional inclusion lines,
15286 as well as general symbol substitution sequences.
15287
15288 The preprocessor conditional inclusion commands have the form
15289
15290 @smallexample
15291 @group
15292 @cartouche
15293 #if @i{expression} @r{[}then@r{]}
15294    lines
15295 #elsif @i{expression} @r{[}then@r{]}
15296    lines
15297 #elsif @i{expression} @r{[}then@r{]}
15298    lines
15299 @dots{}
15300 #else
15301    lines
15302 #end if;
15303 @end cartouche
15304 @end group
15305 @end smallexample
15306
15307 @noindent
15308 In this example, @i{expression} is defined by the following grammar:
15309 @smallexample
15310 @i{expression} ::=  <symbol>
15311 @i{expression} ::=  <symbol> = "<value>"
15312 @i{expression} ::=  <symbol> = <symbol>
15313 @i{expression} ::=  <symbol> 'Defined
15314 @i{expression} ::=  not @i{expression}
15315 @i{expression} ::=  @i{expression} and @i{expression}
15316 @i{expression} ::=  @i{expression} or @i{expression}
15317 @i{expression} ::=  @i{expression} and then @i{expression}
15318 @i{expression} ::=  @i{expression} or else @i{expression}
15319 @i{expression} ::=  ( @i{expression} )
15320 @end smallexample
15321
15322 The following restriction exists: it is not allowed to have "and" or "or"
15323 following "not" in the same expression without parentheses. For example, this
15324 is not allowed:
15325
15326 @smallexample
15327    not X or Y
15328 @end smallexample
15329
15330 This should be one of the following:
15331
15332 @smallexample
15333    (not X) or Y
15334    not (X or Y)
15335 @end smallexample
15336
15337 @noindent
15338 For the first test (@i{expression} ::= <symbol>) the symbol must have
15339 either the value true or false, that is to say the right-hand of the
15340 symbol definition must be one of the (case-insensitive) literals
15341 @code{True} or @code{False}. If the value is true, then the
15342 corresponding lines are included, and if the value is false, they are
15343 excluded.
15344
15345 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15346 the symbol has been defined in the definition file or by a @option{-D}
15347 switch on the command line. Otherwise, the test is false.
15348
15349 The equality tests are case insensitive, as are all the preprocessor lines.
15350
15351 If the symbol referenced is not defined in the symbol definitions file,
15352 then the effect depends on whether or not switch @option{-u}
15353 is specified. If so, then the symbol is treated as if it had the value
15354 false and the test fails. If this switch is not specified, then
15355 it is an error to reference an undefined symbol. It is also an error to
15356 reference a symbol that is defined with a value other than @code{True}
15357 or @code{False}.
15358
15359 The use of the @code{not} operator inverts the sense of this logical test.
15360 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15361 operators, without parentheses. For example, "if not X or Y then" is not
15362 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15363
15364 The @code{then} keyword is optional as shown
15365
15366 The @code{#} must be the first non-blank character on a line, but
15367 otherwise the format is free form. Spaces or tabs may appear between
15368 the @code{#} and the keyword. The keywords and the symbols are case
15369 insensitive as in normal Ada code. Comments may be used on a
15370 preprocessor line, but other than that, no other tokens may appear on a
15371 preprocessor line. Any number of @code{elsif} clauses can be present,
15372 including none at all. The @code{else} is optional, as in Ada.
15373
15374 The @code{#} marking the start of a preprocessor line must be the first
15375 non-blank character on the line, i.e., it must be preceded only by
15376 spaces or horizontal tabs.
15377
15378 Symbol substitution outside of preprocessor lines is obtained by using
15379 the sequence
15380
15381 @smallexample
15382 $symbol
15383 @end smallexample
15384
15385 @noindent
15386 anywhere within a source line, except in a comment or within a
15387 string literal. The identifier
15388 following the @code{$} must match one of the symbols defined in the symbol
15389 definition file, and the result is to substitute the value of the
15390 symbol in place of @code{$symbol} in the output file.
15391
15392 Note that although the substitution of strings within a string literal
15393 is not possible, it is possible to have a symbol whose defined value is
15394 a string literal. So instead of setting XYZ to @code{hello} and writing:
15395
15396 @smallexample
15397 Header : String := "$XYZ";
15398 @end smallexample
15399
15400 @noindent
15401 you should set XYZ to @code{"hello"} and write:
15402
15403 @smallexample
15404 Header : String := $XYZ;
15405 @end smallexample
15406
15407 @noindent
15408 and then the substitution will occur as desired.
15409
15410 @node The GNAT Library Browser gnatls
15411 @chapter The GNAT Library Browser @code{gnatls}
15412 @findex gnatls
15413 @cindex Library browser
15414
15415 @noindent
15416 @code{gnatls} is a tool that outputs information about compiled
15417 units. It gives the relationship between objects, unit names and source
15418 files. It can also be used to check the source dependencies of a unit
15419 as well as various characteristics.
15420
15421 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15422 driver (see @ref{The GNAT Driver and Project Files}).
15423
15424 @menu
15425 * Running gnatls::
15426 * Switches for gnatls::
15427 * Examples of gnatls Usage::
15428 @end menu
15429
15430 @node Running gnatls
15431 @section Running @code{gnatls}
15432
15433 @noindent
15434 The @code{gnatls} command has the form
15435
15436 @smallexample
15437 $ gnatls switches @var{object_or_ali_file}
15438 @end smallexample
15439
15440 @noindent
15441 The main argument is the list of object or @file{ali} files
15442 (@pxref{The Ada Library Information Files})
15443 for which information is requested.
15444
15445 In normal mode, without additional option, @code{gnatls} produces a
15446 four-column listing. Each line represents information for a specific
15447 object. The first column gives the full path of the object, the second
15448 column gives the name of the principal unit in this object, the third
15449 column gives the status of the source and the fourth column gives the
15450 full path of the source representing this unit.
15451 Here is a simple example of use:
15452
15453 @smallexample
15454 $ gnatls *.o
15455 ^./^[]^demo1.o            demo1            DIF demo1.adb
15456 ^./^[]^demo2.o            demo2             OK demo2.adb
15457 ^./^[]^hello.o            h1                OK hello.adb
15458 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15459 ^./^[]^instr.o            instr             OK instr.adb
15460 ^./^[]^tef.o              tef              DIF tef.adb
15461 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15462 ^./^[]^tgef.o             tgef             DIF tgef.adb
15463 @end smallexample
15464
15465 @noindent
15466 The first line can be interpreted as follows: the main unit which is
15467 contained in
15468 object file @file{demo1.o} is demo1, whose main source is in
15469 @file{demo1.adb}. Furthermore, the version of the source used for the
15470 compilation of demo1 has been modified (DIF). Each source file has a status
15471 qualifier which can be:
15472
15473 @table @code
15474 @item OK (unchanged)
15475 The version of the source file used for the compilation of the
15476 specified unit corresponds exactly to the actual source file.
15477
15478 @item MOK (slightly modified)
15479 The version of the source file used for the compilation of the
15480 specified unit differs from the actual source file but not enough to
15481 require recompilation. If you use gnatmake with the qualifier
15482 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15483 MOK will not be recompiled.
15484
15485 @item DIF (modified)
15486 No version of the source found on the path corresponds to the source
15487 used to build this object.
15488
15489 @item ??? (file not found)
15490 No source file was found for this unit.
15491
15492 @item HID (hidden,  unchanged version not first on PATH)
15493 The version of the source that corresponds exactly to the source used
15494 for compilation has been found on the path but it is hidden by another
15495 version of the same source that has been modified.
15496
15497 @end table
15498
15499 @node Switches for gnatls
15500 @section Switches for @code{gnatls}
15501
15502 @noindent
15503 @code{gnatls} recognizes the following switches:
15504
15505 @table @option
15506 @c !sort!
15507 @cindex @option{--version} @command{gnatls}
15508 Display Copyright and version, then exit disregarding all other options.
15509
15510 @item --help
15511 @cindex @option{--help} @command{gnatls}
15512 If @option{--version} was not used, display usage, then exit disregarding
15513 all other options.
15514
15515 @item ^-a^/ALL_UNITS^
15516 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15517 Consider all units, including those of the predefined Ada library.
15518 Especially useful with @option{^-d^/DEPENDENCIES^}.
15519
15520 @item ^-d^/DEPENDENCIES^
15521 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15522 List sources from which specified units depend on.
15523
15524 @item ^-h^/OUTPUT=OPTIONS^
15525 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15526 Output the list of options.
15527
15528 @item ^-o^/OUTPUT=OBJECTS^
15529 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15530 Only output information about object files.
15531
15532 @item ^-s^/OUTPUT=SOURCES^
15533 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15534 Only output information about source files.
15535
15536 @item ^-u^/OUTPUT=UNITS^
15537 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15538 Only output information about compilation units.
15539
15540 @item ^-files^/FILES^=@var{file}
15541 @cindex @option{^-files^/FILES^} (@code{gnatls})
15542 Take as arguments the files listed in text file @var{file}.
15543 Text file @var{file} may contain empty lines that are ignored.
15544 Each nonempty line should contain the name of an existing file.
15545 Several such switches may be specified simultaneously.
15546
15547 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15548 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15549 @itemx ^-I^/SEARCH=^@var{dir}
15550 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15551 @itemx -nostdinc
15552 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15553 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15554 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15555 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15556 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15557 flags (@pxref{Switches for gnatmake}).
15558
15559 @item --RTS=@var{rts-path}
15560 @cindex @option{--RTS} (@code{gnatls})
15561 Specifies the default location of the runtime library. Same meaning as the
15562 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15563
15564 @item ^-v^/OUTPUT=VERBOSE^
15565 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15566 Verbose mode. Output the complete source, object and project paths. Do not use
15567 the default column layout but instead use long format giving as much as
15568 information possible on each requested units, including special
15569 characteristics such as:
15570
15571 @table @code
15572 @item  Preelaborable
15573 The unit is preelaborable in the Ada sense.
15574
15575 @item No_Elab_Code
15576 No elaboration code has been produced by the compiler for this unit.
15577
15578 @item Pure
15579 The unit is pure in the Ada sense.
15580
15581 @item Elaborate_Body
15582 The unit contains a pragma Elaborate_Body.
15583
15584 @item Remote_Types
15585 The unit contains a pragma Remote_Types.
15586
15587 @item Shared_Passive
15588 The unit contains a pragma Shared_Passive.
15589
15590 @item Predefined
15591 This unit is part of the predefined environment and cannot be modified
15592 by the user.
15593
15594 @item Remote_Call_Interface
15595 The unit contains a pragma Remote_Call_Interface.
15596
15597 @end table
15598
15599 @end table
15600
15601 @node Examples of gnatls Usage
15602 @section Example of @code{gnatls} Usage
15603 @ifclear vms
15604
15605 @noindent
15606 Example of using the verbose switch. Note how the source and
15607 object paths are affected by the -I switch.
15608
15609 @smallexample
15610 $ gnatls -v -I.. demo1.o
15611
15612 GNATLS 5.03w (20041123-34)
15613 Copyright 1997-2004 Free Software Foundation, Inc.
15614
15615 Source Search Path:
15616    <Current_Directory>
15617    ../
15618    /home/comar/local/adainclude/
15619
15620 Object Search Path:
15621    <Current_Directory>
15622    ../
15623    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15624
15625 Project Search Path:
15626    <Current_Directory>
15627    /home/comar/local/lib/gnat/
15628
15629 ./demo1.o
15630    Unit =>
15631      Name   => demo1
15632      Kind   => subprogram body
15633      Flags  => No_Elab_Code
15634      Source => demo1.adb    modified
15635 @end smallexample
15636
15637 @noindent
15638 The following is an example of use of the dependency list.
15639 Note the use of the -s switch
15640 which gives a straight list of source files. This can be useful for
15641 building specialized scripts.
15642
15643 @smallexample
15644 $ gnatls -d demo2.o
15645 ./demo2.o   demo2        OK demo2.adb
15646                          OK gen_list.ads
15647                          OK gen_list.adb
15648                          OK instr.ads
15649                          OK instr-child.ads
15650
15651 $ gnatls -d -s -a demo1.o
15652 demo1.adb
15653 /home/comar/local/adainclude/ada.ads
15654 /home/comar/local/adainclude/a-finali.ads
15655 /home/comar/local/adainclude/a-filico.ads
15656 /home/comar/local/adainclude/a-stream.ads
15657 /home/comar/local/adainclude/a-tags.ads
15658 gen_list.ads
15659 gen_list.adb
15660 /home/comar/local/adainclude/gnat.ads
15661 /home/comar/local/adainclude/g-io.ads
15662 instr.ads
15663 /home/comar/local/adainclude/system.ads
15664 /home/comar/local/adainclude/s-exctab.ads
15665 /home/comar/local/adainclude/s-finimp.ads
15666 /home/comar/local/adainclude/s-finroo.ads
15667 /home/comar/local/adainclude/s-secsta.ads
15668 /home/comar/local/adainclude/s-stalib.ads
15669 /home/comar/local/adainclude/s-stoele.ads
15670 /home/comar/local/adainclude/s-stratt.ads
15671 /home/comar/local/adainclude/s-tasoli.ads
15672 /home/comar/local/adainclude/s-unstyp.ads
15673 /home/comar/local/adainclude/unchconv.ads
15674 @end smallexample
15675 @end ifclear
15676
15677 @ifset vms
15678 @smallexample
15679 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15680
15681 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15682 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15683 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15684 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15685 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15686 demo1.adb
15687 gen_list.ads
15688 gen_list.adb
15689 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15690 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15691 instr.ads
15692 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15693 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15694 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15695 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15696 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15697 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15698 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15699 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15700 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15701 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15702 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15703 @end smallexample
15704 @end ifset
15705
15706 @node Cleaning Up Using gnatclean
15707 @chapter Cleaning Up Using @code{gnatclean}
15708 @findex gnatclean
15709 @cindex Cleaning tool
15710
15711 @noindent
15712 @code{gnatclean} is a tool that allows the deletion of files produced by the
15713 compiler, binder and linker, including ALI files, object files, tree files,
15714 expanded source files, library files, interface copy source files, binder
15715 generated files and executable files.
15716
15717 @menu
15718 * Running gnatclean::
15719 * Switches for gnatclean::
15720 @c * Examples of gnatclean Usage::
15721 @end menu
15722
15723 @node Running gnatclean
15724 @section Running @code{gnatclean}
15725
15726 @noindent
15727 The @code{gnatclean} command has the form:
15728
15729 @smallexample
15730 $ gnatclean switches @var{names}
15731 @end smallexample
15732
15733 @noindent
15734 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15735 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15736 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15737
15738 @noindent
15739 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15740 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15741 the linker. In informative-only mode, specified by switch
15742 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15743 normal mode is listed, but no file is actually deleted.
15744
15745 @node Switches for gnatclean
15746 @section Switches for @code{gnatclean}
15747
15748 @noindent
15749 @code{gnatclean} recognizes the following switches:
15750
15751 @table @option
15752 @c !sort!
15753 @cindex @option{--version} @command{gnatclean}
15754 Display Copyright and version, then exit disregarding all other options.
15755
15756 @item --help
15757 @cindex @option{--help} @command{gnatclean}
15758 If @option{--version} was not used, display usage, then exit disregarding
15759 all other options.
15760
15761 @item ^--subdirs^/SUBDIRS^=subdir
15762 Actual object directory of each project file is the subdirectory subdir of the
15763 object directory specified or defaulted in the project file.
15764
15765 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15766 By default, shared library projects are not allowed to import static library
15767 projects. When this switch is used on the command line, this restriction is
15768 relaxed.
15769
15770 @item ^-c^/COMPILER_FILES_ONLY^
15771 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15772 Only attempt to delete the files produced by the compiler, not those produced
15773 by the binder or the linker. The files that are not to be deleted are library
15774 files, interface copy files, binder generated files and executable files.
15775
15776 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15777 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15778 Indicate that ALI and object files should normally be found in directory
15779 @var{dir}.
15780
15781 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15782 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15783 When using project files, if some errors or warnings are detected during
15784 parsing and verbose mode is not in effect (no use of switch
15785 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15786 file, rather than its simple file name.
15787
15788 @item ^-h^/HELP^
15789 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15790 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15791
15792 @item ^-n^/NODELETE^
15793 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15794 Informative-only mode. Do not delete any files. Output the list of the files
15795 that would have been deleted if this switch was not specified.
15796
15797 @item ^-P^/PROJECT_FILE=^@var{project}
15798 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15799 Use project file @var{project}. Only one such switch can be used.
15800 When cleaning a project file, the files produced by the compilation of the
15801 immediate sources or inherited sources of the project files are to be
15802 deleted. This is not depending on the presence or not of executable names
15803 on the command line.
15804
15805 @item ^-q^/QUIET^
15806 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15807 Quiet output. If there are no errors, do not output anything, except in
15808 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15809 (switch ^-n^/NODELETE^).
15810
15811 @item ^-r^/RECURSIVE^
15812 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15813 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15814 clean all imported and extended project files, recursively. If this switch
15815 is not specified, only the files related to the main project file are to be
15816 deleted. This switch has no effect if no project file is specified.
15817
15818 @item ^-v^/VERBOSE^
15819 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15820 Verbose mode.
15821
15822 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15823 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15824 Indicates the verbosity of the parsing of GNAT project files.
15825 @xref{Switches Related to Project Files}.
15826
15827 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15828 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15829 Indicates that external variable @var{name} has the value @var{value}.
15830 The Project Manager will use this value for occurrences of
15831 @code{external(name)} when parsing the project file.
15832 @xref{Switches Related to Project Files}.
15833
15834 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15835 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15836 When searching for ALI and object files, look in directory
15837 @var{dir}.
15838
15839 @item ^-I^/SEARCH=^@var{dir}
15840 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15841 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15842
15843 @item ^-I-^/NOCURRENT_DIRECTORY^
15844 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15845 @cindex Source files, suppressing search
15846 Do not look for ALI or object files in the directory
15847 where @code{gnatclean} was invoked.
15848
15849 @end table
15850
15851 @c @node Examples of gnatclean Usage
15852 @c @section Examples of @code{gnatclean} Usage
15853
15854 @ifclear vms
15855 @node GNAT and Libraries
15856 @chapter GNAT and Libraries
15857 @cindex Library, building, installing, using
15858
15859 @noindent
15860 This chapter describes how to build and use libraries with GNAT, and also shows
15861 how to recompile the GNAT run-time library. You should be familiar with the
15862 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15863 chapter.
15864
15865 @menu
15866 * Introduction to Libraries in GNAT::
15867 * General Ada Libraries::
15868 * Stand-alone Ada Libraries::
15869 * Rebuilding the GNAT Run-Time Library::
15870 @end menu
15871
15872 @node Introduction to Libraries in GNAT
15873 @section Introduction to Libraries in GNAT
15874
15875 @noindent
15876 A library is, conceptually, a collection of objects which does not have its
15877 own main thread of execution, but rather provides certain services to the
15878 applications that use it. A library can be either statically linked with the
15879 application, in which case its code is directly included in the application,
15880 or, on platforms that support it, be dynamically linked, in which case
15881 its code is shared by all applications making use of this library.
15882
15883 GNAT supports both types of libraries.
15884 In the static case, the compiled code can be provided in different ways. The
15885 simplest approach is to provide directly the set of objects resulting from
15886 compilation of the library source files. Alternatively, you can group the
15887 objects into an archive using whatever commands are provided by the operating
15888 system. For the latter case, the objects are grouped into a shared library.
15889
15890 In the GNAT environment, a library has three types of components:
15891 @itemize @bullet
15892 @item
15893 Source files.
15894 @item
15895 @file{ALI} files.
15896 @xref{The Ada Library Information Files}.
15897 @item
15898 Object files, an archive or a shared library.
15899 @end itemize
15900
15901 @noindent
15902 A GNAT library may expose all its source files, which is useful for
15903 documentation purposes. Alternatively, it may expose only the units needed by
15904 an external user to make use of the library. That is to say, the specs
15905 reflecting the library services along with all the units needed to compile
15906 those specs, which can include generic bodies or any body implementing an
15907 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15908 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15909
15910 All compilation units comprising an application, including those in a library,
15911 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15912 computes the elaboration order from the @file{ALI} files and this is why they
15913 constitute a mandatory part of GNAT libraries.
15914 @emph{Stand-alone libraries} are the exception to this rule because a specific
15915 library elaboration routine is produced independently of the application(s)
15916 using the library.
15917
15918 @node General Ada Libraries
15919 @section General Ada Libraries
15920
15921 @menu
15922 * Building a library::
15923 * Installing a library::
15924 * Using a library::
15925 @end menu
15926
15927 @node Building a library
15928 @subsection Building a library
15929
15930 @noindent
15931 The easiest way to build a library is to use the Project Manager,
15932 which supports a special type of project called a @emph{Library Project}
15933 (@pxref{Library Projects}).
15934
15935 A project is considered a library project, when two project-level attributes
15936 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15937 control different aspects of library configuration, additional optional
15938 project-level attributes can be specified:
15939 @table @code
15940 @item Library_Kind
15941 This attribute controls whether the library is to be static or dynamic
15942
15943 @item Library_Version
15944 This attribute specifies the library version; this value is used
15945 during dynamic linking of shared libraries to determine if the currently
15946 installed versions of the binaries are compatible.
15947
15948 @item Library_Options
15949 @item Library_GCC
15950 These attributes specify additional low-level options to be used during
15951 library generation, and redefine the actual application used to generate
15952 library.
15953 @end table
15954
15955 @noindent
15956 The GNAT Project Manager takes full care of the library maintenance task,
15957 including recompilation of the source files for which objects do not exist
15958 or are not up to date, assembly of the library archive, and installation of
15959 the library (i.e., copying associated source, object and @file{ALI} files
15960 to the specified location).
15961
15962 Here is a simple library project file:
15963 @smallexample @c ada
15964 project My_Lib is
15965    for Source_Dirs use ("src1", "src2");
15966    for Object_Dir use "obj";
15967    for Library_Name use "mylib";
15968    for Library_Dir use "lib";
15969    for Library_Kind use "dynamic";
15970 end My_lib;
15971 @end smallexample
15972
15973 @noindent
15974 and the compilation command to build and install the library:
15975
15976 @smallexample @c ada
15977   $ gnatmake -Pmy_lib
15978 @end smallexample
15979
15980 @noindent
15981 It is not entirely trivial to perform manually all the steps required to
15982 produce a library. We recommend that you use the GNAT Project Manager
15983 for this task. In special cases where this is not desired, the necessary
15984 steps are discussed below.
15985
15986 There are various possibilities for compiling the units that make up the
15987 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15988 with a conventional script. For simple libraries, it is also possible to create
15989 a dummy main program which depends upon all the packages that comprise the
15990 interface of the library. This dummy main program can then be given to
15991 @command{gnatmake}, which will ensure that all necessary objects are built.
15992
15993 After this task is accomplished, you should follow the standard procedure
15994 of the underlying operating system to produce the static or shared library.
15995
15996 Here is an example of such a dummy program:
15997 @smallexample @c ada
15998 @group
15999 with My_Lib.Service1;
16000 with My_Lib.Service2;
16001 with My_Lib.Service3;
16002 procedure My_Lib_Dummy is
16003 begin
16004    null;
16005 end;
16006 @end group
16007 @end smallexample
16008
16009 @noindent
16010 Here are the generic commands that will build an archive or a shared library.
16011
16012 @smallexample
16013 # compiling the library
16014 $ gnatmake -c my_lib_dummy.adb
16015
16016 # we don't need the dummy object itself
16017 $ rm my_lib_dummy.o my_lib_dummy.ali
16018
16019 # create an archive with the remaining objects
16020 $ ar rc libmy_lib.a *.o
16021 # some systems may require "ranlib" to be run as well
16022
16023 # or create a shared library
16024 $ gcc -shared -o libmy_lib.so *.o
16025 # some systems may require the code to have been compiled with -fPIC
16026
16027 # remove the object files that are now in the library
16028 $ rm *.o
16029
16030 # Make the ALI files read-only so that gnatmake will not try to
16031 # regenerate the objects that are in the library
16032 $ chmod -w *.ali
16033 @end smallexample
16034
16035 @noindent
16036 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
16037 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
16038 be accessed by the directive @option{-l@var{xxx}} at link time.
16039
16040 @node Installing a library
16041 @subsection Installing a library
16042 @cindex @code{ADA_PROJECT_PATH}
16043 @cindex @code{GPR_PROJECT_PATH}
16044
16045 @noindent
16046 If you use project files, library installation is part of the library build
16047 process (@pxref{Installing a library with project files}).
16048
16049 When project files are not an option, it is also possible, but not recommended,
16050 to install the library so that the sources needed to use the library are on the
16051 Ada source path and the ALI files & libraries be on the Ada Object path (see
16052 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
16053 administrator can place general-purpose libraries in the default compiler
16054 paths, by specifying the libraries' location in the configuration files
16055 @file{ada_source_path} and @file{ada_object_path}. These configuration files
16056 must be located in the GNAT installation tree at the same place as the gcc spec
16057 file. The location of the gcc spec file can be determined as follows:
16058 @smallexample
16059 $ gcc -v
16060 @end smallexample
16061
16062 @noindent
16063 The configuration files mentioned above have a simple format: each line
16064 must contain one unique directory name.
16065 Those names are added to the corresponding path
16066 in their order of appearance in the file. The names can be either absolute
16067 or relative; in the latter case, they are relative to where theses files
16068 are located.
16069
16070 The files @file{ada_source_path} and @file{ada_object_path} might not be
16071 present in a
16072 GNAT installation, in which case, GNAT will look for its run-time library in
16073 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16074 objects and @file{ALI} files). When the files exist, the compiler does not
16075 look in @file{adainclude} and @file{adalib}, and thus the
16076 @file{ada_source_path} file
16077 must contain the location for the GNAT run-time sources (which can simply
16078 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16079 contain the location for the GNAT run-time objects (which can simply
16080 be @file{adalib}).
16081
16082 You can also specify a new default path to the run-time library at compilation
16083 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16084 the run-time library you want your program to be compiled with. This switch is
16085 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16086 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16087
16088 It is possible to install a library before or after the standard GNAT
16089 library, by reordering the lines in the configuration files. In general, a
16090 library must be installed before the GNAT library if it redefines
16091 any part of it.
16092
16093 @node Using a library
16094 @subsection Using a library
16095
16096 @noindent Once again, the project facility greatly simplifies the use of
16097 libraries. In this context, using a library is just a matter of adding a
16098 @code{with} clause in the user project. For instance, to make use of the
16099 library @code{My_Lib} shown in examples in earlier sections, you can
16100 write:
16101
16102 @smallexample @c projectfile
16103 with "my_lib";
16104 project My_Proj is
16105   @dots{}
16106 end My_Proj;
16107 @end smallexample
16108
16109 Even if you have a third-party, non-Ada library, you can still use GNAT's
16110 Project Manager facility to provide a wrapper for it. For example, the
16111 following project, when @code{with}ed by your main project, will link with the
16112 third-party library @file{liba.a}:
16113
16114 @smallexample @c projectfile
16115 @group
16116 project Liba is
16117    for Externally_Built use "true";
16118    for Source_Files use ();
16119    for Library_Dir use "lib";
16120    for Library_Name use "a";
16121    for Library_Kind use "static";
16122 end Liba;
16123 @end group
16124 @end smallexample
16125 This is an alternative to the use of @code{pragma Linker_Options}. It is
16126 especially interesting in the context of systems with several interdependent
16127 static libraries where finding a proper linker order is not easy and best be
16128 left to the tools having visibility over project dependence information.
16129
16130 @noindent
16131 In order to use an Ada library manually, you need to make sure that this
16132 library is on both your source and object path
16133 (see @ref{Search Paths and the Run-Time Library (RTL)}
16134 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16135 in an archive or a shared library, you need to specify the desired
16136 library at link time.
16137
16138 For example, you can use the library @file{mylib} installed in
16139 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16140
16141 @smallexample
16142 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16143   -largs -lmy_lib
16144 @end smallexample
16145
16146 @noindent
16147 This can be expressed more simply:
16148 @smallexample
16149 $ gnatmake my_appl
16150 @end smallexample
16151 @noindent
16152 when the following conditions are met:
16153 @itemize @bullet
16154 @item
16155 @file{/dir/my_lib_src} has been added by the user to the environment
16156 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16157 @file{ada_source_path}
16158 @item
16159 @file{/dir/my_lib_obj} has been added by the user to the environment
16160 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16161 @file{ada_object_path}
16162 @item
16163 a pragma @code{Linker_Options} has been added to one of the sources.
16164 For example:
16165
16166 @smallexample @c ada
16167 pragma Linker_Options ("-lmy_lib");
16168 @end smallexample
16169 @end itemize
16170
16171 @node Stand-alone Ada Libraries
16172 @section Stand-alone Ada Libraries
16173 @cindex Stand-alone library, building, using
16174
16175 @menu
16176 * Introduction to Stand-alone Libraries::
16177 * Building a Stand-alone Library::
16178 * Creating a Stand-alone Library to be used in a non-Ada context::
16179 * Restrictions in Stand-alone Libraries::
16180 @end menu
16181
16182 @node Introduction to Stand-alone Libraries
16183 @subsection Introduction to Stand-alone Libraries
16184
16185 @noindent
16186 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16187 necessary code to
16188 elaborate the Ada units that are included in the library. In contrast with
16189 an ordinary library, which consists of all sources, objects and @file{ALI}
16190 files of the
16191 library, a SAL may specify a restricted subset of compilation units
16192 to serve as a library interface. In this case, the fully
16193 self-sufficient set of files will normally consist of an objects
16194 archive, the sources of interface units' specs, and the @file{ALI}
16195 files of interface units.
16196 If an interface spec contains a generic unit or an inlined subprogram,
16197 the body's
16198 source must also be provided; if the units that must be provided in the source
16199 form depend on other units, the source and @file{ALI} files of those must
16200 also be provided.
16201
16202 The main purpose of a SAL is to minimize the recompilation overhead of client
16203 applications when a new version of the library is installed. Specifically,
16204 if the interface sources have not changed, client applications do not need to
16205 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16206 version, controlled by @code{Library_Version} attribute, is not changed,
16207 then the clients do not need to be relinked.
16208
16209 SALs also allow the library providers to minimize the amount of library source
16210 text exposed to the clients.  Such ``information hiding'' might be useful or
16211 necessary for various reasons.
16212
16213 Stand-alone libraries are also well suited to be used in an executable whose
16214 main routine is not written in Ada.
16215
16216 @node Building a Stand-alone Library
16217 @subsection Building a Stand-alone Library
16218
16219 @noindent
16220 GNAT's Project facility provides a simple way of building and installing
16221 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16222 To be a Stand-alone Library Project, in addition to the two attributes
16223 that make a project a Library Project (@code{Library_Name} and
16224 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16225 @code{Library_Interface} must be defined.  For example:
16226
16227 @smallexample @c projectfile
16228 @group
16229    for Library_Dir use "lib_dir";
16230    for Library_Name use "dummy";
16231    for Library_Interface use ("int1", "int1.child");
16232 @end group
16233 @end smallexample
16234
16235 @noindent
16236 Attribute @code{Library_Interface} has a non-empty string list value,
16237 each string in the list designating a unit contained in an immediate source
16238 of the project file.
16239
16240 When a Stand-alone Library is built, first the binder is invoked to build
16241 a package whose name depends on the library name
16242 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16243 This binder-generated package includes initialization and
16244 finalization procedures whose
16245 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16246 in the example
16247 above). The object corresponding to this package is included in the library.
16248
16249 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16250 calling of these procedures if a static SAL is built, or if a shared SAL
16251 is built
16252 with the project-level attribute @code{Library_Auto_Init} set to
16253 @code{"false"}.
16254
16255 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16256 (those that are listed in attribute @code{Library_Interface}) are copied to
16257 the Library Directory. As a consequence, only the Interface Units may be
16258 imported from Ada units outside of the library. If other units are imported,
16259 the binding phase will fail.
16260
16261 The attribute @code{Library_Src_Dir} may be specified for a
16262 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16263 single string value. Its value must be the path (absolute or relative to the
16264 project directory) of an existing directory. This directory cannot be the
16265 object directory or one of the source directories, but it can be the same as
16266 the library directory. The sources of the Interface
16267 Units of the library that are needed by an Ada client of the library will be
16268 copied to the designated directory, called the Interface Copy directory.
16269 These sources include the specs of the Interface Units, but they may also
16270 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16271 are used, or when there is a generic unit in the spec. Before the sources
16272 are copied to the Interface Copy directory, an attempt is made to delete all
16273 files in the Interface Copy directory.
16274
16275 Building stand-alone libraries by hand is somewhat tedious, but for those
16276 occasions when it is necessary here are the steps that you need to perform:
16277 @itemize @bullet
16278 @item
16279 Compile all library sources.
16280
16281 @item
16282 Invoke the binder with the switch @option{-n} (No Ada main program),
16283 with all the @file{ALI} files of the interfaces, and
16284 with the switch @option{-L} to give specific names to the @code{init}
16285 and @code{final} procedures.  For example:
16286 @smallexample
16287   gnatbind -n int1.ali int2.ali -Lsal1
16288 @end smallexample
16289
16290 @item
16291 Compile the binder generated file:
16292 @smallexample
16293   gcc -c b~int2.adb
16294 @end smallexample
16295
16296 @item
16297 Link the dynamic library with all the necessary object files,
16298 indicating to the linker the names of the @code{init} (and possibly
16299 @code{final}) procedures for automatic initialization (and finalization).
16300 The built library should be placed in a directory different from
16301 the object directory.
16302
16303 @item
16304 Copy the @code{ALI} files of the interface to the library directory,
16305 add in this copy an indication that it is an interface to a SAL
16306 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16307 with letter ``P'') and make the modified copy of the @file{ALI} file
16308 read-only.
16309 @end itemize
16310
16311 @noindent
16312 Using SALs is not different from using other libraries
16313 (see @ref{Using a library}).
16314
16315 @node Creating a Stand-alone Library to be used in a non-Ada context
16316 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16317
16318 @noindent
16319 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16320 a non-Ada context.
16321
16322 The only extra step required is to ensure that library interface subprograms
16323 are compatible with the main program, by means of @code{pragma Export}
16324 or @code{pragma Convention}.
16325
16326 Here is an example of simple library interface for use with C main program:
16327
16328 @smallexample @c ada
16329 package My_Package is
16330
16331    procedure Do_Something;
16332    pragma Export (C, Do_Something, "do_something");
16333
16334    procedure Do_Something_Else;
16335    pragma Export (C, Do_Something_Else, "do_something_else");
16336
16337 end My_Package;
16338 @end smallexample
16339
16340 @noindent
16341 On the foreign language side, you must provide a ``foreign'' view of the
16342 library interface; remember that it should contain elaboration routines in
16343 addition to interface subprograms.
16344
16345 The example below shows the content of @code{mylib_interface.h} (note
16346 that there is no rule for the naming of this file, any name can be used)
16347 @smallexample
16348 /* the library elaboration procedure */
16349 extern void mylibinit (void);
16350
16351 /* the library finalization procedure */
16352 extern void mylibfinal (void);
16353
16354 /* the interface exported by the library */
16355 extern void do_something (void);
16356 extern void do_something_else (void);
16357 @end smallexample
16358
16359 @noindent
16360 Libraries built as explained above can be used from any program, provided
16361 that the elaboration procedures (named @code{mylibinit} in the previous
16362 example) are called before the library services are used. Any number of
16363 libraries can be used simultaneously, as long as the elaboration
16364 procedure of each library is called.
16365
16366 Below is an example of a C program that uses the @code{mylib} library.
16367
16368 @smallexample
16369 #include "mylib_interface.h"
16370
16371 int
16372 main (void)
16373 @{
16374    /* First, elaborate the library before using it */
16375    mylibinit ();
16376
16377    /* Main program, using the library exported entities */
16378    do_something ();
16379    do_something_else ();
16380
16381    /* Library finalization at the end of the program */
16382    mylibfinal ();
16383    return 0;
16384 @}
16385 @end smallexample
16386
16387 @noindent
16388 Note that invoking any library finalization procedure generated by
16389 @code{gnatbind} shuts down the Ada run-time environment.
16390 Consequently, the
16391 finalization of all Ada libraries must be performed at the end of the program.
16392 No call to these libraries or to the Ada run-time library should be made
16393 after the finalization phase.
16394
16395 @node Restrictions in Stand-alone Libraries
16396 @subsection Restrictions in Stand-alone Libraries
16397
16398 @noindent
16399 The pragmas listed below should be used with caution inside libraries,
16400 as they can create incompatibilities with other Ada libraries:
16401 @itemize @bullet
16402 @item pragma @code{Locking_Policy}
16403 @item pragma @code{Queuing_Policy}
16404 @item pragma @code{Task_Dispatching_Policy}
16405 @item pragma @code{Unreserve_All_Interrupts}
16406 @end itemize
16407
16408 @noindent
16409 When using a library that contains such pragmas, the user must make sure
16410 that all libraries use the same pragmas with the same values. Otherwise,
16411 @code{Program_Error} will
16412 be raised during the elaboration of the conflicting
16413 libraries. The usage of these pragmas and its consequences for the user
16414 should therefore be well documented.
16415
16416 Similarly, the traceback in the exception occurrence mechanism should be
16417 enabled or disabled in a consistent manner across all libraries.
16418 Otherwise, Program_Error will be raised during the elaboration of the
16419 conflicting libraries.
16420
16421 If the @code{Version} or @code{Body_Version}
16422 attributes are used inside a library, then you need to
16423 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16424 libraries, so that version identifiers can be properly computed.
16425 In practice these attributes are rarely used, so this is unlikely
16426 to be a consideration.
16427
16428 @node  Rebuilding the GNAT Run-Time Library
16429 @section Rebuilding the GNAT Run-Time Library
16430 @cindex GNAT Run-Time Library, rebuilding
16431 @cindex Building the GNAT Run-Time Library
16432 @cindex Rebuilding the GNAT Run-Time Library
16433 @cindex Run-Time Library, rebuilding
16434
16435 @noindent
16436 It may be useful to recompile the GNAT library in various contexts, the
16437 most important one being the use of partition-wide configuration pragmas
16438 such as @code{Normalize_Scalars}. A special Makefile called
16439 @code{Makefile.adalib} is provided to that effect and can be found in
16440 the directory containing the GNAT library. The location of this
16441 directory depends on the way the GNAT environment has been installed and can
16442 be determined by means of the command:
16443
16444 @smallexample
16445 $ gnatls -v
16446 @end smallexample
16447
16448 @noindent
16449 The last entry in the object search path usually contains the
16450 gnat library. This Makefile contains its own documentation and in
16451 particular the set of instructions needed to rebuild a new library and
16452 to use it.
16453
16454 @node Using the GNU make Utility
16455 @chapter Using the GNU @code{make} Utility
16456 @findex make
16457
16458 @noindent
16459 This chapter offers some examples of makefiles that solve specific
16460 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16461 make, make, GNU @code{make}}), nor does it try to replace the
16462 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16463
16464 All the examples in this section are specific to the GNU version of
16465 make. Although @command{make} is a standard utility, and the basic language
16466 is the same, these examples use some advanced features found only in
16467 @code{GNU make}.
16468
16469 @menu
16470 * Using gnatmake in a Makefile::
16471 * Automatically Creating a List of Directories::
16472 * Generating the Command Line Switches::
16473 * Overcoming Command Line Length Limits::
16474 @end menu
16475
16476 @node Using gnatmake in a Makefile
16477 @section Using gnatmake in a Makefile
16478 @findex makefile
16479 @cindex GNU make
16480
16481 @noindent
16482 Complex project organizations can be handled in a very powerful way by
16483 using GNU make combined with gnatmake. For instance, here is a Makefile
16484 which allows you to build each subsystem of a big project into a separate
16485 shared library. Such a makefile allows you to significantly reduce the link
16486 time of very big applications while maintaining full coherence at
16487 each step of the build process.
16488
16489 The list of dependencies are handled automatically by
16490 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16491 the appropriate directories.
16492
16493 Note that you should also read the example on how to automatically
16494 create the list of directories
16495 (@pxref{Automatically Creating a List of Directories})
16496 which might help you in case your project has a lot of subdirectories.
16497
16498 @smallexample
16499 @iftex
16500 @leftskip=0cm
16501 @font@heightrm=cmr8
16502 @heightrm
16503 @end iftex
16504 ## This Makefile is intended to be used with the following directory
16505 ## configuration:
16506 ##  - The sources are split into a series of csc (computer software components)
16507 ##    Each of these csc is put in its own directory.
16508 ##    Their name are referenced by the directory names.
16509 ##    They will be compiled into shared library (although this would also work
16510 ##    with static libraries
16511 ##  - The main program (and possibly other packages that do not belong to any
16512 ##    csc is put in the top level directory (where the Makefile is).
16513 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16514 ##                    \_ second_csc (sources) __ lib (will contain the library)
16515 ##                    \_ @dots{}
16516 ## Although this Makefile is build for shared library, it is easy to modify
16517 ## to build partial link objects instead (modify the lines with -shared and
16518 ## gnatlink below)
16519 ##
16520 ## With this makefile, you can change any file in the system or add any new
16521 ## file, and everything will be recompiled correctly (only the relevant shared
16522 ## objects will be recompiled, and the main program will be re-linked).
16523
16524 # The list of computer software component for your project. This might be
16525 # generated automatically.
16526 CSC_LIST=aa bb cc
16527
16528 # Name of the main program (no extension)
16529 MAIN=main
16530
16531 # If we need to build objects with -fPIC, uncomment the following line
16532 #NEED_FPIC=-fPIC
16533
16534 # The following variable should give the directory containing libgnat.so
16535 # You can get this directory through 'gnatls -v'. This is usually the last
16536 # directory in the Object_Path.
16537 GLIB=@dots{}
16538
16539 # The directories for the libraries
16540 # (This macro expands the list of CSC to the list of shared libraries, you
16541 # could simply use the expanded form:
16542 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16543 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16544
16545 $@{MAIN@}: objects $@{LIB_DIR@}
16546     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16547     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16548
16549 objects::
16550     # recompile the sources
16551     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16552
16553 # Note: In a future version of GNAT, the following commands will be simplified
16554 # by a new tool, gnatmlib
16555 $@{LIB_DIR@}:
16556     mkdir -p $@{dir $@@ @}
16557     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16558     cd $@{dir $@@ @} && cp -f ../*.ali .
16559
16560 # The dependencies for the modules
16561 # Note that we have to force the expansion of *.o, since in some cases
16562 # make won't be able to do it itself.
16563 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16564 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16565 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16566
16567 # Make sure all of the shared libraries are in the path before starting the
16568 # program
16569 run::
16570     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16571
16572 clean::
16573     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16574     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16575     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16576     $@{RM@} *.o *.ali $@{MAIN@}
16577 @end smallexample
16578
16579 @node Automatically Creating a List of Directories
16580 @section Automatically Creating a List of Directories
16581
16582 @noindent
16583 In most makefiles, you will have to specify a list of directories, and
16584 store it in a variable. For small projects, it is often easier to
16585 specify each of them by hand, since you then have full control over what
16586 is the proper order for these directories, which ones should be
16587 included.
16588
16589 However, in larger projects, which might involve hundreds of
16590 subdirectories, it might be more convenient to generate this list
16591 automatically.
16592
16593 The example below presents two methods. The first one, although less
16594 general, gives you more control over the list. It involves wildcard
16595 characters, that are automatically expanded by @command{make}. Its
16596 shortcoming is that you need to explicitly specify some of the
16597 organization of your project, such as for instance the directory tree
16598 depth, whether some directories are found in a separate tree, @enddots{}
16599
16600 The second method is the most general one. It requires an external
16601 program, called @command{find}, which is standard on all Unix systems. All
16602 the directories found under a given root directory will be added to the
16603 list.
16604
16605 @smallexample
16606 @iftex
16607 @leftskip=0cm
16608 @font@heightrm=cmr8
16609 @heightrm
16610 @end iftex
16611 # The examples below are based on the following directory hierarchy:
16612 # All the directories can contain any number of files
16613 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16614 #                       ->  ab
16615 #                       ->  ac
16616 #                ->  b  ->  ba  ->  baa
16617 #                       ->  bb
16618 #                       ->  bc
16619 # This Makefile creates a variable called DIRS, that can be reused any time
16620 # you need this list (see the other examples in this section)
16621
16622 # The root of your project's directory hierarchy
16623 ROOT_DIRECTORY=.
16624
16625 ####
16626 # First method: specify explicitly the list of directories
16627 # This allows you to specify any subset of all the directories you need.
16628 ####
16629
16630 DIRS := a/aa/ a/ab/ b/ba/
16631
16632 ####
16633 # Second method: use wildcards
16634 # Note that the argument(s) to wildcard below should end with a '/'.
16635 # Since wildcards also return file names, we have to filter them out
16636 # to avoid duplicate directory names.
16637 # We thus use make's @code{dir} and @code{sort} functions.
16638 # It sets DIRs to the following value (note that the directories aaa and baa
16639 # are not given, unless you change the arguments to wildcard).
16640 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16641 ####
16642
16643 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16644                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16645
16646 ####
16647 # Third method: use an external program
16648 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16649 # This is the most complete command: it sets DIRs to the following value:
16650 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16651 ####
16652
16653 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16654
16655 @end smallexample
16656
16657 @node Generating the Command Line Switches
16658 @section Generating the Command Line Switches
16659
16660 @noindent
16661 Once you have created the list of directories as explained in the
16662 previous section (@pxref{Automatically Creating a List of Directories}),
16663 you can easily generate the command line arguments to pass to gnatmake.
16664
16665 For the sake of completeness, this example assumes that the source path
16666 is not the same as the object path, and that you have two separate lists
16667 of directories.
16668
16669 @smallexample
16670 # see "Automatically creating a list of directories" to create
16671 # these variables
16672 SOURCE_DIRS=
16673 OBJECT_DIRS=
16674
16675 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16676 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16677
16678 all:
16679         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16680 @end smallexample
16681
16682 @node Overcoming Command Line Length Limits
16683 @section Overcoming Command Line Length Limits
16684
16685 @noindent
16686 One problem that might be encountered on big projects is that many
16687 operating systems limit the length of the command line. It is thus hard to give
16688 gnatmake the list of source and object directories.
16689
16690 This example shows how you can set up environment variables, which will
16691 make @command{gnatmake} behave exactly as if the directories had been
16692 specified on the command line, but have a much higher length limit (or
16693 even none on most systems).
16694
16695 It assumes that you have created a list of directories in your Makefile,
16696 using one of the methods presented in
16697 @ref{Automatically Creating a List of Directories}.
16698 For the sake of completeness, we assume that the object
16699 path (where the ALI files are found) is different from the sources patch.
16700
16701 Note a small trick in the Makefile below: for efficiency reasons, we
16702 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16703 expanded immediately by @code{make}. This way we overcome the standard
16704 make behavior which is to expand the variables only when they are
16705 actually used.
16706
16707 On Windows, if you are using the standard Windows command shell, you must
16708 replace colons with semicolons in the assignments to these variables.
16709
16710 @smallexample
16711 @iftex
16712 @leftskip=0cm
16713 @font@heightrm=cmr8
16714 @heightrm
16715 @end iftex
16716 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16717 # This is the same thing as putting the -I arguments on the command line.
16718 # (the equivalent of using -aI on the command line would be to define
16719 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16720 # You can of course have different values for these variables.
16721 #
16722 # Note also that we need to keep the previous values of these variables, since
16723 # they might have been set before running 'make' to specify where the GNAT
16724 # library is installed.
16725
16726 # see "Automatically creating a list of directories" to create these
16727 # variables
16728 SOURCE_DIRS=
16729 OBJECT_DIRS=
16730
16731 empty:=
16732 space:=$@{empty@} $@{empty@}
16733 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16734 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16735 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16736 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16737 export ADA_INCLUDE_PATH
16738 export ADA_OBJECTS_PATH
16739
16740 all:
16741         gnatmake main_unit
16742 @end smallexample
16743 @end ifclear
16744
16745 @node Memory Management Issues
16746 @chapter Memory Management Issues
16747
16748 @noindent
16749 This chapter describes some useful memory pools provided in the GNAT library
16750 and in particular the GNAT Debug Pool facility, which can be used to detect
16751 incorrect uses of access values (including ``dangling references'').
16752 @ifclear vms
16753 It also describes the @command{gnatmem} tool, which can be used to track down
16754 ``memory leaks''.
16755 @end ifclear
16756
16757 @menu
16758 * Some Useful Memory Pools::
16759 * The GNAT Debug Pool Facility::
16760 @ifclear vms
16761 * The gnatmem Tool::
16762 @end ifclear
16763 @end menu
16764
16765 @node Some Useful Memory Pools
16766 @section Some Useful Memory Pools
16767 @findex Memory Pool
16768 @cindex storage, pool
16769
16770 @noindent
16771 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16772 storage pool. Allocations use the standard system call @code{malloc} while
16773 deallocations use the standard system call @code{free}. No reclamation is
16774 performed when the pool goes out of scope. For performance reasons, the
16775 standard default Ada allocators/deallocators do not use any explicit storage
16776 pools but if they did, they could use this storage pool without any change in
16777 behavior. That is why this storage pool is used  when the user
16778 manages to make the default implicit allocator explicit as in this example:
16779 @smallexample @c ada
16780    type T1 is access Something;
16781     -- no Storage pool is defined for T2
16782    type T2 is access Something_Else;
16783    for T2'Storage_Pool use T1'Storage_Pool;
16784    -- the above is equivalent to
16785    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16786 @end smallexample
16787
16788 @noindent
16789 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16790 pool. The allocation strategy is similar to @code{Pool_Local}'s
16791 except that the all
16792 storage allocated with this pool is reclaimed when the pool object goes out of
16793 scope. This pool provides a explicit mechanism similar to the implicit one
16794 provided by several Ada 83 compilers for allocations performed through a local
16795 access type and whose purpose was to reclaim memory when exiting the
16796 scope of a given local access. As an example, the following program does not
16797 leak memory even though it does not perform explicit deallocation:
16798
16799 @smallexample @c ada
16800 with System.Pool_Local;
16801 procedure Pooloc1 is
16802    procedure Internal is
16803       type A is access Integer;
16804       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16805       for A'Storage_Pool use X;
16806       v : A;
16807    begin
16808       for I in  1 .. 50 loop
16809          v := new Integer;
16810       end loop;
16811    end Internal;
16812 begin
16813    for I in  1 .. 100 loop
16814       Internal;
16815    end loop;
16816 end Pooloc1;
16817 @end smallexample
16818
16819 @noindent
16820 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16821 @code{Storage_Size} is specified for an access type.
16822 The whole storage for the pool is
16823 allocated at once, usually on the stack at the point where the access type is
16824 elaborated. It is automatically reclaimed when exiting the scope where the
16825 access type is defined. This package is not intended to be used directly by the
16826 user and it is implicitly used for each such declaration:
16827
16828 @smallexample @c ada
16829    type T1 is access Something;
16830    for T1'Storage_Size use 10_000;
16831 @end smallexample
16832
16833 @node The GNAT Debug Pool Facility
16834 @section The GNAT Debug Pool Facility
16835 @findex Debug Pool
16836 @cindex storage, pool, memory corruption
16837
16838 @noindent
16839 The use of unchecked deallocation and unchecked conversion can easily
16840 lead to incorrect memory references. The problems generated by such
16841 references are usually difficult to tackle because the symptoms can be
16842 very remote from the origin of the problem. In such cases, it is
16843 very helpful to detect the problem as early as possible. This is the
16844 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16845
16846 In order to use the GNAT specific debugging pool, the user must
16847 associate a debug pool object with each of the access types that may be
16848 related to suspected memory problems. See Ada Reference Manual 13.11.
16849 @smallexample @c ada
16850 type Ptr is access Some_Type;
16851 Pool : GNAT.Debug_Pools.Debug_Pool;
16852 for Ptr'Storage_Pool use Pool;
16853 @end smallexample
16854
16855 @noindent
16856 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16857 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16858 allow the user to redefine allocation and deallocation strategies. They
16859 also provide a checkpoint for each dereference, through the use of
16860 the primitive operation @code{Dereference} which is implicitly called at
16861 each dereference of an access value.
16862
16863 Once an access type has been associated with a debug pool, operations on
16864 values of the type may raise four distinct exceptions,
16865 which correspond to four potential kinds of memory corruption:
16866 @itemize @bullet
16867 @item
16868 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16869 @item
16870 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16871 @item
16872 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16873 @item
16874 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16875 @end itemize
16876
16877 @noindent
16878 For types associated with a Debug_Pool, dynamic allocation is performed using
16879 the standard GNAT allocation routine. References to all allocated chunks of
16880 memory are kept in an internal dictionary. Several deallocation strategies are
16881 provided, whereupon the user can choose to release the memory to the system,
16882 keep it allocated for further invalid access checks, or fill it with an easily
16883 recognizable pattern for debug sessions. The memory pattern is the old IBM
16884 hexadecimal convention: @code{16#DEADBEEF#}.
16885
16886 See the documentation in the file g-debpoo.ads for more information on the
16887 various strategies.
16888
16889 Upon each dereference, a check is made that the access value denotes a
16890 properly allocated memory location. Here is a complete example of use of
16891 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16892 @smallexample @c ada
16893 @iftex
16894 @leftskip=0cm
16895 @end iftex
16896 with Gnat.Io; use Gnat.Io;
16897 with Unchecked_Deallocation;
16898 with Unchecked_Conversion;
16899 with GNAT.Debug_Pools;
16900 with System.Storage_Elements;
16901 with Ada.Exceptions; use Ada.Exceptions;
16902 procedure Debug_Pool_Test is
16903
16904    type T is access Integer;
16905    type U is access all T;
16906
16907    P : GNAT.Debug_Pools.Debug_Pool;
16908    for T'Storage_Pool use P;
16909
16910    procedure Free is new Unchecked_Deallocation (Integer, T);
16911    function UC is new Unchecked_Conversion (U, T);
16912    A, B : aliased T;
16913
16914    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16915
16916 begin
16917    Info (P);
16918    A := new Integer;
16919    B := new Integer;
16920    B := A;
16921    Info (P);
16922    Free (A);
16923    begin
16924       Put_Line (Integer'Image(B.all));
16925    exception
16926       when E : others => Put_Line ("raised: " & Exception_Name (E));
16927    end;
16928    begin
16929       Free (B);
16930    exception
16931       when E : others => Put_Line ("raised: " & Exception_Name (E));
16932    end;
16933    B := UC(A'Access);
16934    begin
16935       Put_Line (Integer'Image(B.all));
16936    exception
16937       when E : others => Put_Line ("raised: " & Exception_Name (E));
16938    end;
16939    begin
16940       Free (B);
16941    exception
16942       when E : others => Put_Line ("raised: " & Exception_Name (E));
16943    end;
16944    Info (P);
16945 end Debug_Pool_Test;
16946 @end smallexample
16947
16948 @noindent
16949 The debug pool mechanism provides the following precise diagnostics on the
16950 execution of this erroneous program:
16951 @smallexample
16952 Debug Pool info:
16953   Total allocated bytes :  0
16954   Total deallocated bytes :  0
16955   Current Water Mark:  0
16956   High Water Mark:  0
16957
16958 Debug Pool info:
16959   Total allocated bytes :  8
16960   Total deallocated bytes :  0
16961   Current Water Mark:  8
16962   High Water Mark:  8
16963
16964 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16965 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16966 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16967 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16968 Debug Pool info:
16969   Total allocated bytes :  8
16970   Total deallocated bytes :  4
16971   Current Water Mark:  4
16972   High Water Mark:  8
16973 @end smallexample
16974
16975 @ifclear vms
16976 @node The gnatmem Tool
16977 @section The @command{gnatmem} Tool
16978 @findex gnatmem
16979
16980 @noindent
16981 The @code{gnatmem} utility monitors dynamic allocation and
16982 deallocation activity in a program, and displays information about
16983 incorrect deallocations and possible sources of memory leaks.
16984 It is designed to work in association with a static runtime library
16985 only and in this context provides three types of information:
16986 @itemize @bullet
16987 @item
16988 General information concerning memory management, such as the total
16989 number of allocations and deallocations, the amount of allocated
16990 memory and the high water mark, i.e.@: the largest amount of allocated
16991 memory in the course of program execution.
16992
16993 @item
16994 Backtraces for all incorrect deallocations, that is to say deallocations
16995 which do not correspond to a valid allocation.
16996
16997 @item
16998 Information on each allocation that is potentially the origin of a memory
16999 leak.
17000 @end itemize
17001
17002 @menu
17003 * Running gnatmem::
17004 * Switches for gnatmem::
17005 * Example of gnatmem Usage::
17006 @end menu
17007
17008 @node Running gnatmem
17009 @subsection Running @code{gnatmem}
17010
17011 @noindent
17012 @code{gnatmem} makes use of the output created by the special version of
17013 allocation and deallocation routines that record call information. This
17014 allows to obtain accurate dynamic memory usage history at a minimal cost to
17015 the execution speed. Note however, that @code{gnatmem} is not supported on
17016 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
17017 Solaris and Windows NT/2000/XP (x86).
17018
17019 @noindent
17020 The @code{gnatmem} command has the form
17021
17022 @smallexample
17023 @c    $ gnatmem @ovar{switches} user_program
17024 @c Expanding @ovar macro inline (explanation in macro def comments)
17025       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
17026 @end smallexample
17027
17028 @noindent
17029 The program must have been linked with the instrumented version of the
17030 allocation and deallocation routines. This is done by linking with the
17031 @file{libgmem.a} library. For correct symbolic backtrace information,
17032 the user program should be compiled with debugging options
17033 (see @ref{Switches for gcc}). For example to build @file{my_program}:
17034
17035 @smallexample
17036 $ gnatmake -g my_program -largs -lgmem
17037 @end smallexample
17038
17039 @noindent
17040 As library @file{libgmem.a} contains an alternate body for package
17041 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
17042 when an executable is linked with library @file{libgmem.a}. It is then not
17043 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
17044
17045 @noindent
17046 When @file{my_program} is executed, the file @file{gmem.out} is produced.
17047 This file contains information about all allocations and deallocations
17048 performed by the program. It is produced by the instrumented allocations and
17049 deallocations routines and will be used by @code{gnatmem}.
17050
17051 In order to produce symbolic backtrace information for allocations and
17052 deallocations performed by the GNAT run-time library, you need to use a
17053 version of that library that has been compiled with the @option{-g} switch
17054 (see @ref{Rebuilding the GNAT Run-Time Library}).
17055
17056 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17057 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17058 @option{-i} switch, gnatmem will assume that this file can be found in the
17059 current directory. For example, after you have executed @file{my_program},
17060 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17061
17062 @smallexample
17063 $ gnatmem my_program
17064 @end smallexample
17065
17066 @noindent
17067 This will produce the output with the following format:
17068
17069 *************** debut cc
17070 @smallexample
17071 $ gnatmem my_program
17072
17073 Global information
17074 ------------------
17075    Total number of allocations        :  45
17076    Total number of deallocations      :   6
17077    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17078    High Water Mark                    :  11.40 Kilobytes
17079
17080 .
17081 .
17082 .
17083 Allocation Root # 2
17084 -------------------
17085  Number of non freed allocations    :  11
17086  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17087  High Water Mark                    :   1.27 Kilobytes
17088  Backtrace                          :
17089    my_program.adb:23 my_program.alloc
17090 .
17091 .
17092 .
17093 @end smallexample
17094
17095 The first block of output gives general information. In this case, the
17096 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17097 Unchecked_Deallocation routine occurred.
17098
17099 @noindent
17100 Subsequent paragraphs display  information on all allocation roots.
17101 An allocation root is a specific point in the execution of the program
17102 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17103 construct. This root is represented by an execution backtrace (or subprogram
17104 call stack). By default the backtrace depth for allocations roots is 1, so
17105 that a root corresponds exactly to a source location. The backtrace can
17106 be made deeper, to make the root more specific.
17107
17108 @node Switches for gnatmem
17109 @subsection Switches for @code{gnatmem}
17110
17111 @noindent
17112 @code{gnatmem} recognizes the following switches:
17113
17114 @table @option
17115
17116 @item -q
17117 @cindex @option{-q} (@code{gnatmem})
17118 Quiet. Gives the minimum output needed to identify the origin of the
17119 memory leaks. Omits statistical information.
17120
17121 @item @var{N}
17122 @cindex @var{N} (@code{gnatmem})
17123 N is an integer literal (usually between 1 and 10) which controls the
17124 depth of the backtraces defining allocation root. The default value for
17125 N is 1. The deeper the backtrace, the more precise the localization of
17126 the root. Note that the total number of roots can depend on this
17127 parameter. This parameter must be specified @emph{before} the name of the
17128 executable to be analyzed, to avoid ambiguity.
17129
17130 @item -b n
17131 @cindex @option{-b} (@code{gnatmem})
17132 This switch has the same effect as just depth parameter.
17133
17134 @item -i @var{file}
17135 @cindex @option{-i} (@code{gnatmem})
17136 Do the @code{gnatmem} processing starting from @file{file}, rather than
17137 @file{gmem.out} in the current directory.
17138
17139 @item -m n
17140 @cindex @option{-m} (@code{gnatmem})
17141 This switch causes @code{gnatmem} to mask the allocation roots that have less
17142 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17143 examine even the roots that didn't result in leaks.
17144
17145 @item -s order
17146 @cindex @option{-s} (@code{gnatmem})
17147 This switch causes @code{gnatmem} to sort the allocation roots according to the
17148 specified order of sort criteria, each identified by a single letter. The
17149 currently supported criteria are @code{n, h, w} standing respectively for
17150 number of unfreed allocations, high watermark, and final watermark
17151 corresponding to a specific root. The default order is @code{nwh}.
17152
17153 @end table
17154
17155 @node Example of gnatmem Usage
17156 @subsection Example of @code{gnatmem} Usage
17157
17158 @noindent
17159 The following example shows the use of @code{gnatmem}
17160 on a simple memory-leaking program.
17161 Suppose that we have the following Ada program:
17162
17163 @smallexample @c ada
17164 @group
17165 @cartouche
17166 with Unchecked_Deallocation;
17167 procedure Test_Gm is
17168
17169    type T is array (1..1000) of Integer;
17170    type Ptr is access T;
17171    procedure Free is new Unchecked_Deallocation (T, Ptr);
17172    A : Ptr;
17173
17174    procedure My_Alloc is
17175    begin
17176       A := new T;
17177    end My_Alloc;
17178
17179    procedure My_DeAlloc is
17180       B : Ptr := A;
17181    begin
17182       Free (B);
17183    end My_DeAlloc;
17184
17185 begin
17186    My_Alloc;
17187    for I in 1 .. 5 loop
17188       for J in I .. 5 loop
17189          My_Alloc;
17190       end loop;
17191       My_Dealloc;
17192    end loop;
17193 end;
17194 @end cartouche
17195 @end group
17196 @end smallexample
17197
17198 @noindent
17199 The program needs to be compiled with debugging option and linked with
17200 @code{gmem} library:
17201
17202 @smallexample
17203 $ gnatmake -g test_gm -largs -lgmem
17204 @end smallexample
17205
17206 @noindent
17207 Then we execute the program as usual:
17208
17209 @smallexample
17210 $ test_gm
17211 @end smallexample
17212
17213 @noindent
17214 Then @code{gnatmem} is invoked simply with
17215 @smallexample
17216 $ gnatmem test_gm
17217 @end smallexample
17218
17219 @noindent
17220 which produces the following output (result may vary on different platforms):
17221
17222 @smallexample
17223 Global information
17224 ------------------
17225    Total number of allocations        :  18
17226    Total number of deallocations      :   5
17227    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17228    High Water Mark                    :  56.90 Kilobytes
17229
17230 Allocation Root # 1
17231 -------------------
17232  Number of non freed allocations    :  11
17233  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17234  High Water Mark                    :  46.88 Kilobytes
17235  Backtrace                          :
17236    test_gm.adb:11 test_gm.my_alloc
17237
17238 Allocation Root # 2
17239 -------------------
17240  Number of non freed allocations    :   1
17241  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17242  High Water Mark                    :  10.02 Kilobytes
17243  Backtrace                          :
17244    s-secsta.adb:81 system.secondary_stack.ss_init
17245
17246 Allocation Root # 3
17247 -------------------
17248  Number of non freed allocations    :   1
17249  Final Water Mark (non freed mem)   :  12 Bytes
17250  High Water Mark                    :  12 Bytes
17251  Backtrace                          :
17252    s-secsta.adb:181 system.secondary_stack.ss_init
17253 @end smallexample
17254
17255 @noindent
17256 Note that the GNAT run time contains itself a certain number of
17257 allocations that have no  corresponding deallocation,
17258 as shown here for root #2 and root
17259 #3. This is a normal behavior when the number of non-freed allocations
17260 is one, it allocates dynamic data structures that the run time needs for
17261 the complete lifetime of the program. Note also that there is only one
17262 allocation root in the user program with a single line back trace:
17263 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17264 program shows that 'My_Alloc' is called at 2 different points in the
17265 source (line 21 and line 24). If those two allocation roots need to be
17266 distinguished, the backtrace depth parameter can be used:
17267
17268 @smallexample
17269 $ gnatmem 3 test_gm
17270 @end smallexample
17271
17272 @noindent
17273 which will give the following output:
17274
17275 @smallexample
17276 Global information
17277 ------------------
17278    Total number of allocations        :  18
17279    Total number of deallocations      :   5
17280    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17281    High Water Mark                    :  56.90 Kilobytes
17282
17283 Allocation Root # 1
17284 -------------------
17285  Number of non freed allocations    :  10
17286  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17287  High Water Mark                    :  42.97 Kilobytes
17288  Backtrace                          :
17289    test_gm.adb:11 test_gm.my_alloc
17290    test_gm.adb:24 test_gm
17291    b_test_gm.c:52 main
17292
17293 Allocation Root # 2
17294 -------------------
17295  Number of non freed allocations    :   1
17296  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17297  High Water Mark                    :  10.02 Kilobytes
17298  Backtrace                          :
17299    s-secsta.adb:81  system.secondary_stack.ss_init
17300    s-secsta.adb:283 <system__secondary_stack___elabb>
17301    b_test_gm.c:33   adainit
17302
17303 Allocation Root # 3
17304 -------------------
17305  Number of non freed allocations    :   1
17306  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17307  High Water Mark                    :   3.91 Kilobytes
17308  Backtrace                          :
17309    test_gm.adb:11 test_gm.my_alloc
17310    test_gm.adb:21 test_gm
17311    b_test_gm.c:52 main
17312
17313 Allocation Root # 4
17314 -------------------
17315  Number of non freed allocations    :   1
17316  Final Water Mark (non freed mem)   :  12 Bytes
17317  High Water Mark                    :  12 Bytes
17318  Backtrace                          :
17319    s-secsta.adb:181 system.secondary_stack.ss_init
17320    s-secsta.adb:283 <system__secondary_stack___elabb>
17321    b_test_gm.c:33   adainit
17322 @end smallexample
17323
17324 @noindent
17325 The allocation root #1 of the first example has been split in 2 roots #1
17326 and #3 thanks to the more precise associated backtrace.
17327
17328 @end ifclear
17329
17330 @node Stack Related Facilities
17331 @chapter Stack Related Facilities
17332
17333 @noindent
17334 This chapter describes some useful tools associated with stack
17335 checking and analysis. In
17336 particular, it deals with dynamic and static stack usage measurements.
17337
17338 @menu
17339 * Stack Overflow Checking::
17340 * Static Stack Usage Analysis::
17341 * Dynamic Stack Usage Analysis::
17342 @end menu
17343
17344 @node Stack Overflow Checking
17345 @section Stack Overflow Checking
17346 @cindex Stack Overflow Checking
17347 @cindex -fstack-check
17348
17349 @noindent
17350 For most operating systems, @command{gcc} does not perform stack overflow
17351 checking by default. This means that if the main environment task or
17352 some other task exceeds the available stack space, then unpredictable
17353 behavior will occur. Most native systems offer some level of protection by
17354 adding a guard page at the end of each task stack. This mechanism is usually
17355 not enough for dealing properly with stack overflow situations because
17356 a large local variable could ``jump'' above the guard page.
17357 Furthermore, when the
17358 guard page is hit, there may not be any space left on the stack for executing
17359 the exception propagation code. Enabling stack checking avoids
17360 such situations.
17361
17362 To activate stack checking, compile all units with the gcc option
17363 @option{-fstack-check}. For example:
17364
17365 @smallexample
17366 gcc -c -fstack-check package1.adb
17367 @end smallexample
17368
17369 @noindent
17370 Units compiled with this option will generate extra instructions to check
17371 that any use of the stack (for procedure calls or for declaring local
17372 variables in declare blocks) does not exceed the available stack space.
17373 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17374
17375 For declared tasks, the stack size is controlled by the size
17376 given in an applicable @code{Storage_Size} pragma or by the value specified
17377 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17378 the default size as defined in the GNAT runtime otherwise.
17379
17380 For the environment task, the stack size depends on
17381 system defaults and is unknown to the compiler. Stack checking
17382 may still work correctly if a fixed
17383 size stack is allocated, but this cannot be guaranteed.
17384 @ifclear vms
17385 To ensure that a clean exception is signalled for stack
17386 overflow, set the environment variable
17387 @env{GNAT_STACK_LIMIT} to indicate the maximum
17388 stack area that can be used, as in:
17389 @cindex GNAT_STACK_LIMIT
17390
17391 @smallexample
17392 SET GNAT_STACK_LIMIT 1600
17393 @end smallexample
17394
17395 @noindent
17396 The limit is given in kilobytes, so the above declaration would
17397 set the stack limit of the environment task to 1.6 megabytes.
17398 Note that the only purpose of this usage is to limit the amount
17399 of stack used by the environment task. If it is necessary to
17400 increase the amount of stack for the environment task, then this
17401 is an operating systems issue, and must be addressed with the
17402 appropriate operating systems commands.
17403 @end ifclear
17404 @ifset vms
17405 To have a fixed size stack in the environment task, the stack must be put
17406 in the P0 address space and its size specified.  Use these switches to
17407 create a p0 image:
17408
17409 @smallexample
17410 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17411 @end smallexample
17412
17413 @noindent
17414 The quotes are required to keep case.  The number after @samp{STACK=} is the
17415 size of the environmental task stack in pagelets (512 bytes).  In this example
17416 the stack size is about 2 megabytes.
17417
17418 @noindent
17419 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17420 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17421 more details about the @option{/p0image} qualifier and the @option{stack}
17422 option.
17423
17424 @noindent
17425 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17426 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17427 stack in kilobytes.  For example:
17428
17429 @smallexample
17430 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17431 @end smallexample
17432 @end ifset
17433
17434 @node Static Stack Usage Analysis
17435 @section Static Stack Usage Analysis
17436 @cindex Static Stack Usage Analysis
17437 @cindex -fstack-usage
17438
17439 @noindent
17440 A unit compiled with @option{-fstack-usage} will generate an extra file
17441 that specifies
17442 the maximum amount of stack used, on a per-function basis.
17443 The file has the same
17444 basename as the target object file with a @file{.su} extension.
17445 Each line of this file is made up of three fields:
17446
17447 @itemize
17448 @item
17449 The name of the function.
17450 @item
17451 A number of bytes.
17452 @item
17453 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17454 @end itemize
17455
17456 The second field corresponds to the size of the known part of the function
17457 frame.
17458
17459 The qualifier @code{static} means that the function frame size
17460 is purely static.
17461 It usually means that all local variables have a static size.
17462 In this case, the second field is a reliable measure of the function stack
17463 utilization.
17464
17465 The qualifier @code{dynamic} means that the function frame size is not static.
17466 It happens mainly when some local variables have a dynamic size. When this
17467 qualifier appears alone, the second field is not a reliable measure
17468 of the function stack analysis. When it is qualified with  @code{bounded}, it
17469 means that the second field is a reliable maximum of the function stack
17470 utilization.
17471
17472 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17473 subprogram whose stack usage might be larger than the specified amount of
17474 bytes.  The wording is in keeping with the qualifier documented above.
17475
17476 @node Dynamic Stack Usage Analysis
17477 @section Dynamic Stack Usage Analysis
17478
17479 @noindent
17480 It is possible to measure the maximum amount of stack used by a task, by
17481 adding a switch to @command{gnatbind}, as:
17482
17483 @smallexample
17484 $ gnatbind -u0 file
17485 @end smallexample
17486
17487 @noindent
17488 With this option, at each task termination, its stack usage is  output on
17489 @file{stderr}.
17490 It is not always convenient to output the stack usage when the program
17491 is still running. Hence, it is possible to delay this output until program
17492 termination. for a given number of tasks specified as the argument of the
17493 @option{-u} option. For instance:
17494
17495 @smallexample
17496 $ gnatbind -u100 file
17497 @end smallexample
17498
17499 @noindent
17500 will buffer the stack usage information of the first 100 tasks to terminate and
17501 output this info at program termination. Results are displayed in four
17502 columns:
17503
17504 @noindent
17505 Index | Task Name | Stack Size | Stack Usage
17506
17507 @noindent
17508 where:
17509
17510 @table @emph
17511 @item Index
17512 is a number associated with each task.
17513
17514 @item Task Name
17515 is the name of the task analyzed.
17516
17517 @item Stack Size
17518 is the maximum size for the stack.
17519
17520 @item Stack Usage
17521 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17522 is not entirely analyzed, and it's not possible to know exactly how
17523 much has actually been used.
17524
17525 @end table
17526
17527 @noindent
17528 The environment task stack, e.g., the stack that contains the main unit, is
17529 only processed when the environment variable GNAT_STACK_LIMIT is set.
17530
17531 @noindent
17532 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17533 stack usage reports at run-time. See its body for the details.
17534
17535 @c *********************************
17536 @c *            GNATCHECK          *
17537 @c *********************************
17538 @node Verifying Properties Using gnatcheck
17539 @chapter Verifying Properties Using @command{gnatcheck}
17540 @findex gnatcheck
17541 @cindex @command{gnatcheck}
17542
17543 @noindent
17544 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17545 of Ada source files according to a given set of semantic rules.
17546 @cindex ASIS
17547
17548 In order to check compliance with a given rule, @command{gnatcheck} has to
17549 semantically analyze the Ada sources.
17550 Therefore, checks can only be performed on
17551 legal Ada units. Moreover, when a unit depends semantically upon units located
17552 outside the current directory, the source search path has to be provided when
17553 calling @command{gnatcheck}, either through a specified project file or
17554 through @command{gnatcheck} switches.
17555
17556 For full details, refer to @cite{GNATcheck Reference Manual} document.
17557
17558
17559 @c *********************************
17560 @node Creating Sample Bodies Using gnatstub
17561 @chapter Creating Sample Bodies Using @command{gnatstub}
17562 @findex gnatstub
17563
17564 @noindent
17565 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17566 for library unit declarations.
17567
17568 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17569 driver (see @ref{The GNAT Driver and Project Files}).
17570
17571 To create a body stub, @command{gnatstub} has to compile the library
17572 unit declaration. Therefore, bodies can be created only for legal
17573 library units. Moreover, if a library unit depends semantically upon
17574 units located outside the current directory, you have to provide
17575 the source search path when calling @command{gnatstub}, see the description
17576 of @command{gnatstub} switches below.
17577
17578 By default, all the program unit body stubs generated by @code{gnatstub}
17579 raise the predefined @code{Program_Error} exception, which will catch
17580 accidental calls of generated stubs. This behavior can be changed with
17581 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17582
17583 @menu
17584 * Running gnatstub::
17585 * Switches for gnatstub::
17586 @end menu
17587
17588 @node Running gnatstub
17589 @section Running @command{gnatstub}
17590
17591 @noindent
17592 @command{gnatstub} has a command-line interface of the form:
17593
17594 @smallexample
17595 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17596 @c Expanding @ovar macro inline (explanation in macro def comments)
17597 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17598 @end smallexample
17599
17600 @noindent
17601 where
17602 @table @var
17603 @item filename
17604 is the name of the source file that contains a library unit declaration
17605 for which a body must be created. The file name may contain the path
17606 information.
17607 The file name does not have to follow the GNAT file name conventions. If the
17608 name
17609 does not follow GNAT file naming conventions, the name of the body file must
17610 be provided
17611 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17612 If the file name follows the GNAT file naming
17613 conventions and the name of the body file is not provided,
17614 @command{gnatstub}
17615 creates the name
17616 of the body file from the argument file name by replacing the @file{.ads}
17617 suffix
17618 with the @file{.adb} suffix.
17619
17620 @item directory
17621 indicates the directory in which the body stub is to be placed (the default
17622 is the
17623 current directory)
17624
17625 @item @samp{@var{gcc_switches}} is a list of switches for
17626 @command{gcc}. They will be passed on to all compiler invocations made by
17627 @command{gnatstub} to generate the ASIS trees. Here you can provide
17628 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17629 use the @option{-gnatec} switch to set the configuration file,
17630 use the @option{-gnat05} switch if sources should be compiled in
17631 Ada 2005 mode etc.
17632
17633 @item switches
17634 is an optional sequence of switches as described in the next section
17635 @end table
17636
17637 @node Switches for gnatstub
17638 @section Switches for @command{gnatstub}
17639
17640 @table @option
17641 @c !sort!
17642
17643 @item ^-f^/FULL^
17644 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17645 If the destination directory already contains a file with the name of the
17646 body file
17647 for the argument spec file, replace it with the generated body stub.
17648
17649 @item ^-hs^/HEADER=SPEC^
17650 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17651 Put the comment header (i.e., all the comments preceding the
17652 compilation unit) from the source of the library unit declaration
17653 into the body stub.
17654
17655 @item ^-hg^/HEADER=GENERAL^
17656 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17657 Put a sample comment header into the body stub.
17658
17659 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17660 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17661 Use the content of the file as the comment header for a generated body stub.
17662
17663 @ifclear vms
17664 @item -IDIR
17665 @cindex @option{-IDIR} (@command{gnatstub})
17666 @itemx -I-
17667 @cindex @option{-I-} (@command{gnatstub})
17668 @end ifclear
17669 @ifset vms
17670 @item /NOCURRENT_DIRECTORY
17671 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17672 @end ifset
17673 ^These switches have ^This switch has^ the same meaning as in calls to
17674 @command{gcc}.
17675 ^They define ^It defines ^ the source search path in the call to
17676 @command{gcc} issued
17677 by @command{gnatstub} to compile an argument source file.
17678
17679 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17680 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17681 This switch has the same meaning as in calls to @command{gcc}.
17682 It defines the additional configuration file to be passed to the call to
17683 @command{gcc} issued
17684 by @command{gnatstub} to compile an argument source file.
17685
17686 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17687 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17688 (@var{n} is a non-negative integer). Set the maximum line length in the
17689 body stub to @var{n}; the default is 79. The maximum value that can be
17690 specified is 32767. Note that in the special case of configuration
17691 pragma files, the maximum is always 32767 regardless of whether or
17692 not this switch appears.
17693
17694 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17695 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17696 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17697 the generated body sample to @var{n}.
17698 The default indentation is 3.
17699
17700 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17701 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17702 Order local bodies alphabetically. (By default local bodies are ordered
17703 in the same way as the corresponding local specs in the argument spec file.)
17704
17705 @item ^-i^/INDENTATION=^@var{n}
17706 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17707 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17708
17709 @item ^-k^/TREE_FILE=SAVE^
17710 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17711 Do not remove the tree file (i.e., the snapshot of the compiler internal
17712 structures used by @command{gnatstub}) after creating the body stub.
17713
17714 @item ^-l^/LINE_LENGTH=^@var{n}
17715 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17716 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17717
17718 @item ^--no-exception^/NO_EXCEPTION^
17719 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17720 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17721 This is not always possible for function stubs.
17722
17723 @item ^--no-local-header^/NO_LOCAL_HEADER^
17724 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17725 Do not place local comment header with unit name before body stub for a
17726 unit.
17727
17728 @item ^-o ^/BODY=^@var{body-name}
17729 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17730 Body file name.  This should be set if the argument file name does not
17731 follow
17732 the GNAT file naming
17733 conventions. If this switch is omitted the default name for the body will be
17734 obtained
17735 from the argument file name according to the GNAT file naming conventions.
17736
17737 @item ^-q^/QUIET^
17738 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17739 Quiet mode: do not generate a confirmation when a body is
17740 successfully created, and do not generate a message when a body is not
17741 required for an
17742 argument unit.
17743
17744 @item ^-r^/TREE_FILE=REUSE^
17745 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17746 Reuse the tree file (if it exists) instead of creating it.  Instead of
17747 creating the tree file for the library unit declaration, @command{gnatstub}
17748 tries to find it in the current directory and use it for creating
17749 a body. If the tree file is not found, no body is created. This option
17750 also implies @option{^-k^/SAVE^}, whether or not
17751 the latter is set explicitly.
17752
17753 @item ^-t^/TREE_FILE=OVERWRITE^
17754 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17755 Overwrite the existing tree file.  If the current directory already
17756 contains the file which, according to the GNAT file naming rules should
17757 be considered as a tree file for the argument source file,
17758 @command{gnatstub}
17759 will refuse to create the tree file needed to create a sample body
17760 unless this option is set.
17761
17762 @item ^-v^/VERBOSE^
17763 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17764 Verbose mode: generate version information.
17765
17766 @end table
17767
17768 @c *********************************
17769 @node Creating Unit Tests Using gnattest
17770 @chapter Creating Unit Tests Using @command{gnattest}
17771 @findex gnattest
17772
17773 @noindent
17774 @command{gnattest} is an ASIS-based utility that creates unit-test stubs
17775 as well as a test driver infrastructure (harness). @command{gnattest} creates
17776 a stub for each visible subprogram in the packages under consideration when
17777 they do not exist already.
17778
17779 In order to process source files from a project, @command{gnattest} has to
17780 semantically analyze the sources. Therefore, test stubs can only be
17781 generated for legal Ada units. If a unit is dependent on other units,
17782 those units should be among the source files of the project or of other projects
17783 imported by this one.
17784
17785 Generated stubs and harnesses are based on the AUnit testing framework. AUnit is
17786 an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit for Java
17787 or CppUnit for C++. While it is advised that gnattest users read the AUnit
17788 manual, deep knowledge of AUnit is not necessary for using gnattest. For correct
17789 operation of @command{gnattest}, AUnit should be installed and aunit.gpr must be
17790 on the project path. This happens automatically when Aunit is installed at its
17791 default location.
17792 @menu
17793 * Running gnattest::
17794 * Switches for gnattest::
17795 * Project Attributes for gnattest::
17796 * Simple Example::
17797 * Setting Up and Tearing Down the Testing Environment::
17798 * Regenerating Tests::
17799 * Default Test Behavior::
17800 * Testing Primitive Operations of Tagged Types::
17801 * Testing Inheritance::
17802 * Tagged Types Substitutability Testing::
17803 * Testing with Contracts::
17804 * Additional Tests::
17805 * Current Limitations::
17806 @end menu
17807
17808 @node Running gnattest
17809 @section Running @command{gnattest}
17810
17811 @noindent
17812 @command{gnattest} has a command-line interface of the form
17813
17814 @smallexample
17815 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17816 @c Expanding @ovar macro inline (explanation in macro def comments)
17817 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17818 @end smallexample
17819
17820 @noindent
17821 where
17822 @table @var
17823
17824 @item -Pprojname
17825 specifies the project defining the location of source files. When no
17826 file names are provided on the command line, all sources in the project
17827 are used as input. This switch is required.
17828
17829 @item --harness-dir=dirname
17830 specifies the directory that will hold the harness packages and project file
17831 for the test driver. The harness directory should be specified either by that
17832 switch or by the corresponding attribute in the project file.
17833
17834 @item filename
17835 is the name of the source file containing the library unit package declaration
17836 for which a test package will be created. The file name may given with a path.
17837
17838 @item @samp{@var{gcc_switches}} is a list of switches for
17839 @command{gcc}. These switches will be passed on to all compiler invocations
17840 made by @command{gnatstub} to generate a set of ASIS trees. Here you can provide
17841 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17842 use the @option{-gnatec} switch to set the configuration file,
17843 use the @option{-gnat05} switch if sources should be compiled in
17844 Ada 2005 mode, etc.
17845
17846 @item switches
17847 is an optional sequence of switches as described in the next section.
17848
17849 @end table
17850
17851 @command{gnattest} results can be found in two different places.
17852
17853 @itemize @bullet
17854 @item automatic harness
17855 the harness code, which is located either in the harness-dir as specified on
17856 the command line or in the project file. All of this code is generated
17857 completely automatically and can be destroyed and regenerated at will. It is not
17858 recommended to modify this code manually, since it could easily be overridden
17859 by mistake. The entry point in the harness code is the project file named
17860 @command{test_driver.gpr}. Tests can be compiled and run using a command
17861 such as:
17862
17863 @smallexample
17864 gnatmake -P<harness-dir>/test_driver
17865 test_runner
17866 @end smallexample
17867
17868 @item actual unit test stubs
17869 a test stub for each visible subprogram is created in a separate file, if it
17870 doesn't exist already. By default, those separate test files are located in a
17871 "tests" directory that is created in the directory containing the source file
17872 itself. If it is not appropriate to create the tests in subdirectories of the
17873 source, option @option{--separate-root} can be used. For example, if a source
17874 file my_unit.ads in directory src contains a visible subprogram Proc, then
17875 the corresponding unit test will be found in file
17876 src/tests/my_unit-tests-proc_<code>.adb. <code> is a signature encoding used to
17877 differentiate test names in cases of overloading.
17878 @end itemize
17879
17880 @node Switches for gnattest
17881 @section Switches for @command{gnattest}
17882
17883 @table @option
17884 @c !sort!
17885
17886 @item --harness-only
17887 @cindex @option{--harness-only} (@command{gnattest})
17888 When this option is given, @command{gnattest} creates a harness for all
17889 sources, treating them as test packages.
17890
17891 @item --additional-tests=@var{projname}
17892 @cindex @option{--additional-tests} (@command{gnattest})
17893 Sources described in @var{projname} are considered potential additional
17894 manual tests to be added to the test suite.
17895
17896 @item -r
17897 @cindex @option{-r} (@command{gnattest})
17898 Recursively consider all sources from all projects.
17899
17900 @item -q
17901 @cindex @option{-q} (@command{gnattest})
17902 Suppresses noncritical output messages.
17903
17904 @item -v
17905 @cindex @option{-v} (@command{gnattest})
17906 Verbose mode: generates version information.
17907
17908 @item --liskov
17909 @cindex @option{--liskov} (@command{gnattest})
17910 Enables Liskov verification: run all tests from all parents in order
17911 to check substitutability.
17912
17913 @item --stub-default=@var{val}
17914 @cindex @option{--stub-default} (@command{gnattest})
17915 Specifies the default behavior of generated stubs. @var{val} can be either
17916 "fail" or "pass", "fail" being the default.
17917
17918 @item --separate-root=@var{dirname}
17919 @cindex @option{--separate-root} (@command{gnattest})
17920 The directory hierarchy of tested sources is recreated in the @var{dirname}
17921 directory, and test packages are placed in corresponding directories.
17922
17923 @item --subdir=@var{dirname}
17924 @cindex @option{--subdir} (@command{gnattest})
17925 Test packages are placed in subdirectories. This is the default output mode
17926 since it does not require any additional input from the user. Subdirectories
17927 named "tests" will be created by default.
17928
17929 @end table
17930
17931 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
17932
17933 @node Project Attributes for gnattest
17934 @section Project Attributes for @command{gnattest}
17935
17936 @noindent
17937
17938 Most of the command-line options can also be passed to the tool by adding
17939 special attributes to the project file. Those attributes should be put in
17940 package gnattest. Here is the list of attributes:
17941
17942 @itemize @bullet
17943
17944 @item Separate_Stub_Root
17945 is used to select the same output mode as with the --separate-root option.
17946 This attribute cannot be used together with Stub_Subdir.
17947
17948 @item Stub_Subdir
17949 is used to select the same output mode as with the --subdir option.
17950 This attribute cannot be used together with Separate_Stub_Root.
17951
17952 @item Harness_Dir
17953 is used to specify the directory in which to place harness packages and project
17954 file for the test driver, otherwise specified by --harness-dir.
17955
17956 @item Additional_Tests
17957 is used to specify the project file, otherwise given by
17958 --additional-tests switch.
17959
17960 @item Stubs_Default
17961 is used to specify the default behaviour of test stubs, otherwise
17962 specified by --stub-default option. The value of this attribute
17963 should be either "pass" or "fail".
17964
17965 @end itemize
17966
17967 Each of those attributes can be overridden from the command line if needed.
17968 Other @command{gnattest} switches can also be passed via the project
17969 file as an attribute list called GNATtest_Switches.
17970
17971 @node Simple Example
17972 @section Simple Example
17973
17974 @noindent
17975
17976 Let's take a very simple example using the first @command{gnattest} example
17977 located in:
17978
17979 @smallexample
17980 <install_prefix>/share/examples/gnattest/simple
17981 @end smallexample
17982
17983 This project contains a simple package containing one subprogram. By running gnattest:
17984
17985 @smallexample
17986 $ gnattest --harness-dir=driver -Psimple.gpr
17987 @end smallexample
17988
17989 a test driver is created in directory "driver". It can be compiled and run:
17990
17991 @smallexample
17992 $ cd driver
17993 $ gprbuild -Ptest_driver
17994 $ test_runner
17995 @end smallexample
17996
17997 One failed test with diagnosis "test not implemented" is reported.
17998 Since no special output option was specified, the test package Simple.Tests
17999 is located in:
18000
18001 @smallexample
18002 <install_prefix>/share/examples/gnattest/simple/src/tests
18003 @end smallexample
18004
18005 For each package containing visible subprograms, a child test package is
18006 generated. It contains one test routine per tested subprogram. Each
18007 declaration of a test subprogram has a comment specifying which tested
18008 subprogram it corresponds to. All of the test routines have separate bodies.
18009 The test routine located at simple-tests-test_inc_5eaee3.adb contains a single
18010 statement: a call to procedure Assert. It has two arguments: the Boolean
18011 expression we want to check and the diagnosis message to display if
18012 the condition is false.
18013
18014 That is where actual testing code should be written after a proper setup.
18015 An actual check can be performed by replacing the Assert call with:
18016
18017 @smallexample @c ada
18018 Assert (Inc (1) = 2, "wrong incrementation");
18019 @end smallexample
18020
18021 After recompiling and running the test driver, one successfully passed test
18022 is reported.
18023
18024 @node Setting Up and Tearing Down the Testing Environment
18025 @section Setting Up and Tearing Down the Testing Environment
18026
18027 @noindent
18028
18029 Besides test routines themselves, each test package has an inner package
18030 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
18031 User_Set_Up is called before each test routine of the package and
18032 User_Tear_Down is called after each test routine. Those two procedures can
18033 be used to perform necessary initialization and finalization,
18034 memory allocation, etc.
18035
18036 @node Regenerating Tests
18037 @section Regenerating Tests
18038
18039 @noindent
18040
18041 Bodies of test routines and env_mgmt packages are never overridden after they
18042 have been created once. As long as the name of the subprogram, full expanded Ada
18043 names, and the order of its parameters is the same, the old test routine will
18044 fit in its place and no test stub will be generated for the subprogram.
18045
18046 This can be demonstrated with the previous example. By uncommenting declaration
18047 and body of function Dec in simple.ads and simple.adb, running
18048 @command{gnattest} on the project, and then running the test driver:
18049
18050 @smallexample
18051 gnattest --harness-dir=driver -Psimple.gpr
18052 cd driver
18053 gprbuild -Ptest_driver
18054 test_runner
18055 @end smallexample
18056
18057 the old test is not replaced with a stub, nor is it lost, but a new test stub is
18058 created for function Dec.
18059
18060 The only way of regenerating tests stubs is to remove the previously created
18061 tests.
18062
18063 @node Default Test Behavior
18064 @section Default Test Behavior
18065
18066 @noindent
18067
18068 The generated test driver can treat unimplemented tests in two ways:
18069 either count them all as failed (this is useful to see which tests are still
18070 left to implement) or as passed (to sort out unimplemented ones from those
18071 actually failing).
18072
18073 The test driver accepts a switch to specify this behavior: --stub-default=val,
18074 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
18075
18076 The default behavior of the test driver is set with the same switch
18077 as passed to gnattest when generating the test driver.
18078
18079 Passing it to the driver generated on the first example:
18080
18081 @smallexample
18082 test_runner --stub-default=pass
18083 @end smallexample
18084
18085 makes both tests pass, even the unimplemented one.
18086
18087 @node Testing Primitive Operations of Tagged Types
18088 @section Testing Primitive Operations of Tagged Types
18089
18090 @noindent
18091
18092 Creation of test stubs for primitive operations of tagged types entails a number
18093 of features. Test routines for all primitives of a given tagged type are
18094 placed in a separate child package named according to the tagged type. For
18095 example, if you have tagged type T in package P, all tests for primitives
18096 of T will be in P.T_Tests.
18097
18098 Consider running gnattest on the second example (note: actual tests for this
18099 example already exist, so there's no need to worry if the tool reports that
18100 no new stubs were generated):
18101
18102 @smallexample
18103 cd <install_prefix>/share/examples/gnattest/tagged_rec
18104 gnattest --harness-dir=driver -Ptagged_rec.gpr
18105 @end smallexample
18106
18107 Taking a closer look at the test type declared in the test package
18108 Speed1.Controller_Tests is necessary. It is declared in:
18109
18110 @smallexample
18111 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18112 @end smallexample
18113
18114 Test types are direct or indirect descendants of
18115 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
18116 subprograms, the user doesn't need to be concerned with them. However,
18117 when generating test packages for primitive operations, there are some things
18118 the user needs to know.
18119
18120 Type Test_Controller has components that allow assignment of various
18121 derivations of type Controller. And if you look at the specification of
18122 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
18123 actually derives from Test_Controller rather than AUnit type Test_Fixture.
18124 Thus, test types mirror the hierarchy of tested types.
18125
18126 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18127 of primitive operations of type T assigns to Fixture a reference to an
18128 object of that exact type T. Notice, however, that if the tagged type has
18129 discriminants, the User_Set_Up only has a commented template for setting
18130 up the fixture, since filling the discriminant with actual value is up
18131 to the user.
18132
18133 The knowledge of the structure of test types allows additional testing
18134 without additional effort. Those possibilities are described below.
18135
18136 @node Testing Inheritance
18137 @section Testing Inheritance
18138
18139 @noindent
18140
18141 Since the test type hierarchy mimics the hierarchy of tested types, the
18142 inheritance of tests takes place. An example of such inheritance can be
18143 seen by running the test driver generated for the second example. As previously
18144 mentioned, actual tests are already written for this example.
18145
18146 @smallexample
18147 cd driver
18148 gprbuild -Ptest_driver
18149 test_runner
18150 @end smallexample
18151
18152 There are 6 passed tests while there are only 5 testable subprograms. The test
18153 routine for function Speed has been inherited and run against objects of the
18154 derived type.
18155
18156 @node Tagged Types Substitutability Testing
18157 @section Tagged Types Substitutability Testing
18158
18159 @noindent
18160
18161 Tagged Types Substitutability Testing is a way of verifying the Liskov
18162 substitution principle (LSP) by testing. LSP is a principle stating that if
18163 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18164 then objects of type T may be replaced with objects of type S (that is,
18165 objects of type S may be substituted for objects of type T), without
18166 altering any of the desirable properties of the program. When the properties
18167 of the program are expressed in the form of subprogram preconditions and
18168 postconditions (let's call them pre and post), LSP is formulated as relations
18169 between the pre and post of primitive operations and the pre and post of their
18170 derived operations. The pre of a derived operation should not be stronger than
18171 the original pre, and the post of the derived operation should not be weaker
18172 than the original post. Those relations ensure that verifying if a dispatching
18173 call is safe can be done just by using the pre and post of the root operation.
18174
18175 Verifying LSP by testing consists of running all the unit tests associated with
18176 the primitives of a given tagged type with objects of its derived types.
18177
18178 In the example used in the previous section, there was clearly a violation of
18179 LSP. The overriding primitive Adjust_Speed in package Speed2 removes the
18180 functionality of the overridden primitive and thus doesn't respect LSP.
18181 Gnattest has a special option to run overridden parent tests against objects
18182 of the type which have overriding primitives:
18183
18184 @smallexample
18185 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18186 cd driver
18187 gprbuild -Ptest_driver
18188 test_runner
18189 @end smallexample
18190
18191 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18192 against objects of the derived type.
18193
18194 @node Testing with Contracts
18195 @section Testing with Contracts
18196
18197 @noindent
18198
18199 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case.
18200 Test routines are generated, one per each Test_Case associated with a tested
18201 subprogram. Those test routines have special wrappers for tested functions
18202 that have composition of pre- and postcondition of the subprogram with
18203 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
18204 either count for Nominal mode or do not count for Robustness mode).
18205
18206 The third example demonstrates how this works:
18207
18208 @smallexample
18209 cd <install_prefix>/share/examples/gnattest/contracts
18210 gnattest --harness-dir=driver -Pcontracts.gpr
18211 @end smallexample
18212
18213 Putting actual checks within the range of the contract does not cause any
18214 error reports. For example, for the test routine which corresponds to
18215 test case 1:
18216
18217 @smallexample @c ada
18218 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18219 @end smallexample
18220
18221 and for the test routine corresponding to test case 2:
18222
18223 @smallexample @c ada
18224 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18225 @end smallexample
18226
18227 are acceptable:
18228
18229 @smallexample
18230 cd driver
18231 gprbuild -Ptest_driver
18232 test_runner
18233 @end smallexample
18234
18235 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
18236 a precondition violation for test case one. Also, by using any otherwise
18237 correct but positive pair of numbers in the second test routine, you can also
18238 get a precondition violation. Postconditions are checked and reported
18239 the same way.
18240
18241 @node Additional Tests
18242 @section Additional Tests
18243
18244 @noindent
18245 @command{gnattest} can add user-written tests to the main suite of the test
18246 driver. @command{gnattest} traverses the given packages and searches for test
18247 routines. All procedures with a single in out parameter of a type which is
18248 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
18249 specifications are added to the suites and are then executed by the test driver.
18250 (Set_Up and Tear_Down are filtered out.)
18251
18252 An example illustrates two ways of creating test harnesses for user-written
18253 tests. Directory additional_tests contains an AUnit-based test driver written
18254 by hand.
18255
18256 @smallexample
18257 <install_prefix>/share/examples/gnattest/additional_tests/
18258 @end smallexample
18259
18260 To create a test driver for already-written tests, use the --harness-only
18261 option:
18262
18263 @smallexample
18264 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18265   --harness-only
18266 gnatmake -Pharness_only/test_driver.gpr
18267 harness_only/test_runner
18268 @end smallexample
18269
18270 Additional tests can also be executed together with generated tests:
18271
18272 @smallexample
18273 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18274   --harness-dir=mixing
18275 gnatmake -Pmixing/test_driver.gpr
18276 mixing/test_runner
18277 @end smallexample
18278
18279 @node Current Limitations
18280 @section Current Limitations
18281
18282 @noindent
18283
18284 The tool currently does not support following features:
18285
18286 @itemize @bullet
18287 @item generic tests for generic packages and package instantiations
18288 @item tests for protected subprograms and entries
18289 @item aspects Precondition, Postcondition, and Test_Case
18290 @end itemize
18291
18292 @c *********************************
18293 @node Generating Ada Bindings for C and C++ headers
18294 @chapter Generating Ada Bindings for C and C++ headers
18295 @findex binding
18296
18297 @noindent
18298 GNAT now comes with a binding generator for C and C++ headers which is
18299 intended to do 95% of the tedious work of generating Ada specs from C
18300 or C++ header files.
18301
18302 Note that this capability is not intended to generate 100% correct Ada specs,
18303 and will is some cases require manual adjustments, although it can often
18304 be used out of the box in practice.
18305
18306 Some of the known limitations include:
18307
18308 @itemize @bullet
18309 @item only very simple character constant macros are translated into Ada
18310 constants. Function macros (macros with arguments) are partially translated
18311 as comments, to be completed manually if needed.
18312 @item some extensions (e.g. vector types) are not supported
18313 @item pointers to pointers or complex structures are mapped to System.Address
18314 @item identifiers with identical name (except casing) will generate compilation
18315       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18316 @end itemize
18317
18318 The code generated is using the Ada 2005 syntax, which makes it
18319 easier to interface with other languages than previous versions of Ada.
18320
18321 @menu
18322 * Running the binding generator::
18323 * Generating bindings for C++ headers::
18324 * Switches::
18325 @end menu
18326
18327 @node Running the binding generator
18328 @section Running the binding generator
18329
18330 @noindent
18331 The binding generator is part of the @command{gcc} compiler and can be
18332 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18333 spec files for the header files specified on the command line, and all
18334 header files needed by these files transitively. For example:
18335
18336 @smallexample
18337 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18338 $ gcc -c -gnat05 *.ads
18339 @end smallexample
18340
18341 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18342 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18343 correspond to the files @file{/usr/include/time.h},
18344 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18345 mode these Ada specs.
18346
18347 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18348 and will attempt to generate corresponding Ada comments.
18349
18350 If you want to generate a single Ada file and not the transitive closure, you
18351 can use instead the @option{-fdump-ada-spec-slim} switch.
18352
18353 Note that we recommend when possible to use the @command{g++} driver to
18354 generate bindings, even for most C headers, since this will in general
18355 generate better Ada specs. For generating bindings for C++ headers, it is
18356 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18357 is equivalent in this case. If @command{g++} cannot work on your C headers
18358 because of incompatibilities between C and C++, then you can fallback to
18359 @command{gcc} instead.
18360
18361 For an example of better bindings generated from the C++ front-end,
18362 the name of the parameters (when available) are actually ignored by the C
18363 front-end. Consider the following C header:
18364
18365 @smallexample
18366 extern void foo (int variable);
18367 @end smallexample
18368
18369 with the C front-end, @code{variable} is ignored, and the above is handled as:
18370
18371 @smallexample
18372 extern void foo (int);
18373 @end smallexample
18374
18375 generating a generic:
18376
18377 @smallexample
18378 procedure foo (param1 : int);
18379 @end smallexample
18380
18381 with the C++ front-end, the name is available, and we generate:
18382
18383 @smallexample
18384 procedure foo (variable : int);
18385 @end smallexample
18386
18387 In some cases, the generated bindings will be more complete or more meaningful
18388 when defining some macros, which you can do via the @option{-D} switch. This
18389 is for example the case with @file{Xlib.h} under GNU/Linux:
18390
18391 @smallexample
18392 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18393 @end smallexample
18394
18395 The above will generate more complete bindings than a straight call without
18396 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18397
18398 In other cases, it is not possible to parse a header file in a stand alone
18399 manner, because other include files need to be included first. In this
18400 case, the solution is to create a small header file including the needed
18401 @code{#include} and possible @code{#define} directives. For example, to
18402 generate Ada bindings for @file{readline/readline.h}, you need to first
18403 include @file{stdio.h}, so you can create a file with the following two
18404 lines in e.g. @file{readline1.h}:
18405
18406 @smallexample
18407 #include <stdio.h>
18408 #include <readline/readline.h>
18409 @end smallexample
18410
18411 and then generate Ada bindings from this file:
18412
18413 @smallexample
18414 $ g++ -c -fdump-ada-spec readline1.h
18415 @end smallexample
18416
18417 @node Generating bindings for C++ headers
18418 @section Generating bindings for C++ headers
18419
18420 @noindent
18421 Generating bindings for C++ headers is done using the same options, always
18422 with the @command{g++} compiler.
18423
18424 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18425 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18426 multiple inheritance of abstract classes will be mapped to Ada interfaces
18427 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18428 information on interfacing to C++).
18429
18430 For example, given the following C++ header file:
18431
18432 @smallexample
18433 @group
18434 @cartouche
18435 class Carnivore @{
18436 public:
18437    virtual int Number_Of_Teeth () = 0;
18438 @};
18439
18440 class Domestic @{
18441 public:
18442    virtual void Set_Owner (char* Name) = 0;
18443 @};
18444
18445 class Animal @{
18446 public:
18447   int Age_Count;
18448   virtual void Set_Age (int New_Age);
18449 @};
18450
18451 class Dog : Animal, Carnivore, Domestic @{
18452  public:
18453   int  Tooth_Count;
18454   char *Owner;
18455
18456   virtual int  Number_Of_Teeth ();
18457   virtual void Set_Owner (char* Name);
18458
18459   Dog();
18460 @};
18461 @end cartouche
18462 @end group
18463 @end smallexample
18464
18465 The corresponding Ada code is generated:
18466
18467 @smallexample @c ada
18468 @group
18469 @cartouche
18470   package Class_Carnivore is
18471     type Carnivore is limited interface;
18472     pragma Import (CPP, Carnivore);
18473
18474     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18475   end;
18476   use Class_Carnivore;
18477
18478   package Class_Domestic is
18479     type Domestic is limited interface;
18480     pragma Import (CPP, Domestic);
18481
18482     procedure Set_Owner
18483       (this : access Domestic;
18484        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18485   end;
18486   use Class_Domestic;
18487
18488   package Class_Animal is
18489     type Animal is tagged limited record
18490       Age_Count : aliased int;
18491     end record;
18492     pragma Import (CPP, Animal);
18493
18494     procedure Set_Age (this : access Animal; New_Age : int);
18495     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18496   end;
18497   use Class_Animal;
18498
18499   package Class_Dog is
18500     type Dog is new Animal and Carnivore and Domestic with record
18501       Tooth_Count : aliased int;
18502       Owner : Interfaces.C.Strings.chars_ptr;
18503     end record;
18504     pragma Import (CPP, Dog);
18505
18506     function Number_Of_Teeth (this : access Dog) return int;
18507     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18508
18509     procedure Set_Owner
18510       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18511     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18512
18513     function New_Dog return Dog;
18514     pragma CPP_Constructor (New_Dog);
18515     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18516   end;
18517   use Class_Dog;
18518 @end cartouche
18519 @end group
18520 @end smallexample
18521
18522 @node Switches
18523 @section Switches
18524
18525 @table @option
18526 @item -fdump-ada-spec
18527 @cindex @option{-fdump-ada-spec} (@command{gcc})
18528 Generate Ada spec files for the given header files transitively (including
18529 all header files that these headers depend upon).
18530
18531 @item -fdump-ada-spec-slim
18532 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18533 Generate Ada spec files for the header files specified on the command line
18534 only.
18535
18536 @item -C
18537 @cindex @option{-C} (@command{gcc})
18538 Extract comments from headers and generate Ada comments in the Ada spec files.
18539 @end table
18540
18541 @node Other Utility Programs
18542 @chapter Other Utility Programs
18543
18544 @noindent
18545 This chapter discusses some other utility programs available in the Ada
18546 environment.
18547
18548 @menu
18549 * Using Other Utility Programs with GNAT::
18550 * The External Symbol Naming Scheme of GNAT::
18551 * Converting Ada Files to html with gnathtml::
18552 * Installing gnathtml::
18553 @ifset vms
18554 * LSE::
18555 * Profiling::
18556 @end ifset
18557 @end menu
18558
18559 @node Using Other Utility Programs with GNAT
18560 @section Using Other Utility Programs with GNAT
18561
18562 @noindent
18563 The object files generated by GNAT are in standard system format and in
18564 particular the debugging information uses this format. This means
18565 programs generated by GNAT can be used with existing utilities that
18566 depend on these formats.
18567
18568 @ifclear vms
18569 In general, any utility program that works with C will also often work with
18570 Ada programs generated by GNAT. This includes software utilities such as
18571 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18572 as Purify.
18573 @end ifclear
18574
18575 @node The External Symbol Naming Scheme of GNAT
18576 @section The External Symbol Naming Scheme of GNAT
18577
18578 @noindent
18579 In order to interpret the output from GNAT, when using tools that are
18580 originally intended for use with other languages, it is useful to
18581 understand the conventions used to generate link names from the Ada
18582 entity names.
18583
18584 All link names are in all lowercase letters. With the exception of library
18585 procedure names, the mechanism used is simply to use the full expanded
18586 Ada name with dots replaced by double underscores. For example, suppose
18587 we have the following package spec:
18588
18589 @smallexample @c ada
18590 @group
18591 @cartouche
18592 package QRS is
18593    MN : Integer;
18594 end QRS;
18595 @end cartouche
18596 @end group
18597 @end smallexample
18598
18599 @noindent
18600 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18601 the corresponding link name is @code{qrs__mn}.
18602 @findex Export
18603 Of course if a @code{pragma Export} is used this may be overridden:
18604
18605 @smallexample @c ada
18606 @group
18607 @cartouche
18608 package Exports is
18609    Var1 : Integer;
18610    pragma Export (Var1, C, External_Name => "var1_name");
18611    Var2 : Integer;
18612    pragma Export (Var2, C, Link_Name => "var2_link_name");
18613 end Exports;
18614 @end cartouche
18615 @end group
18616 @end smallexample
18617
18618 @noindent
18619 In this case, the link name for @var{Var1} is whatever link name the
18620 C compiler would assign for the C function @var{var1_name}. This typically
18621 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18622 system conventions, but other possibilities exist. The link name for
18623 @var{Var2} is @var{var2_link_name}, and this is not operating system
18624 dependent.
18625
18626 @findex _main
18627 One exception occurs for library level procedures. A potential ambiguity
18628 arises between the required name @code{_main} for the C main program,
18629 and the name we would otherwise assign to an Ada library level procedure
18630 called @code{Main} (which might well not be the main program).
18631
18632 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18633 names. So if we have a library level procedure such as
18634
18635 @smallexample @c ada
18636 @group
18637 @cartouche
18638 procedure Hello (S : String);
18639 @end cartouche
18640 @end group
18641 @end smallexample
18642
18643 @noindent
18644 the external name of this procedure will be @var{_ada_hello}.
18645
18646
18647 @node Converting Ada Files to html with gnathtml
18648 @section Converting Ada Files to HTML with @code{gnathtml}
18649
18650 @noindent
18651 This @code{Perl} script allows Ada source files to be browsed using
18652 standard Web browsers. For installation procedure, see the section
18653 @xref{Installing gnathtml}.
18654
18655 Ada reserved keywords are highlighted in a bold font and Ada comments in
18656 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18657 switch to suppress the generation of cross-referencing information, user
18658 defined variables and types will appear in a different color; you will
18659 be able to click on any identifier and go to its declaration.
18660
18661 The command line is as follow:
18662 @smallexample
18663 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18664 @c Expanding @ovar macro inline (explanation in macro def comments)
18665 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18666 @end smallexample
18667
18668 @noindent
18669 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18670 an html file for every ada file, and a global file called @file{index.htm}.
18671 This file is an index of every identifier defined in the files.
18672
18673 The available ^switches^options^ are the following ones:
18674
18675 @table @option
18676 @item -83
18677 @cindex @option{-83} (@code{gnathtml})
18678 Only the Ada 83 subset of keywords will be highlighted.
18679
18680 @item -cc @var{color}
18681 @cindex @option{-cc} (@code{gnathtml})
18682 This option allows you to change the color used for comments. The default
18683 value is green. The color argument can be any name accepted by html.
18684
18685 @item -d
18686 @cindex @option{-d} (@code{gnathtml})
18687 If the Ada files depend on some other files (for instance through
18688 @code{with} clauses, the latter files will also be converted to html.
18689 Only the files in the user project will be converted to html, not the files
18690 in the run-time library itself.
18691
18692 @item -D
18693 @cindex @option{-D} (@code{gnathtml})
18694 This command is the same as @option{-d} above, but @command{gnathtml} will
18695 also look for files in the run-time library, and generate html files for them.
18696
18697 @item -ext @var{extension}
18698 @cindex @option{-ext} (@code{gnathtml})
18699 This option allows you to change the extension of the generated HTML files.
18700 If you do not specify an extension, it will default to @file{htm}.
18701
18702 @item -f
18703 @cindex @option{-f} (@code{gnathtml})
18704 By default, gnathtml will generate html links only for global entities
18705 ('with'ed units, global variables and types,@dots{}).  If you specify
18706 @option{-f} on the command line, then links will be generated for local
18707 entities too.
18708
18709 @item -l @var{number}
18710 @cindex @option{-l} (@code{gnathtml})
18711 If this ^switch^option^ is provided and @var{number} is not 0, then
18712 @code{gnathtml} will number the html files every @var{number} line.
18713
18714 @item -I @var{dir}
18715 @cindex @option{-I} (@code{gnathtml})
18716 Specify a directory to search for library files (@file{.ALI} files) and
18717 source files. You can provide several -I switches on the command line,
18718 and the directories will be parsed in the order of the command line.
18719
18720 @item -o @var{dir}
18721 @cindex @option{-o} (@code{gnathtml})
18722 Specify the output directory for html files. By default, gnathtml will
18723 saved the generated html files in a subdirectory named @file{html/}.
18724
18725 @item -p @var{file}
18726 @cindex @option{-p} (@code{gnathtml})
18727 If you are using Emacs and the most recent Emacs Ada mode, which provides
18728 a full Integrated Development Environment for compiling, checking,
18729 running and debugging applications, you may use @file{.gpr} files
18730 to give the directories where Emacs can find sources and object files.
18731
18732 Using this ^switch^option^, you can tell gnathtml to use these files.
18733 This allows you to get an html version of your application, even if it
18734 is spread over multiple directories.
18735
18736 @item -sc @var{color}
18737 @cindex @option{-sc} (@code{gnathtml})
18738 This ^switch^option^ allows you to change the color used for symbol
18739 definitions.
18740 The default value is red. The color argument can be any name accepted by html.
18741
18742 @item -t @var{file}
18743 @cindex @option{-t} (@code{gnathtml})
18744 This ^switch^option^ provides the name of a file. This file contains a list of
18745 file names to be converted, and the effect is exactly as though they had
18746 appeared explicitly on the command line. This
18747 is the recommended way to work around the command line length limit on some
18748 systems.
18749
18750 @end table
18751
18752 @node Installing gnathtml
18753 @section Installing @code{gnathtml}
18754
18755 @noindent
18756 @code{Perl} needs to be installed on your machine to run this script.
18757 @code{Perl} is freely available for almost every architecture and
18758 Operating System via the Internet.
18759
18760 On Unix systems, you  may want to modify  the  first line of  the script
18761 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18762 is. The syntax of this line is:
18763 @smallexample
18764 #!full_path_name_to_perl
18765 @end smallexample
18766
18767 @noindent
18768 Alternatively, you may run the script using the following command line:
18769
18770 @smallexample
18771 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18772 @c Expanding @ovar macro inline (explanation in macro def comments)
18773 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18774 @end smallexample
18775
18776 @ifset vms
18777 @node LSE
18778 @section LSE
18779 @findex LSE
18780
18781 @noindent
18782 The GNAT distribution provides an Ada 95 template for the HP Language
18783 Sensitive Editor (LSE), a component of DECset. In order to
18784 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18785
18786 @node Profiling
18787 @section Profiling
18788 @findex PCA
18789
18790 @noindent
18791 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18792 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18793 the collection phase with the /DEBUG qualifier.
18794
18795 @smallexample
18796 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18797 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18798 $ RUN/DEBUG <PROGRAM_NAME>
18799 @end smallexample
18800 @noindent
18801 @end ifset
18802
18803 @ifclear vms
18804 @c ******************************
18805 @node Code Coverage and Profiling
18806 @chapter Code Coverage and Profiling
18807 @cindex Code Coverage
18808 @cindex Profiling
18809
18810 @noindent
18811 This chapter describes how to use @code{gcov} - coverage testing tool - and
18812 @code{gprof} - profiler tool - on your Ada programs.
18813
18814 @menu
18815 * Code Coverage of Ada Programs using gcov::
18816 * Profiling an Ada Program using gprof::
18817 @end menu
18818
18819 @node Code Coverage of Ada Programs using gcov
18820 @section Code Coverage of Ada Programs using gcov
18821 @cindex gcov
18822 @cindex -fprofile-arcs
18823 @cindex -ftest-coverage
18824 @cindex -coverage
18825 @cindex Code Coverage
18826
18827 @noindent
18828 @code{gcov} is a test coverage program: it analyzes the execution of a given
18829 program on selected tests, to help you determine the portions of the program
18830 that are still untested.
18831
18832 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18833 User's Guide. You can refer to this documentation for a more complete
18834 description.
18835
18836 This chapter provides a quick startup guide, and
18837 details some Gnat-specific features.
18838
18839 @menu
18840 * Quick startup guide::
18841 * Gnat specifics::
18842 @end menu
18843
18844 @node Quick startup guide
18845 @subsection Quick startup guide
18846
18847 In order to perform coverage analysis of a program using @code{gcov}, 3
18848 steps are needed:
18849
18850 @itemize @bullet
18851 @item
18852 Code instrumentation during the compilation process
18853 @item
18854 Execution of the instrumented program
18855 @item
18856 Execution of the @code{gcov} tool to generate the result.
18857 @end itemize
18858
18859 The code instrumentation needed by gcov is created at the object level:
18860 The source code is not modified in any way, because the instrumentation code is
18861 inserted by gcc during the compilation process. To compile your code with code
18862 coverage activated, you need to recompile your whole project using the
18863 switches
18864 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18865 @code{-fprofile-arcs}.
18866
18867 @smallexample
18868 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18869    -largs -fprofile-arcs
18870 @end smallexample
18871
18872 This compilation process will create @file{.gcno} files together with
18873 the usual object files.
18874
18875 Once the program is compiled with coverage instrumentation, you can
18876 run it as many times as needed - on portions of a test suite for
18877 example. The first execution will produce @file{.gcda} files at the
18878 same location as the @file{.gcno} files.  The following executions
18879 will update those files, so that a cumulative result of the covered
18880 portions of the program is generated.
18881
18882 Finally, you need to call the @code{gcov} tool. The different options of
18883 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18884
18885 This will create annotated source files with a @file{.gcov} extension:
18886 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18887
18888 @node Gnat specifics
18889 @subsection Gnat specifics
18890
18891 Because Ada semantics, portions of the source code may be shared among
18892 several object files. This is the case for example when generics are
18893 involved, when inlining is active  or when declarations generate  initialisation
18894 calls. In order to take
18895 into account this shared code, you need to call @code{gcov} on all
18896 source files of the tested program at once.
18897
18898 The list of source files might exceed the system's maximum command line
18899 length. In order to bypass this limitation, a new mechanism has been
18900 implemented in @code{gcov}: you can now list all your project's files into a
18901 text file, and provide this file to gcov as a parameter,  preceded by a @@
18902 (e.g. @samp{gcov @@mysrclist.txt}).
18903
18904 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18905 not supported as there can be unresolved symbols during the final link.
18906
18907 @node Profiling an Ada Program using gprof
18908 @section Profiling an Ada Program using gprof
18909 @cindex gprof
18910 @cindex -pg
18911 @cindex Profiling
18912
18913 @noindent
18914 This section is not meant to be an exhaustive documentation of @code{gprof}.
18915 Full documentation for it can be found in the GNU Profiler User's Guide
18916 documentation that is part of this GNAT distribution.
18917
18918 Profiling a program helps determine the parts of a program that are executed
18919 most often, and are therefore the most time-consuming.
18920
18921 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18922 better handle Ada programs and multitasking.
18923 It is currently supported on the following platforms
18924 @itemize @bullet
18925 @item
18926 linux x86/x86_64
18927 @item
18928 solaris sparc/sparc64/x86
18929 @item
18930 windows x86
18931 @end itemize
18932
18933 @noindent
18934 In order to profile a program using @code{gprof}, 3 steps are needed:
18935
18936 @itemize @bullet
18937 @item
18938 Code instrumentation, requiring a full recompilation of the project with the
18939 proper switches.
18940 @item
18941 Execution of the program under the analysis conditions, i.e. with the desired
18942 input.
18943 @item
18944 Analysis of the results using the @code{gprof} tool.
18945 @end itemize
18946
18947 @noindent
18948 The following sections detail the different steps, and indicate how
18949 to interpret the results:
18950 @menu
18951 * Compilation for profiling::
18952 * Program execution::
18953 * Running gprof::
18954 * Interpretation of profiling results::
18955 @end menu
18956
18957 @node Compilation for profiling
18958 @subsection Compilation for profiling
18959 @cindex -pg
18960 @cindex Profiling
18961
18962 In order to profile a program the first step is to tell the compiler
18963 to generate the necessary profiling information. The compiler switch to be used
18964 is @code{-pg}, which must be added to other compilation switches. This
18965 switch needs to be specified both during compilation and link stages, and can
18966 be specified once when using gnatmake:
18967
18968 @smallexample
18969 gnatmake -f -pg -P my_project
18970 @end smallexample
18971
18972 @noindent
18973 Note that only the objects that were compiled with the @samp{-pg} switch will
18974 be profiled; if you need to profile your whole project, use the @samp{-f}
18975 gnatmake switch to force full recompilation.
18976
18977 @node Program execution
18978 @subsection Program execution
18979
18980 @noindent
18981 Once the program has been compiled for profiling, you can run it as usual.
18982
18983 The only constraint imposed by profiling is that the program must terminate
18984 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18985 properly analyzed.
18986
18987 Once the program completes execution, a data file called @file{gmon.out} is
18988 generated in the directory where the program was launched from. If this file
18989 already exists, it will be overwritten.
18990
18991 @node Running gprof
18992 @subsection Running gprof
18993
18994 @noindent
18995 The @code{gprof} tool is called as follow:
18996
18997 @smallexample
18998 gprof my_prog gmon.out
18999 @end smallexample
19000
19001 @noindent
19002 or simpler:
19003
19004 @smallexample
19005 gprof my_prog
19006 @end smallexample
19007
19008 @noindent
19009 The complete form of the gprof command line is the following:
19010
19011 @smallexample
19012 gprof [^switches^options^] [executable [data-file]]
19013 @end smallexample
19014
19015 @noindent
19016 @code{gprof} supports numerous ^switch^options^. The order of these
19017 ^switch^options^ does not matter. The full list of options can be found in
19018 the GNU Profiler User's Guide documentation that comes with this documentation.
19019
19020 The following is the subset of those switches that is most relevant:
19021
19022 @table @option
19023
19024 @item --demangle[=@var{style}]
19025 @itemx --no-demangle
19026 @cindex @option{--demangle} (@code{gprof})
19027 These options control whether symbol names should be demangled when
19028 printing output.  The default is to demangle C++ symbols.  The
19029 @code{--no-demangle} option may be used to turn off demangling. Different
19030 compilers have different mangling styles.  The optional demangling style
19031 argument can be used to choose an appropriate demangling style for your
19032 compiler, in particular Ada symbols generated by GNAT can be demangled using
19033 @code{--demangle=gnat}.
19034
19035 @item -e @var{function_name}
19036 @cindex @option{-e} (@code{gprof})
19037 The @samp{-e @var{function}} option tells @code{gprof} not to print
19038 information about the function @var{function_name} (and its
19039 children@dots{}) in the call graph.  The function will still be listed
19040 as a child of any functions that call it, but its index number will be
19041 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
19042 given; only one @var{function_name} may be indicated with each @samp{-e}
19043 option.
19044
19045 @item -E @var{function_name}
19046 @cindex @option{-E} (@code{gprof})
19047 The @code{-E @var{function}} option works like the @code{-e} option, but
19048 execution time spent in the function (and children who were not called from
19049 anywhere else), will not be used to compute the percentages-of-time for
19050 the call graph.  More than one @samp{-E} option may be given; only one
19051 @var{function_name} may be indicated with each @samp{-E} option.
19052
19053 @item -f @var{function_name}
19054 @cindex @option{-f} (@code{gprof})
19055 The @samp{-f @var{function}} option causes @code{gprof} to limit the
19056 call graph to the function @var{function_name} and its children (and
19057 their children@dots{}).  More than one @samp{-f} option may be given;
19058 only one @var{function_name} may be indicated with each @samp{-f}
19059 option.
19060
19061 @item -F @var{function_name}
19062 @cindex @option{-F} (@code{gprof})
19063 The @samp{-F @var{function}} option works like the @code{-f} option, but
19064 only time spent in the function and its children (and their
19065 children@dots{}) will be used to determine total-time and
19066 percentages-of-time for the call graph.  More than one @samp{-F} option
19067 may be given; only one @var{function_name} may be indicated with each
19068 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
19069
19070 @end table
19071
19072 @node Interpretation of profiling results
19073 @subsection Interpretation of profiling results
19074
19075 @noindent
19076
19077 The results of the profiling analysis are represented by two arrays: the
19078 'flat profile' and the 'call graph'. Full documentation of those outputs
19079 can be found in the GNU Profiler User's Guide.
19080
19081 The flat profile shows the time spent in each function of the program, and how
19082 many time it has been called. This allows you to locate easily the most
19083 time-consuming functions.
19084
19085 The call graph shows, for each subprogram, the subprograms that call it,
19086 and the subprograms that it calls. It also provides an estimate of the time
19087 spent in each of those callers/called subprograms.
19088 @end ifclear
19089
19090 @c ******************************
19091 @node Running and Debugging Ada Programs
19092 @chapter Running and Debugging Ada Programs
19093 @cindex Debugging
19094
19095 @noindent
19096 This chapter discusses how to debug Ada programs.
19097 @ifset vms
19098 It applies to GNAT on the Alpha OpenVMS platform;
19099 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19100 since HP has implemented Ada support in the OpenVMS debugger on I64.
19101 @end ifset
19102
19103 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19104
19105 @enumerate
19106 @item
19107 The illegality may be a violation of the static semantics of Ada. In
19108 that case GNAT diagnoses the constructs in the program that are illegal.
19109 It is then a straightforward matter for the user to modify those parts of
19110 the program.
19111
19112 @item
19113 The illegality may be a violation of the dynamic semantics of Ada. In
19114 that case the program compiles and executes, but may generate incorrect
19115 results, or may terminate abnormally with some exception.
19116
19117 @item
19118 When presented with a program that contains convoluted errors, GNAT
19119 itself may terminate abnormally without providing full diagnostics on
19120 the incorrect user program.
19121 @end enumerate
19122
19123 @menu
19124 * The GNAT Debugger GDB::
19125 * Running GDB::
19126 * Introduction to GDB Commands::
19127 * Using Ada Expressions::
19128 * Calling User-Defined Subprograms::
19129 * Using the Next Command in a Function::
19130 * Ada Exceptions::
19131 * Ada Tasks::
19132 * Debugging Generic Units::
19133 * Remote Debugging using gdbserver::
19134 * GNAT Abnormal Termination or Failure to Terminate::
19135 * Naming Conventions for GNAT Source Files::
19136 * Getting Internal Debugging Information::
19137 * Stack Traceback::
19138 @end menu
19139
19140 @cindex Debugger
19141 @findex gdb
19142
19143 @node The GNAT Debugger GDB
19144 @section The GNAT Debugger GDB
19145
19146 @noindent
19147 @code{GDB} is a general purpose, platform-independent debugger that
19148 can be used to debug mixed-language programs compiled with @command{gcc},
19149 and in particular is capable of debugging Ada programs compiled with
19150 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19151 complex Ada data structures.
19152
19153 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19154 @ifset vms
19155 located in the GNU:[DOCS] directory,
19156 @end ifset
19157 for full details on the usage of @code{GDB}, including a section on
19158 its usage on programs. This manual should be consulted for full
19159 details. The section that follows is a brief introduction to the
19160 philosophy and use of @code{GDB}.
19161
19162 When GNAT programs are compiled, the compiler optionally writes debugging
19163 information into the generated object file, including information on
19164 line numbers, and on declared types and variables. This information is
19165 separate from the generated code. It makes the object files considerably
19166 larger, but it does not add to the size of the actual executable that
19167 will be loaded into memory, and has no impact on run-time performance. The
19168 generation of debug information is triggered by the use of the
19169 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19170 used to carry out the compilations. It is important to emphasize that
19171 the use of these options does not change the generated code.
19172
19173 The debugging information is written in standard system formats that
19174 are used by many tools, including debuggers and profilers. The format
19175 of the information is typically designed to describe C types and
19176 semantics, but GNAT implements a translation scheme which allows full
19177 details about Ada types and variables to be encoded into these
19178 standard C formats. Details of this encoding scheme may be found in
19179 the file exp_dbug.ads in the GNAT source distribution. However, the
19180 details of this encoding are, in general, of no interest to a user,
19181 since @code{GDB} automatically performs the necessary decoding.
19182
19183 When a program is bound and linked, the debugging information is
19184 collected from the object files, and stored in the executable image of
19185 the program. Again, this process significantly increases the size of
19186 the generated executable file, but it does not increase the size of
19187 the executable program itself. Furthermore, if this program is run in
19188 the normal manner, it runs exactly as if the debug information were
19189 not present, and takes no more actual memory.
19190
19191 However, if the program is run under control of @code{GDB}, the
19192 debugger is activated.  The image of the program is loaded, at which
19193 point it is ready to run.  If a run command is given, then the program
19194 will run exactly as it would have if @code{GDB} were not present. This
19195 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19196 entirely non-intrusive until a breakpoint is encountered.  If no
19197 breakpoint is ever hit, the program will run exactly as it would if no
19198 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19199 the debugging information and can respond to user commands to inspect
19200 variables, and more generally to report on the state of execution.
19201
19202 @c **************
19203 @node Running GDB
19204 @section Running GDB
19205
19206 @noindent
19207 This section describes how to initiate the debugger.
19208 @c The above sentence is really just filler, but it was otherwise
19209 @c clumsy to get the first paragraph nonindented given the conditional
19210 @c nature of the description
19211
19212 @ifclear vms
19213 The debugger can be launched from a @code{GPS} menu or
19214 directly from the command line. The description below covers the latter use.
19215 All the commands shown can be used in the @code{GPS} debug console window,
19216 but there are usually more GUI-based ways to achieve the same effect.
19217 @end ifclear
19218
19219 The command to run @code{GDB} is
19220
19221 @smallexample
19222 $ ^gdb program^GDB PROGRAM^
19223 @end smallexample
19224
19225 @noindent
19226 where @code{^program^PROGRAM^} is the name of the executable file. This
19227 activates the debugger and results in a prompt for debugger commands.
19228 The simplest command is simply @code{run}, which causes the program to run
19229 exactly as if the debugger were not present. The following section
19230 describes some of the additional commands that can be given to @code{GDB}.
19231
19232 @c *******************************
19233 @node Introduction to GDB Commands
19234 @section Introduction to GDB Commands
19235
19236 @noindent
19237 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19238 Debugging with GDB, gdb, Debugging with GDB},
19239 @ifset vms
19240 located in the GNU:[DOCS] directory,
19241 @end ifset
19242 for extensive documentation on the use
19243 of these commands, together with examples of their use. Furthermore,
19244 the command @command{help} invoked from within GDB activates a simple help
19245 facility which summarizes the available commands and their options.
19246 In this section we summarize a few of the most commonly
19247 used commands to give an idea of what @code{GDB} is about. You should create
19248 a simple program with debugging information and experiment with the use of
19249 these @code{GDB} commands on the program as you read through the
19250 following section.
19251
19252 @table @code
19253 @item set args @var{arguments}
19254 The @var{arguments} list above is a list of arguments to be passed to
19255 the program on a subsequent run command, just as though the arguments
19256 had been entered on a normal invocation of the program. The @code{set args}
19257 command is not needed if the program does not require arguments.
19258
19259 @item run
19260 The @code{run} command causes execution of the program to start from
19261 the beginning. If the program is already running, that is to say if
19262 you are currently positioned at a breakpoint, then a prompt will ask
19263 for confirmation that you want to abandon the current execution and
19264 restart.
19265
19266 @item breakpoint @var{location}
19267 The breakpoint command sets a breakpoint, that is to say a point at which
19268 execution will halt and @code{GDB} will await further
19269 commands. @var{location} is
19270 either a line number within a file, given in the format @code{file:linenumber},
19271 or it is the name of a subprogram. If you request that a breakpoint be set on
19272 a subprogram that is overloaded, a prompt will ask you to specify on which of
19273 those subprograms you want to breakpoint. You can also
19274 specify that all of them should be breakpointed. If the program is run
19275 and execution encounters the breakpoint, then the program
19276 stops and @code{GDB} signals that the breakpoint was encountered by
19277 printing the line of code before which the program is halted.
19278
19279 @item catch exception @var{name}
19280 This command causes the program execution to stop whenever exception
19281 @var{name} is raised.  If @var{name} is omitted, then the execution is
19282 suspended when any exception is raised.
19283
19284 @item print @var{expression}
19285 This will print the value of the given expression. Most simple
19286 Ada expression formats are properly handled by @code{GDB}, so the expression
19287 can contain function calls, variables, operators, and attribute references.
19288
19289 @item continue
19290 Continues execution following a breakpoint, until the next breakpoint or the
19291 termination of the program.
19292
19293 @item step
19294 Executes a single line after a breakpoint. If the next statement
19295 is a subprogram call, execution continues into (the first statement of)
19296 the called subprogram.
19297
19298 @item next
19299 Executes a single line. If this line is a subprogram call, executes and
19300 returns from the call.
19301
19302 @item list
19303 Lists a few lines around the current source location. In practice, it
19304 is usually more convenient to have a separate edit window open with the
19305 relevant source file displayed. Successive applications of this command
19306 print subsequent lines. The command can be given an argument which is a
19307 line number, in which case it displays a few lines around the specified one.
19308
19309 @item backtrace
19310 Displays a backtrace of the call chain. This command is typically
19311 used after a breakpoint has occurred, to examine the sequence of calls that
19312 leads to the current breakpoint. The display includes one line for each
19313 activation record (frame) corresponding to an active subprogram.
19314
19315 @item up
19316 At a breakpoint, @code{GDB} can display the values of variables local
19317 to the current frame. The command @code{up} can be used to
19318 examine the contents of other active frames, by moving the focus up
19319 the stack, that is to say from callee to caller, one frame at a time.
19320
19321 @item down
19322 Moves the focus of @code{GDB} down from the frame currently being
19323 examined to the frame of its callee (the reverse of the previous command),
19324
19325 @item frame @var{n}
19326 Inspect the frame with the given number. The value 0 denotes the frame
19327 of the current breakpoint, that is to say the top of the call stack.
19328
19329 @end table
19330
19331 @noindent
19332 The above list is a very short introduction to the commands that
19333 @code{GDB} provides. Important additional capabilities, including conditional
19334 breakpoints, the ability to execute command sequences on a breakpoint,
19335 the ability to debug at the machine instruction level and many other
19336 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19337 Debugging with GDB}.  Note that most commands can be abbreviated
19338 (for example, c for continue, bt for backtrace).
19339
19340 @node Using Ada Expressions
19341 @section Using Ada Expressions
19342 @cindex Ada expressions
19343
19344 @noindent
19345 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19346 extensions. The philosophy behind the design of this subset is
19347
19348 @itemize @bullet
19349 @item
19350 That @code{GDB} should provide basic literals and access to operations for
19351 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19352 leaving more sophisticated computations to subprograms written into the
19353 program (which therefore may be called from @code{GDB}).
19354
19355 @item
19356 That type safety and strict adherence to Ada language restrictions
19357 are not particularly important to the @code{GDB} user.
19358
19359 @item
19360 That brevity is important to the @code{GDB} user.
19361 @end itemize
19362
19363 @noindent
19364 Thus, for brevity, the debugger acts as if there were
19365 implicit @code{with} and @code{use} clauses in effect for all user-written
19366 packages, thus making it unnecessary to fully qualify most names with
19367 their packages, regardless of context. Where this causes ambiguity,
19368 @code{GDB} asks the user's intent.
19369
19370 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19371 GDB, gdb, Debugging with GDB}.
19372
19373 @node Calling User-Defined Subprograms
19374 @section Calling User-Defined Subprograms
19375
19376 @noindent
19377 An important capability of @code{GDB} is the ability to call user-defined
19378 subprograms while debugging. This is achieved simply by entering
19379 a subprogram call statement in the form:
19380
19381 @smallexample
19382 call subprogram-name (parameters)
19383 @end smallexample
19384
19385 @noindent
19386 The keyword @code{call} can be omitted in the normal case where the
19387 @code{subprogram-name} does not coincide with any of the predefined
19388 @code{GDB} commands.
19389
19390 The effect is to invoke the given subprogram, passing it the
19391 list of parameters that is supplied. The parameters can be expressions and
19392 can include variables from the program being debugged. The
19393 subprogram must be defined
19394 at the library level within your program, and @code{GDB} will call the
19395 subprogram within the environment of your program execution (which
19396 means that the subprogram is free to access or even modify variables
19397 within your program).
19398
19399 The most important use of this facility is in allowing the inclusion of
19400 debugging routines that are tailored to particular data structures
19401 in your program. Such debugging routines can be written to provide a suitably
19402 high-level description of an abstract type, rather than a low-level dump
19403 of its physical layout. After all, the standard
19404 @code{GDB print} command only knows the physical layout of your
19405 types, not their abstract meaning. Debugging routines can provide information
19406 at the desired semantic level and are thus enormously useful.
19407
19408 For example, when debugging GNAT itself, it is crucial to have access to
19409 the contents of the tree nodes used to represent the program internally.
19410 But tree nodes are represented simply by an integer value (which in turn
19411 is an index into a table of nodes).
19412 Using the @code{print} command on a tree node would simply print this integer
19413 value, which is not very useful. But the PN routine (defined in file
19414 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19415 a useful high level representation of the tree node, which includes the
19416 syntactic category of the node, its position in the source, the integers
19417 that denote descendant nodes and parent node, as well as varied
19418 semantic information. To study this example in more detail, you might want to
19419 look at the body of the PN procedure in the stated file.
19420
19421 @node Using the Next Command in a Function
19422 @section Using the Next Command in a Function
19423
19424 @noindent
19425 When you use the @code{next} command in a function, the current source
19426 location will advance to the next statement as usual. A special case
19427 arises in the case of a @code{return} statement.
19428
19429 Part of the code for a return statement is the ``epilog'' of the function.
19430 This is the code that returns to the caller. There is only one copy of
19431 this epilog code, and it is typically associated with the last return
19432 statement in the function if there is more than one return. In some
19433 implementations, this epilog is associated with the first statement
19434 of the function.
19435
19436 The result is that if you use the @code{next} command from a return
19437 statement that is not the last return statement of the function you
19438 may see a strange apparent jump to the last return statement or to
19439 the start of the function. You should simply ignore this odd jump.
19440 The value returned is always that from the first return statement
19441 that was stepped through.
19442
19443 @node Ada Exceptions
19444 @section Stopping when Ada Exceptions are Raised
19445 @cindex Exceptions
19446
19447 @noindent
19448 You can set catchpoints that stop the program execution when your program
19449 raises selected exceptions.
19450
19451 @table @code
19452 @item catch exception
19453 Set a catchpoint that stops execution whenever (any task in the) program
19454 raises any exception.
19455
19456 @item catch exception @var{name}
19457 Set a catchpoint that stops execution whenever (any task in the) program
19458 raises the exception @var{name}.
19459
19460 @item catch exception unhandled
19461 Set a catchpoint that stops executing whenever (any task in the) program
19462 raises an exception for which there is no handler.
19463
19464 @item info exceptions
19465 @itemx info exceptions @var{regexp}
19466 The @code{info exceptions} command permits the user to examine all defined
19467 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19468 argument, prints out only those exceptions whose name matches @var{regexp}.
19469 @end table
19470
19471 @node Ada Tasks
19472 @section Ada Tasks
19473 @cindex Tasks
19474
19475 @noindent
19476 @code{GDB} allows the following task-related commands:
19477
19478 @table @code
19479 @item info tasks
19480 This command shows a list of current Ada tasks, as in the following example:
19481
19482 @smallexample
19483 @iftex
19484 @leftskip=0cm
19485 @end iftex
19486 (gdb) info tasks
19487   ID       TID P-ID   Thread Pri State                 Name
19488    1   8088000   0   807e000  15 Child Activation Wait main_task
19489    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19490    3   809a800   1   80a4800  15 Child Activation Wait a
19491 *  4   80ae800   3   80b8000  15 Running               c
19492 @end smallexample
19493
19494 @noindent
19495 In this listing, the asterisk before the first task indicates it to be the
19496 currently running task. The first column lists the task ID that is used
19497 to refer to tasks in the following commands.
19498
19499 @item break @var{linespec} task @var{taskid}
19500 @itemx break @var{linespec} task @var{taskid} if @dots{}
19501 @cindex Breakpoints and tasks
19502 These commands are like the @code{break @dots{} thread @dots{}}.
19503 @var{linespec} specifies source lines.
19504
19505 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19506 to specify that you only want @code{GDB} to stop the program when a
19507 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19508 numeric task identifiers assigned by @code{GDB}, shown in the first
19509 column of the @samp{info tasks} display.
19510
19511 If you do not specify @samp{task @var{taskid}} when you set a
19512 breakpoint, the breakpoint applies to @emph{all} tasks of your
19513 program.
19514
19515 You can use the @code{task} qualifier on conditional breakpoints as
19516 well; in this case, place @samp{task @var{taskid}} before the
19517 breakpoint condition (before the @code{if}).
19518
19519 @item task @var{taskno}
19520 @cindex Task switching
19521
19522 This command allows to switch to the task referred by @var{taskno}. In
19523 particular, This allows to browse the backtrace of the specified
19524 task. It is advised to switch back to the original task before
19525 continuing execution otherwise the scheduling of the program may be
19526 perturbed.
19527 @end table
19528
19529 @noindent
19530 For more detailed information on the tasking support,
19531 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19532
19533 @node Debugging Generic Units
19534 @section Debugging Generic Units
19535 @cindex Debugging Generic Units
19536 @cindex Generics
19537
19538 @noindent
19539 GNAT always uses code expansion for generic instantiation. This means that
19540 each time an instantiation occurs, a complete copy of the original code is
19541 made, with appropriate substitutions of formals by actuals.
19542
19543 It is not possible to refer to the original generic entities in
19544 @code{GDB}, but it is always possible to debug a particular instance of
19545 a generic, by using the appropriate expanded names. For example, if we have
19546
19547 @smallexample @c ada
19548 @group
19549 @cartouche
19550 procedure g is
19551
19552    generic package k is
19553       procedure kp (v1 : in out integer);
19554    end k;
19555
19556    package body k is
19557       procedure kp (v1 : in out integer) is
19558       begin
19559          v1 := v1 + 1;
19560       end kp;
19561    end k;
19562
19563    package k1 is new k;
19564    package k2 is new k;
19565
19566    var : integer := 1;
19567
19568 begin
19569    k1.kp (var);
19570    k2.kp (var);
19571    k1.kp (var);
19572    k2.kp (var);
19573 end;
19574 @end cartouche
19575 @end group
19576 @end smallexample
19577
19578 @noindent
19579 Then to break on a call to procedure kp in the k2 instance, simply
19580 use the command:
19581
19582 @smallexample
19583 (gdb) break g.k2.kp
19584 @end smallexample
19585
19586 @noindent
19587 When the breakpoint occurs, you can step through the code of the
19588 instance in the normal manner and examine the values of local variables, as for
19589 other units.
19590
19591 @node Remote Debugging using gdbserver
19592 @section Remote Debugging using gdbserver
19593 @cindex Remote Debugging using gdbserver
19594
19595 @noindent
19596 On platforms where gdbserver is supported, it is possible to use this tool
19597 to debug your application remotely.  This can be useful in situations
19598 where the program needs to be run on a target host that is different
19599 from the host used for development, particularly when the target has
19600 a limited amount of resources (either CPU and/or memory).
19601
19602 To do so, start your program using gdbserver on the target machine.
19603 gdbserver then automatically suspends the execution of your program
19604 at its entry point, waiting for a debugger to connect to it.  The
19605 following commands starts an application and tells gdbserver to
19606 wait for a connection with the debugger on localhost port 4444.
19607
19608 @smallexample
19609 $ gdbserver localhost:4444 program
19610 Process program created; pid = 5685
19611 Listening on port 4444
19612 @end smallexample
19613
19614 Once gdbserver has started listening, we can tell the debugger to establish
19615 a connection with this gdbserver, and then start the same debugging session
19616 as if the program was being debugged on the same host, directly under
19617 the control of GDB.
19618
19619 @smallexample
19620 $ gdb program
19621 (gdb) target remote targethost:4444
19622 Remote debugging using targethost:4444
19623 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19624 (gdb) b foo.adb:3
19625 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19626 (gdb) continue
19627 Continuing.
19628
19629 Breakpoint 1, foo () at foo.adb:4
19630 4       end foo;
19631 @end smallexample
19632
19633 It is also possible to use gdbserver to attach to an already running
19634 program, in which case the execution of that program is simply suspended
19635 until the connection between the debugger and gdbserver is established.
19636
19637 For more information on how to use gdbserver, @ref{Top, Server, Using
19638 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
19639 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19640
19641 @node GNAT Abnormal Termination or Failure to Terminate
19642 @section GNAT Abnormal Termination or Failure to Terminate
19643 @cindex GNAT Abnormal Termination or Failure to Terminate
19644
19645 @noindent
19646 When presented with programs that contain serious errors in syntax
19647 or semantics,
19648 GNAT may on rare occasions  experience problems in operation, such
19649 as aborting with a
19650 segmentation fault or illegal memory access, raising an internal
19651 exception, terminating abnormally, or failing to terminate at all.
19652 In such cases, you can activate
19653 various features of GNAT that can help you pinpoint the construct in your
19654 program that is the likely source of the problem.
19655
19656 The following strategies are presented in increasing order of
19657 difficulty, corresponding to your experience in using GNAT and your
19658 familiarity with compiler internals.
19659
19660 @enumerate
19661 @item
19662 Run @command{gcc} with the @option{-gnatf}. This first
19663 switch causes all errors on a given line to be reported. In its absence,
19664 only the first error on a line is displayed.
19665
19666 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19667 are encountered, rather than after compilation is terminated. If GNAT
19668 terminates prematurely or goes into an infinite loop, the last error
19669 message displayed may help to pinpoint the culprit.
19670
19671 @item
19672 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19673 mode, @command{gcc} produces ongoing information about the progress of the
19674 compilation and provides the name of each procedure as code is
19675 generated. This switch allows you to find which Ada procedure was being
19676 compiled when it encountered a code generation problem.
19677
19678 @item
19679 @cindex @option{-gnatdc} switch
19680 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19681 switch that does for the front-end what @option{^-v^VERBOSE^} does
19682 for the back end. The system prints the name of each unit,
19683 either a compilation unit or nested unit, as it is being analyzed.
19684 @item
19685 Finally, you can start
19686 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19687 front-end of GNAT, and can be run independently (normally it is just
19688 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19689 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19690 @code{where} command is the first line of attack; the variable
19691 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19692 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19693 which the execution stopped, and @code{input_file name} indicates the name of
19694 the source file.
19695 @end enumerate
19696
19697 @node Naming Conventions for GNAT Source Files
19698 @section Naming Conventions for GNAT Source Files
19699
19700 @noindent
19701 In order to examine the workings of the GNAT system, the following
19702 brief description of its organization may be helpful:
19703
19704 @itemize @bullet
19705 @item
19706 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19707
19708 @item
19709 All files prefixed with @file{^par^PAR^} are components of the parser. The
19710 numbers correspond to chapters of the Ada Reference Manual. For example,
19711 parsing of select statements can be found in @file{par-ch9.adb}.
19712
19713 @item
19714 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19715 numbers correspond to chapters of the Ada standard. For example, all
19716 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19717 addition, some features of the language require sufficient special processing
19718 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19719 dynamic dispatching, etc.
19720
19721 @item
19722 All files prefixed with @file{^exp^EXP^} perform normalization and
19723 expansion of the intermediate representation (abstract syntax tree, or AST).
19724 these files use the same numbering scheme as the parser and semantics files.
19725 For example, the construction of record initialization procedures is done in
19726 @file{exp_ch3.adb}.
19727
19728 @item
19729 The files prefixed with @file{^bind^BIND^} implement the binder, which
19730 verifies the consistency of the compilation, determines an order of
19731 elaboration, and generates the bind file.
19732
19733 @item
19734 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19735 data structures used by the front-end.
19736
19737 @item
19738 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19739 the abstract syntax tree as produced by the parser.
19740
19741 @item
19742 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19743 all entities, computed during semantic analysis.
19744
19745 @item
19746 Library management issues are dealt with in files with prefix
19747 @file{^lib^LIB^}.
19748
19749 @item
19750 @findex Ada
19751 @cindex Annex A
19752 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19753 defined in Annex A.
19754
19755 @item
19756 @findex Interfaces
19757 @cindex Annex B
19758 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19759 defined in Annex B.
19760
19761 @item
19762 @findex System
19763 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19764 both language-defined children and GNAT run-time routines.
19765
19766 @item
19767 @findex GNAT
19768 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19769 general-purpose packages, fully documented in their specs. All
19770 the other @file{.c} files are modifications of common @command{gcc} files.
19771 @end itemize
19772
19773 @node Getting Internal Debugging Information
19774 @section Getting Internal Debugging Information
19775
19776 @noindent
19777 Most compilers have internal debugging switches and modes. GNAT
19778 does also, except GNAT internal debugging switches and modes are not
19779 secret. A summary and full description of all the compiler and binder
19780 debug flags are in the file @file{debug.adb}. You must obtain the
19781 sources of the compiler to see the full detailed effects of these flags.
19782
19783 The switches that print the source of the program (reconstructed from
19784 the internal tree) are of general interest for user programs, as are the
19785 options to print
19786 the full internal tree, and the entity table (the symbol table
19787 information). The reconstructed source provides a readable version of the
19788 program after the front-end has completed analysis and  expansion,
19789 and is useful when studying the performance of specific constructs.
19790 For example, constraint checks are indicated, complex aggregates
19791 are replaced with loops and assignments, and tasking primitives
19792 are replaced with run-time calls.
19793
19794 @node Stack Traceback
19795 @section Stack Traceback
19796 @cindex traceback
19797 @cindex stack traceback
19798 @cindex stack unwinding
19799
19800 @noindent
19801 Traceback is a mechanism to display the sequence of subprogram calls that
19802 leads to a specified execution point in a program. Often (but not always)
19803 the execution point is an instruction at which an exception has been raised.
19804 This mechanism is also known as @i{stack unwinding} because it obtains
19805 its information by scanning the run-time stack and recovering the activation
19806 records of all active subprograms. Stack unwinding is one of the most
19807 important tools for program debugging.
19808
19809 The first entry stored in traceback corresponds to the deepest calling level,
19810 that is to say the subprogram currently executing the instruction
19811 from which we want to obtain the traceback.
19812
19813 Note that there is no runtime performance penalty when stack traceback
19814 is enabled, and no exception is raised during program execution.
19815
19816 @menu
19817 * Non-Symbolic Traceback::
19818 * Symbolic Traceback::
19819 @end menu
19820
19821 @node Non-Symbolic Traceback
19822 @subsection Non-Symbolic Traceback
19823 @cindex traceback, non-symbolic
19824
19825 @noindent
19826 Note: this feature is not supported on all platforms. See
19827 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19828 platforms.
19829
19830 @menu
19831 * Tracebacks From an Unhandled Exception::
19832 * Tracebacks From Exception Occurrences (non-symbolic)::
19833 * Tracebacks From Anywhere in a Program (non-symbolic)::
19834 @end menu
19835
19836 @node Tracebacks From an Unhandled Exception
19837 @subsubsection Tracebacks From an Unhandled Exception
19838
19839 @noindent
19840 A runtime non-symbolic traceback is a list of addresses of call instructions.
19841 To enable this feature you must use the @option{-E}
19842 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19843 of exception information. You can retrieve this information using the
19844 @code{addr2line} tool.
19845
19846 Here is a simple example:
19847
19848 @smallexample @c ada
19849 @cartouche
19850 procedure STB is
19851
19852    procedure P1 is
19853    begin
19854       raise Constraint_Error;
19855    end P1;
19856
19857    procedure P2 is
19858    begin
19859       P1;
19860    end P2;
19861
19862 begin
19863    P2;
19864 end STB;
19865 @end cartouche
19866 @end smallexample
19867
19868 @smallexample
19869 $ gnatmake stb -bargs -E
19870 $ stb
19871
19872 Execution terminated by unhandled exception
19873 Exception name: CONSTRAINT_ERROR
19874 Message: stb.adb:5
19875 Call stack traceback locations:
19876 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19877 @end smallexample
19878
19879 @noindent
19880 As we see the traceback lists a sequence of addresses for the unhandled
19881 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19882 guess that this exception come from procedure P1. To translate these
19883 addresses into the source lines where the calls appear, the
19884 @code{addr2line} tool, described below, is invaluable. The use of this tool
19885 requires the program to be compiled with debug information.
19886
19887 @smallexample
19888 $ gnatmake -g stb -bargs -E
19889 $ stb
19890
19891 Execution terminated by unhandled exception
19892 Exception name: CONSTRAINT_ERROR
19893 Message: stb.adb:5
19894 Call stack traceback locations:
19895 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19896
19897 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19898    0x4011f1 0x77e892a4
19899
19900 00401373 at d:/stb/stb.adb:5
19901 0040138B at d:/stb/stb.adb:10
19902 0040139C at d:/stb/stb.adb:14
19903 00401335 at d:/stb/b~stb.adb:104
19904 004011C4 at /build/@dots{}/crt1.c:200
19905 004011F1 at /build/@dots{}/crt1.c:222
19906 77E892A4 in ?? at ??:0
19907 @end smallexample
19908
19909 @noindent
19910 The @code{addr2line} tool has several other useful options:
19911
19912 @table @code
19913 @item --functions
19914 to get the function name corresponding to any location
19915
19916 @item --demangle=gnat
19917 to use the gnat decoding mode for the function names. Note that
19918 for binutils version 2.9.x the option is simply @option{--demangle}.
19919 @end table
19920
19921 @smallexample
19922 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19923    0x40139c 0x401335 0x4011c4 0x4011f1
19924
19925 00401373 in stb.p1 at d:/stb/stb.adb:5
19926 0040138B in stb.p2 at d:/stb/stb.adb:10
19927 0040139C in stb at d:/stb/stb.adb:14
19928 00401335 in main at d:/stb/b~stb.adb:104
19929 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19930 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19931 @end smallexample
19932
19933 @noindent
19934 From this traceback we can see that the exception was raised in
19935 @file{stb.adb} at line 5, which was reached from a procedure call in
19936 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19937 which contains the call to the main program.
19938 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19939 and the output will vary from platform to platform.
19940
19941 It is also possible to use @code{GDB} with these traceback addresses to debug
19942 the program. For example, we can break at a given code location, as reported
19943 in the stack traceback:
19944
19945 @smallexample
19946 $ gdb -nw stb
19947 @ifclear vms
19948 @noindent
19949 Furthermore, this feature is not implemented inside Windows DLL. Only
19950 the non-symbolic traceback is reported in this case.
19951 @end ifclear
19952
19953 (gdb) break *0x401373
19954 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19955 @end smallexample
19956
19957 @noindent
19958 It is important to note that the stack traceback addresses
19959 do not change when debug information is included. This is particularly useful
19960 because it makes it possible to release software without debug information (to
19961 minimize object size), get a field report that includes a stack traceback
19962 whenever an internal bug occurs, and then be able to retrieve the sequence
19963 of calls with the same program compiled with debug information.
19964
19965 @node Tracebacks From Exception Occurrences (non-symbolic)
19966 @subsubsection Tracebacks From Exception Occurrences
19967
19968 @noindent
19969 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19970 The stack traceback is attached to the exception information string, and can
19971 be retrieved in an exception handler within the Ada program, by means of the
19972 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19973
19974 @smallexample @c ada
19975 with Ada.Text_IO;
19976 with Ada.Exceptions;
19977
19978 procedure STB is
19979
19980    use Ada;
19981    use Ada.Exceptions;
19982
19983    procedure P1 is
19984       K : Positive := 1;
19985    begin
19986       K := K - 1;
19987    exception
19988       when E : others =>
19989          Text_IO.Put_Line (Exception_Information (E));
19990    end P1;
19991
19992    procedure P2 is
19993    begin
19994       P1;
19995    end P2;
19996
19997 begin
19998    P2;
19999 end STB;
20000 @end smallexample
20001
20002 @noindent
20003 This program will output:
20004
20005 @smallexample
20006 $ stb
20007
20008 Exception name: CONSTRAINT_ERROR
20009 Message: stb.adb:12
20010 Call stack traceback locations:
20011 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20012 @end smallexample
20013
20014 @node Tracebacks From Anywhere in a Program (non-symbolic)
20015 @subsubsection Tracebacks From Anywhere in a Program
20016
20017 @noindent
20018 It is also possible to retrieve a stack traceback from anywhere in a
20019 program. For this you need to
20020 use the @code{GNAT.Traceback} API. This package includes a procedure called
20021 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20022 display procedures described below. It is not necessary to use the
20023 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20024 is invoked explicitly.
20025
20026 @noindent
20027 In the following example we compute a traceback at a specific location in
20028 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20029 convert addresses to strings:
20030
20031 @smallexample @c ada
20032 with Ada.Text_IO;
20033 with GNAT.Traceback;
20034 with GNAT.Debug_Utilities;
20035
20036 procedure STB is
20037
20038    use Ada;
20039    use GNAT;
20040    use GNAT.Traceback;
20041
20042    procedure P1 is
20043       TB  : Tracebacks_Array (1 .. 10);
20044       --  We are asking for a maximum of 10 stack frames.
20045       Len : Natural;
20046       --  Len will receive the actual number of stack frames returned.
20047    begin
20048       Call_Chain (TB, Len);
20049
20050       Text_IO.Put ("In STB.P1 : ");
20051
20052       for K in 1 .. Len loop
20053          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20054          Text_IO.Put (' ');
20055       end loop;
20056
20057       Text_IO.New_Line;
20058    end P1;
20059
20060    procedure P2 is
20061    begin
20062       P1;
20063    end P2;
20064
20065 begin
20066    P2;
20067 end STB;
20068 @end smallexample
20069
20070 @smallexample
20071 $ gnatmake -g stb
20072 $ stb
20073
20074 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20075 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20076 @end smallexample
20077
20078 @noindent
20079 You can then get further information by invoking the @code{addr2line}
20080 tool as described earlier (note that the hexadecimal addresses
20081 need to be specified in C format, with a leading ``0x'').
20082
20083 @node Symbolic Traceback
20084 @subsection Symbolic Traceback
20085 @cindex traceback, symbolic
20086
20087 @noindent
20088 A symbolic traceback is a stack traceback in which procedure names are
20089 associated with each code location.
20090
20091 @noindent
20092 Note that this feature is not supported on all platforms. See
20093 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20094 list of currently supported platforms.
20095
20096 @noindent
20097 Note that the symbolic traceback requires that the program be compiled
20098 with debug information. If it is not compiled with debug information
20099 only the non-symbolic information will be valid.
20100
20101 @menu
20102 * Tracebacks From Exception Occurrences (symbolic)::
20103 * Tracebacks From Anywhere in a Program (symbolic)::
20104 @end menu
20105
20106 @node Tracebacks From Exception Occurrences (symbolic)
20107 @subsubsection Tracebacks From Exception Occurrences
20108
20109 @smallexample @c ada
20110 with Ada.Text_IO;
20111 with GNAT.Traceback.Symbolic;
20112
20113 procedure STB is
20114
20115    procedure P1 is
20116    begin
20117       raise Constraint_Error;
20118    end P1;
20119
20120    procedure P2 is
20121    begin
20122       P1;
20123    end P2;
20124
20125    procedure P3 is
20126    begin
20127       P2;
20128    end P3;
20129
20130 begin
20131    P3;
20132 exception
20133    when E : others =>
20134       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20135 end STB;
20136 @end smallexample
20137
20138 @smallexample
20139 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20140 $ stb
20141
20142 0040149F in stb.p1 at stb.adb:8
20143 004014B7 in stb.p2 at stb.adb:13
20144 004014CF in stb.p3 at stb.adb:18
20145 004015DD in ada.stb at stb.adb:22
20146 00401461 in main at b~stb.adb:168
20147 004011C4 in __mingw_CRTStartup at crt1.c:200
20148 004011F1 in mainCRTStartup at crt1.c:222
20149 77E892A4 in ?? at ??:0
20150 @end smallexample
20151
20152 @noindent
20153 In the above example the ``.\'' syntax in the @command{gnatmake} command
20154 is currently required by @command{addr2line} for files that are in
20155 the current working directory.
20156 Moreover, the exact sequence of linker options may vary from platform
20157 to platform.
20158 The above @option{-largs} section is for Windows platforms. By contrast,
20159 under Unix there is no need for the @option{-largs} section.
20160 Differences across platforms are due to details of linker implementation.
20161
20162 @node Tracebacks From Anywhere in a Program (symbolic)
20163 @subsubsection Tracebacks From Anywhere in a Program
20164
20165 @noindent
20166 It is possible to get a symbolic stack traceback
20167 from anywhere in a program, just as for non-symbolic tracebacks.
20168 The first step is to obtain a non-symbolic
20169 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20170 information. Here is an example:
20171
20172 @smallexample @c ada
20173 with Ada.Text_IO;
20174 with GNAT.Traceback;
20175 with GNAT.Traceback.Symbolic;
20176
20177 procedure STB is
20178
20179    use Ada;
20180    use GNAT.Traceback;
20181    use GNAT.Traceback.Symbolic;
20182
20183    procedure P1 is
20184       TB  : Tracebacks_Array (1 .. 10);
20185       --  We are asking for a maximum of 10 stack frames.
20186       Len : Natural;
20187       --  Len will receive the actual number of stack frames returned.
20188    begin
20189       Call_Chain (TB, Len);
20190       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20191    end P1;
20192
20193    procedure P2 is
20194    begin
20195       P1;
20196    end P2;
20197
20198 begin
20199    P2;
20200 end STB;
20201 @end smallexample
20202
20203 @c ******************************
20204 @ifset vms
20205 @node Compatibility with HP Ada
20206 @chapter Compatibility with HP Ada
20207 @cindex Compatibility
20208
20209 @noindent
20210 @cindex DEC Ada
20211 @cindex HP Ada
20212 @cindex Compatibility between GNAT and HP Ada
20213 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20214 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20215 GNAT is highly compatible
20216 with HP Ada, and it should generally be straightforward to port code
20217 from the HP Ada environment to GNAT. However, there are a few language
20218 and implementation differences of which the user must be aware. These
20219 differences are discussed in this chapter. In
20220 addition, the operating environment and command structure for the
20221 compiler are different, and these differences are also discussed.
20222
20223 For further details on these and other compatibility issues,
20224 see Appendix E of the HP publication
20225 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20226
20227 Except where otherwise indicated, the description of GNAT for OpenVMS
20228 applies to both the Alpha and I64 platforms.
20229
20230 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20231 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20232
20233 The discussion in this chapter addresses specifically the implementation
20234 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20235 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20236 GNAT always follows the Alpha implementation.
20237
20238 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20239 attributes are recognized, although only a subset of them can sensibly
20240 be implemented.  The description of pragmas in
20241 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20242 indicates whether or not they are applicable to non-VMS systems.
20243
20244 @menu
20245 * Ada Language Compatibility::
20246 * Differences in the Definition of Package System::
20247 * Language-Related Features::
20248 * The Package STANDARD::
20249 * The Package SYSTEM::
20250 * Tasking and Task-Related Features::
20251 * Pragmas and Pragma-Related Features::
20252 * Library of Predefined Units::
20253 * Bindings::
20254 * Main Program Definition::
20255 * Implementation-Defined Attributes::
20256 * Compiler and Run-Time Interfacing::
20257 * Program Compilation and Library Management::
20258 * Input-Output::
20259 * Implementation Limits::
20260 * Tools and Utilities::
20261 @end menu
20262
20263 @node Ada Language Compatibility
20264 @section Ada Language Compatibility
20265
20266 @noindent
20267 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20268 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20269 with Ada 83, and therefore Ada 83 programs will compile
20270 and run under GNAT with
20271 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20272 provides details on specific incompatibilities.
20273
20274 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20275 as well as the pragma @code{ADA_83}, to force the compiler to
20276 operate in Ada 83 mode. This mode does not guarantee complete
20277 conformance to Ada 83, but in practice is sufficient to
20278 eliminate most sources of incompatibilities.
20279 In particular, it eliminates the recognition of the
20280 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20281 in Ada 83 programs is legal, and handles the cases of packages
20282 with optional bodies, and generics that instantiate unconstrained
20283 types without the use of @code{(<>)}.
20284
20285 @node Differences in the Definition of Package System
20286 @section Differences in the Definition of Package @code{System}
20287
20288 @noindent
20289 An Ada compiler is allowed to add
20290 implementation-dependent declarations to package @code{System}.
20291 In normal mode,
20292 GNAT does not take advantage of this permission, and the version of
20293 @code{System} provided by GNAT exactly matches that defined in the Ada
20294 Reference Manual.
20295
20296 However, HP Ada adds an extensive set of declarations to package
20297 @code{System},
20298 as fully documented in the HP Ada manuals. To minimize changes required
20299 for programs that make use of these extensions, GNAT provides the pragma
20300 @code{Extend_System} for extending the definition of package System. By using:
20301 @cindex pragma @code{Extend_System}
20302 @cindex @code{Extend_System} pragma
20303
20304 @smallexample @c ada
20305 @group
20306 @cartouche
20307 pragma Extend_System (Aux_DEC);
20308 @end cartouche
20309 @end group
20310 @end smallexample
20311
20312 @noindent
20313 the set of definitions in @code{System} is extended to include those in
20314 package @code{System.Aux_DEC}.
20315 @cindex @code{System.Aux_DEC} package
20316 @cindex @code{Aux_DEC} package (child of @code{System})
20317 These definitions are incorporated directly into package @code{System},
20318 as though they had been declared there. For a
20319 list of the declarations added, see the spec of this package,
20320 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20321 @cindex @file{s-auxdec.ads} file
20322 The pragma @code{Extend_System} is a configuration pragma, which means that
20323 it can be placed in the file @file{gnat.adc}, so that it will automatically
20324 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20325 for further details.
20326
20327 An alternative approach that avoids the use of the non-standard
20328 @code{Extend_System} pragma is to add a context clause to the unit that
20329 references these facilities:
20330
20331 @smallexample @c ada
20332 @cartouche
20333 with System.Aux_DEC;
20334 use  System.Aux_DEC;
20335 @end cartouche
20336 @end smallexample
20337
20338 @noindent
20339 The effect is not quite semantically identical to incorporating
20340 the declarations directly into package @code{System},
20341 but most programs will not notice a difference
20342 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20343 to reference the entities directly in package @code{System}.
20344 For units containing such references,
20345 the prefixes must either be removed, or the pragma @code{Extend_System}
20346 must be used.
20347
20348 @node Language-Related Features
20349 @section Language-Related Features
20350
20351 @noindent
20352 The following sections highlight differences in types,
20353 representations of types, operations, alignment, and
20354 related topics.
20355
20356 @menu
20357 * Integer Types and Representations::
20358 * Floating-Point Types and Representations::
20359 * Pragmas Float_Representation and Long_Float::
20360 * Fixed-Point Types and Representations::
20361 * Record and Array Component Alignment::
20362 * Address Clauses::
20363 * Other Representation Clauses::
20364 @end menu
20365
20366 @node Integer Types and Representations
20367 @subsection Integer Types and Representations
20368
20369 @noindent
20370 The set of predefined integer types is identical in HP Ada and GNAT.
20371 Furthermore the representation of these integer types is also identical,
20372 including the capability of size clauses forcing biased representation.
20373
20374 In addition,
20375 HP Ada for OpenVMS Alpha systems has defined the
20376 following additional integer types in package @code{System}:
20377
20378 @itemize @bullet
20379
20380 @item
20381 @code{INTEGER_8}
20382
20383 @item
20384 @code{INTEGER_16}
20385
20386 @item
20387 @code{INTEGER_32}
20388
20389 @item
20390 @code{INTEGER_64}
20391
20392 @item
20393 @code{LARGEST_INTEGER}
20394 @end itemize
20395
20396 @noindent
20397 In GNAT, the first four of these types may be obtained from the
20398 standard Ada package @code{Interfaces}.
20399 Alternatively, by use of the pragma @code{Extend_System}, identical
20400 declarations can be referenced directly in package @code{System}.
20401 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20402
20403 @node Floating-Point Types and Representations
20404 @subsection Floating-Point Types and Representations
20405 @cindex Floating-Point types
20406
20407 @noindent
20408 The set of predefined floating-point types is identical in HP Ada and GNAT.
20409 Furthermore the representation of these floating-point
20410 types is also identical. One important difference is that the default
20411 representation for HP Ada is @code{VAX_Float}, but the default representation
20412 for GNAT is IEEE.
20413
20414 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20415 pragma @code{Float_Representation} as described in the HP Ada
20416 documentation.
20417 For example, the declarations:
20418
20419 @smallexample @c ada
20420 @cartouche
20421 type F_Float is digits 6;
20422 pragma Float_Representation (VAX_Float, F_Float);
20423 @end cartouche
20424 @end smallexample
20425
20426 @noindent
20427 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20428 format.
20429 This set of declarations actually appears in @code{System.Aux_DEC},
20430 which contains
20431 the full set of additional floating-point declarations provided in
20432 the HP Ada version of package @code{System}.
20433 This and similar declarations may be accessed in a user program
20434 by using pragma @code{Extend_System}. The use of this
20435 pragma, and the related pragma @code{Long_Float} is described in further
20436 detail in the following section.
20437
20438 @node Pragmas Float_Representation and Long_Float
20439 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20440
20441 @noindent
20442 HP Ada provides the pragma @code{Float_Representation}, which
20443 acts as a program library switch to allow control over
20444 the internal representation chosen for the predefined
20445 floating-point types declared in the package @code{Standard}.
20446 The format of this pragma is as follows:
20447
20448 @smallexample @c ada
20449 @cartouche
20450 pragma Float_Representation(VAX_Float | IEEE_Float);
20451 @end cartouche
20452 @end smallexample
20453
20454 @noindent
20455 This pragma controls the representation of floating-point
20456 types as follows:
20457
20458 @itemize @bullet
20459 @item
20460 @code{VAX_Float} specifies that floating-point
20461 types are represented by default with the VAX system hardware types
20462 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20463 Note that the @code{H-floating}
20464 type was available only on VAX systems, and is not available
20465 in either HP Ada or GNAT.
20466
20467 @item
20468 @code{IEEE_Float} specifies that floating-point
20469 types are represented by default with the IEEE single and
20470 double floating-point types.
20471 @end itemize
20472
20473 @noindent
20474 GNAT provides an identical implementation of the pragma
20475 @code{Float_Representation}, except that it functions as a
20476 configuration pragma. Note that the
20477 notion of configuration pragma corresponds closely to the
20478 HP Ada notion of a program library switch.
20479
20480 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20481 which is different
20482 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20483 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20484 advisable to change the format of numbers passed to standard library
20485 routines, and if necessary explicit type conversions may be needed.
20486
20487 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20488 efficient, and (given that it conforms to an international standard)
20489 potentially more portable.
20490 The situation in which @code{VAX_Float} may be useful is in interfacing
20491 to existing code and data that expect the use of @code{VAX_Float}.
20492 In such a situation use the predefined @code{VAX_Float}
20493 types in package @code{System}, as extended by
20494 @code{Extend_System}. For example, use @code{System.F_Float}
20495 to specify the 32-bit @code{F-Float} format.
20496
20497 @noindent
20498 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20499 to allow control over the internal representation chosen
20500 for the predefined type @code{Long_Float} and for floating-point
20501 type declarations with digits specified in the range 7 .. 15.
20502 The format of this pragma is as follows:
20503
20504 @smallexample @c ada
20505 @cartouche
20506 pragma Long_Float (D_FLOAT | G_FLOAT);
20507 @end cartouche
20508 @end smallexample
20509
20510 @node Fixed-Point Types and Representations
20511 @subsection Fixed-Point Types and Representations
20512
20513 @noindent
20514 On HP Ada for OpenVMS Alpha systems, rounding is
20515 away from zero for both positive and negative numbers.
20516 Therefore, @code{+0.5} rounds to @code{1},
20517 and @code{-0.5} rounds to @code{-1}.
20518
20519 On GNAT the results of operations
20520 on fixed-point types are in accordance with the Ada
20521 rules. In particular, results of operations on decimal
20522 fixed-point types are truncated.
20523
20524 @node Record and Array Component Alignment
20525 @subsection Record and Array Component Alignment
20526
20527 @noindent
20528 On HP Ada for OpenVMS Alpha, all non-composite components
20529 are aligned on natural boundaries. For example, 1-byte
20530 components are aligned on byte boundaries, 2-byte
20531 components on 2-byte boundaries, 4-byte components on 4-byte
20532 byte boundaries, and so on. The OpenVMS Alpha hardware
20533 runs more efficiently with naturally aligned data.
20534
20535 On GNAT, alignment rules are compatible
20536 with HP Ada for OpenVMS Alpha.
20537
20538 @node Address Clauses
20539 @subsection Address Clauses
20540
20541 @noindent
20542 In HP Ada and GNAT, address clauses are supported for
20543 objects and imported subprograms.
20544 The predefined type @code{System.Address} is a private type
20545 in both compilers on Alpha OpenVMS, with the same representation
20546 (it is simply a machine pointer). Addition, subtraction, and comparison
20547 operations are available in the standard Ada package
20548 @code{System.Storage_Elements}, or in package @code{System}
20549 if it is extended to include @code{System.Aux_DEC} using a
20550 pragma @code{Extend_System} as previously described.
20551
20552 Note that code that @code{with}'s both this extended package @code{System}
20553 and the package @code{System.Storage_Elements} should not @code{use}
20554 both packages, or ambiguities will result. In general it is better
20555 not to mix these two sets of facilities. The Ada package was
20556 designed specifically to provide the kind of features that HP Ada
20557 adds directly to package @code{System}.
20558
20559 The type @code{System.Address} is a 64-bit integer type in GNAT for
20560 I64 OpenVMS.  For more information,
20561 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20562
20563 GNAT is compatible with HP Ada in its handling of address
20564 clauses, except for some limitations in
20565 the form of address clauses for composite objects with
20566 initialization. Such address clauses are easily replaced
20567 by the use of an explicitly-defined constant as described
20568 in the Ada Reference Manual (13.1(22)). For example, the sequence
20569 of declarations:
20570
20571 @smallexample @c ada
20572 @cartouche
20573 X, Y : Integer := Init_Func;
20574 Q : String (X .. Y) := "abc";
20575 @dots{}
20576 for Q'Address use Compute_Address;
20577 @end cartouche
20578 @end smallexample
20579
20580 @noindent
20581 will be rejected by GNAT, since the address cannot be computed at the time
20582 that @code{Q} is declared. To achieve the intended effect, write instead:
20583
20584 @smallexample @c ada
20585 @group
20586 @cartouche
20587 X, Y : Integer := Init_Func;
20588 Q_Address : constant Address := Compute_Address;
20589 Q : String (X .. Y) := "abc";
20590 @dots{}
20591 for Q'Address use Q_Address;
20592 @end cartouche
20593 @end group
20594 @end smallexample
20595
20596 @noindent
20597 which will be accepted by GNAT (and other Ada compilers), and is also
20598 compatible with Ada 83. A fuller description of the restrictions
20599 on address specifications is found in @ref{Top, GNAT Reference Manual,
20600 About This Guide, gnat_rm, GNAT Reference Manual}.
20601
20602 @node Other Representation Clauses
20603 @subsection Other Representation Clauses
20604
20605 @noindent
20606 GNAT implements in a compatible manner all the representation
20607 clauses supported by HP Ada. In addition, GNAT
20608 implements the representation clause forms that were introduced in Ada 95,
20609 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20610
20611 @node The Package STANDARD
20612 @section The Package @code{STANDARD}
20613
20614 @noindent
20615 The package @code{STANDARD}, as implemented by HP Ada, is fully
20616 described in the @cite{Ada Reference Manual} and in the
20617 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20618 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20619
20620 In addition, HP Ada supports the Latin-1 character set in
20621 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20622 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20623 the type @code{WIDE_CHARACTER}.
20624
20625 The floating-point types supported by GNAT are those
20626 supported by HP Ada, but the defaults are different, and are controlled by
20627 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20628
20629 @node The Package SYSTEM
20630 @section The Package @code{SYSTEM}
20631
20632 @noindent
20633 HP Ada provides a specific version of the package
20634 @code{SYSTEM} for each platform on which the language is implemented.
20635 For the complete spec of the package @code{SYSTEM}, see
20636 Appendix F of the @cite{HP Ada Language Reference Manual}.
20637
20638 On HP Ada, the package @code{SYSTEM} includes the following conversion
20639 functions:
20640 @itemize @bullet
20641 @item @code{TO_ADDRESS(INTEGER)}
20642
20643 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20644
20645 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20646
20647 @item @code{TO_INTEGER(ADDRESS)}
20648
20649 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20650
20651 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20652 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20653 @end itemize
20654
20655 @noindent
20656 By default, GNAT supplies a version of @code{SYSTEM} that matches
20657 the definition given in the @cite{Ada Reference Manual}.
20658 This
20659 is a subset of the HP system definitions, which is as
20660 close as possible to the original definitions. The only difference
20661 is that the definition of @code{SYSTEM_NAME} is different:
20662
20663 @smallexample @c ada
20664 @cartouche
20665 type Name is (SYSTEM_NAME_GNAT);
20666 System_Name : constant Name := SYSTEM_NAME_GNAT;
20667 @end cartouche
20668 @end smallexample
20669
20670 @noindent
20671 Also, GNAT adds the Ada declarations for
20672 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20673
20674 However, the use of the following pragma causes GNAT
20675 to extend the definition of package @code{SYSTEM} so that it
20676 encompasses the full set of HP-specific extensions,
20677 including the functions listed above:
20678
20679 @smallexample @c ada
20680 @cartouche
20681 pragma Extend_System (Aux_DEC);
20682 @end cartouche
20683 @end smallexample
20684
20685 @noindent
20686 The pragma @code{Extend_System} is a configuration pragma that
20687 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20688 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20689
20690 HP Ada does not allow the recompilation of the package
20691 @code{SYSTEM}. Instead HP Ada provides several pragmas
20692 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20693 to modify values in the package @code{SYSTEM}.
20694 On OpenVMS Alpha systems, the pragma
20695 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20696 its single argument.
20697
20698 GNAT does permit the recompilation of package @code{SYSTEM} using
20699 the special switch @option{-gnatg}, and this switch can be used if
20700 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20701 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20702 or @code{MEMORY_SIZE} by any other means.
20703
20704 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20705 enumeration literal @code{SYSTEM_NAME_GNAT}.
20706
20707 The definitions provided by the use of
20708
20709 @smallexample @c ada
20710 pragma Extend_System (AUX_Dec);
20711 @end smallexample
20712
20713 @noindent
20714 are virtually identical to those provided by the HP Ada 83 package
20715 @code{SYSTEM}. One important difference is that the name of the
20716 @code{TO_ADDRESS}
20717 function for type @code{UNSIGNED_LONGWORD} is changed to
20718 @code{TO_ADDRESS_LONG}.
20719 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20720 discussion of why this change was necessary.
20721
20722 @noindent
20723 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20724 is in fact
20725 an extension to Ada 83 not strictly compatible with the reference manual.
20726 GNAT, in order to be exactly compatible with the standard,
20727 does not provide this capability. In HP Ada 83, the
20728 point of this definition is to deal with a call like:
20729
20730 @smallexample @c ada
20731 TO_ADDRESS (16#12777#);
20732 @end smallexample
20733
20734 @noindent
20735 Normally, according to Ada 83 semantics, one would expect this to be
20736 ambiguous, since it matches both the @code{INTEGER} and
20737 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20738 However, in HP Ada 83, there is no ambiguity, since the
20739 definition using @i{universal_integer} takes precedence.
20740
20741 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20742 it is
20743 not possible to be 100% compatible. Since there are many programs using
20744 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20745 GNAT was
20746 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20747 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20748
20749 @smallexample @c ada
20750 function To_Address (X : Integer) return Address;
20751 pragma Pure_Function (To_Address);
20752
20753 function To_Address_Long (X : Unsigned_Longword) return Address;
20754 pragma Pure_Function (To_Address_Long);
20755 @end smallexample
20756
20757 @noindent
20758 This means that programs using @code{TO_ADDRESS} for
20759 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20760
20761 @node Tasking and Task-Related Features
20762 @section Tasking and Task-Related Features
20763
20764 @noindent
20765 This section compares the treatment of tasking in GNAT
20766 and in HP Ada for OpenVMS Alpha.
20767 The GNAT description applies to both Alpha and I64 OpenVMS.
20768 For detailed information on tasking in
20769 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20770 relevant run-time reference manual.
20771
20772 @menu
20773 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20774 * Assigning Task IDs::
20775 * Task IDs and Delays::
20776 * Task-Related Pragmas::
20777 * Scheduling and Task Priority::
20778 * The Task Stack::
20779 * External Interrupts::
20780 @end menu
20781
20782 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20783 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20784
20785 @noindent
20786 On OpenVMS Alpha systems, each Ada task (except a passive
20787 task) is implemented as a single stream of execution
20788 that is created and managed by the kernel. On these
20789 systems, HP Ada tasking support is based on DECthreads,
20790 an implementation of the POSIX standard for threads.
20791
20792 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20793 code that calls DECthreads routines can be used together.
20794 The interaction between Ada tasks and DECthreads routines
20795 can have some benefits. For example when on OpenVMS Alpha,
20796 HP Ada can call C code that is already threaded.
20797
20798 GNAT uses the facilities of DECthreads,
20799 and Ada tasks are mapped to threads.
20800
20801 @node Assigning Task IDs
20802 @subsection Assigning Task IDs
20803
20804 @noindent
20805 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20806 the environment task that executes the main program. On
20807 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20808 that have been created but are not yet activated.
20809
20810 On OpenVMS Alpha systems, task IDs are assigned at
20811 activation. On GNAT systems, task IDs are also assigned at
20812 task creation but do not have the same form or values as
20813 task ID values in HP Ada. There is no null task, and the
20814 environment task does not have a specific task ID value.
20815
20816 @node Task IDs and Delays
20817 @subsection Task IDs and Delays
20818
20819 @noindent
20820 On OpenVMS Alpha systems, tasking delays are implemented
20821 using Timer System Services. The Task ID is used for the
20822 identification of the timer request (the @code{REQIDT} parameter).
20823 If Timers are used in the application take care not to use
20824 @code{0} for the identification, because cancelling such a timer
20825 will cancel all timers and may lead to unpredictable results.
20826
20827 @node Task-Related Pragmas
20828 @subsection Task-Related Pragmas
20829
20830 @noindent
20831 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20832 specification of the size of the guard area for a task
20833 stack. (The guard area forms an area of memory that has no
20834 read or write access and thus helps in the detection of
20835 stack overflow.) On OpenVMS Alpha systems, if the pragma
20836 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20837 area is created. In the absence of a pragma @code{TASK_STORAGE},
20838 a default guard area is created.
20839
20840 GNAT supplies the following task-related pragmas:
20841
20842 @itemize @bullet
20843 @item  @code{TASK_INFO}
20844
20845 This pragma appears within a task definition and
20846 applies to the task in which it appears. The argument
20847 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20848
20849 @item  @code{TASK_STORAGE}
20850
20851 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20852 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20853 @code{SUPPRESS}, and @code{VOLATILE}.
20854 @end itemize
20855 @node Scheduling and Task Priority
20856 @subsection Scheduling and Task Priority
20857
20858 @noindent
20859 HP Ada implements the Ada language requirement that
20860 when two tasks are eligible for execution and they have
20861 different priorities, the lower priority task does not
20862 execute while the higher priority task is waiting. The HP
20863 Ada Run-Time Library keeps a task running until either the
20864 task is suspended or a higher priority task becomes ready.
20865
20866 On OpenVMS Alpha systems, the default strategy is round-
20867 robin with preemption. Tasks of equal priority take turns
20868 at the processor. A task is run for a certain period of
20869 time and then placed at the tail of the ready queue for
20870 its priority level.
20871
20872 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20873 which can be used to enable or disable round-robin
20874 scheduling of tasks with the same priority.
20875 See the relevant HP Ada run-time reference manual for
20876 information on using the pragmas to control HP Ada task
20877 scheduling.
20878
20879 GNAT follows the scheduling rules of Annex D (Real-Time
20880 Annex) of the @cite{Ada Reference Manual}. In general, this
20881 scheduling strategy is fully compatible with HP Ada
20882 although it provides some additional constraints (as
20883 fully documented in Annex D).
20884 GNAT implements time slicing control in a manner compatible with
20885 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20886 are identical to the HP Ada 83 pragma of the same name.
20887 Note that it is not possible to mix GNAT tasking and
20888 HP Ada 83 tasking in the same program, since the two run-time
20889 libraries are not compatible.
20890
20891 @node The Task Stack
20892 @subsection The Task Stack
20893
20894 @noindent
20895 In HP Ada, a task stack is allocated each time a
20896 non-passive task is activated. As soon as the task is
20897 terminated, the storage for the task stack is deallocated.
20898 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20899 a default stack size is used. Also, regardless of the size
20900 specified, some additional space is allocated for task
20901 management purposes. On OpenVMS Alpha systems, at least
20902 one page is allocated.
20903
20904 GNAT handles task stacks in a similar manner. In accordance with
20905 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20906 an alternative method for controlling the task stack size.
20907 The specification of the attribute @code{T'STORAGE_SIZE} is also
20908 supported in a manner compatible with HP Ada.
20909
20910 @node External Interrupts
20911 @subsection External Interrupts
20912
20913 @noindent
20914 On HP Ada, external interrupts can be associated with task entries.
20915 GNAT is compatible with HP Ada in its handling of external interrupts.
20916
20917 @node Pragmas and Pragma-Related Features
20918 @section Pragmas and Pragma-Related Features
20919
20920 @noindent
20921 Both HP Ada and GNAT supply all language-defined pragmas
20922 as specified by the Ada 83 standard. GNAT also supplies all
20923 language-defined pragmas introduced by Ada 95 and Ada 2005.
20924 In addition, GNAT implements the implementation-defined pragmas
20925 from HP Ada 83.
20926
20927 @itemize @bullet
20928 @item  @code{AST_ENTRY}
20929
20930 @item  @code{COMMON_OBJECT}
20931
20932 @item  @code{COMPONENT_ALIGNMENT}
20933
20934 @item  @code{EXPORT_EXCEPTION}
20935
20936 @item  @code{EXPORT_FUNCTION}
20937
20938 @item  @code{EXPORT_OBJECT}
20939
20940 @item  @code{EXPORT_PROCEDURE}
20941
20942 @item  @code{EXPORT_VALUED_PROCEDURE}
20943
20944 @item  @code{FLOAT_REPRESENTATION}
20945
20946 @item  @code{IDENT}
20947
20948 @item  @code{IMPORT_EXCEPTION}
20949
20950 @item  @code{IMPORT_FUNCTION}
20951
20952 @item  @code{IMPORT_OBJECT}
20953
20954 @item  @code{IMPORT_PROCEDURE}
20955
20956 @item  @code{IMPORT_VALUED_PROCEDURE}
20957
20958 @item  @code{INLINE_GENERIC}
20959
20960 @item  @code{INTERFACE_NAME}
20961
20962 @item  @code{LONG_FLOAT}
20963
20964 @item  @code{MAIN_STORAGE}
20965
20966 @item  @code{PASSIVE}
20967
20968 @item  @code{PSECT_OBJECT}
20969
20970 @item  @code{SHARE_GENERIC}
20971
20972 @item  @code{SUPPRESS_ALL}
20973
20974 @item  @code{TASK_STORAGE}
20975
20976 @item  @code{TIME_SLICE}
20977
20978 @item  @code{TITLE}
20979 @end itemize
20980
20981 @noindent
20982 These pragmas are all fully implemented, with the exception of @code{TITLE},
20983 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20984 recognized, but which have no
20985 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20986 use of Ada protected objects. In GNAT, all generics are inlined.
20987
20988 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20989 a separate subprogram specification which must appear before the
20990 subprogram body.
20991
20992 GNAT also supplies a number of implementation-defined pragmas including the
20993 following:
20994
20995 @itemize @bullet
20996 @item  @code{ABORT_DEFER}
20997
20998 @item  @code{ADA_83}
20999
21000 @item  @code{ADA_95}
21001
21002 @item  @code{ADA_05}
21003
21004 @item  @code{Ada_2005}
21005
21006 @item  @code{Ada_12}
21007
21008 @item  @code{Ada_2012}
21009
21010 @item  @code{ANNOTATE}
21011
21012 @item  @code{ASSERT}
21013
21014 @item  @code{C_PASS_BY_COPY}
21015
21016 @item  @code{CPP_CLASS}
21017
21018 @item  @code{CPP_CONSTRUCTOR}
21019
21020 @item  @code{CPP_DESTRUCTOR}
21021
21022 @item  @code{DEBUG}
21023
21024 @item  @code{EXTEND_SYSTEM}
21025
21026 @item  @code{LINKER_ALIAS}
21027
21028 @item  @code{LINKER_SECTION}
21029
21030 @item  @code{MACHINE_ATTRIBUTE}
21031
21032 @item  @code{NO_RETURN}
21033
21034 @item  @code{PURE_FUNCTION}
21035
21036 @item  @code{SOURCE_FILE_NAME}
21037
21038 @item  @code{SOURCE_REFERENCE}
21039
21040 @item  @code{TASK_INFO}
21041
21042 @item  @code{UNCHECKED_UNION}
21043
21044 @item  @code{UNIMPLEMENTED_UNIT}
21045
21046 @item  @code{UNIVERSAL_DATA}
21047
21048 @item  @code{UNSUPPRESS}
21049
21050 @item  @code{WARNINGS}
21051
21052 @item  @code{WEAK_EXTERNAL}
21053 @end itemize
21054
21055 @noindent
21056 For full details on these and other GNAT implementation-defined pragmas,
21057 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21058 Manual}.
21059
21060 @menu
21061 * Restrictions on the Pragma INLINE::
21062 * Restrictions on the Pragma INTERFACE::
21063 * Restrictions on the Pragma SYSTEM_NAME::
21064 @end menu
21065
21066 @node Restrictions on the Pragma INLINE
21067 @subsection Restrictions on Pragma @code{INLINE}
21068
21069 @noindent
21070 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21071 @itemize @bullet
21072 @item  Parameters cannot have a task type.
21073
21074 @item  Function results cannot be task types, unconstrained
21075 array types, or unconstrained types with discriminants.
21076
21077 @item  Bodies cannot declare the following:
21078 @itemize @bullet
21079 @item  Subprogram body or stub (imported subprogram is allowed)
21080
21081 @item  Tasks
21082
21083 @item  Generic declarations
21084
21085 @item  Instantiations
21086
21087 @item  Exceptions
21088
21089 @item  Access types (types derived from access types allowed)
21090
21091 @item  Array or record types
21092
21093 @item  Dependent tasks
21094
21095 @item  Direct recursive calls of subprogram or containing
21096 subprogram, directly or via a renaming
21097
21098 @end itemize
21099 @end itemize
21100
21101 @noindent
21102 In GNAT, the only restriction on pragma @code{INLINE} is that the
21103 body must occur before the call if both are in the same
21104 unit, and the size must be appropriately small. There are
21105 no other specific restrictions which cause subprograms to
21106 be incapable of being inlined.
21107
21108 @node  Restrictions on the Pragma INTERFACE
21109 @subsection  Restrictions on Pragma @code{INTERFACE}
21110
21111 @noindent
21112 The following restrictions on pragma @code{INTERFACE}
21113 are enforced by both HP Ada and GNAT:
21114 @itemize @bullet
21115 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21116 Default is the default on OpenVMS Alpha systems.
21117
21118 @item  Parameter passing: Language specifies default
21119 mechanisms but can be overridden with an @code{EXPORT} pragma.
21120
21121 @itemize @bullet
21122 @item  Ada: Use internal Ada rules.
21123
21124 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21125 record or task type. Result cannot be a string, an
21126 array, or a record.
21127
21128 @item  Fortran: Parameters cannot have a task type. Result cannot
21129 be a string, an array, or a record.
21130 @end itemize
21131 @end itemize
21132
21133 @noindent
21134 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21135 record parameters for all languages.
21136
21137 @node  Restrictions on the Pragma SYSTEM_NAME
21138 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21139
21140 @noindent
21141 For HP Ada for OpenVMS Alpha, the enumeration literal
21142 for the type @code{NAME} is @code{OPENVMS_AXP}.
21143 In GNAT, the enumeration
21144 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21145
21146 @node  Library of Predefined Units
21147 @section  Library of Predefined Units
21148
21149 @noindent
21150 A library of predefined units is provided as part of the
21151 HP Ada and GNAT implementations. HP Ada does not provide
21152 the package @code{MACHINE_CODE} but instead recommends importing
21153 assembler code.
21154
21155 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21156 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21157 version.
21158 The HP Ada Predefined Library units are modified to remove post-Ada 83
21159 incompatibilities and to make them interoperable with GNAT
21160 (@pxref{Changes to DECLIB}, for details).
21161 The units are located in the @file{DECLIB} directory.
21162
21163 The GNAT RTL is contained in
21164 the @file{ADALIB} directory, and
21165 the default search path is set up to find @code{DECLIB} units in preference
21166 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21167 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21168
21169 @menu
21170 * Changes to DECLIB::
21171 @end menu
21172
21173 @node Changes to DECLIB
21174 @subsection Changes to @code{DECLIB}
21175
21176 @noindent
21177 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21178 compatibility are minor and include the following:
21179
21180 @itemize @bullet
21181 @item  Adjusting the location of pragmas and record representation
21182 clauses to obey Ada 95 (and thus Ada 2005) rules
21183
21184 @item  Adding the proper notation to generic formal parameters
21185 that take unconstrained types in instantiation
21186
21187 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21188 that have package bodies not otherwise allowed
21189
21190 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21191 ``@code{PROTECTD}''.
21192 Currently these are found only in the @code{STARLET} package spec.
21193
21194 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21195 where the address size is constrained to 32 bits.
21196 @end itemize
21197
21198 @noindent
21199 None of the above changes is visible to users.
21200
21201 @node Bindings
21202 @section Bindings
21203
21204 @noindent
21205 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21206 @itemize @bullet
21207
21208 @item  Command Language Interpreter (CLI interface)
21209
21210 @item  DECtalk Run-Time Library (DTK interface)
21211
21212 @item  Librarian utility routines (LBR interface)
21213
21214 @item  General Purpose Run-Time Library (LIB interface)
21215
21216 @item  Math Run-Time Library (MTH interface)
21217
21218 @item  National Character Set Run-Time Library (NCS interface)
21219
21220 @item  Compiled Code Support Run-Time Library (OTS interface)
21221
21222 @item  Parallel Processing Run-Time Library (PPL interface)
21223
21224 @item  Screen Management Run-Time Library (SMG interface)
21225
21226 @item  Sort Run-Time Library (SOR interface)
21227
21228 @item  String Run-Time Library (STR interface)
21229
21230 @item STARLET System Library
21231 @findex Starlet
21232
21233 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21234
21235 @item  X Windows Toolkit (XT interface)
21236
21237 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21238 @end itemize
21239
21240 @noindent
21241 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21242 directory, on both the Alpha and I64 OpenVMS platforms.
21243
21244 The X components of DECLIB compatibility package are located in a separate
21245 library, called XDECGNAT, which is not linked with by default; this library
21246 must be explicitly linked with any application that makes use of any X facilities,
21247 with a command similar to
21248
21249 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21250
21251 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21252 in the
21253 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21254 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21255 @code{Xt}, and @code{X_Lib}
21256 causing the default X/Motif sharable image libraries to be linked in. This
21257 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21258 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21259
21260 It may be necessary to edit these options files to update or correct the
21261 library names if, for example, the newer X/Motif bindings from
21262 @file{ADA$EXAMPLES}
21263 had been (previous to installing GNAT) copied and renamed to supersede the
21264 default @file{ADA$PREDEFINED} versions.
21265
21266 @menu
21267 * Shared Libraries and Options Files::
21268 * Interfaces to C::
21269 @end menu
21270
21271 @node Shared Libraries and Options Files
21272 @subsection Shared Libraries and Options Files
21273
21274 @noindent
21275 When using the HP Ada
21276 predefined X and Motif bindings, the linking with their sharable images is
21277 done automatically by @command{GNAT LINK}.
21278 When using other X and Motif bindings, you need
21279 to add the corresponding sharable images to the command line for
21280 @code{GNAT LINK}. When linking with shared libraries, or with
21281 @file{.OPT} files, you must
21282 also add them to the command line for @command{GNAT LINK}.
21283
21284 A shared library to be used with GNAT is built in the same way as other
21285 libraries under VMS. The VMS Link command can be used in standard fashion.
21286
21287 @node Interfaces to C
21288 @subsection Interfaces to C
21289
21290 @noindent
21291 HP Ada
21292 provides the following Ada types and operations:
21293
21294 @itemize @bullet
21295 @item C types package (@code{C_TYPES})
21296
21297 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21298
21299 @item Other_types (@code{SHORT_INT})
21300 @end itemize
21301
21302 @noindent
21303 Interfacing to C with GNAT, you can use the above approach
21304 described for HP Ada or the facilities of Annex B of
21305 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21306 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21307 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21308
21309 The @option{-gnatF} qualifier forces default and explicit
21310 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21311 to be uppercased for compatibility with the default behavior
21312 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21313
21314 @node Main Program Definition
21315 @section Main Program Definition
21316
21317 @noindent
21318 The following section discusses differences in the
21319 definition of main programs on HP Ada and GNAT.
21320 On HP Ada, main programs are defined to meet the
21321 following conditions:
21322 @itemize @bullet
21323 @item  Procedure with no formal parameters (returns @code{0} upon
21324 normal completion)
21325
21326 @item  Procedure with no formal parameters (returns @code{42} when
21327 an unhandled exception is raised)
21328
21329 @item  Function with no formal parameters whose returned value
21330 is of a discrete type
21331
21332 @item  Procedure with one @code{out} formal of a discrete type for
21333 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21334
21335 @end itemize
21336
21337 @noindent
21338 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21339 a main function or main procedure returns a discrete
21340 value whose size is less than 64 bits (32 on VAX systems),
21341 the value is zero- or sign-extended as appropriate.
21342 On GNAT, main programs are defined as follows:
21343 @itemize @bullet
21344 @item  Must be a non-generic, parameterless subprogram that
21345 is either a procedure or function returning an Ada
21346 @code{STANDARD.INTEGER} (the predefined type)
21347
21348 @item  Cannot be a generic subprogram or an instantiation of a
21349 generic subprogram
21350 @end itemize
21351
21352 @node Implementation-Defined Attributes
21353 @section Implementation-Defined Attributes
21354
21355 @noindent
21356 GNAT provides all HP Ada implementation-defined
21357 attributes.
21358
21359 @node Compiler and Run-Time Interfacing
21360 @section Compiler and Run-Time Interfacing
21361
21362 @noindent
21363 HP Ada provides the following qualifiers to pass options to the linker
21364 (ACS LINK):
21365 @itemize @bullet
21366 @item  @option{/WAIT} and @option{/SUBMIT}
21367
21368 @item  @option{/COMMAND}
21369
21370 @item  @option{/@r{[}NO@r{]}MAP}
21371
21372 @item  @option{/OUTPUT=@var{file-spec}}
21373
21374 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21375 @end itemize
21376
21377 @noindent
21378 To pass options to the linker, GNAT provides the following
21379 switches:
21380
21381 @itemize @bullet
21382 @item   @option{/EXECUTABLE=@var{exec-name}}
21383
21384 @item   @option{/VERBOSE}
21385
21386 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21387 @end itemize
21388
21389 @noindent
21390 For more information on these switches, see
21391 @ref{Switches for gnatlink}.
21392 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21393 to control optimization. HP Ada also supplies the
21394 following pragmas:
21395 @itemize @bullet
21396 @item  @code{OPTIMIZE}
21397
21398 @item  @code{INLINE}
21399
21400 @item  @code{INLINE_GENERIC}
21401
21402 @item  @code{SUPPRESS_ALL}
21403
21404 @item  @code{PASSIVE}
21405 @end itemize
21406
21407 @noindent
21408 In GNAT, optimization is controlled strictly by command
21409 line parameters, as described in the corresponding section of this guide.
21410 The HP pragmas for control of optimization are
21411 recognized but ignored.
21412
21413 Note that in GNAT, the default is optimization off, whereas in HP Ada
21414 the default is that optimization is turned on.
21415
21416 @node Program Compilation and Library Management
21417 @section Program Compilation and Library Management
21418
21419 @noindent
21420 HP Ada and GNAT provide a comparable set of commands to
21421 build programs. HP Ada also provides a program library,
21422 which is a concept that does not exist on GNAT. Instead,
21423 GNAT provides directories of sources that are compiled as
21424 needed.
21425
21426 The following table summarizes
21427 the HP Ada commands and provides
21428 equivalent GNAT commands. In this table, some GNAT
21429 equivalents reflect the fact that GNAT does not use the
21430 concept of a program library. Instead, it uses a model
21431 in which collections of source and object files are used
21432 in a manner consistent with other languages like C and
21433 Fortran. Therefore, standard system file commands are used
21434 to manipulate these elements. Those GNAT commands are marked with
21435 an asterisk.
21436 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21437
21438 @need 1500
21439 @multitable @columnfractions .35 .65
21440
21441 @item @emph{HP Ada Command}
21442 @tab @emph{GNAT Equivalent / Description}
21443
21444 @item @command{ADA}
21445 @tab @command{GNAT COMPILE}@*
21446 Invokes the compiler to compile one or more Ada source files.
21447
21448 @item @command{ACS ATTACH}@*
21449 @tab [No equivalent]@*
21450 Switches control of terminal from current process running the program
21451 library manager.
21452
21453 @item @command{ACS CHECK}
21454 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21455 Forms the execution closure of one
21456 or more compiled units and checks completeness and currency.
21457
21458 @item @command{ACS COMPILE}
21459 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21460 Forms the execution closure of one or
21461 more specified units, checks completeness and currency,
21462 identifies units that have revised source files, compiles same,
21463 and recompiles units that are or will become obsolete.
21464 Also completes incomplete generic instantiations.
21465
21466 @item @command{ACS COPY FOREIGN}
21467 @tab Copy (*)@*
21468 Copies a foreign object file into the program library as a
21469 library unit body.
21470
21471 @item @command{ACS COPY UNIT}
21472 @tab Copy (*)@*
21473 Copies a compiled unit from one program library to another.
21474
21475 @item @command{ACS CREATE LIBRARY}
21476 @tab Create /directory (*)@*
21477 Creates a program library.
21478
21479 @item @command{ACS CREATE SUBLIBRARY}
21480 @tab Create /directory (*)@*
21481 Creates a program sublibrary.
21482
21483 @item @command{ACS DELETE LIBRARY}
21484 @tab @*
21485 Deletes a program library and its contents.
21486
21487 @item @command{ACS DELETE SUBLIBRARY}
21488 @tab @*
21489 Deletes a program sublibrary and its contents.
21490
21491 @item @command{ACS DELETE UNIT}
21492 @tab Delete file (*)@*
21493 On OpenVMS systems, deletes one or more compiled units from
21494 the current program library.
21495
21496 @item @command{ACS DIRECTORY}
21497 @tab Directory (*)@*
21498 On OpenVMS systems, lists units contained in the current
21499 program library.
21500
21501 @item @command{ACS ENTER FOREIGN}
21502 @tab Copy (*)@*
21503 Allows the import of a foreign body as an Ada library
21504 spec and enters a reference to a pointer.
21505
21506 @item @command{ACS ENTER UNIT}
21507 @tab Copy (*)@*
21508 Enters a reference (pointer) from the current program library to
21509 a unit compiled into another program library.
21510
21511 @item @command{ACS EXIT}
21512 @tab [No equivalent]@*
21513 Exits from the program library manager.
21514
21515 @item @command{ACS EXPORT}
21516 @tab Copy (*)@*
21517 Creates an object file that contains system-specific object code
21518 for one or more units. With GNAT, object files can simply be copied
21519 into the desired directory.
21520
21521 @item @command{ACS EXTRACT SOURCE}
21522 @tab Copy (*)@*
21523 Allows access to the copied source file for each Ada compilation unit
21524
21525 @item @command{ACS HELP}
21526 @tab @command{HELP GNAT}@*
21527 Provides online help.
21528
21529 @item @command{ACS LINK}
21530 @tab @command{GNAT LINK}@*
21531 Links an object file containing Ada units into an executable file.
21532
21533 @item @command{ACS LOAD}
21534 @tab Copy (*)@*
21535 Loads (partially compiles) Ada units into the program library.
21536 Allows loading a program from a collection of files into a library
21537 without knowing the relationship among units.
21538
21539 @item @command{ACS MERGE}
21540 @tab Copy (*)@*
21541 Merges into the current program library, one or more units from
21542 another library where they were modified.
21543
21544 @item @command{ACS RECOMPILE}
21545 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21546 Recompiles from   external or copied source files any obsolete
21547 unit in the closure. Also, completes any incomplete generic
21548 instantiations.
21549
21550 @item @command{ACS REENTER}
21551 @tab @command{GNAT MAKE}@*
21552 Reenters current references to units compiled after last entered
21553 with the @command{ACS ENTER UNIT} command.
21554
21555 @item @command{ACS SET LIBRARY}
21556 @tab Set default (*)@*
21557 Defines a program library to be the compilation context as well
21558 as the target library for compiler output and commands in general.
21559
21560 @item @command{ACS SET PRAGMA}
21561 @tab Edit @file{gnat.adc} (*)@*
21562 Redefines specified  values of the library characteristics
21563 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21564 and @code{Float_Representation}.
21565
21566 @item @command{ACS SET SOURCE}
21567 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21568 Defines the source file search list for the @command{ACS COMPILE} command.
21569
21570 @item @command{ACS SHOW LIBRARY}
21571 @tab Directory (*)@*
21572 Lists information about one or more program libraries.
21573
21574 @item @command{ACS SHOW PROGRAM}
21575 @tab [No equivalent]@*
21576 Lists information about the execution closure of one or
21577 more units in the program library.
21578
21579 @item @command{ACS SHOW SOURCE}
21580 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21581 Shows the source file search used when compiling units.
21582
21583 @item @command{ACS SHOW VERSION}
21584 @tab Compile with @option{VERBOSE} option
21585 Displays the version number of the compiler and program library
21586 manager used.
21587
21588 @item @command{ACS SPAWN}
21589 @tab [No equivalent]@*
21590 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21591 command).
21592
21593 @item @command{ACS VERIFY}
21594 @tab [No equivalent]@*
21595 Performs a series of consistency checks on a program library to
21596 determine whether the library structure and library files are in
21597 valid form.
21598 @end multitable
21599
21600 @noindent
21601
21602 @node Input-Output
21603 @section Input-Output
21604
21605 @noindent
21606 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21607 Management Services (RMS) to perform operations on
21608 external files.
21609
21610 @noindent
21611 HP Ada and GNAT predefine an identical set of input-
21612 output packages. To make the use of the
21613 generic @code{TEXT_IO} operations more convenient, HP Ada
21614 provides predefined library packages that instantiate the
21615 integer and floating-point operations for the predefined
21616 integer and floating-point types as shown in the following table.
21617
21618 @multitable @columnfractions .45 .55
21619 @item @emph{Package Name} @tab Instantiation
21620
21621 @item @code{INTEGER_TEXT_IO}
21622 @tab @code{INTEGER_IO(INTEGER)}
21623
21624 @item @code{SHORT_INTEGER_TEXT_IO}
21625 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21626
21627 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21628 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21629
21630 @item @code{FLOAT_TEXT_IO}
21631 @tab @code{FLOAT_IO(FLOAT)}
21632
21633 @item @code{LONG_FLOAT_TEXT_IO}
21634 @tab @code{FLOAT_IO(LONG_FLOAT)}
21635 @end multitable
21636
21637 @noindent
21638 The HP Ada predefined packages and their operations
21639 are implemented using OpenVMS Alpha files and input-output
21640 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21641 Familiarity with the following is recommended:
21642 @itemize @bullet
21643 @item  RMS file organizations and access methods
21644
21645 @item  OpenVMS file specifications and directories
21646
21647 @item  OpenVMS File Definition Language (FDL)
21648 @end itemize
21649
21650 @noindent
21651 GNAT provides I/O facilities that are completely
21652 compatible with HP Ada. The distribution includes the
21653 standard HP Ada versions of all I/O packages, operating
21654 in a manner compatible with HP Ada. In particular, the
21655 following packages are by default the HP Ada (Ada 83)
21656 versions of these packages rather than the renamings
21657 suggested in Annex J of the Ada Reference Manual:
21658 @itemize @bullet
21659 @item  @code{TEXT_IO}
21660
21661 @item  @code{SEQUENTIAL_IO}
21662
21663 @item  @code{DIRECT_IO}
21664 @end itemize
21665
21666 @noindent
21667 The use of the standard child package syntax (for
21668 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21669 packages.
21670 GNAT provides HP-compatible predefined instantiations
21671 of the @code{TEXT_IO} packages, and also
21672 provides the standard predefined instantiations required
21673 by the @cite{Ada Reference Manual}.
21674
21675 For further information on how GNAT interfaces to the file
21676 system or how I/O is implemented in programs written in
21677 mixed languages, see @ref{Implementation of the Standard I/O,,,
21678 gnat_rm, GNAT Reference Manual}.
21679 This chapter covers the following:
21680 @itemize @bullet
21681 @item  Standard I/O packages
21682
21683 @item  @code{FORM} strings
21684
21685 @item  @code{ADA.DIRECT_IO}
21686
21687 @item  @code{ADA.SEQUENTIAL_IO}
21688
21689 @item  @code{ADA.TEXT_IO}
21690
21691 @item  Stream pointer positioning
21692
21693 @item  Reading and writing non-regular files
21694
21695 @item  @code{GET_IMMEDIATE}
21696
21697 @item  Treating @code{TEXT_IO} files as streams
21698
21699 @item  Shared files
21700
21701 @item  Open modes
21702 @end itemize
21703
21704 @node Implementation Limits
21705 @section Implementation Limits
21706
21707 @noindent
21708 The following table lists implementation limits for HP Ada
21709 and GNAT systems.
21710 @multitable @columnfractions .60 .20 .20
21711 @sp 1
21712 @item  @emph{Compilation Parameter}
21713 @tab   @emph{HP Ada}
21714 @tab   @emph{GNAT}
21715 @sp 1
21716
21717 @item  In a subprogram or entry  declaration, maximum number of
21718 formal parameters that are of an unconstrained record type
21719 @tab   32
21720 @tab   No set limit
21721 @sp 1
21722
21723 @item  Maximum identifier length (number of characters)
21724 @tab   255
21725 @tab   32766
21726 @sp 1
21727
21728 @item  Maximum number of characters in a source line
21729 @tab   255
21730 @tab   32766
21731 @sp 1
21732
21733 @item  Maximum collection size   (number of bytes)
21734 @tab   2**31-1
21735 @tab   2**31-1
21736 @sp 1
21737
21738 @item  Maximum number of discriminants for a record type
21739 @tab   245
21740 @tab   No set limit
21741 @sp 1
21742
21743 @item  Maximum number of formal parameters in an entry or
21744 subprogram declaration
21745 @tab   246
21746 @tab    No set limit
21747 @sp 1
21748
21749 @item  Maximum number of dimensions in an array type
21750 @tab   255
21751 @tab   No set limit
21752 @sp 1
21753
21754 @item  Maximum number of library  units and subunits in a compilation.
21755 @tab   4095
21756 @tab   No set limit
21757 @sp 1
21758
21759 @item  Maximum number of library units and subunits in an execution.
21760 @tab   16383
21761 @tab   No set limit
21762 @sp 1
21763
21764 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21765 or @code{PSECT_OBJECT}
21766 @tab   32757
21767 @tab   No set limit
21768 @sp 1
21769
21770 @item  Maximum number of enumeration literals in an enumeration type
21771 definition
21772 @tab   65535
21773 @tab   No set limit
21774 @sp 1
21775
21776 @item  Maximum number of lines in a source file
21777 @tab   65534
21778 @tab   No set limit
21779 @sp 1
21780
21781 @item  Maximum number of bits in any object
21782 @tab   2**31-1
21783 @tab   2**31-1
21784 @sp 1
21785
21786 @item  Maximum size of the static portion of a stack frame (approximate)
21787 @tab   2**31-1
21788 @tab   2**31-1
21789 @end multitable
21790
21791 @node Tools and Utilities
21792 @section Tools and Utilities
21793
21794 @noindent
21795 The following table lists some of the OpenVMS development tools
21796 available for HP Ada, and the corresponding tools for
21797 use with @value{EDITION} on Alpha and I64 platforms.
21798 Aside from the debugger, all the OpenVMS tools identified are part
21799 of the DECset package.
21800
21801 @iftex
21802 @c Specify table in TeX since Texinfo does a poor job
21803 @tex
21804 \smallskip
21805 \smallskip
21806 \settabs\+Language-Sensitive Editor\quad
21807    &Product with HP Ada\quad
21808    &\cr
21809 \+\it Tool
21810    &\it Product with HP Ada
21811    & \it Product with @value{EDITION}\cr
21812 \smallskip
21813 \+Code Management System
21814    &HP CMS
21815    & HP CMS\cr
21816 \smallskip
21817 \+Language-Sensitive Editor
21818    &HP LSE
21819    & emacs or HP LSE (Alpha)\cr
21820 \+
21821    &
21822    & HP LSE (I64)\cr
21823 \smallskip
21824 \+Debugger
21825    &OpenVMS Debug
21826    & gdb (Alpha),\cr
21827 \+
21828    &
21829    & OpenVMS Debug (I64)\cr
21830 \smallskip
21831 \+Source Code Analyzer /
21832    &HP SCA
21833    & GNAT XREF\cr
21834 \+Cross Referencer
21835    &
21836    &\cr
21837 \smallskip
21838 \+Test Manager
21839    &HP Digital Test
21840    & HP DTM\cr
21841 \+
21842    &Manager (DTM)
21843    &\cr
21844 \smallskip
21845 \+Performance and
21846    & HP PCA
21847    & HP PCA\cr
21848 \+Coverage Analyzer
21849    &
21850    &\cr
21851 \smallskip
21852 \+Module Management
21853    & HP MMS
21854    & Not applicable\cr
21855 \+ System
21856    &
21857    &\cr
21858 \smallskip
21859 \smallskip
21860 @end tex
21861 @end iftex
21862
21863 @ifnottex
21864 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21865 @c the TeX version above for the printed version
21866 @flushleft
21867 @c @multitable @columnfractions .3 .4 .4
21868 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
21869 @item @i{Tool}
21870 @tab @i{Tool with HP Ada}
21871 @tab @i{Tool with @value{EDITION}}
21872 @item Code Management@*System
21873 @tab HP CMS
21874 @tab HP CMS
21875 @item Language-Sensitive@*Editor
21876 @tab HP LSE
21877 @tab emacs or HP LSE (Alpha)
21878 @item
21879 @tab
21880 @tab HP LSE (I64)
21881 @item Debugger
21882 @tab OpenVMS Debug
21883 @tab gdb (Alpha),
21884 @item
21885 @tab
21886 @tab OpenVMS Debug (I64)
21887 @item Source Code Analyzer /@*Cross Referencer
21888 @tab HP SCA
21889 @tab GNAT XREF
21890 @item Test Manager
21891 @tab HP Digital Test@*Manager (DTM)
21892 @tab HP DTM
21893 @item Performance and@*Coverage Analyzer
21894 @tab HP PCA
21895 @tab HP PCA
21896 @item Module Management@*System
21897 @tab HP MMS
21898 @tab Not applicable
21899 @end multitable
21900 @end flushleft
21901 @end ifnottex
21902
21903 @end ifset
21904
21905 @c **************************************
21906 @node Platform-Specific Information for the Run-Time Libraries
21907 @appendix Platform-Specific Information for the Run-Time Libraries
21908 @cindex Tasking and threads libraries
21909 @cindex Threads libraries and tasking
21910 @cindex Run-time libraries (platform-specific information)
21911
21912 @noindent
21913 The GNAT run-time implementation may vary with respect to both the
21914 underlying threads library and the exception handling scheme.
21915 For threads support, one or more of the following are supplied:
21916 @itemize @bullet
21917 @item @b{native threads library}, a binding to the thread package from
21918 the underlying operating system
21919
21920 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21921 POSIX thread package
21922 @end itemize
21923
21924 @noindent
21925 For exception handling, either or both of two models are supplied:
21926 @itemize @bullet
21927 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21928 Most programs should experience a substantial speed improvement by
21929 being compiled with a ZCX run-time.
21930 This is especially true for
21931 tasking applications or applications with many exception handlers.}
21932 @cindex Zero-Cost Exceptions
21933 @cindex ZCX (Zero-Cost Exceptions)
21934 which uses binder-generated tables that
21935 are interrogated at run time to locate a handler
21936
21937 @item @b{setjmp / longjmp} (``SJLJ''),
21938 @cindex setjmp/longjmp Exception Model
21939 @cindex SJLJ (setjmp/longjmp Exception Model)
21940 which uses dynamically-set data to establish
21941 the set of handlers
21942 @end itemize
21943
21944 @noindent
21945 This appendix summarizes which combinations of threads and exception support
21946 are supplied on various GNAT platforms.
21947 It then shows how to select a particular library either
21948 permanently or temporarily,
21949 explains the properties of (and tradeoffs among) the various threads
21950 libraries, and provides some additional
21951 information about several specific platforms.
21952
21953 @menu
21954 * Summary of Run-Time Configurations::
21955 * Specifying a Run-Time Library::
21956 * Choosing the Scheduling Policy::
21957 * Solaris-Specific Considerations::
21958 * Linux-Specific Considerations::
21959 * AIX-Specific Considerations::
21960 * Irix-Specific Considerations::
21961 * RTX-Specific Considerations::
21962 * HP-UX-Specific Considerations::
21963 @end menu
21964
21965 @node Summary of Run-Time Configurations
21966 @section Summary of Run-Time Configurations
21967
21968 @multitable @columnfractions .30 .70
21969 @item @b{alpha-openvms}
21970 @item @code{@ @ }@i{rts-native (default)}
21971 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21972 @item @code{@ @ @ @ }Exceptions @tab ZCX
21973 @*
21974 @item @b{alpha-tru64}
21975 @item @code{@ @ }@i{rts-native (default)}
21976 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21977 @item @code{@ @ @ @ }Exceptions @tab ZCX
21978 @*
21979 @item @code{@ @ }@i{rts-sjlj}
21980 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21981 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21982 @*
21983 @item @b{ia64-hp_linux}
21984 @item @code{@ @ }@i{rts-native (default)}
21985 @item @code{@ @ @ @ }Tasking    @tab pthread library
21986 @item @code{@ @ @ @ }Exceptions @tab ZCX
21987 @*
21988 @item @b{ia64-hpux}
21989 @item @code{@ @ }@i{rts-native (default)}
21990 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21991 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21992 @*
21993 @item @b{ia64-openvms}
21994 @item @code{@ @ }@i{rts-native (default)}
21995 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21996 @item @code{@ @ @ @ }Exceptions @tab ZCX
21997 @*
21998 @item @b{ia64-sgi_linux}
21999 @item @code{@ @ }@i{rts-native (default)}
22000 @item @code{@ @ @ @ }Tasking    @tab pthread library
22001 @item @code{@ @ @ @ }Exceptions @tab ZCX
22002 @*
22003 @item @b{mips-irix}
22004 @item @code{@ @ }@i{rts-native (default)}
22005 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22006 @item @code{@ @ @ @ }Exceptions @tab ZCX
22007 @*
22008 @item @b{pa-hpux}
22009 @item @code{@ @ }@i{rts-native (default)}
22010 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22011 @item @code{@ @ @ @ }Exceptions @tab ZCX
22012 @*
22013 @item @code{@ @ }@i{rts-sjlj}
22014 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22015 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22016 @*
22017 @item @b{ppc-aix}
22018 @item @code{@ @ }@i{rts-native (default)}
22019 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22020 @item @code{@ @ @ @ }Exceptions @tab ZCX
22021 @*
22022 @item @code{@ @ }@i{rts-sjlj}
22023 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22024 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22025 @*
22026 @item @b{ppc-darwin}
22027 @item @code{@ @ }@i{rts-native (default)}
22028 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22029 @item @code{@ @ @ @ }Exceptions @tab ZCX
22030 @*
22031 @item @b{sparc-solaris}  @tab
22032 @item @code{@ @ }@i{rts-native (default)}
22033 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22034 @item @code{@ @ @ @ }Exceptions @tab ZCX
22035 @*
22036 @item @code{@ @ }@i{rts-pthread}
22037 @item @code{@ @ @ @ }Tasking    @tab pthread library
22038 @item @code{@ @ @ @ }Exceptions @tab ZCX
22039 @*
22040 @item @code{@ @ }@i{rts-sjlj}
22041 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22042 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22043 @*
22044 @item @b{sparc64-solaris}  @tab
22045 @item @code{@ @ }@i{rts-native (default)}
22046 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22047 @item @code{@ @ @ @ }Exceptions @tab ZCX
22048 @*
22049 @item @b{x86-linux}
22050 @item @code{@ @ }@i{rts-native (default)}
22051 @item @code{@ @ @ @ }Tasking    @tab pthread library
22052 @item @code{@ @ @ @ }Exceptions @tab ZCX
22053 @*
22054 @item @code{@ @ }@i{rts-sjlj}
22055 @item @code{@ @ @ @ }Tasking    @tab pthread library
22056 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22057 @*
22058 @item @b{x86-lynx}
22059 @item @code{@ @ }@i{rts-native (default)}
22060 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22061 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22062 @*
22063 @item @b{x86-solaris}
22064 @item @code{@ @ }@i{rts-native (default)}
22065 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
22066 @item @code{@ @ @ @ }Exceptions @tab ZCX
22067 @*
22068 @item @code{@ @ }@i{rts-sjlj}
22069 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22070 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22071 @*
22072 @item @b{x86-windows}
22073 @item @code{@ @ }@i{rts-native (default)}
22074 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22075 @item @code{@ @ @ @ }Exceptions @tab ZCX
22076 @*
22077 @item @code{@ @ }@i{rts-sjlj}
22078 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22079 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22080 @*
22081 @item @b{x86-windows-rtx}
22082 @item @code{@ @ }@i{rts-rtx-rtss (default)}
22083 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
22084 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22085 @*
22086 @item @code{@ @ }@i{rts-rtx-w32}
22087 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
22088 @item @code{@ @ @ @ }Exceptions @tab ZCX
22089 @*
22090 @item @b{x86_64-linux}
22091 @item @code{@ @ }@i{rts-native (default)}
22092 @item @code{@ @ @ @ }Tasking    @tab pthread library
22093 @item @code{@ @ @ @ }Exceptions @tab ZCX
22094 @*
22095 @item @code{@ @ }@i{rts-sjlj}
22096 @item @code{@ @ @ @ }Tasking    @tab pthread library
22097 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22098 @*
22099 @end multitable
22100
22101 @node Specifying a Run-Time Library
22102 @section Specifying a Run-Time Library
22103
22104 @noindent
22105 The @file{adainclude} subdirectory containing the sources of the GNAT
22106 run-time library, and the @file{adalib} subdirectory containing the
22107 @file{ALI} files and the static and/or shared GNAT library, are located
22108 in the gcc target-dependent area:
22109
22110 @smallexample
22111 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22112 @end smallexample
22113
22114 @noindent
22115 As indicated above, on some platforms several run-time libraries are supplied.
22116 These libraries are installed in the target dependent area and
22117 contain a complete source and binary subdirectory. The detailed description
22118 below explains the differences between the different libraries in terms of
22119 their thread support.
22120
22121 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22122 This default run time is selected by the means of soft links.
22123 For example on x86-linux:
22124
22125 @smallexample
22126 @group
22127  $(target-dir)
22128      |
22129      +--- adainclude----------+
22130      |                        |
22131      +--- adalib-----------+  |
22132      |                     |  |
22133      +--- rts-native       |  |
22134      |    |                |  |
22135      |    +--- adainclude <---+
22136      |    |                |
22137      |    +--- adalib <----+
22138      |
22139      +--- rts-sjlj
22140           |
22141           +--- adainclude
22142           |
22143           +--- adalib
22144 @end group
22145 @end smallexample
22146
22147 @noindent
22148 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22149 these soft links can be modified with the following commands:
22150
22151 @smallexample
22152 $ cd $target
22153 $ rm -f adainclude adalib
22154 $ ln -s rts-sjlj/adainclude adainclude
22155 $ ln -s rts-sjlj/adalib adalib
22156 @end smallexample
22157
22158 @noindent
22159 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22160 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22161 @file{$target/ada_object_path}.
22162
22163 Selecting another run-time library temporarily can be
22164 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22165 @cindex @option{--RTS} option
22166
22167 @node Choosing the Scheduling Policy
22168 @section Choosing the Scheduling Policy
22169
22170 @noindent
22171 When using a POSIX threads implementation, you have a choice of several
22172 scheduling policies: @code{SCHED_FIFO},
22173 @cindex @code{SCHED_FIFO} scheduling policy
22174 @code{SCHED_RR}
22175 @cindex @code{SCHED_RR} scheduling policy
22176 and @code{SCHED_OTHER}.
22177 @cindex @code{SCHED_OTHER} scheduling policy
22178 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22179 or @code{SCHED_RR} requires special (e.g., root) privileges.
22180
22181 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22182 @code{SCHED_FIFO},
22183 @cindex @code{SCHED_FIFO} scheduling policy
22184 you can use one of the following:
22185
22186 @itemize @bullet
22187 @item
22188 @code{pragma Time_Slice (0.0)}
22189 @cindex pragma Time_Slice
22190 @item
22191 the corresponding binder option @option{-T0}
22192 @cindex @option{-T0} option
22193 @item
22194 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22195 @cindex pragma Task_Dispatching_Policy
22196 @end itemize
22197
22198 @noindent
22199 To specify @code{SCHED_RR},
22200 @cindex @code{SCHED_RR} scheduling policy
22201 you should use @code{pragma Time_Slice} with a
22202 value greater than @code{0.0}, or else use the corresponding @option{-T}
22203 binder option.
22204
22205 @node Solaris-Specific Considerations
22206 @section Solaris-Specific Considerations
22207 @cindex Solaris Sparc threads libraries
22208
22209 @noindent
22210 This section addresses some topics related to the various threads libraries
22211 on Sparc Solaris.
22212
22213 @menu
22214 * Solaris Threads Issues::
22215 @end menu
22216
22217 @node Solaris Threads Issues
22218 @subsection Solaris Threads Issues
22219
22220 @noindent
22221 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22222 library based on POSIX threads --- @emph{rts-pthread}.
22223 @cindex rts-pthread threads library
22224 This run-time library has the advantage of being mostly shared across all
22225 POSIX-compliant thread implementations, and it also provides under
22226 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22227 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22228 and @code{PTHREAD_PRIO_PROTECT}
22229 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22230 semantics that can be selected using the predefined pragma
22231 @code{Locking_Policy}
22232 @cindex pragma Locking_Policy (under rts-pthread)
22233 with respectively
22234 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22235 @cindex @code{Inheritance_Locking} (under rts-pthread)
22236 @cindex @code{Ceiling_Locking} (under rts-pthread)
22237
22238 As explained above, the native run-time library is based on the Solaris thread
22239 library (@code{libthread}) and is the default library.
22240
22241 When the Solaris threads library is used (this is the default), programs
22242 compiled with GNAT can automatically take advantage of
22243 and can thus execute on multiple processors.
22244 The user can alternatively specify a processor on which the program should run
22245 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22246 is made by
22247 setting the environment variable @env{GNAT_PROCESSOR}
22248 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22249 to one of the following:
22250
22251 @table @code
22252 @item -2
22253 Use the default configuration (run the program on all
22254 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22255 unset
22256
22257 @item -1
22258 Let the run-time implementation choose one processor and run the program on
22259 that processor
22260
22261 @item 0 .. Last_Proc
22262 Run the program on the specified processor.
22263 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22264 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22265 @end table
22266
22267 @node Linux-Specific Considerations
22268 @section Linux-Specific Considerations
22269 @cindex Linux threads libraries
22270
22271 @noindent
22272 On GNU/Linux without NPTL support (usually system with GNU C Library
22273 older than 2.3), the signal model is not POSIX compliant, which means
22274 that to send a signal to the process, you need to send the signal to all
22275 threads, e.g.@: by using @code{killpg()}.
22276
22277 @node AIX-Specific Considerations
22278 @section AIX-Specific Considerations
22279 @cindex AIX resolver library
22280
22281 @noindent
22282 On AIX, the resolver library initializes some internal structure on
22283 the first call to @code{get*by*} functions, which are used to implement
22284 @code{GNAT.Sockets.Get_Host_By_Name} and
22285 @code{GNAT.Sockets.Get_Host_By_Address}.
22286 If such initialization occurs within an Ada task, and the stack size for
22287 the task is the default size, a stack overflow may occur.
22288
22289 To avoid this overflow, the user should either ensure that the first call
22290 to @code{GNAT.Sockets.Get_Host_By_Name} or
22291 @code{GNAT.Sockets.Get_Host_By_Addrss}
22292 occurs in the environment task, or use @code{pragma Storage_Size} to
22293 specify a sufficiently large size for the stack of the task that contains
22294 this call.
22295
22296 @node Irix-Specific Considerations
22297 @section Irix-Specific Considerations
22298 @cindex Irix libraries
22299
22300 @noindent
22301 The GCC support libraries coming with the Irix compiler have moved to
22302 their canonical place with respect to the general Irix ABI related
22303 conventions. Running applications built with the default shared GNAT
22304 run-time now requires the LD_LIBRARY_PATH environment variable to
22305 include this location. A possible way to achieve this is to issue the
22306 following command line on a bash prompt:
22307
22308 @smallexample
22309 @group
22310 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22311 @end group
22312 @end smallexample
22313
22314 @node RTX-Specific Considerations
22315 @section RTX-Specific Considerations
22316 @cindex RTX libraries
22317
22318 @noindent
22319 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22320 API. Applications can be built to work in two different modes:
22321
22322 @itemize @bullet
22323 @item
22324 Windows executables that run in Ring 3 to utilize memory protection
22325 (@emph{rts-rtx-w32}).
22326
22327 @item
22328 Real-time subsystem (RTSS) executables that run in Ring 0, where
22329 performance can be optimized with RTSS applications taking precedent
22330 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22331 the Microsoft linker to handle RTSS libraries.
22332
22333 @end itemize
22334
22335 @node HP-UX-Specific Considerations
22336 @section HP-UX-Specific Considerations
22337 @cindex HP-UX Scheduling
22338
22339 @noindent
22340 On HP-UX, appropriate privileges are required to change the scheduling
22341 parameters of a task. The calling process must have appropriate
22342 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22343 successfully change the scheduling parameters.
22344
22345 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22346 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22347 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22348
22349 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22350 one of the following:
22351
22352 @itemize @bullet
22353 @item
22354 @code{pragma Time_Slice (0.0)}
22355 @cindex pragma Time_Slice
22356 @item
22357 the corresponding binder option @option{-T0}
22358 @cindex @option{-T0} option
22359 @item
22360 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22361 @cindex pragma Task_Dispatching_Policy
22362 @end itemize
22363
22364 @noindent
22365 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22366 you should use @code{pragma Time_Slice} with a
22367 value greater than @code{0.0}, or use the corresponding @option{-T}
22368 binder option, or set the @code{pragma Task_Dispatching_Policy
22369 (Round_Robin_Within_Priorities)}.
22370
22371 @c *******************************
22372 @node Example of Binder Output File
22373 @appendix Example of Binder Output File
22374
22375 @noindent
22376 This Appendix displays the source code for @command{gnatbind}'s output
22377 file generated for a simple ``Hello World'' program.
22378 Comments have been added for clarification purposes.
22379
22380 @smallexample @c adanocomment
22381 @iftex
22382 @leftskip=0cm
22383 @end iftex
22384 --  The package is called Ada_Main unless this name is actually used
22385 --  as a unit name in the partition, in which case some other unique
22386 --  name is used.
22387
22388 with System;
22389 package ada_main is
22390
22391    Elab_Final_Code : Integer;
22392    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22393
22394    --  The main program saves the parameters (argument count,
22395    --  argument values, environment pointer) in global variables
22396    --  for later access by other units including
22397    --  Ada.Command_Line.
22398
22399    gnat_argc : Integer;
22400    gnat_argv : System.Address;
22401    gnat_envp : System.Address;
22402
22403    --  The actual variables are stored in a library routine. This
22404    --  is useful for some shared library situations, where there
22405    --  are problems if variables are not in the library.
22406
22407    pragma Import (C, gnat_argc);
22408    pragma Import (C, gnat_argv);
22409    pragma Import (C, gnat_envp);
22410
22411    --  The exit status is similarly an external location
22412
22413    gnat_exit_status : Integer;
22414    pragma Import (C, gnat_exit_status);
22415
22416    GNAT_Version : constant String :=
22417                     "GNAT Version: 6.0.0w (20061115)";
22418    pragma Export (C, GNAT_Version, "__gnat_version");
22419
22420    --  This is the generated adafinal routine that performs
22421    --  finalization at the end of execution. In the case where
22422    --  Ada is the main program, this main program makes a call
22423    --  to adafinal at program termination.
22424
22425    procedure adafinal;
22426    pragma Export (C, adafinal, "adafinal");
22427
22428    --  This is the generated adainit routine that performs
22429    --  initialization at the start of execution. In the case
22430    --  where Ada is the main program, this main program makes
22431    --  a call to adainit at program startup.
22432
22433    procedure adainit;
22434    pragma Export (C, adainit, "adainit");
22435
22436    --  This routine is called at the start of execution. It is
22437    --  a dummy routine that is used by the debugger to breakpoint
22438    --  at the start of execution.
22439
22440    procedure Break_Start;
22441    pragma Import (C, Break_Start, "__gnat_break_start");
22442
22443    --  This is the actual generated main program (it would be
22444    --  suppressed if the no main program switch were used). As
22445    --  required by standard system conventions, this program has
22446    --  the external name main.
22447
22448    function main
22449      (argc : Integer;
22450       argv : System.Address;
22451       envp : System.Address)
22452       return Integer;
22453    pragma Export (C, main, "main");
22454
22455    --  The following set of constants give the version
22456    --  identification values for every unit in the bound
22457    --  partition. This identification is computed from all
22458    --  dependent semantic units, and corresponds to the
22459    --  string that would be returned by use of the
22460    --  Body_Version or Version attributes.
22461
22462    type Version_32 is mod 2 ** 32;
22463    u00001 : constant Version_32 := 16#7880BEB3#;
22464    u00002 : constant Version_32 := 16#0D24CBD0#;
22465    u00003 : constant Version_32 := 16#3283DBEB#;
22466    u00004 : constant Version_32 := 16#2359F9ED#;
22467    u00005 : constant Version_32 := 16#664FB847#;
22468    u00006 : constant Version_32 := 16#68E803DF#;
22469    u00007 : constant Version_32 := 16#5572E604#;
22470    u00008 : constant Version_32 := 16#46B173D8#;
22471    u00009 : constant Version_32 := 16#156A40CF#;
22472    u00010 : constant Version_32 := 16#033DABE0#;
22473    u00011 : constant Version_32 := 16#6AB38FEA#;
22474    u00012 : constant Version_32 := 16#22B6217D#;
22475    u00013 : constant Version_32 := 16#68A22947#;
22476    u00014 : constant Version_32 := 16#18CC4A56#;
22477    u00015 : constant Version_32 := 16#08258E1B#;
22478    u00016 : constant Version_32 := 16#367D5222#;
22479    u00017 : constant Version_32 := 16#20C9ECA4#;
22480    u00018 : constant Version_32 := 16#50D32CB6#;
22481    u00019 : constant Version_32 := 16#39A8BB77#;
22482    u00020 : constant Version_32 := 16#5CF8FA2B#;
22483    u00021 : constant Version_32 := 16#2F1EB794#;
22484    u00022 : constant Version_32 := 16#31AB6444#;
22485    u00023 : constant Version_32 := 16#1574B6E9#;
22486    u00024 : constant Version_32 := 16#5109C189#;
22487    u00025 : constant Version_32 := 16#56D770CD#;
22488    u00026 : constant Version_32 := 16#02F9DE3D#;
22489    u00027 : constant Version_32 := 16#08AB6B2C#;
22490    u00028 : constant Version_32 := 16#3FA37670#;
22491    u00029 : constant Version_32 := 16#476457A0#;
22492    u00030 : constant Version_32 := 16#731E1B6E#;
22493    u00031 : constant Version_32 := 16#23C2E789#;
22494    u00032 : constant Version_32 := 16#0F1BD6A1#;
22495    u00033 : constant Version_32 := 16#7C25DE96#;
22496    u00034 : constant Version_32 := 16#39ADFFA2#;
22497    u00035 : constant Version_32 := 16#571DE3E7#;
22498    u00036 : constant Version_32 := 16#5EB646AB#;
22499    u00037 : constant Version_32 := 16#4249379B#;
22500    u00038 : constant Version_32 := 16#0357E00A#;
22501    u00039 : constant Version_32 := 16#3784FB72#;
22502    u00040 : constant Version_32 := 16#2E723019#;
22503    u00041 : constant Version_32 := 16#623358EA#;
22504    u00042 : constant Version_32 := 16#107F9465#;
22505    u00043 : constant Version_32 := 16#6843F68A#;
22506    u00044 : constant Version_32 := 16#63305874#;
22507    u00045 : constant Version_32 := 16#31E56CE1#;
22508    u00046 : constant Version_32 := 16#02917970#;
22509    u00047 : constant Version_32 := 16#6CCBA70E#;
22510    u00048 : constant Version_32 := 16#41CD4204#;
22511    u00049 : constant Version_32 := 16#572E3F58#;
22512    u00050 : constant Version_32 := 16#20729FF5#;
22513    u00051 : constant Version_32 := 16#1D4F93E8#;
22514    u00052 : constant Version_32 := 16#30B2EC3D#;
22515    u00053 : constant Version_32 := 16#34054F96#;
22516    u00054 : constant Version_32 := 16#5A199860#;
22517    u00055 : constant Version_32 := 16#0E7F912B#;
22518    u00056 : constant Version_32 := 16#5760634A#;
22519    u00057 : constant Version_32 := 16#5D851835#;
22520
22521    --  The following Export pragmas export the version numbers
22522    --  with symbolic names ending in B (for body) or S
22523    --  (for spec) so that they can be located in a link. The
22524    --  information provided here is sufficient to track down
22525    --  the exact versions of units used in a given build.
22526
22527    pragma Export (C, u00001, "helloB");
22528    pragma Export (C, u00002, "system__standard_libraryB");
22529    pragma Export (C, u00003, "system__standard_libraryS");
22530    pragma Export (C, u00004, "adaS");
22531    pragma Export (C, u00005, "ada__text_ioB");
22532    pragma Export (C, u00006, "ada__text_ioS");
22533    pragma Export (C, u00007, "ada__exceptionsB");
22534    pragma Export (C, u00008, "ada__exceptionsS");
22535    pragma Export (C, u00009, "gnatS");
22536    pragma Export (C, u00010, "gnat__heap_sort_aB");
22537    pragma Export (C, u00011, "gnat__heap_sort_aS");
22538    pragma Export (C, u00012, "systemS");
22539    pragma Export (C, u00013, "system__exception_tableB");
22540    pragma Export (C, u00014, "system__exception_tableS");
22541    pragma Export (C, u00015, "gnat__htableB");
22542    pragma Export (C, u00016, "gnat__htableS");
22543    pragma Export (C, u00017, "system__exceptionsS");
22544    pragma Export (C, u00018, "system__machine_state_operationsB");
22545    pragma Export (C, u00019, "system__machine_state_operationsS");
22546    pragma Export (C, u00020, "system__machine_codeS");
22547    pragma Export (C, u00021, "system__storage_elementsB");
22548    pragma Export (C, u00022, "system__storage_elementsS");
22549    pragma Export (C, u00023, "system__secondary_stackB");
22550    pragma Export (C, u00024, "system__secondary_stackS");
22551    pragma Export (C, u00025, "system__parametersB");
22552    pragma Export (C, u00026, "system__parametersS");
22553    pragma Export (C, u00027, "system__soft_linksB");
22554    pragma Export (C, u00028, "system__soft_linksS");
22555    pragma Export (C, u00029, "system__stack_checkingB");
22556    pragma Export (C, u00030, "system__stack_checkingS");
22557    pragma Export (C, u00031, "system__tracebackB");
22558    pragma Export (C, u00032, "system__tracebackS");
22559    pragma Export (C, u00033, "ada__streamsS");
22560    pragma Export (C, u00034, "ada__tagsB");
22561    pragma Export (C, u00035, "ada__tagsS");
22562    pragma Export (C, u00036, "system__string_opsB");
22563    pragma Export (C, u00037, "system__string_opsS");
22564    pragma Export (C, u00038, "interfacesS");
22565    pragma Export (C, u00039, "interfaces__c_streamsB");
22566    pragma Export (C, u00040, "interfaces__c_streamsS");
22567    pragma Export (C, u00041, "system__file_ioB");
22568    pragma Export (C, u00042, "system__file_ioS");
22569    pragma Export (C, u00043, "ada__finalizationB");
22570    pragma Export (C, u00044, "ada__finalizationS");
22571    pragma Export (C, u00045, "system__finalization_rootB");
22572    pragma Export (C, u00046, "system__finalization_rootS");
22573    pragma Export (C, u00047, "system__finalization_implementationB");
22574    pragma Export (C, u00048, "system__finalization_implementationS");
22575    pragma Export (C, u00049, "system__string_ops_concat_3B");
22576    pragma Export (C, u00050, "system__string_ops_concat_3S");
22577    pragma Export (C, u00051, "system__stream_attributesB");
22578    pragma Export (C, u00052, "system__stream_attributesS");
22579    pragma Export (C, u00053, "ada__io_exceptionsS");
22580    pragma Export (C, u00054, "system__unsigned_typesS");
22581    pragma Export (C, u00055, "system__file_control_blockS");
22582    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22583    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22584
22585    -- BEGIN ELABORATION ORDER
22586    -- ada (spec)
22587    -- gnat (spec)
22588    -- gnat.heap_sort_a (spec)
22589    -- gnat.heap_sort_a (body)
22590    -- gnat.htable (spec)
22591    -- gnat.htable (body)
22592    -- interfaces (spec)
22593    -- system (spec)
22594    -- system.machine_code (spec)
22595    -- system.parameters (spec)
22596    -- system.parameters (body)
22597    -- interfaces.c_streams (spec)
22598    -- interfaces.c_streams (body)
22599    -- system.standard_library (spec)
22600    -- ada.exceptions (spec)
22601    -- system.exception_table (spec)
22602    -- system.exception_table (body)
22603    -- ada.io_exceptions (spec)
22604    -- system.exceptions (spec)
22605    -- system.storage_elements (spec)
22606    -- system.storage_elements (body)
22607    -- system.machine_state_operations (spec)
22608    -- system.machine_state_operations (body)
22609    -- system.secondary_stack (spec)
22610    -- system.stack_checking (spec)
22611    -- system.soft_links (spec)
22612    -- system.soft_links (body)
22613    -- system.stack_checking (body)
22614    -- system.secondary_stack (body)
22615    -- system.standard_library (body)
22616    -- system.string_ops (spec)
22617    -- system.string_ops (body)
22618    -- ada.tags (spec)
22619    -- ada.tags (body)
22620    -- ada.streams (spec)
22621    -- system.finalization_root (spec)
22622    -- system.finalization_root (body)
22623    -- system.string_ops_concat_3 (spec)
22624    -- system.string_ops_concat_3 (body)
22625    -- system.traceback (spec)
22626    -- system.traceback (body)
22627    -- ada.exceptions (body)
22628    -- system.unsigned_types (spec)
22629    -- system.stream_attributes (spec)
22630    -- system.stream_attributes (body)
22631    -- system.finalization_implementation (spec)
22632    -- system.finalization_implementation (body)
22633    -- ada.finalization (spec)
22634    -- ada.finalization (body)
22635    -- ada.finalization.list_controller (spec)
22636    -- ada.finalization.list_controller (body)
22637    -- system.file_control_block (spec)
22638    -- system.file_io (spec)
22639    -- system.file_io (body)
22640    -- ada.text_io (spec)
22641    -- ada.text_io (body)
22642    -- hello (body)
22643    -- END ELABORATION ORDER
22644
22645 end ada_main;
22646
22647 --  The following source file name pragmas allow the generated file
22648 --  names to be unique for different main programs. They are needed
22649 --  since the package name will always be Ada_Main.
22650
22651 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22652 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22653
22654 --  Generated package body for Ada_Main starts here
22655
22656 package body ada_main is
22657
22658    --  The actual finalization is performed by calling the
22659    --  library routine in System.Standard_Library.Adafinal
22660
22661    procedure Do_Finalize;
22662    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22663
22664    -------------
22665    -- adainit --
22666    -------------
22667
22668 @findex adainit
22669    procedure adainit is
22670
22671       --  These booleans are set to True once the associated unit has
22672       --  been elaborated. It is also used to avoid elaborating the
22673       --  same unit twice.
22674
22675       E040 : Boolean;
22676       pragma Import (Ada, E040, "interfaces__c_streams_E");
22677
22678       E008 : Boolean;
22679       pragma Import (Ada, E008, "ada__exceptions_E");
22680
22681       E014 : Boolean;
22682       pragma Import (Ada, E014, "system__exception_table_E");
22683
22684       E053 : Boolean;
22685       pragma Import (Ada, E053, "ada__io_exceptions_E");
22686
22687       E017 : Boolean;
22688       pragma Import (Ada, E017, "system__exceptions_E");
22689
22690       E024 : Boolean;
22691       pragma Import (Ada, E024, "system__secondary_stack_E");
22692
22693       E030 : Boolean;
22694       pragma Import (Ada, E030, "system__stack_checking_E");
22695
22696       E028 : Boolean;
22697       pragma Import (Ada, E028, "system__soft_links_E");
22698
22699       E035 : Boolean;
22700       pragma Import (Ada, E035, "ada__tags_E");
22701
22702       E033 : Boolean;
22703       pragma Import (Ada, E033, "ada__streams_E");
22704
22705       E046 : Boolean;
22706       pragma Import (Ada, E046, "system__finalization_root_E");
22707
22708       E048 : Boolean;
22709       pragma Import (Ada, E048, "system__finalization_implementation_E");
22710
22711       E044 : Boolean;
22712       pragma Import (Ada, E044, "ada__finalization_E");
22713
22714       E057 : Boolean;
22715       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22716
22717       E055 : Boolean;
22718       pragma Import (Ada, E055, "system__file_control_block_E");
22719
22720       E042 : Boolean;
22721       pragma Import (Ada, E042, "system__file_io_E");
22722
22723       E006 : Boolean;
22724       pragma Import (Ada, E006, "ada__text_io_E");
22725
22726       --  Set_Globals is a library routine that stores away the
22727       --  value of the indicated set of global values in global
22728       --  variables within the library.
22729
22730       procedure Set_Globals
22731         (Main_Priority            : Integer;
22732          Time_Slice_Value         : Integer;
22733          WC_Encoding              : Character;
22734          Locking_Policy           : Character;
22735          Queuing_Policy           : Character;
22736          Task_Dispatching_Policy  : Character;
22737          Adafinal                 : System.Address;
22738          Unreserve_All_Interrupts : Integer;
22739          Exception_Tracebacks     : Integer);
22740 @findex __gnat_set_globals
22741       pragma Import (C, Set_Globals, "__gnat_set_globals");
22742
22743       --  SDP_Table_Build is a library routine used to build the
22744       --  exception tables. See unit Ada.Exceptions in files
22745       --  a-except.ads/adb for full details of how zero cost
22746       --  exception handling works. This procedure, the call to
22747       --  it, and the two following tables are all omitted if the
22748       --  build is in longjmp/setjmp exception mode.
22749
22750 @findex SDP_Table_Build
22751 @findex Zero Cost Exceptions
22752       procedure SDP_Table_Build
22753         (SDP_Addresses   : System.Address;
22754          SDP_Count       : Natural;
22755          Elab_Addresses  : System.Address;
22756          Elab_Addr_Count : Natural);
22757       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22758
22759       --  Table of Unit_Exception_Table addresses. Used for zero
22760       --  cost exception handling to build the top level table.
22761
22762       ST : aliased constant array (1 .. 23) of System.Address := (
22763         Hello'UET_Address,
22764         Ada.Text_Io'UET_Address,
22765         Ada.Exceptions'UET_Address,
22766         Gnat.Heap_Sort_A'UET_Address,
22767         System.Exception_Table'UET_Address,
22768         System.Machine_State_Operations'UET_Address,
22769         System.Secondary_Stack'UET_Address,
22770         System.Parameters'UET_Address,
22771         System.Soft_Links'UET_Address,
22772         System.Stack_Checking'UET_Address,
22773         System.Traceback'UET_Address,
22774         Ada.Streams'UET_Address,
22775         Ada.Tags'UET_Address,
22776         System.String_Ops'UET_Address,
22777         Interfaces.C_Streams'UET_Address,
22778         System.File_Io'UET_Address,
22779         Ada.Finalization'UET_Address,
22780         System.Finalization_Root'UET_Address,
22781         System.Finalization_Implementation'UET_Address,
22782         System.String_Ops_Concat_3'UET_Address,
22783         System.Stream_Attributes'UET_Address,
22784         System.File_Control_Block'UET_Address,
22785         Ada.Finalization.List_Controller'UET_Address);
22786
22787       --  Table of addresses of elaboration routines. Used for
22788       --  zero cost exception handling to make sure these
22789       --  addresses are included in the top level procedure
22790       --  address table.
22791
22792       EA : aliased constant array (1 .. 23) of System.Address := (
22793         adainit'Code_Address,
22794         Do_Finalize'Code_Address,
22795         Ada.Exceptions'Elab_Spec'Address,
22796         System.Exceptions'Elab_Spec'Address,
22797         Interfaces.C_Streams'Elab_Spec'Address,
22798         System.Exception_Table'Elab_Body'Address,
22799         Ada.Io_Exceptions'Elab_Spec'Address,
22800         System.Stack_Checking'Elab_Spec'Address,
22801         System.Soft_Links'Elab_Body'Address,
22802         System.Secondary_Stack'Elab_Body'Address,
22803         Ada.Tags'Elab_Spec'Address,
22804         Ada.Tags'Elab_Body'Address,
22805         Ada.Streams'Elab_Spec'Address,
22806         System.Finalization_Root'Elab_Spec'Address,
22807         Ada.Exceptions'Elab_Body'Address,
22808         System.Finalization_Implementation'Elab_Spec'Address,
22809         System.Finalization_Implementation'Elab_Body'Address,
22810         Ada.Finalization'Elab_Spec'Address,
22811         Ada.Finalization.List_Controller'Elab_Spec'Address,
22812         System.File_Control_Block'Elab_Spec'Address,
22813         System.File_Io'Elab_Body'Address,
22814         Ada.Text_Io'Elab_Spec'Address,
22815         Ada.Text_Io'Elab_Body'Address);
22816
22817    --  Start of processing for adainit
22818
22819    begin
22820
22821       --  Call SDP_Table_Build to build the top level procedure
22822       --  table for zero cost exception handling (omitted in
22823       --  longjmp/setjmp mode).
22824
22825       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22826
22827       --  Call Set_Globals to record various information for
22828       --  this partition.  The values are derived by the binder
22829       --  from information stored in the ali files by the compiler.
22830
22831 @findex __gnat_set_globals
22832       Set_Globals
22833         (Main_Priority            => -1,
22834          --  Priority of main program, -1 if no pragma Priority used
22835
22836          Time_Slice_Value         => -1,
22837          --  Time slice from Time_Slice pragma, -1 if none used
22838
22839          WC_Encoding              => 'b',
22840          --  Wide_Character encoding used, default is brackets
22841
22842          Locking_Policy           => ' ',
22843          --  Locking_Policy used, default of space means not
22844          --  specified, otherwise it is the first character of
22845          --  the policy name.
22846
22847          Queuing_Policy           => ' ',
22848          --  Queuing_Policy used, default of space means not
22849          --  specified, otherwise it is the first character of
22850          --  the policy name.
22851
22852          Task_Dispatching_Policy  => ' ',
22853          --  Task_Dispatching_Policy used, default of space means
22854          --  not specified, otherwise first character of the
22855          --  policy name.
22856
22857          Adafinal                 => System.Null_Address,
22858          --  Address of Adafinal routine, not used anymore
22859
22860          Unreserve_All_Interrupts => 0,
22861          --  Set true if pragma Unreserve_All_Interrupts was used
22862
22863          Exception_Tracebacks     => 0);
22864          --  Indicates if exception tracebacks are enabled
22865
22866       Elab_Final_Code := 1;
22867
22868       --  Now we have the elaboration calls for all units in the partition.
22869       --  The Elab_Spec and Elab_Body attributes generate references to the
22870       --  implicit elaboration procedures generated by the compiler for
22871       --  each unit that requires elaboration.
22872
22873       if not E040 then
22874          Interfaces.C_Streams'Elab_Spec;
22875       end if;
22876       E040 := True;
22877       if not E008 then
22878          Ada.Exceptions'Elab_Spec;
22879       end if;
22880       if not E014 then
22881          System.Exception_Table'Elab_Body;
22882          E014 := True;
22883       end if;
22884       if not E053 then
22885          Ada.Io_Exceptions'Elab_Spec;
22886          E053 := True;
22887       end if;
22888       if not E017 then
22889          System.Exceptions'Elab_Spec;
22890          E017 := True;
22891       end if;
22892       if not E030 then
22893          System.Stack_Checking'Elab_Spec;
22894       end if;
22895       if not E028 then
22896          System.Soft_Links'Elab_Body;
22897          E028 := True;
22898       end if;
22899       E030 := True;
22900       if not E024 then
22901          System.Secondary_Stack'Elab_Body;
22902          E024 := True;
22903       end if;
22904       if not E035 then
22905          Ada.Tags'Elab_Spec;
22906       end if;
22907       if not E035 then
22908          Ada.Tags'Elab_Body;
22909          E035 := True;
22910       end if;
22911       if not E033 then
22912          Ada.Streams'Elab_Spec;
22913          E033 := True;
22914       end if;
22915       if not E046 then
22916          System.Finalization_Root'Elab_Spec;
22917       end if;
22918       E046 := True;
22919       if not E008 then
22920          Ada.Exceptions'Elab_Body;
22921          E008 := True;
22922       end if;
22923       if not E048 then
22924          System.Finalization_Implementation'Elab_Spec;
22925       end if;
22926       if not E048 then
22927          System.Finalization_Implementation'Elab_Body;
22928          E048 := True;
22929       end if;
22930       if not E044 then
22931          Ada.Finalization'Elab_Spec;
22932       end if;
22933       E044 := True;
22934       if not E057 then
22935          Ada.Finalization.List_Controller'Elab_Spec;
22936       end if;
22937       E057 := True;
22938       if not E055 then
22939          System.File_Control_Block'Elab_Spec;
22940          E055 := True;
22941       end if;
22942       if not E042 then
22943          System.File_Io'Elab_Body;
22944          E042 := True;
22945       end if;
22946       if not E006 then
22947          Ada.Text_Io'Elab_Spec;
22948       end if;
22949       if not E006 then
22950          Ada.Text_Io'Elab_Body;
22951          E006 := True;
22952       end if;
22953
22954       Elab_Final_Code := 0;
22955    end adainit;
22956
22957    --------------
22958    -- adafinal --
22959    --------------
22960
22961 @findex adafinal
22962    procedure adafinal is
22963    begin
22964       Do_Finalize;
22965    end adafinal;
22966
22967    ----------
22968    -- main --
22969    ----------
22970
22971    --  main is actually a function, as in the ANSI C standard,
22972    --  defined to return the exit status. The three parameters
22973    --  are the argument count, argument values and environment
22974    --  pointer.
22975
22976 @findex Main Program
22977    function main
22978      (argc : Integer;
22979       argv : System.Address;
22980       envp : System.Address)
22981       return Integer
22982    is
22983       --  The initialize routine performs low level system
22984       --  initialization using a standard library routine which
22985       --  sets up signal handling and performs any other
22986       --  required setup. The routine can be found in file
22987       --  a-init.c.
22988
22989 @findex __gnat_initialize
22990       procedure initialize;
22991       pragma Import (C, initialize, "__gnat_initialize");
22992
22993       --  The finalize routine performs low level system
22994       --  finalization using a standard library routine. The
22995       --  routine is found in file a-final.c and in the standard
22996       --  distribution is a dummy routine that does nothing, so
22997       --  really this is a hook for special user finalization.
22998
22999 @findex __gnat_finalize
23000       procedure finalize;
23001       pragma Import (C, finalize, "__gnat_finalize");
23002
23003       --  We get to the main program of the partition by using
23004       --  pragma Import because if we try to with the unit and
23005       --  call it Ada style, then not only do we waste time
23006       --  recompiling it, but also, we don't really know the right
23007       --  switches (e.g.@: identifier character set) to be used
23008       --  to compile it.
23009
23010       procedure Ada_Main_Program;
23011       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23012
23013    --  Start of processing for main
23014
23015    begin
23016       --  Save global variables
23017
23018       gnat_argc := argc;
23019       gnat_argv := argv;
23020       gnat_envp := envp;
23021
23022       --  Call low level system initialization
23023
23024       Initialize;
23025
23026       --  Call our generated Ada initialization routine
23027
23028       adainit;
23029
23030       --  This is the point at which we want the debugger to get
23031       --  control
23032
23033       Break_Start;
23034
23035       --  Now we call the main program of the partition
23036
23037       Ada_Main_Program;
23038
23039       --  Perform Ada finalization
23040
23041       adafinal;
23042
23043       --  Perform low level system finalization
23044
23045       Finalize;
23046
23047       --  Return the proper exit status
23048       return (gnat_exit_status);
23049    end;
23050
23051 --  This section is entirely comments, so it has no effect on the
23052 --  compilation of the Ada_Main package. It provides the list of
23053 --  object files and linker options, as well as some standard
23054 --  libraries needed for the link. The gnatlink utility parses
23055 --  this b~hello.adb file to read these comment lines to generate
23056 --  the appropriate command line arguments for the call to the
23057 --  system linker. The BEGIN/END lines are used for sentinels for
23058 --  this parsing operation.
23059
23060 --  The exact file names will of course depend on the environment,
23061 --  host/target and location of files on the host system.
23062
23063 @findex Object file list
23064 -- BEGIN Object file/option list
23065    --   ./hello.o
23066    --   -L./
23067    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23068    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23069 -- END Object file/option list
23070
23071 end ada_main;
23072 @end smallexample
23073
23074 @noindent
23075 The Ada code in the above example is exactly what is generated by the
23076 binder. We have added comments to more clearly indicate the function
23077 of each part of the generated @code{Ada_Main} package.
23078
23079 The code is standard Ada in all respects, and can be processed by any
23080 tools that handle Ada. In particular, it is possible to use the debugger
23081 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23082 suppose that for reasons that you do not understand, your program is crashing
23083 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23084 you can place a breakpoint on the call:
23085
23086 @smallexample @c ada
23087 Ada.Text_Io'Elab_Body;
23088 @end smallexample
23089
23090 @noindent
23091 and trace the elaboration routine for this package to find out where
23092 the problem might be (more usually of course you would be debugging
23093 elaboration code in your own application).
23094
23095 @node Elaboration Order Handling in GNAT
23096 @appendix Elaboration Order Handling in GNAT
23097 @cindex Order of elaboration
23098 @cindex Elaboration control
23099
23100 @menu
23101 * Elaboration Code::
23102 * Checking the Elaboration Order::
23103 * Controlling the Elaboration Order::
23104 * Controlling Elaboration in GNAT - Internal Calls::
23105 * Controlling Elaboration in GNAT - External Calls::
23106 * Default Behavior in GNAT - Ensuring Safety::
23107 * Treatment of Pragma Elaborate::
23108 * Elaboration Issues for Library Tasks::
23109 * Mixing Elaboration Models::
23110 * What to Do If the Default Elaboration Behavior Fails::
23111 * Elaboration for Access-to-Subprogram Values::
23112 * Summary of Procedures for Elaboration Control::
23113 * Other Elaboration Order Considerations::
23114 @end menu
23115
23116 @noindent
23117 This chapter describes the handling of elaboration code in Ada and
23118 in GNAT, and discusses how the order of elaboration of program units can
23119 be controlled in GNAT, either automatically or with explicit programming
23120 features.
23121
23122 @node Elaboration Code
23123 @section Elaboration Code
23124
23125 @noindent
23126 Ada provides rather general mechanisms for executing code at elaboration
23127 time, that is to say before the main program starts executing. Such code arises
23128 in three contexts:
23129
23130 @table @asis
23131 @item Initializers for variables.
23132 Variables declared at the library level, in package specs or bodies, can
23133 require initialization that is performed at elaboration time, as in:
23134 @smallexample @c ada
23135 @cartouche
23136 Sqrt_Half : Float := Sqrt (0.5);
23137 @end cartouche
23138 @end smallexample
23139
23140 @item Package initialization code
23141 Code in a @code{BEGIN-END} section at the outer level of a package body is
23142 executed as part of the package body elaboration code.
23143
23144 @item Library level task allocators
23145 Tasks that are declared using task allocators at the library level
23146 start executing immediately and hence can execute at elaboration time.
23147 @end table
23148
23149 @noindent
23150 Subprogram calls are possible in any of these contexts, which means that
23151 any arbitrary part of the program may be executed as part of the elaboration
23152 code. It is even possible to write a program which does all its work at
23153 elaboration time, with a null main program, although stylistically this
23154 would usually be considered an inappropriate way to structure
23155 a program.
23156
23157 An important concern arises in the context of elaboration code:
23158 we have to be sure that it is executed in an appropriate order. What we
23159 have is a series of elaboration code sections, potentially one section
23160 for each unit in the program. It is important that these execute
23161 in the correct order. Correctness here means that, taking the above
23162 example of the declaration of @code{Sqrt_Half},
23163 if some other piece of
23164 elaboration code references @code{Sqrt_Half},
23165 then it must run after the
23166 section of elaboration code that contains the declaration of
23167 @code{Sqrt_Half}.
23168
23169 There would never be any order of elaboration problem if we made a rule
23170 that whenever you @code{with} a unit, you must elaborate both the spec and body
23171 of that unit before elaborating the unit doing the @code{with}'ing:
23172
23173 @smallexample @c ada
23174 @group
23175 @cartouche
23176 with Unit_1;
23177 package Unit_2 is @dots{}
23178 @end cartouche
23179 @end group
23180 @end smallexample
23181
23182 @noindent
23183 would require that both the body and spec of @code{Unit_1} be elaborated
23184 before the spec of @code{Unit_2}. However, a rule like that would be far too
23185 restrictive. In particular, it would make it impossible to have routines
23186 in separate packages that were mutually recursive.
23187
23188 You might think that a clever enough compiler could look at the actual
23189 elaboration code and determine an appropriate correct order of elaboration,
23190 but in the general case, this is not possible. Consider the following
23191 example.
23192
23193 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23194 that references
23195 the variable @code{Sqrt_1}, which is declared in the elaboration code
23196 of the body of @code{Unit_1}:
23197
23198 @smallexample @c ada
23199 @cartouche
23200 Sqrt_1 : Float := Sqrt (0.1);
23201 @end cartouche
23202 @end smallexample
23203
23204 @noindent
23205 The elaboration code of the body of @code{Unit_1} also contains:
23206
23207 @smallexample @c ada
23208 @group
23209 @cartouche
23210 if expression_1 = 1 then
23211    Q := Unit_2.Func_2;
23212 end if;
23213 @end cartouche
23214 @end group
23215 @end smallexample
23216
23217 @noindent
23218 @code{Unit_2} is exactly parallel,
23219 it has a procedure @code{Func_2} that references
23220 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23221 the body @code{Unit_2}:
23222
23223 @smallexample @c ada
23224 @cartouche
23225 Sqrt_2 : Float := Sqrt (0.1);
23226 @end cartouche
23227 @end smallexample
23228
23229 @noindent
23230 The elaboration code of the body of @code{Unit_2} also contains:
23231
23232 @smallexample @c ada
23233 @group
23234 @cartouche
23235 if expression_2 = 2 then
23236    Q := Unit_1.Func_1;
23237 end if;
23238 @end cartouche
23239 @end group
23240 @end smallexample
23241
23242 @noindent
23243 Now the question is, which of the following orders of elaboration is
23244 acceptable:
23245
23246 @smallexample
23247 @group
23248 Spec of Unit_1
23249 Spec of Unit_2
23250 Body of Unit_1
23251 Body of Unit_2
23252 @end group
23253 @end smallexample
23254
23255 @noindent
23256 or
23257
23258 @smallexample
23259 @group
23260 Spec of Unit_2
23261 Spec of Unit_1
23262 Body of Unit_2
23263 Body of Unit_1
23264 @end group
23265 @end smallexample
23266
23267 @noindent
23268 If you carefully analyze the flow here, you will see that you cannot tell
23269 at compile time the answer to this question.
23270 If @code{expression_1} is not equal to 1,
23271 and @code{expression_2} is not equal to 2,
23272 then either order is acceptable, because neither of the function calls is
23273 executed. If both tests evaluate to true, then neither order is acceptable
23274 and in fact there is no correct order.
23275
23276 If one of the two expressions is true, and the other is false, then one
23277 of the above orders is correct, and the other is incorrect. For example,
23278 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23279 then the call to @code{Func_1}
23280 will occur, but not the call to @code{Func_2.}
23281 This means that it is essential
23282 to elaborate the body of @code{Unit_1} before
23283 the body of @code{Unit_2}, so the first
23284 order of elaboration is correct and the second is wrong.
23285
23286 By making @code{expression_1} and @code{expression_2}
23287 depend on input data, or perhaps
23288 the time of day, we can make it impossible for the compiler or binder
23289 to figure out which of these expressions will be true, and hence it
23290 is impossible to guarantee a safe order of elaboration at run time.
23291
23292 @node Checking the Elaboration Order
23293 @section Checking the Elaboration Order
23294
23295 @noindent
23296 In some languages that involve the same kind of elaboration problems,
23297 e.g.@: Java and C++, the programmer is expected to worry about these
23298 ordering problems himself, and it is common to
23299 write a program in which an incorrect elaboration order  gives
23300 surprising results, because it references variables before they
23301 are initialized.
23302 Ada is designed to be a safe language, and a programmer-beware approach is
23303 clearly not sufficient. Consequently, the language provides three lines
23304 of defense:
23305
23306 @table @asis
23307 @item Standard rules
23308 Some standard rules restrict the possible choice of elaboration
23309 order. In particular, if you @code{with} a unit, then its spec is always
23310 elaborated before the unit doing the @code{with}. Similarly, a parent
23311 spec is always elaborated before the child spec, and finally
23312 a spec is always elaborated before its corresponding body.
23313
23314 @item Dynamic elaboration checks
23315 @cindex Elaboration checks
23316 @cindex Checks, elaboration
23317 Dynamic checks are made at run time, so that if some entity is accessed
23318 before it is elaborated (typically  by means of a subprogram call)
23319 then the exception (@code{Program_Error}) is raised.
23320
23321 @item Elaboration control
23322 Facilities are provided for the programmer to specify the desired order
23323 of elaboration.
23324 @end table
23325
23326 Let's look at these facilities in more detail. First, the rules for
23327 dynamic checking. One possible rule would be simply to say that the
23328 exception is raised if you access a variable which has not yet been
23329 elaborated. The trouble with this approach is that it could require
23330 expensive checks on every variable reference. Instead Ada has two
23331 rules which are a little more restrictive, but easier to check, and
23332 easier to state:
23333
23334 @table @asis
23335 @item Restrictions on calls
23336 A subprogram can only be called at elaboration time if its body
23337 has been elaborated. The rules for elaboration given above guarantee
23338 that the spec of the subprogram has been elaborated before the
23339 call, but not the body. If this rule is violated, then the
23340 exception @code{Program_Error} is raised.
23341
23342 @item Restrictions on instantiations
23343 A generic unit can only be instantiated if the body of the generic
23344 unit has been elaborated. Again, the rules for elaboration given above
23345 guarantee that the spec of the generic unit has been elaborated
23346 before the instantiation, but not the body. If this rule is
23347 violated, then the exception @code{Program_Error} is raised.
23348 @end table
23349
23350 @noindent
23351 The idea is that if the body has been elaborated, then any variables
23352 it references must have been elaborated; by checking for the body being
23353 elaborated we guarantee that none of its references causes any
23354 trouble. As we noted above, this is a little too restrictive, because a
23355 subprogram that has no non-local references in its body may in fact be safe
23356 to call. However, it really would be unsafe to rely on this, because
23357 it would mean that the caller was aware of details of the implementation
23358 in the body. This goes against the basic tenets of Ada.
23359
23360 A plausible implementation can be described as follows.
23361 A Boolean variable is associated with each subprogram
23362 and each generic unit. This variable is initialized to False, and is set to
23363 True at the point body is elaborated. Every call or instantiation checks the
23364 variable, and raises @code{Program_Error} if the variable is False.
23365
23366 Note that one might think that it would be good enough to have one Boolean
23367 variable for each package, but that would not deal with cases of trying
23368 to call a body in the same package as the call
23369 that has not been elaborated yet.
23370 Of course a compiler may be able to do enough analysis to optimize away
23371 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23372 does such optimizations, but still the easiest conceptual model is to
23373 think of there being one variable per subprogram.
23374
23375 @node Controlling the Elaboration Order
23376 @section Controlling the Elaboration Order
23377
23378 @noindent
23379 In the previous section we discussed the rules in Ada which ensure
23380 that @code{Program_Error} is raised if an incorrect elaboration order is
23381 chosen. This prevents erroneous executions, but we need mechanisms to
23382 specify a correct execution and avoid the exception altogether.
23383 To achieve this, Ada provides a number of features for controlling
23384 the order of elaboration. We discuss these features in this section.
23385
23386 First, there are several ways of indicating to the compiler that a given
23387 unit has no elaboration problems:
23388
23389 @table @asis
23390 @item packages that do not require a body
23391 A library package that does not require a body does not permit
23392 a body (this rule was introduced in Ada 95).
23393 Thus if we have a such a package, as in:
23394
23395 @smallexample @c ada
23396 @group
23397 @cartouche
23398 package Definitions is
23399    generic
23400       type m is new integer;
23401    package Subp is
23402       type a is array (1 .. 10) of m;
23403       type b is array (1 .. 20) of m;
23404    end Subp;
23405 end Definitions;
23406 @end cartouche
23407 @end group
23408 @end smallexample
23409
23410 @noindent
23411 A package that @code{with}'s @code{Definitions} may safely instantiate
23412 @code{Definitions.Subp} because the compiler can determine that there
23413 definitely is no package body to worry about in this case
23414
23415 @item pragma Pure
23416 @cindex pragma Pure
23417 @findex Pure
23418 Places sufficient restrictions on a unit to guarantee that
23419 no call to any subprogram in the unit can result in an
23420 elaboration problem. This means that the compiler does not need
23421 to worry about the point of elaboration of such units, and in
23422 particular, does not need to check any calls to any subprograms
23423 in this unit.
23424
23425 @item pragma Preelaborate
23426 @findex Preelaborate
23427 @cindex pragma Preelaborate
23428 This pragma places slightly less stringent restrictions on a unit than
23429 does pragma Pure,
23430 but these restrictions are still sufficient to ensure that there
23431 are no elaboration problems with any calls to the unit.
23432
23433 @item pragma Elaborate_Body
23434 @findex Elaborate_Body
23435 @cindex pragma Elaborate_Body
23436 This pragma requires that the body of a unit be elaborated immediately
23437 after its spec. Suppose a unit @code{A} has such a pragma,
23438 and unit @code{B} does
23439 a @code{with} of unit @code{A}. Recall that the standard rules require
23440 the spec of unit @code{A}
23441 to be elaborated before the @code{with}'ing unit; given the pragma in
23442 @code{A}, we also know that the body of @code{A}
23443 will be elaborated before @code{B}, so
23444 that calls to @code{A} are safe and do not need a check.
23445 @end table
23446
23447 @noindent
23448 Note that,
23449 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23450 the use of
23451 @code{Elaborate_Body} does not guarantee that the program is
23452 free of elaboration problems, because it may not be possible
23453 to satisfy the requested elaboration order.
23454 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23455 If a programmer
23456 marks @code{Unit_1} as @code{Elaborate_Body},
23457 and not @code{Unit_2,} then the order of
23458 elaboration will be:
23459
23460 @smallexample
23461 @group
23462 Spec of Unit_2
23463 Spec of Unit_1
23464 Body of Unit_1
23465 Body of Unit_2
23466 @end group
23467 @end smallexample
23468
23469 @noindent
23470 Now that means that the call to @code{Func_1} in @code{Unit_2}
23471 need not be checked,
23472 it must be safe. But the call to @code{Func_2} in
23473 @code{Unit_1} may still fail if
23474 @code{Expression_1} is equal to 1,
23475 and the programmer must still take
23476 responsibility for this not being the case.
23477
23478 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23479 eliminated, except for calls entirely within a body, which are
23480 in any case fully under programmer control. However, using the pragma
23481 everywhere is not always possible.
23482 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23483 we marked both of them as having pragma @code{Elaborate_Body}, then
23484 clearly there would be no possible elaboration order.
23485
23486 The above pragmas allow a server to guarantee safe use by clients, and
23487 clearly this is the preferable approach. Consequently a good rule
23488 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23489 and if this is not possible,
23490 mark them as @code{Elaborate_Body} if possible.
23491 As we have seen, there are situations where neither of these
23492 three pragmas can be used.
23493 So we also provide methods for clients to control the
23494 order of elaboration of the servers on which they depend:
23495
23496 @table @asis
23497 @item pragma Elaborate (unit)
23498 @findex Elaborate
23499 @cindex pragma Elaborate
23500 This pragma is placed in the context clause, after a @code{with} clause,
23501 and it requires that the body of the named unit be elaborated before
23502 the unit in which the pragma occurs. The idea is to use this pragma
23503 if the current unit calls at elaboration time, directly or indirectly,
23504 some subprogram in the named unit.
23505
23506 @item pragma Elaborate_All (unit)
23507 @findex Elaborate_All
23508 @cindex pragma Elaborate_All
23509 This is a stronger version of the Elaborate pragma. Consider the
23510 following example:
23511
23512 @smallexample
23513 Unit A @code{with}'s unit B and calls B.Func in elab code
23514 Unit B @code{with}'s unit C, and B.Func calls C.Func
23515 @end smallexample
23516
23517 @noindent
23518 Now if we put a pragma @code{Elaborate (B)}
23519 in unit @code{A}, this ensures that the
23520 body of @code{B} is elaborated before the call, but not the
23521 body of @code{C}, so
23522 the call to @code{C.Func} could still cause @code{Program_Error} to
23523 be raised.
23524
23525 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23526 not only that the body of the named unit be elaborated before the
23527 unit doing the @code{with}, but also the bodies of all units that the
23528 named unit uses, following @code{with} links transitively. For example,
23529 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23530 then it requires
23531 not only that the body of @code{B} be elaborated before @code{A},
23532 but also the
23533 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23534 @end table
23535
23536 @noindent
23537 We are now in a position to give a usage rule in Ada for avoiding
23538 elaboration problems, at least if dynamic dispatching and access to
23539 subprogram values are not used. We will handle these cases separately
23540 later.
23541
23542 The rule is simple. If a unit has elaboration code that can directly or
23543 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23544 a generic package in a @code{with}'ed unit,
23545 then if the @code{with}'ed unit does not have
23546 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23547 a pragma @code{Elaborate_All}
23548 for the @code{with}'ed unit. By following this rule a client is
23549 assured that calls can be made without risk of an exception.
23550
23551 For generic subprogram instantiations, the rule can be relaxed to
23552 require only a pragma @code{Elaborate} since elaborating the body
23553 of a subprogram cannot cause any transitive elaboration (we are
23554 not calling the subprogram in this case, just elaborating its
23555 declaration).
23556
23557 If this rule is not followed, then a program may be in one of four
23558 states:
23559
23560 @table @asis
23561 @item No order exists
23562 No order of elaboration exists which follows the rules, taking into
23563 account any @code{Elaborate}, @code{Elaborate_All},
23564 or @code{Elaborate_Body} pragmas. In
23565 this case, an Ada compiler must diagnose the situation at bind
23566 time, and refuse to build an executable program.
23567
23568 @item One or more orders exist, all incorrect
23569 One or more acceptable elaboration orders exist, and all of them
23570 generate an elaboration order problem. In this case, the binder
23571 can build an executable program, but @code{Program_Error} will be raised
23572 when the program is run.
23573
23574 @item Several orders exist, some right, some incorrect
23575 One or more acceptable elaboration orders exists, and some of them
23576 work, and some do not. The programmer has not controlled
23577 the order of elaboration, so the binder may or may not pick one of
23578 the correct orders, and the program may or may not raise an
23579 exception when it is run. This is the worst case, because it means
23580 that the program may fail when moved to another compiler, or even
23581 another version of the same compiler.
23582
23583 @item One or more orders exists, all correct
23584 One ore more acceptable elaboration orders exist, and all of them
23585 work. In this case the program runs successfully. This state of
23586 affairs can be guaranteed by following the rule we gave above, but
23587 may be true even if the rule is not followed.
23588 @end table
23589
23590 @noindent
23591 Note that one additional advantage of following our rules on the use
23592 of @code{Elaborate} and @code{Elaborate_All}
23593 is that the program continues to stay in the ideal (all orders OK) state
23594 even if maintenance
23595 changes some bodies of some units. Conversely, if a program that does
23596 not follow this rule happens to be safe at some point, this state of affairs
23597 may deteriorate silently as a result of maintenance changes.
23598
23599 You may have noticed that the above discussion did not mention
23600 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23601 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23602 code in the body makes calls to some other unit, so it is still necessary
23603 to use @code{Elaborate_All} on such units.
23604
23605 @node Controlling Elaboration in GNAT - Internal Calls
23606 @section Controlling Elaboration in GNAT - Internal Calls
23607
23608 @noindent
23609 In the case of internal calls, i.e., calls within a single package, the
23610 programmer has full control over the order of elaboration, and it is up
23611 to the programmer to elaborate declarations in an appropriate order. For
23612 example writing:
23613
23614 @smallexample @c ada
23615 @group
23616 @cartouche
23617 function One return Float;
23618
23619 Q : Float := One;
23620
23621 function One return Float is
23622 begin
23623      return 1.0;
23624 end One;
23625 @end cartouche
23626 @end group
23627 @end smallexample
23628
23629 @noindent
23630 will obviously raise @code{Program_Error} at run time, because function
23631 One will be called before its body is elaborated. In this case GNAT will
23632 generate a warning that the call will raise @code{Program_Error}:
23633
23634 @smallexample
23635 @group
23636 @cartouche
23637  1. procedure y is
23638  2.    function One return Float;
23639  3.
23640  4.    Q : Float := One;
23641                     |
23642     >>> warning: cannot call "One" before body is elaborated
23643     >>> warning: Program_Error will be raised at run time
23644
23645  5.
23646  6.    function One return Float is
23647  7.    begin
23648  8.         return 1.0;
23649  9.    end One;
23650 10.
23651 11. begin
23652 12.    null;
23653 13. end;
23654 @end cartouche
23655 @end group
23656 @end smallexample
23657
23658 @noindent
23659 Note that in this particular case, it is likely that the call is safe, because
23660 the function @code{One} does not access any global variables.
23661 Nevertheless in Ada, we do not want the validity of the check to depend on
23662 the contents of the body (think about the separate compilation case), so this
23663 is still wrong, as we discussed in the previous sections.
23664
23665 The error is easily corrected by rearranging the declarations so that the
23666 body of @code{One} appears before the declaration containing the call
23667 (note that in Ada 95 and Ada 2005,
23668 declarations can appear in any order, so there is no restriction that
23669 would prevent this reordering, and if we write:
23670
23671 @smallexample @c ada
23672 @group
23673 @cartouche
23674 function One return Float;
23675
23676 function One return Float is
23677 begin
23678      return 1.0;
23679 end One;
23680
23681 Q : Float := One;
23682 @end cartouche
23683 @end group
23684 @end smallexample
23685
23686 @noindent
23687 then all is well, no warning is generated, and no
23688 @code{Program_Error} exception
23689 will be raised.
23690 Things are more complicated when a chain of subprograms is executed:
23691
23692 @smallexample @c ada
23693 @group
23694 @cartouche
23695 function A return Integer;
23696 function B return Integer;
23697 function C return Integer;
23698
23699 function B return Integer is begin return A; end;
23700 function C return Integer is begin return B; end;
23701
23702 X : Integer := C;
23703
23704 function A return Integer is begin return 1; end;
23705 @end cartouche
23706 @end group
23707 @end smallexample
23708
23709 @noindent
23710 Now the call to @code{C}
23711 at elaboration time in the declaration of @code{X} is correct, because
23712 the body of @code{C} is already elaborated,
23713 and the call to @code{B} within the body of
23714 @code{C} is correct, but the call
23715 to @code{A} within the body of @code{B} is incorrect, because the body
23716 of @code{A} has not been elaborated, so @code{Program_Error}
23717 will be raised on the call to @code{A}.
23718 In this case GNAT will generate a
23719 warning that @code{Program_Error} may be
23720 raised at the point of the call. Let's look at the warning:
23721
23722 @smallexample
23723 @group
23724 @cartouche
23725  1. procedure x is
23726  2.    function A return Integer;
23727  3.    function B return Integer;
23728  4.    function C return Integer;
23729  5.
23730  6.    function B return Integer is begin return A; end;
23731                                                     |
23732     >>> warning: call to "A" before body is elaborated may
23733                  raise Program_Error
23734     >>> warning: "B" called at line 7
23735     >>> warning: "C" called at line 9
23736
23737  7.    function C return Integer is begin return B; end;
23738  8.
23739  9.    X : Integer := C;
23740 10.
23741 11.    function A return Integer is begin return 1; end;
23742 12.
23743 13. begin
23744 14.    null;
23745 15. end;
23746 @end cartouche
23747 @end group
23748 @end smallexample
23749
23750 @noindent
23751 Note that the message here says ``may raise'', instead of the direct case,
23752 where the message says ``will be raised''. That's because whether
23753 @code{A} is
23754 actually called depends in general on run-time flow of control.
23755 For example, if the body of @code{B} said
23756
23757 @smallexample @c ada
23758 @group
23759 @cartouche
23760 function B return Integer is
23761 begin
23762    if some-condition-depending-on-input-data then
23763       return A;
23764    else
23765       return 1;
23766    end if;
23767 end B;
23768 @end cartouche
23769 @end group
23770 @end smallexample
23771
23772 @noindent
23773 then we could not know until run time whether the incorrect call to A would
23774 actually occur, so @code{Program_Error} might
23775 or might not be raised. It is possible for a compiler to
23776 do a better job of analyzing bodies, to
23777 determine whether or not @code{Program_Error}
23778 might be raised, but it certainly
23779 couldn't do a perfect job (that would require solving the halting problem
23780 and is provably impossible), and because this is a warning anyway, it does
23781 not seem worth the effort to do the analysis. Cases in which it
23782 would be relevant are rare.
23783
23784 In practice, warnings of either of the forms given
23785 above will usually correspond to
23786 real errors, and should be examined carefully and eliminated.
23787 In the rare case where a warning is bogus, it can be suppressed by any of
23788 the following methods:
23789
23790 @itemize @bullet
23791 @item
23792 Compile with the @option{-gnatws} switch set
23793
23794 @item
23795 Suppress @code{Elaboration_Check} for the called subprogram
23796
23797 @item
23798 Use pragma @code{Warnings_Off} to turn warnings off for the call
23799 @end itemize
23800
23801 @noindent
23802 For the internal elaboration check case,
23803 GNAT by default generates the
23804 necessary run-time checks to ensure
23805 that @code{Program_Error} is raised if any
23806 call fails an elaboration check. Of course this can only happen if a
23807 warning has been issued as described above. The use of pragma
23808 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23809 some of these checks, meaning that it may be possible (but is not
23810 guaranteed) for a program to be able to call a subprogram whose body
23811 is not yet elaborated, without raising a @code{Program_Error} exception.
23812
23813 @node Controlling Elaboration in GNAT - External Calls
23814 @section Controlling Elaboration in GNAT - External Calls
23815
23816 @noindent
23817 The previous section discussed the case in which the execution of a
23818 particular thread of elaboration code occurred entirely within a
23819 single unit. This is the easy case to handle, because a programmer
23820 has direct and total control over the order of elaboration, and
23821 furthermore, checks need only be generated in cases which are rare
23822 and which the compiler can easily detect.
23823 The situation is more complex when separate compilation is taken into account.
23824 Consider the following:
23825
23826 @smallexample @c ada
23827 @cartouche
23828 @group
23829 package Math is
23830    function Sqrt (Arg : Float) return Float;
23831 end Math;
23832
23833 package body Math is
23834    function Sqrt (Arg : Float) return Float is
23835    begin
23836          @dots{}
23837    end Sqrt;
23838 end Math;
23839 @end group
23840 @group
23841 with Math;
23842 package Stuff is
23843    X : Float := Math.Sqrt (0.5);
23844 end Stuff;
23845
23846 with Stuff;
23847 procedure Main is
23848 begin
23849    @dots{}
23850 end Main;
23851 @end group
23852 @end cartouche
23853 @end smallexample
23854
23855 @noindent
23856 where @code{Main} is the main program. When this program is executed, the
23857 elaboration code must first be executed, and one of the jobs of the
23858 binder is to determine the order in which the units of a program are
23859 to be elaborated. In this case we have four units: the spec and body
23860 of @code{Math},
23861 the spec of @code{Stuff} and the body of @code{Main}).
23862 In what order should the four separate sections of elaboration code
23863 be executed?
23864
23865 There are some restrictions in the order of elaboration that the binder
23866 can choose. In particular, if unit U has a @code{with}
23867 for a package @code{X}, then you
23868 are assured that the spec of @code{X}
23869 is elaborated before U , but you are
23870 not assured that the body of @code{X}
23871 is elaborated before U.
23872 This means that in the above case, the binder is allowed to choose the
23873 order:
23874
23875 @smallexample
23876 spec of Math
23877 spec of Stuff
23878 body of Math
23879 body of Main
23880 @end smallexample
23881
23882 @noindent
23883 but that's not good, because now the call to @code{Math.Sqrt}
23884 that happens during
23885 the elaboration of the @code{Stuff}
23886 spec happens before the body of @code{Math.Sqrt} is
23887 elaborated, and hence causes @code{Program_Error} exception to be raised.
23888 At first glance, one might say that the binder is misbehaving, because
23889 obviously you want to elaborate the body of something you @code{with}
23890 first, but
23891 that is not a general rule that can be followed in all cases. Consider
23892
23893 @smallexample @c ada
23894 @group
23895 @cartouche
23896 package X is @dots{}
23897
23898 package Y is @dots{}
23899
23900 with X;
23901 package body Y is @dots{}
23902
23903 with Y;
23904 package body X is @dots{}
23905 @end cartouche
23906 @end group
23907 @end smallexample
23908
23909 @noindent
23910 This is a common arrangement, and, apart from the order of elaboration
23911 problems that might arise in connection with elaboration code, this works fine.
23912 A rule that says that you must first elaborate the body of anything you
23913 @code{with} cannot work in this case:
23914 the body of @code{X} @code{with}'s @code{Y},
23915 which means you would have to
23916 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23917 which means
23918 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23919 loop that cannot be broken.
23920
23921 It is true that the binder can in many cases guess an order of elaboration
23922 that is unlikely to cause a @code{Program_Error}
23923 exception to be raised, and it tries to do so (in the
23924 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23925 by default
23926 elaborate the body of @code{Math} right after its spec, so all will be well).
23927
23928 However, a program that blindly relies on the binder to be helpful can
23929 get into trouble, as we discussed in the previous sections, so
23930 GNAT
23931 provides a number of facilities for assisting the programmer in
23932 developing programs that are robust with respect to elaboration order.
23933
23934 @node Default Behavior in GNAT - Ensuring Safety
23935 @section Default Behavior in GNAT - Ensuring Safety
23936
23937 @noindent
23938 The default behavior in GNAT ensures elaboration safety. In its
23939 default mode GNAT implements the
23940 rule we previously described as the right approach. Let's restate it:
23941
23942 @itemize
23943 @item
23944 @emph{If a unit has elaboration code that can directly or indirectly make a
23945 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23946 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23947 does not have pragma @code{Pure} or
23948 @code{Preelaborate}, then the client should have an
23949 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23950
23951 @emph{In the case of instantiating a generic subprogram, it is always
23952 sufficient to have only an @code{Elaborate} pragma for the
23953 @code{with}'ed unit.}
23954 @end itemize
23955
23956 @noindent
23957 By following this rule a client is assured that calls and instantiations
23958 can be made without risk of an exception.
23959
23960 In this mode GNAT traces all calls that are potentially made from
23961 elaboration code, and puts in any missing implicit @code{Elaborate}
23962 and @code{Elaborate_All} pragmas.
23963 The advantage of this approach is that no elaboration problems
23964 are possible if the binder can find an elaboration order that is
23965 consistent with these implicit @code{Elaborate} and
23966 @code{Elaborate_All} pragmas. The
23967 disadvantage of this approach is that no such order may exist.
23968
23969 If the binder does not generate any diagnostics, then it means that it has
23970 found an elaboration order that is guaranteed to be safe. However, the binder
23971 may still be relying on implicitly generated @code{Elaborate} and
23972 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23973 guaranteed.
23974
23975 If it is important to guarantee portability, then the compilations should
23976 use the
23977 @option{-gnatwl}
23978 (warn on elaboration problems) switch. This will cause warning messages
23979 to be generated indicating the missing @code{Elaborate} and
23980 @code{Elaborate_All} pragmas.
23981 Consider the following source program:
23982
23983 @smallexample @c ada
23984 @group
23985 @cartouche
23986 with k;
23987 package j is
23988   m : integer := k.r;
23989 end;
23990 @end cartouche
23991 @end group
23992 @end smallexample
23993
23994 @noindent
23995 where it is clear that there
23996 should be a pragma @code{Elaborate_All}
23997 for unit @code{k}. An implicit pragma will be generated, and it is
23998 likely that the binder will be able to honor it. However, if you want
23999 to port this program to some other Ada compiler than GNAT.
24000 it is safer to include the pragma explicitly in the source. If this
24001 unit is compiled with the
24002 @option{-gnatwl}
24003 switch, then the compiler outputs a warning:
24004
24005 @smallexample
24006 @group
24007 @cartouche
24008 1. with k;
24009 2. package j is
24010 3.   m : integer := k.r;
24011                      |
24012    >>> warning: call to "r" may raise Program_Error
24013    >>> warning: missing pragma Elaborate_All for "k"
24014
24015 4. end;
24016 @end cartouche
24017 @end group
24018 @end smallexample
24019
24020 @noindent
24021 and these warnings can be used as a guide for supplying manually
24022 the missing pragmas. It is usually a bad idea to use this warning
24023 option during development. That's because it will warn you when
24024 you need to put in a pragma, but cannot warn you when it is time
24025 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24026 unnecessary dependencies and even false circularities.
24027
24028 This default mode is more restrictive than the Ada Reference
24029 Manual, and it is possible to construct programs which will compile
24030 using the dynamic model described there, but will run into a
24031 circularity using the safer static model we have described.
24032
24033 Of course any Ada compiler must be able to operate in a mode
24034 consistent with the requirements of the Ada Reference Manual,
24035 and in particular must have the capability of implementing the
24036 standard dynamic model of elaboration with run-time checks.
24037
24038 In GNAT, this standard mode can be achieved either by the use of
24039 the @option{-gnatE} switch on the compiler (@command{gcc} or
24040 @command{gnatmake}) command, or by the use of the configuration pragma:
24041
24042 @smallexample @c ada
24043 pragma Elaboration_Checks (DYNAMIC);
24044 @end smallexample
24045
24046 @noindent
24047 Either approach will cause the unit affected to be compiled using the
24048 standard dynamic run-time elaboration checks described in the Ada
24049 Reference Manual. The static model is generally preferable, since it
24050 is clearly safer to rely on compile and link time checks rather than
24051 run-time checks. However, in the case of legacy code, it may be
24052 difficult to meet the requirements of the static model. This
24053 issue is further discussed in
24054 @ref{What to Do If the Default Elaboration Behavior Fails}.
24055
24056 Note that the static model provides a strict subset of the allowed
24057 behavior and programs of the Ada Reference Manual, so if you do
24058 adhere to the static model and no circularities exist,
24059 then you are assured that your program will
24060 work using the dynamic model, providing that you remove any
24061 pragma Elaborate statements from the source.
24062
24063 @node Treatment of Pragma Elaborate
24064 @section Treatment of Pragma Elaborate
24065 @cindex Pragma Elaborate
24066
24067 @noindent
24068 The use of @code{pragma Elaborate}
24069 should generally be avoided in Ada 95 and Ada 2005 programs,
24070 since there is no guarantee that transitive calls
24071 will be properly handled. Indeed at one point, this pragma was placed
24072 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24073
24074 Now that's a bit restrictive. In practice, the case in which
24075 @code{pragma Elaborate} is useful is when the caller knows that there
24076 are no transitive calls, or that the called unit contains all necessary
24077 transitive @code{pragma Elaborate} statements, and legacy code often
24078 contains such uses.
24079
24080 Strictly speaking the static mode in GNAT should ignore such pragmas,
24081 since there is no assurance at compile time that the necessary safety
24082 conditions are met. In practice, this would cause GNAT to be incompatible
24083 with correctly written Ada 83 code that had all necessary
24084 @code{pragma Elaborate} statements in place. Consequently, we made the
24085 decision that GNAT in its default mode will believe that if it encounters
24086 a @code{pragma Elaborate} then the programmer knows what they are doing,
24087 and it will trust that no elaboration errors can occur.
24088
24089 The result of this decision is two-fold. First to be safe using the
24090 static mode, you should remove all @code{pragma Elaborate} statements.
24091 Second, when fixing circularities in existing code, you can selectively
24092 use @code{pragma Elaborate} statements to convince the static mode of
24093 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24094 statement.
24095
24096 When using the static mode with @option{-gnatwl}, any use of
24097 @code{pragma Elaborate} will generate a warning about possible
24098 problems.
24099
24100 @node Elaboration Issues for Library Tasks
24101 @section Elaboration Issues for Library Tasks
24102 @cindex Library tasks, elaboration issues
24103 @cindex Elaboration of library tasks
24104
24105 @noindent
24106 In this section we examine special elaboration issues that arise for
24107 programs that declare library level tasks.
24108
24109 Generally the model of execution of an Ada program is that all units are
24110 elaborated, and then execution of the program starts. However, the
24111 declaration of library tasks definitely does not fit this model. The
24112 reason for this is that library tasks start as soon as they are declared
24113 (more precisely, as soon as the statement part of the enclosing package
24114 body is reached), that is to say before elaboration
24115 of the program is complete. This means that if such a task calls a
24116 subprogram, or an entry in another task, the callee may or may not be
24117 elaborated yet, and in the standard
24118 Reference Manual model of dynamic elaboration checks, you can even
24119 get timing dependent Program_Error exceptions, since there can be
24120 a race between the elaboration code and the task code.
24121
24122 The static model of elaboration in GNAT seeks to avoid all such
24123 dynamic behavior, by being conservative, and the conservative
24124 approach in this particular case is to assume that all the code
24125 in a task body is potentially executed at elaboration time if
24126 a task is declared at the library level.
24127
24128 This can definitely result in unexpected circularities. Consider
24129 the following example
24130
24131 @smallexample @c ada
24132 package Decls is
24133   task Lib_Task is
24134      entry Start;
24135   end Lib_Task;
24136
24137   type My_Int is new Integer;
24138
24139   function Ident (M : My_Int) return My_Int;
24140 end Decls;
24141
24142 with Utils;
24143 package body Decls is
24144   task body Lib_Task is
24145   begin
24146      accept Start;
24147      Utils.Put_Val (2);
24148   end Lib_Task;
24149
24150   function Ident (M : My_Int) return My_Int is
24151   begin
24152      return M;
24153   end Ident;
24154 end Decls;
24155
24156 with Decls;
24157 package Utils is
24158   procedure Put_Val (Arg : Decls.My_Int);
24159 end Utils;
24160
24161 with Text_IO;
24162 package body Utils is
24163   procedure Put_Val (Arg : Decls.My_Int) is
24164   begin
24165      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24166   end Put_Val;
24167 end Utils;
24168
24169 with Decls;
24170 procedure Main is
24171 begin
24172    Decls.Lib_Task.Start;
24173 end;
24174 @end smallexample
24175
24176 @noindent
24177 If the above example is compiled in the default static elaboration
24178 mode, then a circularity occurs. The circularity comes from the call
24179 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24180 this call occurs in elaboration code, we need an implicit pragma
24181 @code{Elaborate_All} for @code{Utils}. This means that not only must
24182 the spec and body of @code{Utils} be elaborated before the body
24183 of @code{Decls}, but also the spec and body of any unit that is
24184 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24185 the body of @code{Decls}. This is the transitive implication of
24186 pragma @code{Elaborate_All} and it makes sense, because in general
24187 the body of @code{Put_Val} might have a call to something in a
24188 @code{with'ed} unit.
24189
24190 In this case, the body of Utils (actually its spec) @code{with's}
24191 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24192 must be elaborated before itself, in case there is a call from the
24193 body of @code{Utils}.
24194
24195 Here is the exact chain of events we are worrying about:
24196
24197 @enumerate
24198 @item
24199 In the body of @code{Decls} a call is made from within the body of a library
24200 task to a subprogram in the package @code{Utils}. Since this call may
24201 occur at elaboration time (given that the task is activated at elaboration
24202 time), we have to assume the worst, i.e., that the
24203 call does happen at elaboration time.
24204
24205 @item
24206 This means that the body and spec of @code{Util} must be elaborated before
24207 the body of @code{Decls} so that this call does not cause an access before
24208 elaboration.
24209
24210 @item
24211 Within the body of @code{Util}, specifically within the body of
24212 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24213 by this package.
24214
24215 @item
24216 One such @code{with}'ed package is package @code{Decls}, so there
24217 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24218 In fact there is such a call in this example, but we would have to
24219 assume that there was such a call even if it were not there, since
24220 we are not supposed to write the body of @code{Decls} knowing what
24221 is in the body of @code{Utils}; certainly in the case of the
24222 static elaboration model, the compiler does not know what is in
24223 other bodies and must assume the worst.
24224
24225 @item
24226 This means that the spec and body of @code{Decls} must also be
24227 elaborated before we elaborate the unit containing the call, but
24228 that unit is @code{Decls}! This means that the body of @code{Decls}
24229 must be elaborated before itself, and that's a circularity.
24230 @end enumerate
24231
24232 @noindent
24233 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24234 the body of @code{Decls} you will get a true Ada Reference Manual
24235 circularity that makes the program illegal.
24236
24237 In practice, we have found that problems with the static model of
24238 elaboration in existing code often arise from library tasks, so
24239 we must address this particular situation.
24240
24241 Note that if we compile and run the program above, using the dynamic model of
24242 elaboration (that is to say use the @option{-gnatE} switch),
24243 then it compiles, binds,
24244 links, and runs, printing the expected result of 2. Therefore in some sense
24245 the circularity here is only apparent, and we need to capture
24246 the properties of this program that  distinguish it from other library-level
24247 tasks that have real elaboration problems.
24248
24249 We have four possible answers to this question:
24250
24251 @itemize @bullet
24252
24253 @item
24254 Use the dynamic model of elaboration.
24255
24256 If we use the @option{-gnatE} switch, then as noted above, the program works.
24257 Why is this? If we examine the task body, it is apparent that the task cannot
24258 proceed past the
24259 @code{accept} statement until after elaboration has been completed, because
24260 the corresponding entry call comes from the main program, not earlier.
24261 This is why the dynamic model works here. But that's really giving
24262 up on a precise analysis, and we prefer to take this approach only if we cannot
24263 solve the
24264 problem in any other manner. So let us examine two ways to reorganize
24265 the program to avoid the potential elaboration problem.
24266
24267 @item
24268 Split library tasks into separate packages.
24269
24270 Write separate packages, so that library tasks are isolated from
24271 other declarations as much as possible. Let us look at a variation on
24272 the above program.
24273
24274 @smallexample @c ada
24275 package Decls1 is
24276   task Lib_Task is
24277      entry Start;
24278   end Lib_Task;
24279 end Decls1;
24280
24281 with Utils;
24282 package body Decls1 is
24283   task body Lib_Task is
24284   begin
24285      accept Start;
24286      Utils.Put_Val (2);
24287   end Lib_Task;
24288 end Decls1;
24289
24290 package Decls2 is
24291   type My_Int is new Integer;
24292   function Ident (M : My_Int) return My_Int;
24293 end Decls2;
24294
24295 with Utils;
24296 package body Decls2 is
24297   function Ident (M : My_Int) return My_Int is
24298   begin
24299      return M;
24300   end Ident;
24301 end Decls2;
24302
24303 with Decls2;
24304 package Utils is
24305   procedure Put_Val (Arg : Decls2.My_Int);
24306 end Utils;
24307
24308 with Text_IO;
24309 package body Utils is
24310   procedure Put_Val (Arg : Decls2.My_Int) is
24311   begin
24312      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24313   end Put_Val;
24314 end Utils;
24315
24316 with Decls1;
24317 procedure Main is
24318 begin
24319    Decls1.Lib_Task.Start;
24320 end;
24321 @end smallexample
24322
24323 @noindent
24324 All we have done is to split @code{Decls} into two packages, one
24325 containing the library task, and one containing everything else. Now
24326 there is no cycle, and the program compiles, binds, links and executes
24327 using the default static model of elaboration.
24328
24329 @item
24330 Declare separate task types.
24331
24332 A significant part of the problem arises because of the use of the
24333 single task declaration form. This means that the elaboration of
24334 the task type, and the elaboration of the task itself (i.e.@: the
24335 creation of the task) happen at the same time. A good rule
24336 of style in Ada is to always create explicit task types. By
24337 following the additional step of placing task objects in separate
24338 packages from the task type declaration, many elaboration problems
24339 are avoided. Here is another modified example of the example program:
24340
24341 @smallexample @c ada
24342 package Decls is
24343   task type Lib_Task_Type is
24344      entry Start;
24345   end Lib_Task_Type;
24346
24347   type My_Int is new Integer;
24348
24349   function Ident (M : My_Int) return My_Int;
24350 end Decls;
24351
24352 with Utils;
24353 package body Decls is
24354   task body Lib_Task_Type is
24355   begin
24356      accept Start;
24357      Utils.Put_Val (2);
24358   end Lib_Task_Type;
24359
24360   function Ident (M : My_Int) return My_Int is
24361   begin
24362      return M;
24363   end Ident;
24364 end Decls;
24365
24366 with Decls;
24367 package Utils is
24368   procedure Put_Val (Arg : Decls.My_Int);
24369 end Utils;
24370
24371 with Text_IO;
24372 package body Utils is
24373   procedure Put_Val (Arg : Decls.My_Int) is
24374   begin
24375      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24376   end Put_Val;
24377 end Utils;
24378
24379 with Decls;
24380 package Declst is
24381    Lib_Task : Decls.Lib_Task_Type;
24382 end Declst;
24383
24384 with Declst;
24385 procedure Main is
24386 begin
24387    Declst.Lib_Task.Start;
24388 end;
24389 @end smallexample
24390
24391 @noindent
24392 What we have done here is to replace the @code{task} declaration in
24393 package @code{Decls} with a @code{task type} declaration. Then we
24394 introduce a separate package @code{Declst} to contain the actual
24395 task object. This separates the elaboration issues for
24396 the @code{task type}
24397 declaration, which causes no trouble, from the elaboration issues
24398 of the task object, which is also unproblematic, since it is now independent
24399 of the elaboration of  @code{Utils}.
24400 This separation of concerns also corresponds to
24401 a generally sound engineering principle of separating declarations
24402 from instances. This version of the program also compiles, binds, links,
24403 and executes, generating the expected output.
24404
24405 @item
24406 Use No_Entry_Calls_In_Elaboration_Code restriction.
24407 @cindex No_Entry_Calls_In_Elaboration_Code
24408
24409 The previous two approaches described how a program can be restructured
24410 to avoid the special problems caused by library task bodies. in practice,
24411 however, such restructuring may be difficult to apply to existing legacy code,
24412 so we must consider solutions that do not require massive rewriting.
24413
24414 Let us consider more carefully why our original sample program works
24415 under the dynamic model of elaboration. The reason is that the code
24416 in the task body blocks immediately on the @code{accept}
24417 statement. Now of course there is nothing to prohibit elaboration
24418 code from making entry calls (for example from another library level task),
24419 so we cannot tell in isolation that
24420 the task will not execute the accept statement  during elaboration.
24421
24422 However, in practice it is very unusual to see elaboration code
24423 make any entry calls, and the pattern of tasks starting
24424 at elaboration time and then immediately blocking on @code{accept} or
24425 @code{select} statements is very common. What this means is that
24426 the compiler is being too pessimistic when it analyzes the
24427 whole package body as though it might be executed at elaboration
24428 time.
24429
24430 If we know that the elaboration code contains no entry calls, (a very safe
24431 assumption most of the time, that could almost be made the default
24432 behavior), then we can compile all units of the program under control
24433 of the following configuration pragma:
24434
24435 @smallexample
24436 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24437 @end smallexample
24438
24439 @noindent
24440 This pragma can be placed in the @file{gnat.adc} file in the usual
24441 manner. If we take our original unmodified program and compile it
24442 in the presence of a @file{gnat.adc} containing the above pragma,
24443 then once again, we can compile, bind, link, and execute, obtaining
24444 the expected result. In the presence of this pragma, the compiler does
24445 not trace calls in a task body, that appear after the first @code{accept}
24446 or @code{select} statement, and therefore does not report a potential
24447 circularity in the original program.
24448
24449 The compiler will check to the extent it can that the above
24450 restriction is not violated, but it is not always possible to do a
24451 complete check at compile time, so it is important to use this
24452 pragma only if the stated restriction is in fact met, that is to say
24453 no task receives an entry call before elaboration of all units is completed.
24454
24455 @end itemize
24456
24457 @node Mixing Elaboration Models
24458 @section Mixing Elaboration Models
24459 @noindent
24460 So far, we have assumed that the entire program is either compiled
24461 using the dynamic model or static model, ensuring consistency. It
24462 is possible to mix the two models, but rules have to be followed
24463 if this mixing is done to ensure that elaboration checks are not
24464 omitted.
24465
24466 The basic rule is that @emph{a unit compiled with the static model cannot
24467 be @code{with'ed} by a unit compiled with the dynamic model}. The
24468 reason for this is that in the static model, a unit assumes that
24469 its clients guarantee to use (the equivalent of) pragma
24470 @code{Elaborate_All} so that no elaboration checks are required
24471 in inner subprograms, and this assumption is violated if the
24472 client is compiled with dynamic checks.
24473
24474 The precise rule is as follows. A unit that is compiled with dynamic
24475 checks can only @code{with} a unit that meets at least one of the
24476 following criteria:
24477
24478 @itemize @bullet
24479
24480 @item
24481 The @code{with'ed} unit is itself compiled with dynamic elaboration
24482 checks (that is with the @option{-gnatE} switch.
24483
24484 @item
24485 The @code{with'ed} unit is an internal GNAT implementation unit from
24486 the System, Interfaces, Ada, or GNAT hierarchies.
24487
24488 @item
24489 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24490
24491 @item
24492 The @code{with'ing} unit (that is the client) has an explicit pragma
24493 @code{Elaborate_All} for the @code{with'ed} unit.
24494
24495 @end itemize
24496
24497 @noindent
24498 If this rule is violated, that is if a unit with dynamic elaboration
24499 checks @code{with's} a unit that does not meet one of the above four
24500 criteria, then the binder (@code{gnatbind}) will issue a warning
24501 similar to that in the following example:
24502
24503 @smallexample
24504 warning: "x.ads" has dynamic elaboration checks and with's
24505 warning:   "y.ads" which has static elaboration checks
24506 @end smallexample
24507
24508 @noindent
24509 These warnings indicate that the rule has been violated, and that as a result
24510 elaboration checks may be missed in the resulting executable file.
24511 This warning may be suppressed using the @option{-ws} binder switch
24512 in the usual manner.
24513
24514 One useful application of this mixing rule is in the case of a subsystem
24515 which does not itself @code{with} units from the remainder of the
24516 application. In this case, the entire subsystem can be compiled with
24517 dynamic checks to resolve a circularity in the subsystem, while
24518 allowing the main application that uses this subsystem to be compiled
24519 using the more reliable default static model.
24520
24521 @node What to Do If the Default Elaboration Behavior Fails
24522 @section What to Do If the Default Elaboration Behavior Fails
24523
24524 @noindent
24525 If the binder cannot find an acceptable order, it outputs detailed
24526 diagnostics. For example:
24527 @smallexample
24528 @group
24529 @iftex
24530 @leftskip=0cm
24531 @end iftex
24532 error: elaboration circularity detected
24533 info:   "proc (body)" must be elaborated before "pack (body)"
24534 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24535 info:     recompile "pack (body)" with -gnatwl
24536 info:                             for full details
24537 info:       "proc (body)"
24538 info:         is needed by its spec:
24539 info:       "proc (spec)"
24540 info:         which is withed by:
24541 info:       "pack (body)"
24542 info:  "pack (body)" must be elaborated before "proc (body)"
24543 info:     reason: pragma Elaborate in unit "proc (body)"
24544 @end group
24545
24546 @end smallexample
24547
24548 @noindent
24549 In this case we have a cycle that the binder cannot break. On the one
24550 hand, there is an explicit pragma Elaborate in @code{proc} for
24551 @code{pack}. This means that the body of @code{pack} must be elaborated
24552 before the body of @code{proc}. On the other hand, there is elaboration
24553 code in @code{pack} that calls a subprogram in @code{proc}. This means
24554 that for maximum safety, there should really be a pragma
24555 Elaborate_All in @code{pack} for @code{proc} which would require that
24556 the body of @code{proc} be elaborated before the body of
24557 @code{pack}. Clearly both requirements cannot be satisfied.
24558 Faced with a circularity of this kind, you have three different options.
24559
24560 @table @asis
24561 @item Fix the program
24562 The most desirable option from the point of view of long-term maintenance
24563 is to rearrange the program so that the elaboration problems are avoided.
24564 One useful technique is to place the elaboration code into separate
24565 child packages. Another is to move some of the initialization code to
24566 explicitly called subprograms, where the program controls the order
24567 of initialization explicitly. Although this is the most desirable option,
24568 it may be impractical and involve too much modification, especially in
24569 the case of complex legacy code.
24570
24571 @item Perform dynamic checks
24572 If the compilations are done using the
24573 @option{-gnatE}
24574 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24575 manner. Dynamic checks are generated for all calls that could possibly result
24576 in raising an exception. With this switch, the compiler does not generate
24577 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24578 exactly as specified in the @cite{Ada Reference Manual}.
24579 The binder will generate
24580 an executable program that may or may not raise @code{Program_Error}, and then
24581 it is the programmer's job to ensure that it does not raise an exception. Note
24582 that it is important to compile all units with the switch, it cannot be used
24583 selectively.
24584
24585 @item Suppress checks
24586 The drawback of dynamic checks is that they generate a
24587 significant overhead at run time, both in space and time. If you
24588 are absolutely sure that your program cannot raise any elaboration
24589 exceptions, and you still want to use the dynamic elaboration model,
24590 then you can use the configuration pragma
24591 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24592 example this pragma could be placed in the @file{gnat.adc} file.
24593
24594 @item Suppress checks selectively
24595 When you know that certain calls or instantiations in elaboration code cannot
24596 possibly lead to an elaboration error, and the binder nevertheless complains
24597 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24598 elaboration circularities, it is possible to remove those warnings locally and
24599 obtain a program that will bind. Clearly this can be unsafe, and it is the
24600 responsibility of the programmer to make sure that the resulting program has no
24601 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24602 used with different granularity to suppress warnings and break elaboration
24603 circularities:
24604
24605 @itemize @bullet
24606 @item
24607 Place the pragma that names the called subprogram in the declarative part
24608 that contains the call.
24609
24610 @item
24611 Place the pragma in the declarative part, without naming an entity. This
24612 disables warnings on all calls in the corresponding  declarative region.
24613
24614 @item
24615 Place the pragma in the package spec that declares the called subprogram,
24616 and name the subprogram. This disables warnings on all elaboration calls to
24617 that subprogram.
24618
24619 @item
24620 Place the pragma in the package spec that declares the called subprogram,
24621 without naming any entity. This disables warnings on all elaboration calls to
24622 all subprograms declared in this spec.
24623
24624 @item Use Pragma Elaborate
24625 As previously described in section @xref{Treatment of Pragma Elaborate},
24626 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24627 that no elaboration checks are required on calls to the designated unit.
24628 There may be cases in which the caller knows that no transitive calls
24629 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24630 case where @code{pragma Elaborate_All} would cause a circularity.
24631 @end itemize
24632
24633 @noindent
24634 These five cases are listed in order of decreasing safety, and therefore
24635 require increasing programmer care in their application. Consider the
24636 following program:
24637
24638 @smallexample @c adanocomment
24639 package Pack1 is
24640   function F1 return Integer;
24641   X1 : Integer;
24642 end Pack1;
24643
24644 package Pack2 is
24645   function F2 return Integer;
24646   function Pure (x : integer) return integer;
24647   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24648   --  pragma Suppress (Elaboration_Check);              -- (4)
24649 end Pack2;
24650
24651 with Pack2;
24652 package body Pack1 is
24653   function F1 return Integer is
24654   begin
24655     return 100;
24656   end F1;
24657   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24658 begin
24659   declare
24660     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24661     --  pragma Suppress(Elaboration_Check);             -- (2)
24662   begin
24663     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24664   end;
24665 end Pack1;
24666
24667 with Pack1;
24668 package body Pack2 is
24669   function F2 return Integer is
24670   begin
24671      return Pack1.F1;
24672   end F2;
24673   function Pure (x : integer) return integer is
24674   begin
24675      return x ** 3 - 3 * x;
24676   end;
24677 end Pack2;
24678
24679 with Pack1, Ada.Text_IO;
24680 procedure Proc3 is
24681 begin
24682   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24683 end Proc3;
24684 @end smallexample
24685 In the absence of any pragmas, an attempt to bind this program produces
24686 the following diagnostics:
24687 @smallexample
24688 @group
24689 @iftex
24690 @leftskip=.5cm
24691 @end iftex
24692 error: elaboration circularity detected
24693 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24694 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24695 info:       recompile "pack1 (body)" with -gnatwl for full details
24696 info:          "pack1 (body)"
24697 info:             must be elaborated along with its spec:
24698 info:          "pack1 (spec)"
24699 info:             which is withed by:
24700 info:          "pack2 (body)"
24701 info:             which must be elaborated along with its spec:
24702 info:          "pack2 (spec)"
24703 info:             which is withed by:
24704 info:          "pack1 (body)"
24705 @end group
24706 @end smallexample
24707 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24708 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24709 F2 is safe, even though F2 calls F1, because the call appears after the
24710 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24711 remove the warning on the call. It is also possible to use pragma (2)
24712 because there are no other potentially unsafe calls in the block.
24713
24714 @noindent
24715 The call to @code{Pure} is safe because this function does not depend on the
24716 state of @code{Pack2}. Therefore any call to this function is safe, and it
24717 is correct to place pragma (3) in the corresponding package spec.
24718
24719 @noindent
24720 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24721 warnings on all calls to functions declared therein. Note that this is not
24722 necessarily safe, and requires more detailed examination of the subprogram
24723 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24724 be already elaborated.
24725 @end table
24726
24727 @noindent
24728 It is hard to generalize on which of these four approaches should be
24729 taken. Obviously if it is possible to fix the program so that the default
24730 treatment works, this is preferable, but this may not always be practical.
24731 It is certainly simple enough to use
24732 @option{-gnatE}
24733 but the danger in this case is that, even if the GNAT binder
24734 finds a correct elaboration order, it may not always do so,
24735 and certainly a binder from another Ada compiler might not. A
24736 combination of testing and analysis (for which the warnings generated
24737 with the
24738 @option{-gnatwl}
24739 switch can be useful) must be used to ensure that the program is free
24740 of errors. One switch that is useful in this testing is the
24741 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24742 switch for
24743 @code{gnatbind}.
24744 Normally the binder tries to find an order that has the best chance
24745 of avoiding elaboration problems. However, if this switch is used, the binder
24746 plays a devil's advocate role, and tries to choose the order that
24747 has the best chance of failing. If your program works even with this
24748 switch, then it has a better chance of being error free, but this is still
24749 not a guarantee.
24750
24751 For an example of this approach in action, consider the C-tests (executable
24752 tests) from the ACVC suite. If these are compiled and run with the default
24753 treatment, then all but one of them succeed without generating any error
24754 diagnostics from the binder. However, there is one test that fails, and
24755 this is not surprising, because the whole point of this test is to ensure
24756 that the compiler can handle cases where it is impossible to determine
24757 a correct order statically, and it checks that an exception is indeed
24758 raised at run time.
24759
24760 This one test must be compiled and run using the
24761 @option{-gnatE}
24762 switch, and then it passes. Alternatively, the entire suite can
24763 be run using this switch. It is never wrong to run with the dynamic
24764 elaboration switch if your code is correct, and we assume that the
24765 C-tests are indeed correct (it is less efficient, but efficiency is
24766 not a factor in running the ACVC tests.)
24767
24768 @node Elaboration for Access-to-Subprogram Values
24769 @section Elaboration for Access-to-Subprogram Values
24770 @cindex Access-to-subprogram
24771
24772 @noindent
24773 Access-to-subprogram types (introduced in Ada 95) complicate
24774 the handling of elaboration. The trouble is that it becomes
24775 impossible to tell at compile time which procedure
24776 is being called. This means that it is not possible for the binder
24777 to analyze the elaboration requirements in this case.
24778
24779 If at the point at which the access value is created
24780 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24781 the body of the subprogram is
24782 known to have been elaborated, then the access value is safe, and its use
24783 does not require a check. This may be achieved by appropriate arrangement
24784 of the order of declarations if the subprogram is in the current unit,
24785 or, if the subprogram is in another unit, by using pragma
24786 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24787 on the referenced unit.
24788
24789 If the referenced body is not known to have been elaborated at the point
24790 the access value is created, then any use of the access value must do a
24791 dynamic check, and this dynamic check will fail and raise a
24792 @code{Program_Error} exception if the body has not been elaborated yet.
24793 GNAT will generate the necessary checks, and in addition, if the
24794 @option{-gnatwl}
24795 switch is set, will generate warnings that such checks are required.
24796
24797 The use of dynamic dispatching for tagged types similarly generates
24798 a requirement for dynamic checks, and premature calls to any primitive
24799 operation of a tagged type before the body of the operation has been
24800 elaborated, will result in the raising of @code{Program_Error}.
24801
24802 @node Summary of Procedures for Elaboration Control
24803 @section Summary of Procedures for Elaboration Control
24804 @cindex Elaboration control
24805
24806 @noindent
24807 First, compile your program with the default options, using none of
24808 the special elaboration control switches. If the binder successfully
24809 binds your program, then you can be confident that, apart from issues
24810 raised by the use of access-to-subprogram types and dynamic dispatching,
24811 the program is free of elaboration errors. If it is important that the
24812 program be portable, then use the
24813 @option{-gnatwl}
24814 switch to generate warnings about missing @code{Elaborate} or
24815 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24816
24817 If the program fails to bind using the default static elaboration
24818 handling, then you can fix the program to eliminate the binder
24819 message, or recompile the entire program with the
24820 @option{-gnatE} switch to generate dynamic elaboration checks,
24821 and, if you are sure there really are no elaboration problems,
24822 use a global pragma @code{Suppress (Elaboration_Check)}.
24823
24824 @node Other Elaboration Order Considerations
24825 @section Other Elaboration Order Considerations
24826 @noindent
24827 This section has been entirely concerned with the issue of finding a valid
24828 elaboration order, as defined by the Ada Reference Manual. In a case
24829 where several elaboration orders are valid, the task is to find one
24830 of the possible valid elaboration orders (and the static model in GNAT
24831 will ensure that this is achieved).
24832
24833 The purpose of the elaboration rules in the Ada Reference Manual is to
24834 make sure that no entity is accessed before it has been elaborated. For
24835 a subprogram, this means that the spec and body must have been elaborated
24836 before the subprogram is called. For an object, this means that the object
24837 must have been elaborated before its value is read or written. A violation
24838 of either of these two requirements is an access before elaboration order,
24839 and this section has been all about avoiding such errors.
24840
24841 In the case where more than one order of elaboration is possible, in the
24842 sense that access before elaboration errors are avoided, then any one of
24843 the orders is ``correct'' in the sense that it meets the requirements of
24844 the Ada Reference Manual, and no such error occurs.
24845
24846 However, it may be the case for a given program, that there are
24847 constraints on the order of elaboration that come not from consideration
24848 of avoiding elaboration errors, but rather from extra-lingual logic
24849 requirements. Consider this example:
24850
24851 @smallexample @c ada
24852 with Init_Constants;
24853 package Constants is
24854    X : Integer := 0;
24855    Y : Integer := 0;
24856 end Constants;
24857
24858 package Init_Constants is
24859    procedure P; -- require a body
24860 end Init_Constants;
24861
24862 with Constants;
24863 package body Init_Constants is
24864    procedure P is begin null; end;
24865 begin
24866    Constants.X := 3;
24867    Constants.Y := 4;
24868 end Init_Constants;
24869
24870 with Constants;
24871 package Calc is
24872    Z : Integer := Constants.X + Constants.Y;
24873 end Calc;
24874
24875 with Calc;
24876 with Text_IO; use Text_IO;
24877 procedure Main is
24878 begin
24879    Put_Line (Calc.Z'Img);
24880 end Main;
24881 @end smallexample
24882
24883 @noindent
24884 In this example, there is more than one valid order of elaboration. For
24885 example both the following are correct orders:
24886
24887 @smallexample
24888 Init_Constants spec
24889 Constants spec
24890 Calc spec
24891 Init_Constants body
24892 Main body
24893
24894   and
24895
24896 Init_Constants spec
24897 Init_Constants body
24898 Constants spec
24899 Calc spec
24900 Main body
24901 @end smallexample
24902
24903 @noindent
24904 There is no language rule to prefer one or the other, both are correct
24905 from an order of elaboration point of view. But the programmatic effects
24906 of the two orders are very different. In the first, the elaboration routine
24907 of @code{Calc} initializes @code{Z} to zero, and then the main program
24908 runs with this value of zero. But in the second order, the elaboration
24909 routine of @code{Calc} runs after the body of Init_Constants has set
24910 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24911 runs.
24912
24913 One could perhaps by applying pretty clever non-artificial intelligence
24914 to the situation guess that it is more likely that the second order of
24915 elaboration is the one desired, but there is no formal linguistic reason
24916 to prefer one over the other. In fact in this particular case, GNAT will
24917 prefer the second order, because of the rule that bodies are elaborated
24918 as soon as possible, but it's just luck that this is what was wanted
24919 (if indeed the second order was preferred).
24920
24921 If the program cares about the order of elaboration routines in a case like
24922 this, it is important to specify the order required. In this particular
24923 case, that could have been achieved by adding to the spec of Calc:
24924
24925 @smallexample @c ada
24926 pragma Elaborate_All (Constants);
24927 @end smallexample
24928
24929 @noindent
24930 which requires that the body (if any) and spec of @code{Constants},
24931 as well as the body and spec of any unit @code{with}'ed by
24932 @code{Constants} be elaborated before @code{Calc} is elaborated.
24933
24934 Clearly no automatic method can always guess which alternative you require,
24935 and if you are working with legacy code that had constraints of this kind
24936 which were not properly specified by adding @code{Elaborate} or
24937 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24938 compilers can choose different orders.
24939
24940 However, GNAT does attempt to diagnose the common situation where there
24941 are uninitialized variables in the visible part of a package spec, and the
24942 corresponding package body has an elaboration block that directly or
24943 indirectly initialized one or more of these variables. This is the situation
24944 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24945 a warning that suggests this addition if it detects this situation.
24946
24947 The @code{gnatbind}
24948 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24949 out problems. This switch causes bodies to be elaborated as late as possible
24950 instead of as early as possible. In the example above, it would have forced
24951 the choice of the first elaboration order. If you get different results
24952 when using this switch, and particularly if one set of results is right,
24953 and one is wrong as far as you are concerned, it shows that you have some
24954 missing @code{Elaborate} pragmas. For the example above, we have the
24955 following output:
24956
24957 @smallexample
24958 gnatmake -f -q main
24959 main
24960  7
24961 gnatmake -f -q main -bargs -p
24962 main
24963  0
24964 @end smallexample
24965
24966 @noindent
24967 It is of course quite unlikely that both these results are correct, so
24968 it is up to you in a case like this to investigate the source of the
24969 difference, by looking at the two elaboration orders that are chosen,
24970 and figuring out which is correct, and then adding the necessary
24971 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24972
24973
24974
24975 @c *******************************
24976 @node Conditional Compilation
24977 @appendix Conditional Compilation
24978 @c *******************************
24979 @cindex Conditional compilation
24980
24981 @noindent
24982 It is often necessary to arrange for a single source program
24983 to serve multiple purposes, where it is compiled in different
24984 ways to achieve these different goals. Some examples of the
24985 need for this feature are
24986
24987 @itemize @bullet
24988 @item  Adapting a program to a different hardware environment
24989 @item  Adapting a program to a different target architecture
24990 @item  Turning debugging features on and off
24991 @item  Arranging for a program to compile with different compilers
24992 @end itemize
24993
24994 @noindent
24995 In C, or C++, the typical approach would be to use the preprocessor
24996 that is defined as part of the language. The Ada language does not
24997 contain such a feature. This is not an oversight, but rather a very
24998 deliberate design decision, based on the experience that overuse of
24999 the preprocessing features in C and C++ can result in programs that
25000 are extremely difficult to maintain. For example, if we have ten
25001 switches that can be on or off, this means that there are a thousand
25002 separate programs, any one of which might not even be syntactically
25003 correct, and even if syntactically correct, the resulting program
25004 might not work correctly. Testing all combinations can quickly become
25005 impossible.
25006
25007 Nevertheless, the need to tailor programs certainly exists, and in
25008 this Appendix we will discuss how this can
25009 be achieved using Ada in general, and GNAT in particular.
25010
25011 @menu
25012 * Use of Boolean Constants::
25013 * Debugging - A Special Case::
25014 * Conditionalizing Declarations::
25015 * Use of Alternative Implementations::
25016 * Preprocessing::
25017 @end menu
25018
25019 @node Use of Boolean Constants
25020 @section Use of Boolean Constants
25021
25022 @noindent
25023 In the case where the difference is simply which code
25024 sequence is executed, the cleanest solution is to use Boolean
25025 constants to control which code is executed.
25026
25027 @smallexample @c ada
25028 @group
25029 FP_Initialize_Required : constant Boolean := True;
25030 @dots{}
25031 if FP_Initialize_Required then
25032 @dots{}
25033 end if;
25034 @end group
25035 @end smallexample
25036
25037 @noindent
25038 Not only will the code inside the @code{if} statement not be executed if
25039 the constant Boolean is @code{False}, but it will also be completely
25040 deleted from the program.
25041 However, the code is only deleted after the @code{if} statement
25042 has been checked for syntactic and semantic correctness.
25043 (In contrast, with preprocessors the code is deleted before the
25044 compiler ever gets to see it, so it is not checked until the switch
25045 is turned on.)
25046 @cindex Preprocessors (contrasted with conditional compilation)
25047
25048 Typically the Boolean constants will be in a separate package,
25049 something like:
25050
25051 @smallexample @c ada
25052 @group
25053 package Config is
25054    FP_Initialize_Required : constant Boolean := True;
25055    Reset_Available        : constant Boolean := False;
25056    @dots{}
25057 end Config;
25058 @end group
25059 @end smallexample
25060
25061 @noindent
25062 The @code{Config} package exists in multiple forms for the various targets,
25063 with an appropriate script selecting the version of @code{Config} needed.
25064 Then any other unit requiring conditional compilation can do a @code{with}
25065 of @code{Config} to make the constants visible.
25066
25067
25068 @node Debugging - A Special Case
25069 @section Debugging - A Special Case
25070
25071 @noindent
25072 A common use of conditional code is to execute statements (for example
25073 dynamic checks, or output of intermediate results) under control of a
25074 debug switch, so that the debugging behavior can be turned on and off.
25075 This can be done using a Boolean constant to control whether the code
25076 is active:
25077
25078 @smallexample @c ada
25079 @group
25080 if Debugging then
25081    Put_Line ("got to the first stage!");
25082 end if;
25083 @end group
25084 @end smallexample
25085
25086 @noindent
25087 or
25088
25089 @smallexample @c ada
25090 @group
25091 if Debugging and then Temperature > 999.0 then
25092    raise Temperature_Crazy;
25093 end if;
25094 @end group
25095 @end smallexample
25096
25097 @noindent
25098 Since this is a common case, there are special features to deal with
25099 this in a convenient manner. For the case of tests, Ada 2005 has added
25100 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25101 @cindex pragma @code{Assert}
25102 on the @code{Assert} pragma that has always been available in GNAT, so this
25103 feature may be used with GNAT even if you are not using Ada 2005 features.
25104 The use of pragma @code{Assert} is described in
25105 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25106 example, the last test could be written:
25107
25108 @smallexample @c ada
25109 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25110 @end smallexample
25111
25112 @noindent
25113 or simply
25114
25115 @smallexample @c ada
25116 pragma Assert (Temperature <= 999.0);
25117 @end smallexample
25118
25119 @noindent
25120 In both cases, if assertions are active and the temperature is excessive,
25121 the exception @code{Assert_Failure} will be raised, with the given string in
25122 the first case or a string indicating the location of the pragma in the second
25123 case used as the exception message.
25124
25125 You can turn assertions on and off by using the @code{Assertion_Policy}
25126 pragma.
25127 @cindex pragma @code{Assertion_Policy}
25128 This is an Ada 2005 pragma which is implemented in all modes by
25129 GNAT, but only in the latest versions of GNAT which include Ada 2005
25130 capability. Alternatively, you can use the @option{-gnata} switch
25131 @cindex @option{-gnata} switch
25132 to enable assertions from the command line (this is recognized by all versions
25133 of GNAT).
25134
25135 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25136 @code{Debug} can be used:
25137 @cindex pragma @code{Debug}
25138
25139 @smallexample @c ada
25140 pragma Debug (Put_Line ("got to the first stage!"));
25141 @end smallexample
25142
25143 @noindent
25144 If debug pragmas are enabled, the argument, which must be of the form of
25145 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25146 Only one call can be present, but of course a special debugging procedure
25147 containing any code you like can be included in the program and then
25148 called in a pragma @code{Debug} argument as needed.
25149
25150 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25151 construct is that pragma @code{Debug} can appear in declarative contexts,
25152 such as at the very beginning of a procedure, before local declarations have
25153 been elaborated.
25154
25155 Debug pragmas are enabled using either the @option{-gnata} switch that also
25156 controls assertions, or with a separate Debug_Policy pragma.
25157 @cindex pragma @code{Debug_Policy}
25158 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25159 in Ada 95 and Ada 83 programs as well), and is analogous to
25160 pragma @code{Assertion_Policy} to control assertions.
25161
25162 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25163 and thus they can appear in @file{gnat.adc} if you are not using a
25164 project file, or in the file designated to contain configuration pragmas
25165 in a project file.
25166 They then apply to all subsequent compilations. In practice the use of
25167 the @option{-gnata} switch is often the most convenient method of controlling
25168 the status of these pragmas.
25169
25170 Note that a pragma is not a statement, so in contexts where a statement
25171 sequence is required, you can't just write a pragma on its own. You have
25172 to add a @code{null} statement.
25173
25174 @smallexample @c ada
25175 @group
25176 if @dots{} then
25177    @dots{} -- some statements
25178 else
25179    pragma Assert (Num_Cases < 10);
25180    null;
25181 end if;
25182 @end group
25183 @end smallexample
25184
25185
25186 @node Conditionalizing Declarations
25187 @section Conditionalizing Declarations
25188
25189 @noindent
25190 In some cases, it may be necessary to conditionalize declarations to meet
25191 different requirements. For example we might want a bit string whose length
25192 is set to meet some hardware message requirement.
25193
25194 In some cases, it may be possible to do this using declare blocks controlled
25195 by conditional constants:
25196
25197 @smallexample @c ada
25198 @group
25199 if Small_Machine then
25200    declare
25201       X : Bit_String (1 .. 10);
25202    begin
25203       @dots{}
25204    end;
25205 else
25206    declare
25207       X : Large_Bit_String (1 .. 1000);
25208    begin
25209       @dots{}
25210    end;
25211 end if;
25212 @end group
25213 @end smallexample
25214
25215 @noindent
25216 Note that in this approach, both declarations are analyzed by the
25217 compiler so this can only be used where both declarations are legal,
25218 even though one of them will not be used.
25219
25220 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25221 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25222 that are parameterized by these constants. For example
25223
25224 @smallexample @c ada
25225 @group
25226 for Rec use
25227   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25228 end record;
25229 @end group
25230 @end smallexample
25231
25232 @noindent
25233 If @code{Bits_Per_Word} is set to 32, this generates either
25234
25235 @smallexample @c ada
25236 @group
25237 for Rec use
25238   Field1 at 0 range 0 .. 32;
25239 end record;
25240 @end group
25241 @end smallexample
25242
25243 @noindent
25244 for the big endian case, or
25245
25246 @smallexample @c ada
25247 @group
25248 for Rec use record
25249   Field1 at 0 range 10 .. 32;
25250 end record;
25251 @end group
25252 @end smallexample
25253
25254 @noindent
25255 for the little endian case. Since a powerful subset of Ada expression
25256 notation is usable for creating static constants, clever use of this
25257 feature can often solve quite difficult problems in conditionalizing
25258 compilation (note incidentally that in Ada 95, the little endian
25259 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25260 need to define this one yourself).
25261
25262
25263 @node Use of Alternative Implementations
25264 @section Use of Alternative Implementations
25265
25266 @noindent
25267 In some cases, none of the approaches described above are adequate. This
25268 can occur for example if the set of declarations required is radically
25269 different for two different configurations.
25270
25271 In this situation, the official Ada way of dealing with conditionalizing
25272 such code is to write separate units for the different cases. As long as
25273 this does not result in excessive duplication of code, this can be done
25274 without creating maintenance problems. The approach is to share common
25275 code as far as possible, and then isolate the code and declarations
25276 that are different. Subunits are often a convenient method for breaking
25277 out a piece of a unit that is to be conditionalized, with separate files
25278 for different versions of the subunit for different targets, where the
25279 build script selects the right one to give to the compiler.
25280 @cindex Subunits (and conditional compilation)
25281
25282 As an example, consider a situation where a new feature in Ada 2005
25283 allows something to be done in a really nice way. But your code must be able
25284 to compile with an Ada 95 compiler. Conceptually you want to say:
25285
25286 @smallexample @c ada
25287 @group
25288 if Ada_2005 then
25289    @dots{} neat Ada 2005 code
25290 else
25291    @dots{} not quite as neat Ada 95 code
25292 end if;
25293 @end group
25294 @end smallexample
25295
25296 @noindent
25297 where @code{Ada_2005} is a Boolean constant.
25298
25299 But this won't work when @code{Ada_2005} is set to @code{False},
25300 since the @code{then} clause will be illegal for an Ada 95 compiler.
25301 (Recall that although such unreachable code would eventually be deleted
25302 by the compiler, it still needs to be legal.  If it uses features
25303 introduced in Ada 2005, it will be illegal in Ada 95.)
25304
25305 So instead we write
25306
25307 @smallexample @c ada
25308 procedure Insert is separate;
25309 @end smallexample
25310
25311 @noindent
25312 Then we have two files for the subunit @code{Insert}, with the two sets of
25313 code.
25314 If the package containing this is called @code{File_Queries}, then we might
25315 have two files
25316
25317 @itemize @bullet
25318 @item    @file{file_queries-insert-2005.adb}
25319 @item    @file{file_queries-insert-95.adb}
25320 @end itemize
25321
25322 @noindent
25323 and the build script renames the appropriate file to
25324
25325 @smallexample
25326 file_queries-insert.adb
25327 @end smallexample
25328
25329 @noindent
25330 and then carries out the compilation.
25331
25332 This can also be done with project files' naming schemes. For example:
25333
25334 @smallexample @c project
25335 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25336 @end smallexample
25337
25338 @noindent
25339 Note also that with project files it is desirable to use a different extension
25340 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25341 conflict may arise through another commonly used feature: to declare as part
25342 of the project a set of directories containing all the sources obeying the
25343 default naming scheme.
25344
25345 The use of alternative units is certainly feasible in all situations,
25346 and for example the Ada part of the GNAT run-time is conditionalized
25347 based on the target architecture using this approach. As a specific example,
25348 consider the implementation of the AST feature in VMS. There is one
25349 spec:
25350
25351 @smallexample
25352 s-asthan.ads
25353 @end smallexample
25354
25355 @noindent
25356 which is the same for all architectures, and three bodies:
25357
25358 @table @file
25359 @item    s-asthan.adb
25360 used for all non-VMS operating systems
25361 @item    s-asthan-vms-alpha.adb
25362 used for VMS on the Alpha
25363 @item    s-asthan-vms-ia64.adb
25364 used for VMS on the ia64
25365 @end table
25366
25367 @noindent
25368 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25369 this operating system feature is not available, and the two remaining
25370 versions interface with the corresponding versions of VMS to provide
25371 VMS-compatible AST handling. The GNAT build script knows the architecture
25372 and operating system, and automatically selects the right version,
25373 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25374
25375 Another style for arranging alternative implementations is through Ada's
25376 access-to-subprogram facility.
25377 In case some functionality is to be conditionally included,
25378 you can declare an access-to-procedure variable @code{Ref} that is initialized
25379 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25380 when appropriate.
25381 In some library package, set @code{Ref} to @code{Proc'Access} for some
25382 procedure @code{Proc} that performs the relevant processing.
25383 The initialization only occurs if the library package is included in the
25384 program.
25385 The same idea can also be implemented using tagged types and dispatching
25386 calls.
25387
25388
25389 @node Preprocessing
25390 @section Preprocessing
25391 @cindex Preprocessing
25392
25393 @noindent
25394 Although it is quite possible to conditionalize code without the use of
25395 C-style preprocessing, as described earlier in this section, it is
25396 nevertheless convenient in some cases to use the C approach. Moreover,
25397 older Ada compilers have often provided some preprocessing capability,
25398 so legacy code may depend on this approach, even though it is not
25399 standard.
25400
25401 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25402 extent on the various preprocessors that have been used
25403 with legacy code on other compilers, to enable easier transition).
25404
25405 The preprocessor may be used in two separate modes. It can be used quite
25406 separately from the compiler, to generate a separate output source file
25407 that is then fed to the compiler as a separate step. This is the
25408 @code{gnatprep} utility, whose use is fully described in
25409 @ref{Preprocessing Using gnatprep}.
25410 @cindex @code{gnatprep}
25411
25412 The preprocessing language allows such constructs as
25413
25414 @smallexample
25415 @group
25416 #if DEBUG or PRIORITY > 4 then
25417    bunch of declarations
25418 #else
25419    completely different bunch of declarations
25420 #end if;
25421 @end group
25422 @end smallexample
25423
25424 @noindent
25425 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25426 defined either on the command line or in a separate file.
25427
25428 The other way of running the preprocessor is even closer to the C style and
25429 often more convenient. In this approach the preprocessing is integrated into
25430 the compilation process. The compiler is fed the preprocessor input which
25431 includes @code{#if} lines etc, and then the compiler carries out the
25432 preprocessing internally and processes the resulting output.
25433 For more details on this approach, see @ref{Integrated Preprocessing}.
25434
25435
25436 @c *******************************
25437 @node Inline Assembler
25438 @appendix Inline Assembler
25439 @c *******************************
25440
25441 @noindent
25442 If you need to write low-level software that interacts directly
25443 with the hardware, Ada provides two ways to incorporate assembly
25444 language code into your program.  First, you can import and invoke
25445 external routines written in assembly language, an Ada feature fully
25446 supported by GNAT@.  However, for small sections of code it may be simpler
25447 or more efficient to include assembly language statements directly
25448 in your Ada source program, using the facilities of the implementation-defined
25449 package @code{System.Machine_Code}, which incorporates the gcc
25450 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25451 including the following:
25452
25453 @itemize @bullet
25454 @item No need to use non-Ada tools
25455 @item Consistent interface over different targets
25456 @item Automatic usage of the proper calling conventions
25457 @item Access to Ada constants and variables
25458 @item Definition of intrinsic routines
25459 @item Possibility of inlining a subprogram comprising assembler code
25460 @item Code optimizer can take Inline Assembler code into account
25461 @end itemize
25462
25463 This chapter presents a series of examples to show you how to use
25464 the Inline Assembler.  Although it focuses on the Intel x86,
25465 the general approach applies also to other processors.
25466 It is assumed that you are familiar with Ada
25467 and with assembly language programming.
25468
25469 @menu
25470 * Basic Assembler Syntax::
25471 * A Simple Example of Inline Assembler::
25472 * Output Variables in Inline Assembler::
25473 * Input Variables in Inline Assembler::
25474 * Inlining Inline Assembler Code::
25475 * Other Asm Functionality::
25476 @end menu
25477
25478 @c ---------------------------------------------------------------------------
25479 @node Basic Assembler Syntax
25480 @section Basic Assembler Syntax
25481
25482 @noindent
25483 The assembler used by GNAT and gcc is based not on the Intel assembly
25484 language, but rather on a language that descends from the AT&T Unix
25485 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25486 The following table summarizes the main features of @emph{as} syntax
25487 and points out the differences from the Intel conventions.
25488 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25489 pre-processor) documentation for further information.
25490
25491 @table @asis
25492 @item Register names
25493 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25494 @*
25495 Intel: No extra punctuation; for example @code{eax}
25496
25497 @item Immediate operand
25498 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25499 @*
25500 Intel: No extra punctuation; for example @code{4}
25501
25502 @item Address
25503 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25504 @*
25505 Intel: No extra punctuation; for example @code{loc}
25506
25507 @item Memory contents
25508 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25509 @*
25510 Intel: Square brackets; for example @code{[loc]}
25511
25512 @item Register contents
25513 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25514 @*
25515 Intel: Square brackets; for example @code{[eax]}
25516
25517 @item Hexadecimal numbers
25518 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25519 @*
25520 Intel: Trailing ``h''; for example @code{A0h}
25521
25522 @item Operand size
25523 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25524 a 16-bit word
25525 @*
25526 Intel: Implicit, deduced by assembler; for example @code{mov}
25527
25528 @item Instruction repetition
25529 gcc / @emph{as}: Split into two lines; for example
25530 @*
25531 @code{rep}
25532 @*
25533 @code{stosl}
25534 @*
25535 Intel: Keep on one line; for example @code{rep stosl}
25536
25537 @item Order of operands
25538 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25539 @*
25540 Intel: Destination first; for example @code{mov eax, 4}
25541 @end table
25542
25543 @c ---------------------------------------------------------------------------
25544 @node A Simple Example of Inline Assembler
25545 @section A Simple Example of Inline Assembler
25546
25547 @noindent
25548 The following example will generate a single assembly language statement,
25549 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25550 the example will be useful in illustrating the basics of
25551 the Inline Assembler facility.
25552
25553 @smallexample @c ada
25554 @group
25555 with System.Machine_Code; use System.Machine_Code;
25556 procedure Nothing is
25557 begin
25558    Asm ("nop");
25559 end Nothing;
25560 @end group
25561 @end smallexample
25562
25563 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25564 here it takes one parameter, a @emph{template string} that must be a static
25565 expression and that will form the generated instruction.
25566 @code{Asm} may be regarded as a compile-time procedure that parses
25567 the template string and additional parameters (none here),
25568 from which it generates a sequence of assembly language instructions.
25569
25570 The examples in this chapter will illustrate several of the forms
25571 for invoking @code{Asm}; a complete specification of the syntax
25572 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25573 Manual}.
25574
25575 Under the standard GNAT conventions, the @code{Nothing} procedure
25576 should be in a file named @file{nothing.adb}.
25577 You can build the executable in the usual way:
25578 @smallexample
25579 gnatmake nothing
25580 @end smallexample
25581 However, the interesting aspect of this example is not its run-time behavior
25582 but rather the generated assembly code.
25583 To see this output, invoke the compiler as follows:
25584 @smallexample
25585    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25586 @end smallexample
25587 where the options are:
25588
25589 @table @code
25590 @item -c
25591 compile only (no bind or link)
25592 @item -S
25593 generate assembler listing
25594 @item -fomit-frame-pointer
25595 do not set up separate stack frames
25596 @item -gnatp
25597 do not add runtime checks
25598 @end table
25599
25600 This gives a human-readable assembler version of the code. The resulting
25601 file will have the same name as the Ada source file, but with a @code{.s}
25602 extension. In our example, the file @file{nothing.s} has the following
25603 contents:
25604
25605 @smallexample
25606 @group
25607 .file "nothing.adb"
25608 gcc2_compiled.:
25609 ___gnu_compiled_ada:
25610 .text
25611    .align 4
25612 .globl __ada_nothing
25613 __ada_nothing:
25614 #APP
25615    nop
25616 #NO_APP
25617    jmp L1
25618    .align 2,0x90
25619 L1:
25620    ret
25621 @end group
25622 @end smallexample
25623
25624 The assembly code you included is clearly indicated by
25625 the compiler, between the @code{#APP} and @code{#NO_APP}
25626 delimiters. The character before the 'APP' and 'NOAPP'
25627 can differ on different targets. For example, GNU/Linux uses '#APP' while
25628 on NT you will see '/APP'.
25629
25630 If you make a mistake in your assembler code (such as using the
25631 wrong size modifier, or using a wrong operand for the instruction) GNAT
25632 will report this error in a temporary file, which will be deleted when
25633 the compilation is finished.  Generating an assembler file will help
25634 in such cases, since you can assemble this file separately using the
25635 @emph{as} assembler that comes with gcc.
25636
25637 Assembling the file using the command
25638
25639 @smallexample
25640 as @file{nothing.s}
25641 @end smallexample
25642 @noindent
25643 will give you error messages whose lines correspond to the assembler
25644 input file, so you can easily find and correct any mistakes you made.
25645 If there are no errors, @emph{as} will generate an object file
25646 @file{nothing.out}.
25647
25648 @c ---------------------------------------------------------------------------
25649 @node Output Variables in Inline Assembler
25650 @section Output Variables in Inline Assembler
25651
25652 @noindent
25653 The examples in this section, showing how to access the processor flags,
25654 illustrate how to specify the destination operands for assembly language
25655 statements.
25656
25657 @smallexample @c ada
25658 @group
25659 with Interfaces; use Interfaces;
25660 with Ada.Text_IO; use Ada.Text_IO;
25661 with System.Machine_Code; use System.Machine_Code;
25662 procedure Get_Flags is
25663    Flags : Unsigned_32;
25664    use ASCII;
25665 begin
25666    Asm ("pushfl"          & LF & HT & -- push flags on stack
25667         "popl %%eax"      & LF & HT & -- load eax with flags
25668         "movl %%eax, %0",             -- store flags in variable
25669         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25670    Put_Line ("Flags register:" & Flags'Img);
25671 end Get_Flags;
25672 @end group
25673 @end smallexample
25674
25675 In order to have a nicely aligned assembly listing, we have separated
25676 multiple assembler statements in the Asm template string with linefeed
25677 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25678 The resulting section of the assembly output file is:
25679
25680 @smallexample
25681 @group
25682 #APP
25683    pushfl
25684    popl %eax
25685    movl %eax, -40(%ebp)
25686 #NO_APP
25687 @end group
25688 @end smallexample
25689
25690 It would have been legal to write the Asm invocation as:
25691
25692 @smallexample
25693 Asm ("pushfl popl %%eax movl %%eax, %0")
25694 @end smallexample
25695
25696 but in the generated assembler file, this would come out as:
25697
25698 @smallexample
25699 #APP
25700    pushfl popl %eax movl %eax, -40(%ebp)
25701 #NO_APP
25702 @end smallexample
25703
25704 which is not so convenient for the human reader.
25705
25706 We use Ada comments
25707 at the end of each line to explain what the assembler instructions
25708 actually do.  This is a useful convention.
25709
25710 When writing Inline Assembler instructions, you need to precede each register
25711 and variable name with a percent sign.  Since the assembler already requires
25712 a percent sign at the beginning of a register name, you need two consecutive
25713 percent signs for such names in the Asm template string, thus @code{%%eax}.
25714 In the generated assembly code, one of the percent signs will be stripped off.
25715
25716 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25717 variables: operands you later define using @code{Input} or @code{Output}
25718 parameters to @code{Asm}.
25719 An output variable is illustrated in
25720 the third statement in the Asm template string:
25721 @smallexample
25722 movl %%eax, %0
25723 @end smallexample
25724 The intent is to store the contents of the eax register in a variable that can
25725 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25726 necessarily work, since the compiler might optimize by using a register
25727 to hold Flags, and the expansion of the @code{movl} instruction would not be
25728 aware of this optimization.  The solution is not to store the result directly
25729 but rather to advise the compiler to choose the correct operand form;
25730 that is the purpose of the @code{%0} output variable.
25731
25732 Information about the output variable is supplied in the @code{Outputs}
25733 parameter to @code{Asm}:
25734 @smallexample
25735 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25736 @end smallexample
25737
25738 The output is defined by the @code{Asm_Output} attribute of the target type;
25739 the general format is
25740 @smallexample
25741 Type'Asm_Output (constraint_string, variable_name)
25742 @end smallexample
25743
25744 The constraint string directs the compiler how
25745 to store/access the associated variable.  In the example
25746 @smallexample
25747 Unsigned_32'Asm_Output ("=m", Flags);
25748 @end smallexample
25749 the @code{"m"} (memory) constraint tells the compiler that the variable
25750 @code{Flags} should be stored in a memory variable, thus preventing
25751 the optimizer from keeping it in a register.  In contrast,
25752 @smallexample
25753 Unsigned_32'Asm_Output ("=r", Flags);
25754 @end smallexample
25755 uses the @code{"r"} (register) constraint, telling the compiler to
25756 store the variable in a register.
25757
25758 If the constraint is preceded by the equal character (@strong{=}), it tells
25759 the compiler that the variable will be used to store data into it.
25760
25761 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25762 allowing the optimizer to choose whatever it deems best.
25763
25764 There are a fairly large number of constraints, but the ones that are
25765 most useful (for the Intel x86 processor) are the following:
25766
25767 @table @code
25768 @item =
25769 output constraint
25770 @item g
25771 global (i.e.@: can be stored anywhere)
25772 @item m
25773 in memory
25774 @item I
25775 a constant
25776 @item a
25777 use eax
25778 @item b
25779 use ebx
25780 @item c
25781 use ecx
25782 @item d
25783 use edx
25784 @item S
25785 use esi
25786 @item D
25787 use edi
25788 @item r
25789 use one of eax, ebx, ecx or edx
25790 @item q
25791 use one of eax, ebx, ecx, edx, esi or edi
25792 @end table
25793
25794 The full set of constraints is described in the gcc and @emph{as}
25795 documentation; note that it is possible to combine certain constraints
25796 in one constraint string.
25797
25798 You specify the association of an output variable with an assembler operand
25799 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25800 integer.  Thus in
25801 @smallexample @c ada
25802 @group
25803 Asm ("pushfl"          & LF & HT & -- push flags on stack
25804      "popl %%eax"      & LF & HT & -- load eax with flags
25805      "movl %%eax, %0",             -- store flags in variable
25806      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25807 @end group
25808 @end smallexample
25809 @noindent
25810 @code{%0} will be replaced in the expanded code by the appropriate operand,
25811 whatever
25812 the compiler decided for the @code{Flags} variable.
25813
25814 In general, you may have any number of output variables:
25815 @itemize @bullet
25816 @item
25817 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25818 @item
25819 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25820 of @code{Asm_Output} attributes
25821 @end itemize
25822
25823 For example:
25824 @smallexample @c ada
25825 @group
25826 Asm ("movl %%eax, %0" & LF & HT &
25827      "movl %%ebx, %1" & LF & HT &
25828      "movl %%ecx, %2",
25829      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25830                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25831                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25832 @end group
25833 @end smallexample
25834 @noindent
25835 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25836 in the Ada program.
25837
25838 As a variation on the @code{Get_Flags} example, we can use the constraints
25839 string to direct the compiler to store the eax register into the @code{Flags}
25840 variable, instead of including the store instruction explicitly in the
25841 @code{Asm} template string:
25842
25843 @smallexample @c ada
25844 @group
25845 with Interfaces; use Interfaces;
25846 with Ada.Text_IO; use Ada.Text_IO;
25847 with System.Machine_Code; use System.Machine_Code;
25848 procedure Get_Flags_2 is
25849    Flags : Unsigned_32;
25850    use ASCII;
25851 begin
25852    Asm ("pushfl"      & LF & HT & -- push flags on stack
25853         "popl %%eax",             -- save flags in eax
25854         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25855    Put_Line ("Flags register:" & Flags'Img);
25856 end Get_Flags_2;
25857 @end group
25858 @end smallexample
25859
25860 @noindent
25861 The @code{"a"} constraint tells the compiler that the @code{Flags}
25862 variable will come from the eax register. Here is the resulting code:
25863
25864 @smallexample
25865 @group
25866 #APP
25867    pushfl
25868    popl %eax
25869 #NO_APP
25870    movl %eax,-40(%ebp)
25871 @end group
25872 @end smallexample
25873
25874 @noindent
25875 The compiler generated the store of eax into Flags after
25876 expanding the assembler code.
25877
25878 Actually, there was no need to pop the flags into the eax register;
25879 more simply, we could just pop the flags directly into the program variable:
25880
25881 @smallexample @c ada
25882 @group
25883 with Interfaces; use Interfaces;
25884 with Ada.Text_IO; use Ada.Text_IO;
25885 with System.Machine_Code; use System.Machine_Code;
25886 procedure Get_Flags_3 is
25887    Flags : Unsigned_32;
25888    use ASCII;
25889 begin
25890    Asm ("pushfl"  & LF & HT & -- push flags on stack
25891         "pop %0",             -- save flags in Flags
25892         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25893    Put_Line ("Flags register:" & Flags'Img);
25894 end Get_Flags_3;
25895 @end group
25896 @end smallexample
25897
25898 @c ---------------------------------------------------------------------------
25899 @node Input Variables in Inline Assembler
25900 @section Input Variables in Inline Assembler
25901
25902 @noindent
25903 The example in this section illustrates how to specify the source operands
25904 for assembly language statements.
25905 The program simply increments its input value by 1:
25906
25907 @smallexample @c ada
25908 @group
25909 with Interfaces; use Interfaces;
25910 with Ada.Text_IO; use Ada.Text_IO;
25911 with System.Machine_Code; use System.Machine_Code;
25912 procedure Increment is
25913
25914    function Incr (Value : Unsigned_32) return Unsigned_32 is
25915       Result : Unsigned_32;
25916    begin
25917       Asm ("incl %0",
25918            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25919            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25920       return Result;
25921    end Incr;
25922
25923    Value : Unsigned_32;
25924
25925 begin
25926    Value := 5;
25927    Put_Line ("Value before is" & Value'Img);
25928    Value := Incr (Value);
25929    Put_Line ("Value after is" & Value'Img);
25930 end Increment;
25931 @end group
25932 @end smallexample
25933
25934 The @code{Outputs} parameter to @code{Asm} specifies
25935 that the result will be in the eax register and that it is to be stored
25936 in the @code{Result} variable.
25937
25938 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25939 but with an @code{Asm_Input} attribute.
25940 The @code{"="} constraint, indicating an output value, is not present.
25941
25942 You can have multiple input variables, in the same way that you can have more
25943 than one output variable.
25944
25945 The parameter count (%0, %1) etc, now starts at the first input
25946 statement, and continues with the output statements.
25947 When both parameters use the same variable, the
25948 compiler will treat them as the same %n operand, which is the case here.
25949
25950 Just as the @code{Outputs} parameter causes the register to be stored into the
25951 target variable after execution of the assembler statements, so does the
25952 @code{Inputs} parameter cause its variable to be loaded into the register
25953 before execution of the assembler statements.
25954
25955 Thus the effect of the @code{Asm} invocation is:
25956 @enumerate
25957 @item load the 32-bit value of @code{Value} into eax
25958 @item execute the @code{incl %eax} instruction
25959 @item store the contents of eax into the @code{Result} variable
25960 @end enumerate
25961
25962 The resulting assembler file (with @option{-O2} optimization) contains:
25963 @smallexample
25964 @group
25965 _increment__incr.1:
25966    subl $4,%esp
25967    movl 8(%esp),%eax
25968 #APP
25969    incl %eax
25970 #NO_APP
25971    movl %eax,%edx
25972    movl %ecx,(%esp)
25973    addl $4,%esp
25974    ret
25975 @end group
25976 @end smallexample
25977
25978 @c ---------------------------------------------------------------------------
25979 @node Inlining Inline Assembler Code
25980 @section Inlining Inline Assembler Code
25981
25982 @noindent
25983 For a short subprogram such as the @code{Incr} function in the previous
25984 section, the overhead of the call and return (creating / deleting the stack
25985 frame) can be significant, compared to the amount of code in the subprogram
25986 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25987 which directs the compiler to expand invocations of the subprogram at the
25988 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25989 Here is the resulting program:
25990
25991 @smallexample @c ada
25992 @group
25993 with Interfaces; use Interfaces;
25994 with Ada.Text_IO; use Ada.Text_IO;
25995 with System.Machine_Code; use System.Machine_Code;
25996 procedure Increment_2 is
25997
25998    function Incr (Value : Unsigned_32) return Unsigned_32 is
25999       Result : Unsigned_32;
26000    begin
26001       Asm ("incl %0",
26002            Inputs  => Unsigned_32'Asm_Input ("a", Value),
26003            Outputs => Unsigned_32'Asm_Output ("=a", Result));
26004       return Result;
26005    end Incr;
26006    pragma Inline (Increment);
26007
26008    Value : Unsigned_32;
26009
26010 begin
26011    Value := 5;
26012    Put_Line ("Value before is" & Value'Img);
26013    Value := Increment (Value);
26014    Put_Line ("Value after is" & Value'Img);
26015 end Increment_2;
26016 @end group
26017 @end smallexample
26018
26019 Compile the program with both optimization (@option{-O2}) and inlining
26020 (@option{-gnatn}) enabled.
26021
26022 The @code{Incr} function is still compiled as usual, but at the
26023 point in @code{Increment} where our function used to be called:
26024
26025 @smallexample
26026 @group
26027 pushl %edi
26028 call _increment__incr.1
26029 @end group
26030 @end smallexample
26031
26032 @noindent
26033 the code for the function body directly appears:
26034
26035 @smallexample
26036 @group
26037 movl %esi,%eax
26038 #APP
26039    incl %eax
26040 #NO_APP
26041    movl %eax,%edx
26042 @end group
26043 @end smallexample
26044
26045 @noindent
26046 thus saving the overhead of stack frame setup and an out-of-line call.
26047
26048 @c ---------------------------------------------------------------------------
26049 @node Other Asm Functionality
26050 @section Other @code{Asm} Functionality
26051
26052 @noindent
26053 This section describes two important parameters to the @code{Asm}
26054 procedure: @code{Clobber}, which identifies register usage;
26055 and @code{Volatile}, which inhibits unwanted optimizations.
26056
26057 @menu
26058 * The Clobber Parameter::
26059 * The Volatile Parameter::
26060 @end menu
26061
26062 @c ---------------------------------------------------------------------------
26063 @node The Clobber Parameter
26064 @subsection The @code{Clobber} Parameter
26065
26066 @noindent
26067 One of the dangers of intermixing assembly language and a compiled language
26068 such as Ada is that the compiler needs to be aware of which registers are
26069 being used by the assembly code.  In some cases, such as the earlier examples,
26070 the constraint string is sufficient to indicate register usage (e.g.,
26071 @code{"a"} for
26072 the eax register).  But more generally, the compiler needs an explicit
26073 identification of the registers that are used by the Inline Assembly
26074 statements.
26075
26076 Using a register that the compiler doesn't know about
26077 could be a side effect of an instruction (like @code{mull}
26078 storing its result in both eax and edx).
26079 It can also arise from explicit register usage in your
26080 assembly code; for example:
26081 @smallexample
26082 @group
26083 Asm ("movl %0, %%ebx" & LF & HT &
26084      "movl %%ebx, %1",
26085      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26086      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26087 @end group
26088 @end smallexample
26089 @noindent
26090 where the compiler (since it does not analyze the @code{Asm} template string)
26091 does not know you are using the ebx register.
26092
26093 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26094 to identify the registers that will be used by your assembly code:
26095
26096 @smallexample
26097 @group
26098 Asm ("movl %0, %%ebx" & LF & HT &
26099      "movl %%ebx, %1",
26100      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26101      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26102      Clobber => "ebx");
26103 @end group
26104 @end smallexample
26105
26106 The Clobber parameter is a static string expression specifying the
26107 register(s) you are using.  Note that register names are @emph{not} prefixed
26108 by a percent sign. Also, if more than one register is used then their names
26109 are separated by commas; e.g., @code{"eax, ebx"}
26110
26111 The @code{Clobber} parameter has several additional uses:
26112 @enumerate
26113 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26114 @item Use ``register'' name @code{memory} if you changed a memory location
26115 @end enumerate
26116
26117 @c ---------------------------------------------------------------------------
26118 @node The Volatile Parameter
26119 @subsection The @code{Volatile} Parameter
26120 @cindex Volatile parameter
26121
26122 @noindent
26123 Compiler optimizations in the presence of Inline Assembler may sometimes have
26124 unwanted effects.  For example, when an @code{Asm} invocation with an input
26125 variable is inside a loop, the compiler might move the loading of the input
26126 variable outside the loop, regarding it as a one-time initialization.
26127
26128 If this effect is not desired, you can disable such optimizations by setting
26129 the @code{Volatile} parameter to @code{True}; for example:
26130
26131 @smallexample @c ada
26132 @group
26133 Asm ("movl %0, %%ebx" & LF & HT &
26134      "movl %%ebx, %1",
26135      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26136      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26137      Clobber  => "ebx",
26138      Volatile => True);
26139 @end group
26140 @end smallexample
26141
26142 By default, @code{Volatile} is set to @code{False} unless there is no
26143 @code{Outputs} parameter.
26144
26145 Although setting @code{Volatile} to @code{True} prevents unwanted
26146 optimizations, it will also disable other optimizations that might be
26147 important for efficiency. In general, you should set @code{Volatile}
26148 to @code{True} only if the compiler's optimizations have created
26149 problems.
26150 @c END OF INLINE ASSEMBLER CHAPTER
26151 @c ===============================
26152
26153 @c ***********************************
26154 @c * Compatibility and Porting Guide *
26155 @c ***********************************
26156 @node Compatibility and Porting Guide
26157 @appendix Compatibility and Porting Guide
26158
26159 @noindent
26160 This chapter describes the compatibility issues that may arise between
26161 GNAT and other Ada compilation systems (including those for Ada 83),
26162 and shows how GNAT can expedite porting
26163 applications developed in other Ada environments.
26164
26165 @menu
26166 * Compatibility with Ada 83::
26167 * Compatibility between Ada 95 and Ada 2005::
26168 * Implementation-dependent characteristics::
26169 * Compatibility with Other Ada Systems::
26170 * Representation Clauses::
26171 @ifclear vms
26172 @c Brief section is only in non-VMS version
26173 @c Full chapter is in VMS version
26174 * Compatibility with HP Ada 83::
26175 @end ifclear
26176 @ifset vms
26177 * Transitioning to 64-Bit GNAT for OpenVMS::
26178 @end ifset
26179 @end menu
26180
26181 @node Compatibility with Ada 83
26182 @section Compatibility with Ada 83
26183 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26184
26185 @noindent
26186 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26187 particular, the design intention was that the difficulties associated
26188 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26189 that occur when moving from one Ada 83 system to another.
26190
26191 However, there are a number of points at which there are minor
26192 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26193 full details of these issues,
26194 and should be consulted for a complete treatment.
26195 In practice the
26196 following subsections treat the most likely issues to be encountered.
26197
26198 @menu
26199 * Legal Ada 83 programs that are illegal in Ada 95::
26200 * More deterministic semantics::
26201 * Changed semantics::
26202 * Other language compatibility issues::
26203 @end menu
26204
26205 @node Legal Ada 83 programs that are illegal in Ada 95
26206 @subsection Legal Ada 83 programs that are illegal in Ada 95
26207
26208 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26209 Ada 95 and thus also in Ada 2005:
26210
26211 @table @emph
26212 @item Character literals
26213 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26214 @code{Wide_Character} as a new predefined character type, some uses of
26215 character literals that were legal in Ada 83 are illegal in Ada 95.
26216 For example:
26217 @smallexample @c ada
26218    for Char in 'A' .. 'Z' loop @dots{} end loop;
26219 @end smallexample
26220
26221 @noindent
26222 The problem is that @code{'A'} and @code{'Z'} could be from either
26223 @code{Character} or @code{Wide_Character}.  The simplest correction
26224 is to make the type explicit; e.g.:
26225 @smallexample @c ada
26226    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26227 @end smallexample
26228
26229 @item New reserved words
26230 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26231 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26232 Existing Ada 83 code using any of these identifiers must be edited to
26233 use some alternative name.
26234
26235 @item Freezing rules
26236 The rules in Ada 95 are slightly different with regard to the point at
26237 which entities are frozen, and representation pragmas and clauses are
26238 not permitted past the freeze point.  This shows up most typically in
26239 the form of an error message complaining that a representation item
26240 appears too late, and the appropriate corrective action is to move
26241 the item nearer to the declaration of the entity to which it refers.
26242
26243 A particular case is that representation pragmas
26244 @ifset vms
26245 (including the
26246 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26247 @end ifset
26248 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26249 declaration must be introduced to which the pragma can be applied.
26250
26251 @item Optional bodies for library packages
26252 In Ada 83, a package that did not require a package body was nevertheless
26253 allowed to have one.  This lead to certain surprises in compiling large
26254 systems (situations in which the body could be unexpectedly ignored by the
26255 binder).  In Ada 95, if a package does not require a body then it is not
26256 permitted to have a body.  To fix this problem, simply remove a redundant
26257 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26258 into the spec that makes the body required.  One approach is to add a private
26259 part to the package declaration (if necessary), and define a parameterless
26260 procedure called @code{Requires_Body}, which must then be given a dummy
26261 procedure body in the package body, which then becomes required.
26262 Another approach (assuming that this does not introduce elaboration
26263 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26264 since one effect of this pragma is to require the presence of a package body.
26265
26266 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26267 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26268 @code{Constraint_Error}.
26269 This means that it is illegal to have separate exception handlers for
26270 the two exceptions.  The fix is simply to remove the handler for the
26271 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26272 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26273
26274 @item Indefinite subtypes in generics
26275 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26276 as the actual for a generic formal private type, but then the instantiation
26277 would be illegal if there were any instances of declarations of variables
26278 of this type in the generic body.  In Ada 95, to avoid this clear violation
26279 of the methodological principle known as the ``contract model'',
26280 the generic declaration explicitly indicates whether
26281 or not such instantiations are permitted.  If a generic formal parameter
26282 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26283 type name, then it can be instantiated with indefinite types, but no
26284 stand-alone variables can be declared of this type.  Any attempt to declare
26285 such a variable will result in an illegality at the time the generic is
26286 declared.  If the @code{(<>)} notation is not used, then it is illegal
26287 to instantiate the generic with an indefinite type.
26288 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26289 It will show up as a compile time error, and
26290 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26291 @end table
26292
26293 @node More deterministic semantics
26294 @subsection More deterministic semantics
26295
26296 @table @emph
26297 @item Conversions
26298 Conversions from real types to integer types round away from 0.  In Ada 83
26299 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26300 implementation freedom was intended to support unbiased rounding in
26301 statistical applications, but in practice it interfered with portability.
26302 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26303 is required.  Numeric code may be affected by this change in semantics.
26304 Note, though, that this issue is no worse than already existed in Ada 83
26305 when porting code from one vendor to another.
26306
26307 @item Tasking
26308 The Real-Time Annex introduces a set of policies that define the behavior of
26309 features that were implementation dependent in Ada 83, such as the order in
26310 which open select branches are executed.
26311 @end table
26312
26313 @node Changed semantics
26314 @subsection Changed semantics
26315
26316 @noindent
26317 The worst kind of incompatibility is one where a program that is legal in
26318 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26319 possible in Ada 83.  Fortunately this is extremely rare, but the one
26320 situation that you should be alert to is the change in the predefined type
26321 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26322
26323 @table @emph
26324 @item Range of type @code{Character}
26325 The range of @code{Standard.Character} is now the full 256 characters
26326 of Latin-1, whereas in most Ada 83 implementations it was restricted
26327 to 128 characters. Although some of the effects of
26328 this change will be manifest in compile-time rejection of legal
26329 Ada 83 programs it is possible for a working Ada 83 program to have
26330 a different effect in Ada 95, one that was not permitted in Ada 83.
26331 As an example, the expression
26332 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26333 delivers @code{255} as its value.
26334 In general, you should look at the logic of any
26335 character-processing Ada 83 program and see whether it needs to be adapted
26336 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26337 character handling package that may be relevant if code needs to be adapted
26338 to account for the additional Latin-1 elements.
26339 The desirable fix is to
26340 modify the program to accommodate the full character set, but in some cases
26341 it may be convenient to define a subtype or derived type of Character that
26342 covers only the restricted range.
26343 @cindex Latin-1
26344 @end table
26345
26346 @node Other language compatibility issues
26347 @subsection Other language compatibility issues
26348
26349 @table @emph
26350 @item @option{-gnat83} switch
26351 All implementations of GNAT provide a switch that causes GNAT to operate
26352 in Ada 83 mode.  In this mode, some but not all compatibility problems
26353 of the type described above are handled automatically.  For example, the
26354 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26355 as identifiers as in Ada 83.
26356 However,
26357 in practice, it is usually advisable to make the necessary modifications
26358 to the program to remove the need for using this switch.
26359 See @ref{Compiling Different Versions of Ada}.
26360
26361 @item Support for removed Ada 83 pragmas and attributes
26362 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26363 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26364 compilers are allowed, but not required, to implement these missing
26365 elements.  In contrast with some other compilers, GNAT implements all
26366 such pragmas and attributes, eliminating this compatibility concern.  These
26367 include @code{pragma Interface} and the floating point type attributes
26368 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26369 @end table
26370
26371
26372 @node Compatibility between Ada 95 and Ada 2005
26373 @section Compatibility between Ada 95 and Ada 2005
26374 @cindex Compatibility between Ada 95 and Ada 2005
26375
26376 @noindent
26377 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26378 a number of incompatibilities. Several are enumerated below;
26379 for a complete description please see the
26380 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26381 @cite{Rationale for Ada 2005}.
26382
26383 @table @emph
26384 @item New reserved words.
26385 The words @code{interface}, @code{overriding} and @code{synchronized} are
26386 reserved in Ada 2005.
26387 A pre-Ada 2005 program that uses any of these as an identifier will be
26388 illegal.
26389
26390 @item New declarations in predefined packages.
26391 A number of packages in the predefined environment contain new declarations:
26392 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26393 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26394 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26395 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26396 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26397 If an Ada 95 program does a @code{with} and @code{use} of any of these
26398 packages, the new declarations may cause name clashes.
26399
26400 @item Access parameters.
26401 A nondispatching subprogram with an access parameter cannot be renamed
26402 as a dispatching operation.  This was permitted in Ada 95.
26403
26404 @item Access types, discriminants, and constraints.
26405 Rule changes in this area have led to some incompatibilities; for example,
26406 constrained subtypes of some access types are not permitted in Ada 2005.
26407
26408 @item Aggregates for limited types.
26409 The allowance of aggregates for limited types in Ada 2005 raises the
26410 possibility of ambiguities in legal Ada 95 programs, since additional types
26411 now need to be considered in expression resolution.
26412
26413 @item Fixed-point multiplication and division.
26414 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26415 were legal in Ada 95 and invoked the predefined versions of these operations,
26416 are now ambiguous.
26417 The ambiguity may be resolved either by applying a type conversion to the
26418 expression, or by explicitly invoking the operation from package
26419 @code{Standard}.
26420
26421 @item Return-by-reference types.
26422 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26423 can declare a function returning a value from an anonymous access type.
26424 @end table
26425
26426
26427 @node Implementation-dependent characteristics
26428 @section Implementation-dependent characteristics
26429 @noindent
26430 Although the Ada language defines the semantics of each construct as
26431 precisely as practical, in some situations (for example for reasons of
26432 efficiency, or where the effect is heavily dependent on the host or target
26433 platform) the implementation is allowed some freedom.  In porting Ada 83
26434 code to GNAT, you need to be aware of whether / how the existing code
26435 exercised such implementation dependencies.  Such characteristics fall into
26436 several categories, and GNAT offers specific support in assisting the
26437 transition from certain Ada 83 compilers.
26438
26439 @menu
26440 * Implementation-defined pragmas::
26441 * Implementation-defined attributes::
26442 * Libraries::
26443 * Elaboration order::
26444 * Target-specific aspects::
26445 @end menu
26446
26447 @node Implementation-defined pragmas
26448 @subsection Implementation-defined pragmas
26449
26450 @noindent
26451 Ada compilers are allowed to supplement the language-defined pragmas, and
26452 these are a potential source of non-portability.  All GNAT-defined pragmas
26453 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26454 Reference Manual}, and these include several that are specifically
26455 intended to correspond to other vendors' Ada 83 pragmas.
26456 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26457 For compatibility with HP Ada 83, GNAT supplies the pragmas
26458 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26459 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26460 and @code{Volatile}.
26461 Other relevant pragmas include @code{External} and @code{Link_With}.
26462 Some vendor-specific
26463 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26464 recognized, thus
26465 avoiding compiler rejection of units that contain such pragmas; they are not
26466 relevant in a GNAT context and hence are not otherwise implemented.
26467
26468 @node Implementation-defined attributes
26469 @subsection Implementation-defined attributes
26470
26471 Analogous to pragmas, the set of attributes may be extended by an
26472 implementation.  All GNAT-defined attributes are described in
26473 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26474 Manual}, and these include several that are specifically intended
26475 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26476 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26477 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26478 @code{Type_Class}.
26479
26480 @node Libraries
26481 @subsection Libraries
26482 @noindent
26483 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26484 code uses vendor-specific libraries then there are several ways to manage
26485 this in Ada 95 or Ada 2005:
26486 @enumerate
26487 @item
26488 If the source code for the libraries (specs and bodies) are
26489 available, then the libraries can be migrated in the same way as the
26490 application.
26491 @item
26492 If the source code for the specs but not the bodies are
26493 available, then you can reimplement the bodies.
26494 @item
26495 Some features introduced by Ada 95 obviate the need for library support.  For
26496 example most Ada 83 vendors supplied a package for unsigned integers.  The
26497 Ada 95 modular type feature is the preferred way to handle this need, so
26498 instead of migrating or reimplementing the unsigned integer package it may
26499 be preferable to retrofit the application using modular types.
26500 @end enumerate
26501
26502 @node Elaboration order
26503 @subsection Elaboration order
26504 @noindent
26505 The implementation can choose any elaboration order consistent with the unit
26506 dependency relationship.  This freedom means that some orders can result in
26507 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26508 to invoke a subprogram its body has been elaborated, or to instantiate a
26509 generic before the generic body has been elaborated.  By default GNAT
26510 attempts to choose a safe order (one that will not encounter access before
26511 elaboration problems) by implicitly inserting @code{Elaborate} or
26512 @code{Elaborate_All} pragmas where
26513 needed.  However, this can lead to the creation of elaboration circularities
26514 and a resulting rejection of the program by gnatbind.  This issue is
26515 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26516 In brief, there are several
26517 ways to deal with this situation:
26518
26519 @itemize @bullet
26520 @item
26521 Modify the program to eliminate the circularities, e.g.@: by moving
26522 elaboration-time code into explicitly-invoked procedures
26523 @item
26524 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26525 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26526 @code{Elaborate_All}
26527 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26528 (by selectively suppressing elaboration checks via pragma
26529 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26530 @end itemize
26531
26532 @node Target-specific aspects
26533 @subsection Target-specific aspects
26534 @noindent
26535 Low-level applications need to deal with machine addresses, data
26536 representations, interfacing with assembler code, and similar issues.  If
26537 such an Ada 83 application is being ported to different target hardware (for
26538 example where the byte endianness has changed) then you will need to
26539 carefully examine the program logic; the porting effort will heavily depend
26540 on the robustness of the original design.  Moreover, Ada 95 (and thus
26541 Ada 2005) are sometimes
26542 incompatible with typical Ada 83 compiler practices regarding implicit
26543 packing, the meaning of the Size attribute, and the size of access values.
26544 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26545
26546 @node Compatibility with Other Ada Systems
26547 @section Compatibility with Other Ada Systems
26548
26549 @noindent
26550 If programs avoid the use of implementation dependent and
26551 implementation defined features, as documented in the @cite{Ada
26552 Reference Manual}, there should be a high degree of portability between
26553 GNAT and other Ada systems.  The following are specific items which
26554 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26555 compilers, but do not affect porting code to GNAT@.
26556 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26557 the following issues may or may not arise for Ada 2005 programs
26558 when other compilers appear.)
26559
26560 @table @emph
26561 @item Ada 83 Pragmas and Attributes
26562 Ada 95 compilers are allowed, but not required, to implement the missing
26563 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26564 GNAT implements all such pragmas and attributes, eliminating this as
26565 a compatibility concern, but some other Ada 95 compilers reject these
26566 pragmas and attributes.
26567
26568 @item Specialized Needs Annexes
26569 GNAT implements the full set of special needs annexes.  At the
26570 current time, it is the only Ada 95 compiler to do so.  This means that
26571 programs making use of these features may not be portable to other Ada
26572 95 compilation systems.
26573
26574 @item Representation Clauses
26575 Some other Ada 95 compilers implement only the minimal set of
26576 representation clauses required by the Ada 95 reference manual.  GNAT goes
26577 far beyond this minimal set, as described in the next section.
26578 @end table
26579
26580 @node Representation Clauses
26581 @section Representation Clauses
26582
26583 @noindent
26584 The Ada 83 reference manual was quite vague in describing both the minimal
26585 required implementation of representation clauses, and also their precise
26586 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26587 minimal set of capabilities required is still quite limited.
26588
26589 GNAT implements the full required set of capabilities in
26590 Ada 95 and Ada 2005, but also goes much further, and in particular
26591 an effort has been made to be compatible with existing Ada 83 usage to the
26592 greatest extent possible.
26593
26594 A few cases exist in which Ada 83 compiler behavior is incompatible with
26595 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26596 intentional or accidental dependence on specific implementation dependent
26597 characteristics of these Ada 83 compilers.  The following is a list of
26598 the cases most likely to arise in existing Ada 83 code.
26599
26600 @table @emph
26601 @item Implicit Packing
26602 Some Ada 83 compilers allowed a Size specification to cause implicit
26603 packing of an array or record.  This could cause expensive implicit
26604 conversions for change of representation in the presence of derived
26605 types, and the Ada design intends to avoid this possibility.
26606 Subsequent AI's were issued to make it clear that such implicit
26607 change of representation in response to a Size clause is inadvisable,
26608 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26609 Reference Manuals as implementation advice that is followed by GNAT@.
26610 The problem will show up as an error
26611 message rejecting the size clause.  The fix is simply to provide
26612 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26613 a Component_Size clause.
26614
26615 @item Meaning of Size Attribute
26616 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26617 the minimal number of bits required to hold values of the type.  For example,
26618 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26619 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26620 some 32 in this situation.  This problem will usually show up as a compile
26621 time error, but not always.  It is a good idea to check all uses of the
26622 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26623 Object_Size can provide a useful way of duplicating the behavior of
26624 some Ada 83 compiler systems.
26625
26626 @item Size of Access Types
26627 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26628 and that therefore it will be the same size as a System.Address value.  This
26629 assumption is true for GNAT in most cases with one exception.  For the case of
26630 a pointer to an unconstrained array type (where the bounds may vary from one
26631 value of the access type to another), the default is to use a ``fat pointer'',
26632 which is represented as two separate pointers, one to the bounds, and one to
26633 the array.  This representation has a number of advantages, including improved
26634 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26635 code which makes the assumption that, for example, pointers fit in 32 bits on
26636 a machine with 32-bit addressing.
26637
26638 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26639 access types in this case (where the designated type is an unconstrained array
26640 type).  These thin pointers are indeed the same size as a System.Address value.
26641 To specify a thin pointer, use a size clause for the type, for example:
26642
26643 @smallexample @c ada
26644 type X is access all String;
26645 for X'Size use Standard'Address_Size;
26646 @end smallexample
26647
26648 @noindent
26649 which will cause the type X to be represented using a single pointer.
26650 When using this representation, the bounds are right behind the array.
26651 This representation is slightly less efficient, and does not allow quite
26652 such flexibility in the use of foreign pointers or in using the
26653 Unrestricted_Access attribute to create pointers to non-aliased objects.
26654 But for any standard portable use of the access type it will work in
26655 a functionally correct manner and allow porting of existing code.
26656 Note that another way of forcing a thin pointer representation
26657 is to use a component size clause for the element size in an array,
26658 or a record representation clause for an access field in a record.
26659 @end table
26660
26661 @ifclear vms
26662 @c This brief section is only in the non-VMS version
26663 @c The complete chapter on HP Ada is in the VMS version
26664 @node Compatibility with HP Ada 83
26665 @section Compatibility with HP Ada 83
26666
26667 @noindent
26668 The VMS version of GNAT fully implements all the pragmas and attributes
26669 provided by HP Ada 83, as well as providing the standard HP Ada 83
26670 libraries, including Starlet.  In addition, data layouts and parameter
26671 passing conventions are highly compatible.  This means that porting
26672 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26673 most other porting efforts.  The following are some of the most
26674 significant differences between GNAT and HP Ada 83.
26675
26676 @table @emph
26677 @item Default floating-point representation
26678 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26679 it is VMS format.  GNAT does implement the necessary pragmas
26680 (Long_Float, Float_Representation) for changing this default.
26681
26682 @item System
26683 The package System in GNAT exactly corresponds to the definition in the
26684 Ada 95 reference manual, which means that it excludes many of the
26685 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26686 that contains the additional definitions, and a special pragma,
26687 Extend_System allows this package to be treated transparently as an
26688 extension of package System.
26689
26690 @item To_Address
26691 The definitions provided by Aux_DEC are exactly compatible with those
26692 in the HP Ada 83 version of System, with one exception.
26693 HP Ada provides the following declarations:
26694
26695 @smallexample @c ada
26696 TO_ADDRESS (INTEGER)
26697 TO_ADDRESS (UNSIGNED_LONGWORD)
26698 TO_ADDRESS (@i{universal_integer})
26699 @end smallexample
26700
26701 @noindent
26702 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26703 an extension to Ada 83 not strictly compatible with the reference manual.
26704 In GNAT, we are constrained to be exactly compatible with the standard,
26705 and this means we cannot provide this capability.  In HP Ada 83, the
26706 point of this definition is to deal with a call like:
26707
26708 @smallexample @c ada
26709 TO_ADDRESS (16#12777#);
26710 @end smallexample
26711
26712 @noindent
26713 Normally, according to the Ada 83 standard, one would expect this to be
26714 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26715 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26716 definition using @i{universal_integer} takes precedence.
26717
26718 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26719 is not possible to be 100% compatible.  Since there are many programs using
26720 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26721 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26722 declarations provided in the GNAT version of AUX_Dec are:
26723
26724 @smallexample @c ada
26725 function To_Address (X : Integer) return Address;
26726 pragma Pure_Function (To_Address);
26727
26728 function To_Address_Long (X : Unsigned_Longword)
26729  return Address;
26730 pragma Pure_Function (To_Address_Long);
26731 @end smallexample
26732
26733 @noindent
26734 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26735 change the name to TO_ADDRESS_LONG@.
26736
26737 @item Task_Id values
26738 The Task_Id values assigned will be different in the two systems, and GNAT
26739 does not provide a specified value for the Task_Id of the environment task,
26740 which in GNAT is treated like any other declared task.
26741 @end table
26742
26743 @noindent
26744 For full details on these and other less significant compatibility issues,
26745 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26746 Overview and Comparison on HP Platforms}.
26747
26748 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26749 attributes are recognized, although only a subset of them can sensibly
26750 be implemented.  The description of pragmas in @ref{Implementation
26751 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26752 indicates whether or not they are applicable to non-VMS systems.
26753 @end ifclear
26754
26755 @ifset vms
26756 @node Transitioning to 64-Bit GNAT for OpenVMS
26757 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26758
26759 @noindent
26760 This section is meant to assist users of pre-2006 @value{EDITION}
26761 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26762 the version of the GNAT technology supplied in 2006 and later for
26763 OpenVMS on both Alpha and I64.
26764
26765 @menu
26766 * Introduction to transitioning::
26767 * Migration of 32 bit code::
26768 * Taking advantage of 64 bit addressing::
26769 * Technical details::
26770 @end menu
26771
26772 @node Introduction to transitioning
26773 @subsection Introduction
26774
26775 @noindent
26776 64-bit @value{EDITION} for Open VMS has been designed to meet
26777 three main goals:
26778
26779 @enumerate
26780 @item
26781 Providing a full conforming implementation of Ada 95 and Ada 2005
26782
26783 @item
26784 Allowing maximum backward compatibility, thus easing migration of existing
26785 Ada source code
26786
26787 @item
26788 Supplying a path for exploiting the full 64-bit address range
26789 @end enumerate
26790
26791 @noindent
26792 Ada's strong typing semantics has made it
26793 impractical to have different 32-bit and 64-bit modes. As soon as
26794 one object could possibly be outside the 32-bit address space, this
26795 would make it necessary for the @code{System.Address} type to be 64 bits.
26796 In particular, this would cause inconsistencies if 32-bit code is
26797 called from 64-bit code that raises an exception.
26798
26799 This issue has been resolved by always using 64-bit addressing
26800 at the system level, but allowing for automatic conversions between
26801 32-bit and 64-bit addresses where required. Thus users who
26802 do not currently require 64-bit addressing capabilities, can
26803 recompile their code with only minimal changes (and indeed
26804 if the code is written in portable Ada, with no assumptions about
26805 the size of the @code{Address} type, then no changes at all are necessary).
26806 At the same time,
26807 this approach provides a simple, gradual upgrade path to future
26808 use of larger memories than available for 32-bit systems.
26809 Also, newly written applications or libraries will by default
26810 be fully compatible with future systems exploiting 64-bit
26811 addressing capabilities.
26812
26813 @ref{Migration of 32 bit code}, will focus on porting applications
26814 that do not require more than 2 GB of
26815 addressable memory. This code will be referred to as
26816 @emph{32-bit code}.
26817 For applications intending to exploit the full 64-bit address space,
26818 @ref{Taking advantage of 64 bit addressing},
26819 will consider further changes that may be required.
26820 Such code will be referred to below as @emph{64-bit code}.
26821
26822 @node Migration of 32 bit code
26823 @subsection Migration of 32-bit code
26824
26825 @menu
26826 * Address types::
26827 * Access types and 32/64-bit allocation::
26828 * Unchecked conversions::
26829 * Predefined constants::
26830 * Interfacing with C::
26831 * 32/64-bit descriptors::
26832 * Experience with source compatibility::
26833 @end menu
26834
26835 @node Address types
26836 @subsubsection Address types
26837
26838 @noindent
26839 To solve the problem of mixing 64-bit and 32-bit addressing,
26840 while maintaining maximum backward compatibility, the following
26841 approach has been taken:
26842
26843 @itemize @bullet
26844 @item
26845 @code{System.Address} always has a size of 64 bits
26846 @cindex @code{System.Address} size
26847 @cindex @code{Address} size
26848
26849 @item
26850 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26851 @cindex @code{System.Short_Address} size
26852 @cindex @code{Short_Address} size
26853 @end itemize
26854
26855 @noindent
26856 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26857 a @code{Short_Address}
26858 may be used where an @code{Address} is required, and vice versa, without
26859 needing explicit type conversions.
26860 By virtue of the Open VMS parameter passing conventions,
26861 even imported
26862 and exported subprograms that have 32-bit address parameters are
26863 compatible with those that have 64-bit address parameters.
26864 (See @ref{Making code 64 bit clean} for details.)
26865
26866 The areas that may need attention are those where record types have
26867 been defined that contain components of the type @code{System.Address}, and
26868 where objects of this type are passed to code expecting a record layout with
26869 32-bit addresses.
26870
26871 Different compilers on different platforms cannot be
26872 expected to represent the same type in the same way,
26873 since alignment constraints
26874 and other system-dependent properties affect the compiler's decision.
26875 For that reason, Ada code
26876 generally uses representation clauses to specify the expected
26877 layout where required.
26878
26879 If such a representation clause uses 32 bits for a component having
26880 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26881 will detect that error and produce a specific diagnostic message.
26882 The developer should then determine whether the representation
26883 should be 64 bits or not and make either of two changes:
26884 change the size to 64 bits and leave the type as @code{System.Address}, or
26885 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26886 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26887 required in any code setting or accessing the field; the compiler will
26888 automatically perform any needed conversions between address
26889 formats.
26890
26891 @node Access types and 32/64-bit allocation
26892 @subsubsection Access types and 32/64-bit allocation
26893 @cindex 32-bit allocation
26894 @cindex 64-bit allocation
26895
26896 @noindent
26897 By default, objects designated by access values are always allocated in
26898 the 64-bit address space, and access values themselves are represented
26899 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26900 is required (for example if the address of an allocated object is assigned
26901 to a @code{Short_Address} variable), then several alternatives are available:
26902
26903 @itemize @bullet
26904 @item
26905 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26906 definition is @code{access T} versus @code{access all T} or
26907 @code{access constant T}), may be declared with a @code{'Size} representation
26908 clause that establishes the size as 32 bits.
26909 In such circumstances allocations for that type will
26910 be from the 32-bit heap.  Such a clause is not permitted
26911 for a general access type (declared with @code{access all} or
26912 @code{access constant}) as values of such types must be able to refer
26913 to any object of the designated type, including objects residing outside
26914 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26915 type definitions, however, since general access types were introduced
26916 in @w{Ada 95}.
26917
26918 @item
26919 Switches for @command{GNAT BIND} control whether the internal GNAT
26920 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26921 @cindex @code{__gnat_malloc}
26922 The switches are respectively @option{-H64} (the default) and
26923 @option{-H32}.
26924 @cindex @option{-H32} (@command{gnatbind})
26925 @cindex @option{-H64} (@command{gnatbind})
26926
26927 @item
26928 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26929 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26930 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26931 If this variable is left
26932 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26933 then the default (64-bit) allocation is used.
26934 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26935 then 32-bit allocation is used.  The gnatbind qualifiers described above
26936 override this logical name.
26937
26938 @item
26939 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26940 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26941 at a low level to convert explicit calls to @code{malloc} and related
26942 functions from the C run-time library so that they perform allocations
26943 in the 32-bit heap.
26944 Since all internal allocations from GNAT use @code{__gnat_malloc},
26945 this switch is not required unless the program makes explicit calls on
26946 @code{malloc} (or related functions) from interfaced C code.
26947 @end itemize
26948
26949
26950 @node Unchecked conversions
26951 @subsubsection Unchecked conversions
26952
26953 @noindent
26954 In the case of an @code{Unchecked_Conversion} where the source type is a
26955 64-bit access type or the type @code{System.Address}, and the target
26956 type is a 32-bit type, the compiler will generate a warning.
26957 Even though the generated code will still perform the required
26958 conversions, it is highly recommended in these cases to use
26959 respectively a 32-bit access type or @code{System.Short_Address}
26960 as the source type.
26961
26962 @node Predefined constants
26963 @subsubsection Predefined constants
26964
26965 @noindent
26966 The following table shows the correspondence between pre-2006 versions of
26967 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26968 (``New''):
26969
26970 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26971 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26972 @item   @code{System.Word_Size}          @tab 32      @tab 64
26973 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26974 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26975 @item   @code{System.Address_Size}       @tab 32      @tab 64
26976 @end multitable
26977
26978 @noindent
26979 If you need to refer to the specific
26980 memory size of a 32-bit implementation, instead of the
26981 actual memory size, use @code{System.Short_Memory_Size}
26982 rather than @code{System.Memory_Size}.
26983 Similarly, references to @code{System.Address_Size} may need
26984 to be replaced by @code{System.Short_Address'Size}.
26985 The program @command{gnatfind} may be useful for locating
26986 references to the above constants, so that you can verify that they
26987 are still correct.
26988
26989 @node Interfacing with C
26990 @subsubsection Interfacing with C
26991
26992 @noindent
26993 In order to minimize the impact of the transition to 64-bit addresses on
26994 legacy programs, some fundamental types in the @code{Interfaces.C}
26995 package hierarchy continue to be represented in 32 bits.
26996 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26997 This eases integration with the default HP C layout choices, for example
26998 as found in the system routines in @code{DECC$SHR.EXE}.
26999 Because of this implementation choice, the type fully compatible with
27000 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
27001 Depending on the context the compiler will issue a
27002 warning or an error when type @code{Address} is used, alerting the user to a
27003 potential problem. Otherwise 32-bit programs that use
27004 @code{Interfaces.C} should normally not require code modifications
27005
27006 The other issue arising with C interfacing concerns pragma @code{Convention}.
27007 For VMS 64-bit systems, there is an issue of the appropriate default size
27008 of C convention pointers in the absence of an explicit size clause. The HP
27009 C compiler can choose either 32 or 64 bits depending on compiler options.
27010 GNAT chooses 32-bits rather than 64-bits in the default case where no size
27011 clause is given. This proves a better choice for porting 32-bit legacy
27012 applications. In order to have a 64-bit representation, it is necessary to
27013 specify a size representation clause. For example:
27014
27015 @smallexample @c ada
27016 type int_star is access Interfaces.C.int;
27017 pragma Convention(C, int_star);
27018 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
27019 @end smallexample
27020
27021 @node 32/64-bit descriptors
27022 @subsubsection 32/64-bit descriptors
27023
27024 @noindent
27025 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
27026 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
27027 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
27028 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
27029 @cindex @code{Short_Descriptor} mechanism for imported subprograms
27030
27031 If the configuration pragma @code{Short_Descriptors} is supplied, then
27032 all descriptors will be 32 bits.
27033 @cindex pragma @code{Short_Descriptors}
27034
27035 @node Experience with source compatibility
27036 @subsubsection Experience with source compatibility
27037
27038 @noindent
27039 The Security Server and STARLET on I64 provide an interesting ``test case''
27040 for source compatibility issues, since it is in such system code
27041 where assumptions about @code{Address} size might be expected to occur.
27042 Indeed, there were a small number of occasions in the Security Server
27043 file @file{jibdef.ads}
27044 where a representation clause for a record type specified
27045 32 bits for a component of type @code{Address}.
27046 All of these errors were detected by the compiler.
27047 The repair was obvious and immediate; to simply replace @code{Address} by
27048 @code{Short_Address}.
27049
27050 In the case of STARLET, there were several record types that should
27051 have had representation clauses but did not.  In these record types
27052 there was an implicit assumption that an @code{Address} value occupied
27053 32 bits.
27054 These compiled without error, but their usage resulted in run-time error
27055 returns from STARLET system calls.
27056 Future GNAT technology enhancements may include a tool that detects and flags
27057 these sorts of potential source code porting problems.
27058
27059 @c ****************************************
27060 @node Taking advantage of 64 bit addressing
27061 @subsection Taking advantage of 64-bit addressing
27062
27063 @menu
27064 * Making code 64 bit clean::
27065 * Allocating memory from the 64 bit storage pool::
27066 * Restrictions on use of 64 bit objects::
27067 * STARLET and other predefined libraries::
27068 @end menu
27069
27070 @node Making code 64 bit clean
27071 @subsubsection Making code 64-bit clean
27072
27073 @noindent
27074 In order to prevent problems that may occur when (parts of) a
27075 system start using memory outside the 32-bit address range,
27076 we recommend some additional guidelines:
27077
27078 @itemize @bullet
27079 @item
27080 For imported subprograms that take parameters of the
27081 type @code{System.Address}, ensure that these subprograms can
27082 indeed handle 64-bit addresses. If not, or when in doubt,
27083 change the subprogram declaration to specify
27084 @code{System.Short_Address} instead.
27085
27086 @item
27087 Resolve all warnings related to size mismatches in
27088 unchecked conversions. Failing to do so causes
27089 erroneous execution if the source object is outside
27090 the 32-bit address space.
27091
27092 @item
27093 (optional) Explicitly use the 32-bit storage pool
27094 for access types used in a 32-bit context, or use
27095 generic access types where possible
27096 (@pxref{Restrictions on use of 64 bit objects}).
27097 @end itemize
27098
27099 @noindent
27100 If these rules are followed, the compiler will automatically insert
27101 any necessary checks to ensure that no addresses or access values
27102 passed to 32-bit code ever refer to objects outside the 32-bit
27103 address range.
27104 Any attempt to do this will raise @code{Constraint_Error}.
27105
27106 @node Allocating memory from the 64 bit storage pool
27107 @subsubsection Allocating memory from the 64-bit storage pool
27108
27109 @noindent
27110 By default, all allocations -- for both pool-specific and general
27111 access types -- use the 64-bit storage pool.  To override
27112 this default, for an individual access type or globally, see
27113 @ref{Access types and 32/64-bit allocation}.
27114
27115 @node Restrictions on use of 64 bit objects
27116 @subsubsection Restrictions on use of 64-bit objects
27117
27118 @noindent
27119 Taking the address of an object allocated from a 64-bit storage pool,
27120 and then passing this address to a subprogram expecting
27121 @code{System.Short_Address},
27122 or assigning it to a variable of type @code{Short_Address}, will cause
27123 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27124 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27125 no exception is raised and execution
27126 will become erroneous.
27127
27128 @node STARLET and other predefined libraries
27129 @subsubsection STARLET and other predefined libraries
27130
27131 @noindent
27132 All code that comes as part of GNAT is 64-bit clean, but the
27133 restrictions given in @ref{Restrictions on use of 64 bit objects},
27134 still apply. Look at the package
27135 specs to see in which contexts objects allocated
27136 in 64-bit address space are acceptable.
27137
27138 @node Technical details
27139 @subsection Technical details
27140
27141 @noindent
27142 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27143 Ada standard with respect to the type of @code{System.Address}. Previous
27144 versions of @value{EDITION} have defined this type as private and implemented it as a
27145 modular type.
27146
27147 In order to allow defining @code{System.Short_Address} as a proper subtype,
27148 and to match the implicit sign extension in parameter passing,
27149 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27150 visible (i.e., non-private) integer type.
27151 Standard operations on the type, such as the binary operators ``+'', ``-'',
27152 etc., that take @code{Address} operands and return an @code{Address} result,
27153 have been hidden by declaring these
27154 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27155 ambiguities that would otherwise result from overloading.
27156 (Note that, although @code{Address} is a visible integer type,
27157 good programming practice dictates against exploiting the type's
27158 integer properties such as literals, since this will compromise
27159 code portability.)
27160
27161 Defining @code{Address} as a visible integer type helps achieve
27162 maximum compatibility for existing Ada code,
27163 without sacrificing the capabilities of the 64-bit architecture.
27164 @end ifset
27165
27166 @c ************************************************
27167 @ifset unw
27168 @node Microsoft Windows Topics
27169 @appendix Microsoft Windows Topics
27170 @cindex Windows NT
27171 @cindex Windows 95
27172 @cindex Windows 98
27173
27174 @noindent
27175 This chapter describes topics that are specific to the Microsoft Windows
27176 platforms (NT, 2000, and XP Professional).
27177
27178 @menu
27179 * Using GNAT on Windows::
27180 * Using a network installation of GNAT::
27181 * CONSOLE and WINDOWS subsystems::
27182 * Temporary Files::
27183 * Mixed-Language Programming on Windows::
27184 * Windows Calling Conventions::
27185 * Introduction to Dynamic Link Libraries (DLLs)::
27186 * Using DLLs with GNAT::
27187 * Building DLLs with GNAT Project files::
27188 * Building DLLs with GNAT::
27189 * Building DLLs with gnatdll::
27190 * GNAT and Windows Resources::
27191 * Debugging a DLL::
27192 * Setting Stack Size from gnatlink::
27193 * Setting Heap Size from gnatlink::
27194 @end menu
27195
27196 @node Using GNAT on Windows
27197 @section Using GNAT on Windows
27198
27199 @noindent
27200 One of the strengths of the GNAT technology is that its tool set
27201 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27202 @code{gdb} debugger, etc.) is used in the same way regardless of the
27203 platform.
27204
27205 On Windows this tool set is complemented by a number of Microsoft-specific
27206 tools that have been provided to facilitate interoperability with Windows
27207 when this is required. With these tools:
27208
27209 @itemize @bullet
27210
27211 @item
27212 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27213 subsystems.
27214
27215 @item
27216 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27217 relocatable and non-relocatable DLLs are supported).
27218
27219 @item
27220 You can build Ada DLLs for use in other applications. These applications
27221 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27222 relocatable and non-relocatable Ada DLLs are supported.
27223
27224 @item
27225 You can include Windows resources in your Ada application.
27226
27227 @item
27228 You can use or create COM/DCOM objects.
27229 @end itemize
27230
27231 @noindent
27232 Immediately below are listed all known general GNAT-for-Windows restrictions.
27233 Other restrictions about specific features like Windows Resources and DLLs
27234 are listed in separate sections below.
27235
27236 @itemize @bullet
27237
27238 @item
27239 It is not possible to use @code{GetLastError} and @code{SetLastError}
27240 when tasking, protected records, or exceptions are used. In these
27241 cases, in order to implement Ada semantics, the GNAT run-time system
27242 calls certain Win32 routines that set the last error variable to 0 upon
27243 success. It should be possible to use @code{GetLastError} and
27244 @code{SetLastError} when tasking, protected record, and exception
27245 features are not used, but it is not guaranteed to work.
27246
27247 @item
27248 It is not possible to link against Microsoft libraries except for
27249 import libraries. Interfacing must be done by the mean of DLLs.
27250
27251 @item
27252 When the compilation environment is located on FAT32 drives, users may
27253 experience recompilations of the source files that have not changed if
27254 Daylight Saving Time (DST) state has changed since the last time files
27255 were compiled. NTFS drives do not have this problem.
27256
27257 @item
27258 No components of the GNAT toolset use any entries in the Windows
27259 registry. The only entries that can be created are file associations and
27260 PATH settings, provided the user has chosen to create them at installation
27261 time, as well as some minimal book-keeping information needed to correctly
27262 uninstall or integrate different GNAT products.
27263 @end itemize
27264
27265 @node Using a network installation of GNAT
27266 @section Using a network installation of GNAT
27267
27268 @noindent
27269 Make sure the system on which GNAT is installed is accessible from the
27270 current machine, i.e., the install location is shared over the network.
27271 Shared resources are accessed on Windows by means of UNC paths, which
27272 have the format @code{\\server\sharename\path}
27273
27274 In order to use such a network installation, simply add the UNC path of the
27275 @file{bin} directory of your GNAT installation in front of your PATH. For
27276 example, if GNAT is installed in @file{\GNAT} directory of a share location
27277 called @file{c-drive} on a machine @file{LOKI}, the following command will
27278 make it available:
27279
27280 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27281
27282 Be aware that every compilation using the network installation results in the
27283 transfer of large amounts of data across the network and will likely cause
27284 serious performance penalty.
27285
27286 @node CONSOLE and WINDOWS subsystems
27287 @section CONSOLE and WINDOWS subsystems
27288 @cindex CONSOLE Subsystem
27289 @cindex WINDOWS Subsystem
27290 @cindex -mwindows
27291
27292 @noindent
27293 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27294 (which is the default subsystem) will always create a console when
27295 launching the application. This is not something desirable when the
27296 application has a Windows GUI. To get rid of this console the
27297 application must be using the @code{WINDOWS} subsystem. To do so
27298 the @option{-mwindows} linker option must be specified.
27299
27300 @smallexample
27301 $ gnatmake winprog -largs -mwindows
27302 @end smallexample
27303
27304 @node Temporary Files
27305 @section Temporary Files
27306 @cindex Temporary files
27307
27308 @noindent
27309 It is possible to control where temporary files gets created by setting
27310 the @env{TMP} environment variable. The file will be created:
27311
27312 @itemize
27313 @item Under the directory pointed to by the @env{TMP} environment variable if
27314 this directory exists.
27315
27316 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27317 set (or not pointing to a directory) and if this directory exists.
27318
27319 @item Under the current working directory otherwise.
27320 @end itemize
27321
27322 @noindent
27323 This allows you to determine exactly where the temporary
27324 file will be created. This is particularly useful in networked
27325 environments where you may not have write access to some
27326 directories.
27327
27328 @node Mixed-Language Programming on Windows
27329 @section Mixed-Language Programming on Windows
27330
27331 @noindent
27332 Developing pure Ada applications on Windows is no different than on
27333 other GNAT-supported platforms. However, when developing or porting an
27334 application that contains a mix of Ada and C/C++, the choice of your
27335 Windows C/C++ development environment conditions your overall
27336 interoperability strategy.
27337
27338 If you use @command{gcc} to compile the non-Ada part of your application,
27339 there are no Windows-specific restrictions that affect the overall
27340 interoperability with your Ada code. If you do want to use the
27341 Microsoft tools for your non-Ada code, you have two choices:
27342
27343 @enumerate
27344 @item
27345 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27346 application. In this case, use the Microsoft or whatever environment to
27347 build the DLL and use GNAT to build your executable
27348 (@pxref{Using DLLs with GNAT}).
27349
27350 @item
27351 Or you can encapsulate your Ada code in a DLL to be linked with the
27352 other part of your application. In this case, use GNAT to build the DLL
27353 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27354 or whatever environment to build your executable.
27355 @end enumerate
27356
27357 @node Windows Calling Conventions
27358 @section Windows Calling Conventions
27359 @findex Stdcall
27360 @findex APIENTRY
27361
27362 This section pertain only to Win32. On Win64 there is a single native
27363 calling convention. All convention specifiers are ignored on this
27364 platform.
27365
27366 @menu
27367 * C Calling Convention::
27368 * Stdcall Calling Convention::
27369 * Win32 Calling Convention::
27370 * DLL Calling Convention::
27371 @end menu
27372
27373 @noindent
27374 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27375 (callee), there are several ways to push @code{G}'s parameters on the
27376 stack and there are several possible scenarios to clean up the stack
27377 upon @code{G}'s return. A calling convention is an agreed upon software
27378 protocol whereby the responsibilities between the caller (@code{F}) and
27379 the callee (@code{G}) are clearly defined. Several calling conventions
27380 are available for Windows:
27381
27382 @itemize @bullet
27383 @item
27384 @code{C} (Microsoft defined)
27385
27386 @item
27387 @code{Stdcall} (Microsoft defined)
27388
27389 @item
27390 @code{Win32} (GNAT specific)
27391
27392 @item
27393 @code{DLL} (GNAT specific)
27394 @end itemize
27395
27396 @node C Calling Convention
27397 @subsection @code{C} Calling Convention
27398
27399 @noindent
27400 This is the default calling convention used when interfacing to C/C++
27401 routines compiled with either @command{gcc} or Microsoft Visual C++.
27402
27403 In the @code{C} calling convention subprogram parameters are pushed on the
27404 stack by the caller from right to left. The caller itself is in charge of
27405 cleaning up the stack after the call. In addition, the name of a routine
27406 with @code{C} calling convention is mangled by adding a leading underscore.
27407
27408 The name to use on the Ada side when importing (or exporting) a routine
27409 with @code{C} calling convention is the name of the routine. For
27410 instance the C function:
27411
27412 @smallexample
27413 int get_val (long);
27414 @end smallexample
27415
27416 @noindent
27417 should be imported from Ada as follows:
27418
27419 @smallexample @c ada
27420 @group
27421 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27422 pragma Import (C, Get_Val, External_Name => "get_val");
27423 @end group
27424 @end smallexample
27425
27426 @noindent
27427 Note that in this particular case the @code{External_Name} parameter could
27428 have been omitted since, when missing, this parameter is taken to be the
27429 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27430 is missing, as in the above example, this parameter is set to be the
27431 @code{External_Name} with a leading underscore.
27432
27433 When importing a variable defined in C, you should always use the @code{C}
27434 calling convention unless the object containing the variable is part of a
27435 DLL (in which case you should use the @code{Stdcall} calling
27436 convention, @pxref{Stdcall Calling Convention}).
27437
27438 @node Stdcall Calling Convention
27439 @subsection @code{Stdcall} Calling Convention
27440
27441 @noindent
27442 This convention, which was the calling convention used for Pascal
27443 programs, is used by Microsoft for all the routines in the Win32 API for
27444 efficiency reasons. It must be used to import any routine for which this
27445 convention was specified.
27446
27447 In the @code{Stdcall} calling convention subprogram parameters are pushed
27448 on the stack by the caller from right to left. The callee (and not the
27449 caller) is in charge of cleaning the stack on routine exit. In addition,
27450 the name of a routine with @code{Stdcall} calling convention is mangled by
27451 adding a leading underscore (as for the @code{C} calling convention) and a
27452 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27453 bytes) of the parameters passed to the routine.
27454
27455 The name to use on the Ada side when importing a C routine with a
27456 @code{Stdcall} calling convention is the name of the C routine. The leading
27457 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27458 the compiler. For instance the Win32 function:
27459
27460 @smallexample
27461 @b{APIENTRY} int get_val (long);
27462 @end smallexample
27463
27464 @noindent
27465 should be imported from Ada as follows:
27466
27467 @smallexample @c ada
27468 @group
27469 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27470 pragma Import (Stdcall, Get_Val);
27471 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27472 @end group
27473 @end smallexample
27474
27475 @noindent
27476 As for the @code{C} calling convention, when the @code{External_Name}
27477 parameter is missing, it is taken to be the name of the Ada entity in lower
27478 case. If instead of writing the above import pragma you write:
27479
27480 @smallexample @c ada
27481 @group
27482 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27483 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27484 @end group
27485 @end smallexample
27486
27487 @noindent
27488 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27489 of specifying the @code{External_Name} parameter you specify the
27490 @code{Link_Name} as in the following example:
27491
27492 @smallexample @c ada
27493 @group
27494 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27495 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27496 @end group
27497 @end smallexample
27498
27499 @noindent
27500 then the imported routine is @code{retrieve_val}, that is, there is no
27501 decoration at all. No leading underscore and no Stdcall suffix
27502 @code{@@}@code{@var{nn}}.
27503
27504 @noindent
27505 This is especially important as in some special cases a DLL's entry
27506 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27507 name generated for a call has it.
27508
27509 @noindent
27510 It is also possible to import variables defined in a DLL by using an
27511 import pragma for a variable. As an example, if a DLL contains a
27512 variable defined as:
27513
27514 @smallexample
27515 int my_var;
27516 @end smallexample
27517
27518 @noindent
27519 then, to access this variable from Ada you should write:
27520
27521 @smallexample @c ada
27522 @group
27523 My_Var : Interfaces.C.int;
27524 pragma Import (Stdcall, My_Var);
27525 @end group
27526 @end smallexample
27527
27528 @noindent
27529 Note that to ease building cross-platform bindings this convention
27530 will be handled as a @code{C} calling convention on non-Windows platforms.
27531
27532 @node Win32 Calling Convention
27533 @subsection @code{Win32} Calling Convention
27534
27535 @noindent
27536 This convention, which is GNAT-specific is fully equivalent to the
27537 @code{Stdcall} calling convention described above.
27538
27539 @node DLL Calling Convention
27540 @subsection @code{DLL} Calling Convention
27541
27542 @noindent
27543 This convention, which is GNAT-specific is fully equivalent to the
27544 @code{Stdcall} calling convention described above.
27545
27546 @node Introduction to Dynamic Link Libraries (DLLs)
27547 @section Introduction to Dynamic Link Libraries (DLLs)
27548 @findex DLL
27549
27550 @noindent
27551 A Dynamically Linked Library (DLL) is a library that can be shared by
27552 several applications running under Windows. A DLL can contain any number of
27553 routines and variables.
27554
27555 One advantage of DLLs is that you can change and enhance them without
27556 forcing all the applications that depend on them to be relinked or
27557 recompiled. However, you should be aware than all calls to DLL routines are
27558 slower since, as you will understand below, such calls are indirect.
27559
27560 To illustrate the remainder of this section, suppose that an application
27561 wants to use the services of a DLL @file{API.dll}. To use the services
27562 provided by @file{API.dll} you must statically link against the DLL or
27563 an import library which contains a jump table with an entry for each
27564 routine and variable exported by the DLL. In the Microsoft world this
27565 import library is called @file{API.lib}. When using GNAT this import
27566 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27567 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27568
27569 After you have linked your application with the DLL or the import library
27570 and you run your application, here is what happens:
27571
27572 @enumerate
27573 @item
27574 Your application is loaded into memory.
27575
27576 @item
27577 The DLL @file{API.dll} is mapped into the address space of your
27578 application. This means that:
27579
27580 @itemize @bullet
27581 @item
27582 The DLL will use the stack of the calling thread.
27583
27584 @item
27585 The DLL will use the virtual address space of the calling process.
27586
27587 @item
27588 The DLL will allocate memory from the virtual address space of the calling
27589 process.
27590
27591 @item
27592 Handles (pointers) can be safely exchanged between routines in the DLL
27593 routines and routines in the application using the DLL.
27594 @end itemize
27595
27596 @item
27597 The entries in the jump table (from the import library @file{libAPI.dll.a}
27598 or @file{API.lib} or automatically created when linking against a DLL)
27599 which is part of your application are initialized with the addresses
27600 of the routines and variables in @file{API.dll}.
27601
27602 @item
27603 If present in @file{API.dll}, routines @code{DllMain} or
27604 @code{DllMainCRTStartup} are invoked. These routines typically contain
27605 the initialization code needed for the well-being of the routines and
27606 variables exported by the DLL.
27607 @end enumerate
27608
27609 @noindent
27610 There is an additional point which is worth mentioning. In the Windows
27611 world there are two kind of DLLs: relocatable and non-relocatable
27612 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27613 in the target application address space. If the addresses of two
27614 non-relocatable DLLs overlap and these happen to be used by the same
27615 application, a conflict will occur and the application will run
27616 incorrectly. Hence, when possible, it is always preferable to use and
27617 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27618 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27619 User's Guide) removes the debugging symbols from the DLL but the DLL can
27620 still be relocated.
27621
27622 As a side note, an interesting difference between Microsoft DLLs and
27623 Unix shared libraries, is the fact that on most Unix systems all public
27624 routines are exported by default in a Unix shared library, while under
27625 Windows it is possible (but not required) to list exported routines in
27626 a definition file (@pxref{The Definition File}).
27627
27628 @node Using DLLs with GNAT
27629 @section Using DLLs with GNAT
27630
27631 @menu
27632 * Creating an Ada Spec for the DLL Services::
27633 * Creating an Import Library::
27634 @end menu
27635
27636 @noindent
27637 To use the services of a DLL, say @file{API.dll}, in your Ada application
27638 you must have:
27639
27640 @enumerate
27641 @item
27642 The Ada spec for the routines and/or variables you want to access in
27643 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27644 header files provided with the DLL.
27645
27646 @item
27647 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27648 mentioned an import library is a statically linked library containing the
27649 import table which will be filled at load time to point to the actual
27650 @file{API.dll} routines. Sometimes you don't have an import library for the
27651 DLL you want to use. The following sections will explain how to build
27652 one. Note that this is optional.
27653
27654 @item
27655 The actual DLL, @file{API.dll}.
27656 @end enumerate
27657
27658 @noindent
27659 Once you have all the above, to compile an Ada application that uses the
27660 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27661 you simply issue the command
27662
27663 @smallexample
27664 $ gnatmake my_ada_app -largs -lAPI
27665 @end smallexample
27666
27667 @noindent
27668 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27669 tells the GNAT linker to look for an import library. The linker will
27670 look for a library name in this specific order:
27671
27672 @enumerate
27673 @item @file{libAPI.dll.a}
27674 @item @file{API.dll.a}
27675 @item @file{libAPI.a}
27676 @item @file{API.lib}
27677 @item @file{libAPI.dll}
27678 @item @file{API.dll}
27679 @end enumerate
27680
27681 The first three are the GNU style import libraries. The third is the
27682 Microsoft style import libraries. The last two are the actual DLL names.
27683
27684 Note that if the Ada package spec for @file{API.dll} contains the
27685 following pragma
27686
27687 @smallexample @c ada
27688 pragma Linker_Options ("-lAPI");
27689 @end smallexample
27690
27691 @noindent
27692 you do not have to add @option{-largs -lAPI} at the end of the
27693 @command{gnatmake} command.
27694
27695 If any one of the items above is missing you will have to create it
27696 yourself. The following sections explain how to do so using as an
27697 example a fictitious DLL called @file{API.dll}.
27698
27699 @node Creating an Ada Spec for the DLL Services
27700 @subsection Creating an Ada Spec for the DLL Services
27701
27702 @noindent
27703 A DLL typically comes with a C/C++ header file which provides the
27704 definitions of the routines and variables exported by the DLL. The Ada
27705 equivalent of this header file is a package spec that contains definitions
27706 for the imported entities. If the DLL you intend to use does not come with
27707 an Ada spec you have to generate one such spec yourself. For example if
27708 the header file of @file{API.dll} is a file @file{api.h} containing the
27709 following two definitions:
27710
27711 @smallexample
27712 @group
27713 @cartouche
27714 int some_var;
27715 int get (char *);
27716 @end cartouche
27717 @end group
27718 @end smallexample
27719
27720 @noindent
27721 then the equivalent Ada spec could be:
27722
27723 @smallexample @c ada
27724 @group
27725 @cartouche
27726 with Interfaces.C.Strings;
27727 package API is
27728    use Interfaces;
27729
27730    Some_Var : C.int;
27731    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27732
27733 private
27734    pragma Import (C, Get);
27735    pragma Import (DLL, Some_Var);
27736 end API;
27737 @end cartouche
27738 @end group
27739 @end smallexample
27740
27741 @noindent
27742 Note that a variable is
27743 @strong{always imported with a DLL convention}. A function
27744 can have @code{C} or @code{Stdcall} convention.
27745 (@pxref{Windows Calling Conventions}).
27746
27747 @node Creating an Import Library
27748 @subsection Creating an Import Library
27749 @cindex Import library
27750
27751 @menu
27752 * The Definition File::
27753 * GNAT-Style Import Library::
27754 * Microsoft-Style Import Library::
27755 @end menu
27756
27757 @noindent
27758 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27759 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27760 with @file{API.dll} you can skip this section. You can also skip this
27761 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27762 as in this case it is possible to link directly against the
27763 DLL. Otherwise read on.
27764
27765 @node The Definition File
27766 @subsubsection The Definition File
27767 @cindex Definition file
27768 @findex .def
27769
27770 @noindent
27771 As previously mentioned, and unlike Unix systems, the list of symbols
27772 that are exported from a DLL must be provided explicitly in Windows.
27773 The main goal of a definition file is precisely that: list the symbols
27774 exported by a DLL. A definition file (usually a file with a @code{.def}
27775 suffix) has the following structure:
27776
27777 @smallexample
27778 @group
27779 @cartouche
27780 @r{[}LIBRARY @var{name}@r{]}
27781 @r{[}DESCRIPTION @var{string}@r{]}
27782 EXPORTS
27783    @var{symbol1}
27784    @var{symbol2}
27785    @dots{}
27786 @end cartouche
27787 @end group
27788 @end smallexample
27789
27790 @table @code
27791 @item LIBRARY @var{name}
27792 This section, which is optional, gives the name of the DLL.
27793
27794 @item DESCRIPTION @var{string}
27795 This section, which is optional, gives a description string that will be
27796 embedded in the import library.
27797
27798 @item EXPORTS
27799 This section gives the list of exported symbols (procedures, functions or
27800 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27801 section of @file{API.def} looks like:
27802
27803 @smallexample
27804 @group
27805 @cartouche
27806 EXPORTS
27807    some_var
27808    get
27809 @end cartouche
27810 @end group
27811 @end smallexample
27812 @end table
27813
27814 @noindent
27815 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27816 (@pxref{Windows Calling Conventions}) for a Stdcall
27817 calling convention function in the exported symbols list.
27818
27819 @noindent
27820 There can actually be other sections in a definition file, but these
27821 sections are not relevant to the discussion at hand.
27822
27823 @node GNAT-Style Import Library
27824 @subsubsection GNAT-Style Import Library
27825
27826 @noindent
27827 To create a static import library from @file{API.dll} with the GNAT tools
27828 you should proceed as follows:
27829
27830 @enumerate
27831 @item
27832 Create the definition file @file{API.def} (@pxref{The Definition File}).
27833 For that use the @code{dll2def} tool as follows:
27834
27835 @smallexample
27836 $ dll2def API.dll > API.def
27837 @end smallexample
27838
27839 @noindent
27840 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27841 to standard output the list of entry points in the DLL. Note that if
27842 some routines in the DLL have the @code{Stdcall} convention
27843 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27844 suffix then you'll have to edit @file{api.def} to add it, and specify
27845 @option{-k} to @command{gnatdll} when creating the import library.
27846
27847 @noindent
27848 Here are some hints to find the right @code{@@}@var{nn} suffix.
27849
27850 @enumerate
27851 @item
27852 If you have the Microsoft import library (.lib), it is possible to get
27853 the right symbols by using Microsoft @code{dumpbin} tool (see the
27854 corresponding Microsoft documentation for further details).
27855
27856 @smallexample
27857 $ dumpbin /exports api.lib
27858 @end smallexample
27859
27860 @item
27861 If you have a message about a missing symbol at link time the compiler
27862 tells you what symbol is expected. You just have to go back to the
27863 definition file and add the right suffix.
27864 @end enumerate
27865
27866 @item
27867 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27868 (@pxref{Using gnatdll}) as follows:
27869
27870 @smallexample
27871 $ gnatdll -e API.def -d API.dll
27872 @end smallexample
27873
27874 @noindent
27875 @code{gnatdll} takes as input a definition file @file{API.def} and the
27876 name of the DLL containing the services listed in the definition file
27877 @file{API.dll}. The name of the static import library generated is
27878 computed from the name of the definition file as follows: if the
27879 definition file name is @var{xyz}@code{.def}, the import library name will
27880 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27881 @option{-e} could have been removed because the name of the definition
27882 file (before the ``@code{.def}'' suffix) is the same as the name of the
27883 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27884 @end enumerate
27885
27886 @node Microsoft-Style Import Library
27887 @subsubsection Microsoft-Style Import Library
27888
27889 @noindent
27890 With GNAT you can either use a GNAT-style or Microsoft-style import
27891 library. A Microsoft import library is needed only if you plan to make an
27892 Ada DLL available to applications developed with Microsoft
27893 tools (@pxref{Mixed-Language Programming on Windows}).
27894
27895 To create a Microsoft-style import library for @file{API.dll} you
27896 should proceed as follows:
27897
27898 @enumerate
27899 @item
27900 Create the definition file @file{API.def} from the DLL. For this use either
27901 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27902 tool (see the corresponding Microsoft documentation for further details).
27903
27904 @item
27905 Build the actual import library using Microsoft's @code{lib} utility:
27906
27907 @smallexample
27908 $ lib -machine:IX86 -def:API.def -out:API.lib
27909 @end smallexample
27910
27911 @noindent
27912 If you use the above command the definition file @file{API.def} must
27913 contain a line giving the name of the DLL:
27914
27915 @smallexample
27916 LIBRARY      "API"
27917 @end smallexample
27918
27919 @noindent
27920 See the Microsoft documentation for further details about the usage of
27921 @code{lib}.
27922 @end enumerate
27923
27924 @node Building DLLs with GNAT Project files
27925 @section Building DLLs with GNAT Project files
27926 @cindex DLLs, building
27927
27928 @noindent
27929 There is nothing specific to Windows in the build process.
27930 @pxref{Library Projects}.
27931
27932 @noindent
27933 Due to a system limitation, it is not possible under Windows to create threads
27934 when inside the @code{DllMain} routine which is used for auto-initialization
27935 of shared libraries, so it is not possible to have library level tasks in SALs.
27936
27937 @node Building DLLs with GNAT
27938 @section Building DLLs with GNAT
27939 @cindex DLLs, building
27940
27941 @noindent
27942 This section explain how to build DLLs using the GNAT built-in DLL
27943 support. With the following procedure it is straight forward to build
27944 and use DLLs with GNAT.
27945
27946 @enumerate
27947
27948 @item building object files
27949
27950 The first step is to build all objects files that are to be included
27951 into the DLL. This is done by using the standard @command{gnatmake} tool.
27952
27953 @item building the DLL
27954
27955 To build the DLL you must use @command{gcc}'s @option{-shared} and
27956 @option{-shared-libgcc} options. It is quite simple to use this method:
27957
27958 @smallexample
27959 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27960 @end smallexample
27961
27962 It is important to note that in this case all symbols found in the
27963 object files are automatically exported. It is possible to restrict
27964 the set of symbols to export by passing to @command{gcc} a definition
27965 file, @pxref{The Definition File}. For example:
27966
27967 @smallexample
27968 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27969 @end smallexample
27970
27971 If you use a definition file you must export the elaboration procedures
27972 for every package that required one. Elaboration procedures are named
27973 using the package name followed by "_E".
27974
27975 @item preparing DLL to be used
27976
27977 For the DLL to be used by client programs the bodies must be hidden
27978 from it and the .ali set with read-only attribute. This is very important
27979 otherwise GNAT will recompile all packages and will not actually use
27980 the code in the DLL. For example:
27981
27982 @smallexample
27983 $ mkdir apilib
27984 $ copy *.ads *.ali api.dll apilib
27985 $ attrib +R apilib\*.ali
27986 @end smallexample
27987
27988 @end enumerate
27989
27990 At this point it is possible to use the DLL by directly linking
27991 against it. Note that you must use the GNAT shared runtime when using
27992 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27993 option.
27994
27995 @smallexample
27996 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27997 @end smallexample
27998
27999 @node Building DLLs with gnatdll
28000 @section Building DLLs with gnatdll
28001 @cindex DLLs, building
28002
28003 @menu
28004 * Limitations When Using Ada DLLs from Ada::
28005 * Exporting Ada Entities::
28006 * Ada DLLs and Elaboration::
28007 * Ada DLLs and Finalization::
28008 * Creating a Spec for Ada DLLs::
28009 * Creating the Definition File::
28010 * Using gnatdll::
28011 @end menu
28012
28013 @noindent
28014 Note that it is preferred to use GNAT Project files
28015 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
28016 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
28017
28018 This section explains how to build DLLs containing Ada code using
28019 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
28020 remainder of this section.
28021
28022 The steps required to build an Ada DLL that is to be used by Ada as well as
28023 non-Ada applications are as follows:
28024
28025 @enumerate
28026 @item
28027 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
28028 @code{Stdcall} calling convention to avoid any Ada name mangling for the
28029 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
28030 skip this step if you plan to use the Ada DLL only from Ada applications.
28031
28032 @item
28033 Your Ada code must export an initialization routine which calls the routine
28034 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
28035 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
28036 routine exported by the Ada DLL must be invoked by the clients of the DLL
28037 to initialize the DLL.
28038
28039 @item
28040 When useful, the DLL should also export a finalization routine which calls
28041 routine @code{adafinal} generated by @command{gnatbind} to perform the
28042 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
28043 The finalization routine exported by the Ada DLL must be invoked by the
28044 clients of the DLL when the DLL services are no further needed.
28045
28046 @item
28047 You must provide a spec for the services exported by the Ada DLL in each
28048 of the programming languages to which you plan to make the DLL available.
28049
28050 @item
28051 You must provide a definition file listing the exported entities
28052 (@pxref{The Definition File}).
28053
28054 @item
28055 Finally you must use @code{gnatdll} to produce the DLL and the import
28056 library (@pxref{Using gnatdll}).
28057 @end enumerate
28058
28059 @noindent
28060 Note that a relocatable DLL stripped using the @code{strip}
28061 binutils tool will not be relocatable anymore. To build a DLL without
28062 debug information pass @code{-largs -s} to @code{gnatdll}. This
28063 restriction does not apply to a DLL built using a Library Project.
28064 @pxref{Library Projects}.
28065
28066 @node Limitations When Using Ada DLLs from Ada
28067 @subsection Limitations When Using Ada DLLs from Ada
28068
28069 @noindent
28070 When using Ada DLLs from Ada applications there is a limitation users
28071 should be aware of. Because on Windows the GNAT run time is not in a DLL of
28072 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
28073 each Ada DLL includes the services of the GNAT run time that are necessary
28074 to the Ada code inside the DLL. As a result, when an Ada program uses an
28075 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
28076 one in the main program.
28077
28078 It is therefore not possible to exchange GNAT run-time objects between the
28079 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28080 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
28081 types, etc.
28082
28083 It is completely safe to exchange plain elementary, array or record types,
28084 Windows object handles, etc.
28085
28086 @node Exporting Ada Entities
28087 @subsection Exporting Ada Entities
28088 @cindex Export table
28089
28090 @noindent
28091 Building a DLL is a way to encapsulate a set of services usable from any
28092 application. As a result, the Ada entities exported by a DLL should be
28093 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28094 any Ada name mangling. As an example here is an Ada package
28095 @code{API}, spec and body, exporting two procedures, a function, and a
28096 variable:
28097
28098 @smallexample @c ada
28099 @group
28100 @cartouche
28101 with Interfaces.C; use Interfaces;
28102 package API is
28103    Count : C.int := 0;
28104    function Factorial (Val : C.int) return C.int;
28105
28106    procedure Initialize_API;
28107    procedure Finalize_API;
28108    --  Initialization & Finalization routines. More in the next section.
28109 private
28110    pragma Export (C, Initialize_API);
28111    pragma Export (C, Finalize_API);
28112    pragma Export (C, Count);
28113    pragma Export (C, Factorial);
28114 end API;
28115 @end cartouche
28116 @end group
28117 @end smallexample
28118
28119 @smallexample @c ada
28120 @group
28121 @cartouche
28122 package body API is
28123    function Factorial (Val : C.int) return C.int is
28124       Fact : C.int := 1;
28125    begin
28126       Count := Count + 1;
28127       for K in 1 .. Val loop
28128          Fact := Fact * K;
28129       end loop;
28130       return Fact;
28131    end Factorial;
28132
28133    procedure Initialize_API is
28134       procedure Adainit;
28135       pragma Import (C, Adainit);
28136    begin
28137       Adainit;
28138    end Initialize_API;
28139
28140    procedure Finalize_API is
28141       procedure Adafinal;
28142       pragma Import (C, Adafinal);
28143    begin
28144       Adafinal;
28145    end Finalize_API;
28146 end API;
28147 @end cartouche
28148 @end group
28149 @end smallexample
28150
28151 @noindent
28152 If the Ada DLL you are building will only be used by Ada applications
28153 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28154 convention. As an example, the previous package could be written as
28155 follows:
28156
28157 @smallexample @c ada
28158 @group
28159 @cartouche
28160 package API is
28161    Count : Integer := 0;
28162    function Factorial (Val : Integer) return Integer;
28163
28164    procedure Initialize_API;
28165    procedure Finalize_API;
28166    --  Initialization and Finalization routines.
28167 end API;
28168 @end cartouche
28169 @end group
28170 @end smallexample
28171
28172 @smallexample @c ada
28173 @group
28174 @cartouche
28175 package body API is
28176    function Factorial (Val : Integer) return Integer is
28177       Fact : Integer := 1;
28178    begin
28179       Count := Count + 1;
28180       for K in 1 .. Val loop
28181          Fact := Fact * K;
28182       end loop;
28183       return Fact;
28184    end Factorial;
28185
28186    @dots{}
28187    --  The remainder of this package body is unchanged.
28188 end API;
28189 @end cartouche
28190 @end group
28191 @end smallexample
28192
28193 @noindent
28194 Note that if you do not export the Ada entities with a @code{C} or
28195 @code{Stdcall} convention you will have to provide the mangled Ada names
28196 in the definition file of the Ada DLL
28197 (@pxref{Creating the Definition File}).
28198
28199 @node Ada DLLs and Elaboration
28200 @subsection Ada DLLs and Elaboration
28201 @cindex DLLs and elaboration
28202
28203 @noindent
28204 The DLL that you are building contains your Ada code as well as all the
28205 routines in the Ada library that are needed by it. The first thing a
28206 user of your DLL must do is elaborate the Ada code
28207 (@pxref{Elaboration Order Handling in GNAT}).
28208
28209 To achieve this you must export an initialization routine
28210 (@code{Initialize_API} in the previous example), which must be invoked
28211 before using any of the DLL services. This elaboration routine must call
28212 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28213 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28214 @code{Initialize_Api} for an example. Note that the GNAT binder is
28215 automatically invoked during the DLL build process by the @code{gnatdll}
28216 tool (@pxref{Using gnatdll}).
28217
28218 When a DLL is loaded, Windows systematically invokes a routine called
28219 @code{DllMain}. It would therefore be possible to call @code{adainit}
28220 directly from @code{DllMain} without having to provide an explicit
28221 initialization routine. Unfortunately, it is not possible to call
28222 @code{adainit} from the @code{DllMain} if your program has library level
28223 tasks because access to the @code{DllMain} entry point is serialized by
28224 the system (that is, only a single thread can execute ``through'' it at a
28225 time), which means that the GNAT run time will deadlock waiting for the
28226 newly created task to complete its initialization.
28227
28228 @node Ada DLLs and Finalization
28229 @subsection Ada DLLs and Finalization
28230 @cindex DLLs and finalization
28231
28232 @noindent
28233 When the services of an Ada DLL are no longer needed, the client code should
28234 invoke the DLL finalization routine, if available. The DLL finalization
28235 routine is in charge of releasing all resources acquired by the DLL. In the
28236 case of the Ada code contained in the DLL, this is achieved by calling
28237 routine @code{adafinal} generated by the GNAT binder
28238 (@pxref{Binding with Non-Ada Main Programs}).
28239 See the body of @code{Finalize_Api} for an
28240 example. As already pointed out the GNAT binder is automatically invoked
28241 during the DLL build process by the @code{gnatdll} tool
28242 (@pxref{Using gnatdll}).
28243
28244 @node Creating a Spec for Ada DLLs
28245 @subsection Creating a Spec for Ada DLLs
28246
28247 @noindent
28248 To use the services exported by the Ada DLL from another programming
28249 language (e.g.@: C), you have to translate the specs of the exported Ada
28250 entities in that language. For instance in the case of @code{API.dll},
28251 the corresponding C header file could look like:
28252
28253 @smallexample
28254 @group
28255 @cartouche
28256 extern int *_imp__count;
28257 #define count (*_imp__count)
28258 int factorial (int);
28259 @end cartouche
28260 @end group
28261 @end smallexample
28262
28263 @noindent
28264 It is important to understand that when building an Ada DLL to be used by
28265 other Ada applications, you need two different specs for the packages
28266 contained in the DLL: one for building the DLL and the other for using
28267 the DLL. This is because the @code{DLL} calling convention is needed to
28268 use a variable defined in a DLL, but when building the DLL, the variable
28269 must have either the @code{Ada} or @code{C} calling convention. As an
28270 example consider a DLL comprising the following package @code{API}:
28271
28272 @smallexample @c ada
28273 @group
28274 @cartouche
28275 package API is
28276    Count : Integer := 0;
28277    @dots{}
28278    --  Remainder of the package omitted.
28279 end API;
28280 @end cartouche
28281 @end group
28282 @end smallexample
28283
28284 @noindent
28285 After producing a DLL containing package @code{API}, the spec that
28286 must be used to import @code{API.Count} from Ada code outside of the
28287 DLL is:
28288
28289 @smallexample @c ada
28290 @group
28291 @cartouche
28292 package API is
28293    Count : Integer;
28294    pragma Import (DLL, Count);
28295 end API;
28296 @end cartouche
28297 @end group
28298 @end smallexample
28299
28300 @node Creating the Definition File
28301 @subsection Creating the Definition File
28302
28303 @noindent
28304 The definition file is the last file needed to build the DLL. It lists
28305 the exported symbols. As an example, the definition file for a DLL
28306 containing only package @code{API} (where all the entities are exported
28307 with a @code{C} calling convention) is:
28308
28309 @smallexample
28310 @group
28311 @cartouche
28312 EXPORTS
28313     count
28314     factorial
28315     finalize_api
28316     initialize_api
28317 @end cartouche
28318 @end group
28319 @end smallexample
28320
28321 @noindent
28322 If the @code{C} calling convention is missing from package @code{API},
28323 then the definition file contains the mangled Ada names of the above
28324 entities, which in this case are:
28325
28326 @smallexample
28327 @group
28328 @cartouche
28329 EXPORTS
28330     api__count
28331     api__factorial
28332     api__finalize_api
28333     api__initialize_api
28334 @end cartouche
28335 @end group
28336 @end smallexample
28337
28338 @node Using gnatdll
28339 @subsection Using @code{gnatdll}
28340 @findex gnatdll
28341
28342 @menu
28343 * gnatdll Example::
28344 * gnatdll behind the Scenes::
28345 * Using dlltool::
28346 @end menu
28347
28348 @noindent
28349 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28350 and non-Ada sources that make up your DLL have been compiled.
28351 @code{gnatdll} is actually in charge of two distinct tasks: build the
28352 static import library for the DLL and the actual DLL. The form of the
28353 @code{gnatdll} command is
28354
28355 @smallexample
28356 @cartouche
28357 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28358 @c Expanding @ovar macro inline (explanation in macro def comments)
28359 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28360 @end cartouche
28361 @end smallexample
28362
28363 @noindent
28364 where @var{list-of-files} is a list of ALI and object files. The object
28365 file list must be the exact list of objects corresponding to the non-Ada
28366 sources whose services are to be included in the DLL. The ALI file list
28367 must be the exact list of ALI files for the corresponding Ada sources
28368 whose services are to be included in the DLL. If @var{list-of-files} is
28369 missing, only the static import library is generated.
28370
28371 @noindent
28372 You may specify any of the following switches to @code{gnatdll}:
28373
28374 @table @code
28375 @c @item -a@ovar{address}
28376 @c Expanding @ovar macro inline (explanation in macro def comments)
28377 @item -a@r{[}@var{address}@r{]}
28378 @cindex @option{-a} (@code{gnatdll})
28379 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28380 specified the default address @var{0x11000000} will be used. By default,
28381 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28382 advise the reader to build relocatable DLL.
28383
28384 @item -b @var{address}
28385 @cindex @option{-b} (@code{gnatdll})
28386 Set the relocatable DLL base address. By default the address is
28387 @code{0x11000000}.
28388
28389 @item -bargs @var{opts}
28390 @cindex @option{-bargs} (@code{gnatdll})
28391 Binder options. Pass @var{opts} to the binder.
28392
28393 @item -d @var{dllfile}
28394 @cindex @option{-d} (@code{gnatdll})
28395 @var{dllfile} is the name of the DLL. This switch must be present for
28396 @code{gnatdll} to do anything. The name of the generated import library is
28397 obtained algorithmically from @var{dllfile} as shown in the following
28398 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28399 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28400 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28401 as shown in the following example:
28402 if @var{dllfile} is @code{xyz.dll}, the definition
28403 file used is @code{xyz.def}.
28404
28405 @item -e @var{deffile}
28406 @cindex @option{-e} (@code{gnatdll})
28407 @var{deffile} is the name of the definition file.
28408
28409 @item -g
28410 @cindex @option{-g} (@code{gnatdll})
28411 Generate debugging information. This information is stored in the object
28412 file and copied from there to the final DLL file by the linker,
28413 where it can be read by the debugger. You must use the
28414 @option{-g} switch if you plan on using the debugger or the symbolic
28415 stack traceback.
28416
28417 @item -h
28418 @cindex @option{-h} (@code{gnatdll})
28419 Help mode. Displays @code{gnatdll} switch usage information.
28420
28421 @item -Idir
28422 @cindex @option{-I} (@code{gnatdll})
28423 Direct @code{gnatdll} to search the @var{dir} directory for source and
28424 object files needed to build the DLL.
28425 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28426
28427 @item -k
28428 @cindex @option{-k} (@code{gnatdll})
28429 Removes the @code{@@}@var{nn} suffix from the import library's exported
28430 names, but keeps them for the link names. You must specify this
28431 option if you want to use a @code{Stdcall} function in a DLL for which
28432 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28433 of the Windows NT DLL for example. This option has no effect when
28434 @option{-n} option is specified.
28435
28436 @item -l @var{file}
28437 @cindex @option{-l} (@code{gnatdll})
28438 The list of ALI and object files used to build the DLL are listed in
28439 @var{file}, instead of being given in the command line. Each line in
28440 @var{file} contains the name of an ALI or object file.
28441
28442 @item -n
28443 @cindex @option{-n} (@code{gnatdll})
28444 No Import. Do not create the import library.
28445
28446 @item -q
28447 @cindex @option{-q} (@code{gnatdll})
28448 Quiet mode. Do not display unnecessary messages.
28449
28450 @item -v
28451 @cindex @option{-v} (@code{gnatdll})
28452 Verbose mode. Display extra information.
28453
28454 @item -largs @var{opts}
28455 @cindex @option{-largs} (@code{gnatdll})
28456 Linker options. Pass @var{opts} to the linker.
28457 @end table
28458
28459 @node gnatdll Example
28460 @subsubsection @code{gnatdll} Example
28461
28462 @noindent
28463 As an example the command to build a relocatable DLL from @file{api.adb}
28464 once @file{api.adb} has been compiled and @file{api.def} created is
28465
28466 @smallexample
28467 $ gnatdll -d api.dll api.ali
28468 @end smallexample
28469
28470 @noindent
28471 The above command creates two files: @file{libapi.dll.a} (the import
28472 library) and @file{api.dll} (the actual DLL). If you want to create
28473 only the DLL, just type:
28474
28475 @smallexample
28476 $ gnatdll -d api.dll -n api.ali
28477 @end smallexample
28478
28479 @noindent
28480 Alternatively if you want to create just the import library, type:
28481
28482 @smallexample
28483 $ gnatdll -d api.dll
28484 @end smallexample
28485
28486 @node gnatdll behind the Scenes
28487 @subsubsection @code{gnatdll} behind the Scenes
28488
28489 @noindent
28490 This section details the steps involved in creating a DLL. @code{gnatdll}
28491 does these steps for you. Unless you are interested in understanding what
28492 goes on behind the scenes, you should skip this section.
28493
28494 We use the previous example of a DLL containing the Ada package @code{API},
28495 to illustrate the steps necessary to build a DLL. The starting point is a
28496 set of objects that will make up the DLL and the corresponding ALI
28497 files. In the case of this example this means that @file{api.o} and
28498 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28499 the following:
28500
28501 @enumerate
28502 @item
28503 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28504 the information necessary to generate relocation information for the
28505 DLL.
28506
28507 @smallexample
28508 @group
28509 $ gnatbind -n api
28510 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28511 @end group
28512 @end smallexample
28513
28514 @noindent
28515 In addition to the base file, the @command{gnatlink} command generates an
28516 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28517 asks @command{gnatlink} to generate the routines @code{DllMain} and
28518 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28519 is loaded into memory.
28520
28521 @item
28522 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28523 export table (@file{api.exp}). The export table contains the relocation
28524 information in a form which can be used during the final link to ensure
28525 that the Windows loader is able to place the DLL anywhere in memory.
28526
28527 @smallexample
28528 @group
28529 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28530           --output-exp api.exp
28531 @end group
28532 @end smallexample
28533
28534 @item
28535 @code{gnatdll} builds the base file using the new export table. Note that
28536 @command{gnatbind} must be called once again since the binder generated file
28537 has been deleted during the previous call to @command{gnatlink}.
28538
28539 @smallexample
28540 @group
28541 $ gnatbind -n api
28542 $ gnatlink api -o api.jnk api.exp -mdll
28543       -Wl,--base-file,api.base
28544 @end group
28545 @end smallexample
28546
28547 @item
28548 @code{gnatdll} builds the new export table using the new base file and
28549 generates the DLL import library @file{libAPI.dll.a}.
28550
28551 @smallexample
28552 @group
28553 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28554           --output-exp api.exp --output-lib libAPI.a
28555 @end group
28556 @end smallexample
28557
28558 @item
28559 Finally @code{gnatdll} builds the relocatable DLL using the final export
28560 table.
28561
28562 @smallexample
28563 @group
28564 $ gnatbind -n api
28565 $ gnatlink api api.exp -o api.dll -mdll
28566 @end group
28567 @end smallexample
28568 @end enumerate
28569
28570 @node Using dlltool
28571 @subsubsection Using @code{dlltool}
28572
28573 @noindent
28574 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28575 DLLs and static import libraries. This section summarizes the most
28576 common @code{dlltool} switches. The form of the @code{dlltool} command
28577 is
28578
28579 @smallexample
28580 @c $ dlltool @ovar{switches}
28581 @c Expanding @ovar macro inline (explanation in macro def comments)
28582 $ dlltool @r{[}@var{switches}@r{]}
28583 @end smallexample
28584
28585 @noindent
28586 @code{dlltool} switches include:
28587
28588 @table @option
28589 @item --base-file @var{basefile}
28590 @cindex @option{--base-file} (@command{dlltool})
28591 Read the base file @var{basefile} generated by the linker. This switch
28592 is used to create a relocatable DLL.
28593
28594 @item --def @var{deffile}
28595 @cindex @option{--def} (@command{dlltool})
28596 Read the definition file.
28597
28598 @item --dllname @var{name}
28599 @cindex @option{--dllname} (@command{dlltool})
28600 Gives the name of the DLL. This switch is used to embed the name of the
28601 DLL in the static import library generated by @code{dlltool} with switch
28602 @option{--output-lib}.
28603
28604 @item -k
28605 @cindex @option{-k} (@command{dlltool})
28606 Kill @code{@@}@var{nn} from exported names
28607 (@pxref{Windows Calling Conventions}
28608 for a discussion about @code{Stdcall}-style symbols.
28609
28610 @item --help
28611 @cindex @option{--help} (@command{dlltool})
28612 Prints the @code{dlltool} switches with a concise description.
28613
28614 @item --output-exp @var{exportfile}
28615 @cindex @option{--output-exp} (@command{dlltool})
28616 Generate an export file @var{exportfile}. The export file contains the
28617 export table (list of symbols in the DLL) and is used to create the DLL.
28618
28619 @item --output-lib @var{libfile}
28620 @cindex @option{--output-lib} (@command{dlltool})
28621 Generate a static import library @var{libfile}.
28622
28623 @item -v
28624 @cindex @option{-v} (@command{dlltool})
28625 Verbose mode.
28626
28627 @item --as @var{assembler-name}
28628 @cindex @option{--as} (@command{dlltool})
28629 Use @var{assembler-name} as the assembler. The default is @code{as}.
28630 @end table
28631
28632 @node GNAT and Windows Resources
28633 @section GNAT and Windows Resources
28634 @cindex Resources, windows
28635
28636 @menu
28637 * Building Resources::
28638 * Compiling Resources::
28639 * Using Resources::
28640 @end menu
28641
28642 @noindent
28643 Resources are an easy way to add Windows specific objects to your
28644 application. The objects that can be added as resources include:
28645
28646 @itemize @bullet
28647 @item menus
28648
28649 @item accelerators
28650
28651 @item dialog boxes
28652
28653 @item string tables
28654
28655 @item bitmaps
28656
28657 @item cursors
28658
28659 @item icons
28660
28661 @item fonts
28662
28663 @item version information
28664 @end itemize
28665
28666 For example, a version information resource can be defined as follow and
28667 embedded into an executable or DLL:
28668
28669 A version information resource can be used to embed information into an
28670 executable or a DLL. These information can be viewed using the file properties
28671 from the Windows Explorer. Here is an example of a version information
28672 resource:
28673
28674 @smallexample
28675 @group
28676 1 VERSIONINFO
28677 FILEVERSION     1,0,0,0
28678 PRODUCTVERSION  1,0,0,0
28679 BEGIN
28680   BLOCK "StringFileInfo"
28681   BEGIN
28682     BLOCK "080904E4"
28683     BEGIN
28684       VALUE "CompanyName", "My Company Name"
28685       VALUE "FileDescription", "My application"
28686       VALUE "FileVersion", "1.0"
28687       VALUE "InternalName", "my_app"
28688       VALUE "LegalCopyright", "My Name"
28689       VALUE "OriginalFilename", "my_app.exe"
28690       VALUE "ProductName", "My App"
28691       VALUE "ProductVersion", "1.0"
28692     END
28693   END
28694
28695   BLOCK "VarFileInfo"
28696   BEGIN
28697     VALUE "Translation", 0x809, 1252
28698   END
28699 END
28700 @end group
28701 @end smallexample
28702
28703 The value @code{0809} (langID) is for the U.K English language and
28704 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28705 multilingual.
28706
28707 @noindent
28708 This section explains how to build, compile and use resources. Note that this
28709 section does not cover all resource objects, for a complete description see
28710 the corresponding Microsoft documentation.
28711
28712 @node Building Resources
28713 @subsection Building Resources
28714 @cindex Resources, building
28715
28716 @noindent
28717 A resource file is an ASCII file. By convention resource files have an
28718 @file{.rc} extension.
28719 The easiest way to build a resource file is to use Microsoft tools
28720 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28721 @code{dlgedit.exe} to build dialogs.
28722 It is always possible to build an @file{.rc} file yourself by writing a
28723 resource script.
28724
28725 It is not our objective to explain how to write a resource file. A
28726 complete description of the resource script language can be found in the
28727 Microsoft documentation.
28728
28729 @node Compiling Resources
28730 @subsection Compiling Resources
28731 @findex rc
28732 @findex windres
28733 @cindex Resources, compiling
28734
28735 @noindent
28736 This section describes how to build a GNAT-compatible (COFF) object file
28737 containing the resources. This is done using the Resource Compiler
28738 @code{windres} as follows:
28739
28740 @smallexample
28741 $ windres -i myres.rc -o myres.o
28742 @end smallexample
28743
28744 @noindent
28745 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28746 file. You can specify an alternate preprocessor (usually named
28747 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28748 parameter. A list of all possible options may be obtained by entering
28749 the command @code{windres} @option{--help}.
28750
28751 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28752 to produce a @file{.res} file (binary resource file). See the
28753 corresponding Microsoft documentation for further details. In this case
28754 you need to use @code{windres} to translate the @file{.res} file to a
28755 GNAT-compatible object file as follows:
28756
28757 @smallexample
28758 $ windres -i myres.res -o myres.o
28759 @end smallexample
28760
28761 @node Using Resources
28762 @subsection Using Resources
28763 @cindex Resources, using
28764
28765 @noindent
28766 To include the resource file in your program just add the
28767 GNAT-compatible object file for the resource(s) to the linker
28768 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28769 option:
28770
28771 @smallexample
28772 $ gnatmake myprog -largs myres.o
28773 @end smallexample
28774
28775 @node Debugging a DLL
28776 @section Debugging a DLL
28777 @cindex DLL debugging
28778
28779 @menu
28780 * Program and DLL Both Built with GCC/GNAT::
28781 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28782 @end menu
28783
28784 @noindent
28785 Debugging a DLL is similar to debugging a standard program. But
28786 we have to deal with two different executable parts: the DLL and the
28787 program that uses it. We have the following four possibilities:
28788
28789 @enumerate 1
28790 @item
28791 The program and the DLL are built with @code{GCC/GNAT}.
28792 @item
28793 The program is built with foreign tools and the DLL is built with
28794 @code{GCC/GNAT}.
28795 @item
28796 The program is built with @code{GCC/GNAT} and the DLL is built with
28797 foreign tools.
28798 @end enumerate
28799
28800 @noindent
28801 In this section we address only cases one and two above.
28802 There is no point in trying to debug
28803 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28804 information in it. To do so you must use a debugger compatible with the
28805 tools suite used to build the DLL.
28806
28807 @node Program and DLL Both Built with GCC/GNAT
28808 @subsection Program and DLL Both Built with GCC/GNAT
28809
28810 @noindent
28811 This is the simplest case. Both the DLL and the program have @code{GDB}
28812 compatible debugging information. It is then possible to break anywhere in
28813 the process. Let's suppose here that the main procedure is named
28814 @code{ada_main} and that in the DLL there is an entry point named
28815 @code{ada_dll}.
28816
28817 @noindent
28818 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28819 program must have been built with the debugging information (see GNAT -g
28820 switch). Here are the step-by-step instructions for debugging it:
28821
28822 @enumerate 1
28823 @item Launch @code{GDB} on the main program.
28824
28825 @smallexample
28826 $ gdb -nw ada_main
28827 @end smallexample
28828
28829 @item Start the program and stop at the beginning of the main procedure
28830
28831 @smallexample
28832 (gdb) start
28833 @end smallexample
28834
28835 @noindent
28836 This step is required to be able to set a breakpoint inside the DLL. As long
28837 as the program is not run, the DLL is not loaded. This has the
28838 consequence that the DLL debugging information is also not loaded, so it is not
28839 possible to set a breakpoint in the DLL.
28840
28841 @item Set a breakpoint inside the DLL
28842
28843 @smallexample
28844 (gdb) break ada_dll
28845 (gdb) cont
28846 @end smallexample
28847
28848 @end enumerate
28849
28850 @noindent
28851 At this stage a breakpoint is set inside the DLL. From there on
28852 you can use the standard approach to debug the whole program
28853 (@pxref{Running and Debugging Ada Programs}).
28854
28855 @ignore
28856 @c This used to work, probably because the DLLs were non-relocatable
28857 @c keep this section around until the problem is sorted out.
28858
28859 To break on the @code{DllMain} routine it is not possible to follow
28860 the procedure above. At the time the program stop on @code{ada_main}
28861 the @code{DllMain} routine as already been called. Either you can use
28862 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28863
28864 @enumerate 1
28865 @item Launch @code{GDB} on the main program.
28866
28867 @smallexample
28868 $ gdb ada_main
28869 @end smallexample
28870
28871 @item Load DLL symbols
28872
28873 @smallexample
28874 (gdb) add-sym api.dll
28875 @end smallexample
28876
28877 @item Set a breakpoint inside the DLL
28878
28879 @smallexample
28880 (gdb) break ada_dll.adb:45
28881 @end smallexample
28882
28883 Note that at this point it is not possible to break using the routine symbol
28884 directly as the program is not yet running. The solution is to break
28885 on the proper line (break in @file{ada_dll.adb} line 45).
28886
28887 @item Start the program
28888
28889 @smallexample
28890 (gdb) run
28891 @end smallexample
28892
28893 @end enumerate
28894 @end ignore
28895
28896 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28897 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28898
28899 @menu
28900 * Debugging the DLL Directly::
28901 * Attaching to a Running Process::
28902 @end menu
28903
28904 @noindent
28905 In this case things are slightly more complex because it is not possible to
28906 start the main program and then break at the beginning to load the DLL and the
28907 associated DLL debugging information. It is not possible to break at the
28908 beginning of the program because there is no @code{GDB} debugging information,
28909 and therefore there is no direct way of getting initial control. This
28910 section addresses this issue by describing some methods that can be used
28911 to break somewhere in the DLL to debug it.
28912
28913 @noindent
28914 First suppose that the main procedure is named @code{main} (this is for
28915 example some C code built with Microsoft Visual C) and that there is a
28916 DLL named @code{test.dll} containing an Ada entry point named
28917 @code{ada_dll}.
28918
28919 @noindent
28920 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28921 been built with debugging information (see GNAT -g option).
28922
28923 @node Debugging the DLL Directly
28924 @subsubsection Debugging the DLL Directly
28925
28926 @enumerate 1
28927 @item
28928 Find out the executable starting address
28929
28930 @smallexample
28931 $ objdump --file-header main.exe
28932 @end smallexample
28933
28934 The starting address is reported on the last line. For example:
28935
28936 @smallexample
28937 main.exe:     file format pei-i386
28938 architecture: i386, flags 0x0000010a:
28939 EXEC_P, HAS_DEBUG, D_PAGED
28940 start address 0x00401010
28941 @end smallexample
28942
28943 @item
28944 Launch the debugger on the executable.
28945
28946 @smallexample
28947 $ gdb main.exe
28948 @end smallexample
28949
28950 @item
28951 Set a breakpoint at the starting address, and launch the program.
28952
28953 @smallexample
28954 $ (gdb) break *0x00401010
28955 $ (gdb) run
28956 @end smallexample
28957
28958 The program will stop at the given address.
28959
28960 @item
28961 Set a breakpoint on a DLL subroutine.
28962
28963 @smallexample
28964 (gdb) break ada_dll.adb:45
28965 @end smallexample
28966
28967 Or if you want to break using a symbol on the DLL, you need first to
28968 select the Ada language (language used by the DLL).
28969
28970 @smallexample
28971 (gdb) set language ada
28972 (gdb) break ada_dll
28973 @end smallexample
28974
28975 @item
28976 Continue the program.
28977
28978 @smallexample
28979 (gdb) cont
28980 @end smallexample
28981
28982 @noindent
28983 This will run the program until it reaches the breakpoint that has been
28984 set. From that point you can use the standard way to debug a program
28985 as described in (@pxref{Running and Debugging Ada Programs}).
28986
28987 @end enumerate
28988
28989 @noindent
28990 It is also possible to debug the DLL by attaching to a running process.
28991
28992 @node Attaching to a Running Process
28993 @subsubsection Attaching to a Running Process
28994 @cindex DLL debugging, attach to process
28995
28996 @noindent
28997 With @code{GDB} it is always possible to debug a running process by
28998 attaching to it. It is possible to debug a DLL this way. The limitation
28999 of this approach is that the DLL must run long enough to perform the
29000 attach operation. It may be useful for instance to insert a time wasting
29001 loop in the code of the DLL to meet this criterion.
29002
29003 @enumerate 1
29004
29005 @item Launch the main program @file{main.exe}.
29006
29007 @smallexample
29008 $ main
29009 @end smallexample
29010
29011 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
29012 that the process PID for @file{main.exe} is 208.
29013
29014 @item Launch gdb.
29015
29016 @smallexample
29017 $ gdb
29018 @end smallexample
29019
29020 @item Attach to the running process to be debugged.
29021
29022 @smallexample
29023 (gdb) attach 208
29024 @end smallexample
29025
29026 @item Load the process debugging information.
29027
29028 @smallexample
29029 (gdb) symbol-file main.exe
29030 @end smallexample
29031
29032 @item Break somewhere in the DLL.
29033
29034 @smallexample
29035 (gdb) break ada_dll
29036 @end smallexample
29037
29038 @item Continue process execution.
29039
29040 @smallexample
29041 (gdb) cont
29042 @end smallexample
29043
29044 @end enumerate
29045
29046 @noindent
29047 This last step will resume the process execution, and stop at
29048 the breakpoint we have set. From there you can use the standard
29049 approach to debug a program as described in
29050 (@pxref{Running and Debugging Ada Programs}).
29051
29052 @node Setting Stack Size from gnatlink
29053 @section Setting Stack Size from @command{gnatlink}
29054
29055 @noindent
29056 It is possible to specify the program stack size at link time. On modern
29057 versions of Windows, starting with XP, this is mostly useful to set the size of
29058 the main stack (environment task). The other task stacks are set with pragma
29059 Storage_Size or with the @command{gnatbind -d} command.
29060
29061 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
29062 reserve size of individual tasks, the link-time stack size applies to all
29063 tasks, and pragma Storage_Size has no effect.
29064 In particular, Stack Overflow checks are made against this
29065 link-time specified size.
29066
29067 This setting can be done with
29068 @command{gnatlink} using either:
29069
29070 @itemize @bullet
29071
29072 @item using @option{-Xlinker} linker option
29073
29074 @smallexample
29075 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
29076 @end smallexample
29077
29078 This sets the stack reserve size to 0x10000 bytes and the stack commit
29079 size to 0x1000 bytes.
29080
29081 @item using @option{-Wl} linker option
29082
29083 @smallexample
29084 $ gnatlink hello -Wl,--stack=0x1000000
29085 @end smallexample
29086
29087 This sets the stack reserve size to 0x1000000 bytes. Note that with
29088 @option{-Wl} option it is not possible to set the stack commit size
29089 because the coma is a separator for this option.
29090
29091 @end itemize
29092
29093 @node Setting Heap Size from gnatlink
29094 @section Setting Heap Size from @command{gnatlink}
29095
29096 @noindent
29097 Under Windows systems, it is possible to specify the program heap size from
29098 @command{gnatlink} using either:
29099
29100 @itemize @bullet
29101
29102 @item using @option{-Xlinker} linker option
29103
29104 @smallexample
29105 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29106 @end smallexample
29107
29108 This sets the heap reserve size to 0x10000 bytes and the heap commit
29109 size to 0x1000 bytes.
29110
29111 @item using @option{-Wl} linker option
29112
29113 @smallexample
29114 $ gnatlink hello -Wl,--heap=0x1000000
29115 @end smallexample
29116
29117 This sets the heap reserve size to 0x1000000 bytes. Note that with
29118 @option{-Wl} option it is not possible to set the heap commit size
29119 because the coma is a separator for this option.
29120
29121 @end itemize
29122
29123 @end ifset
29124
29125 @c **********************************
29126 @c * GNU Free Documentation License *
29127 @c **********************************
29128 @include fdl.texi
29129 @c GNU Free Documentation License
29130
29131 @node Index,,GNU Free Documentation License, Top
29132 @unnumbered Index
29133
29134 @printindex cp
29135
29136 @contents
29137 @c Put table of contents at end, otherwise it precedes the "title page" in
29138 @c the .txt version
29139 @c Edit the pdf file to move the contents to the beginning, after the title
29140 @c page
29141
29142 @bye